diff --git a/src/Refine_DefMap.cpp b/src/Refine_DefMap.cpp index 1b00acc21..6e5cb7284 100644 --- a/src/Refine_DefMap.cpp +++ b/src/Refine_DefMap.cpp @@ -36,7 +36,8 @@ #include "Refine_DefMap.h" #include "darks_dialog.h" -enum { +enum +{ ID_PREVIEW = 10001, }; @@ -63,8 +64,9 @@ static void AddTableEntryPair(wxWindow *parent, wxFlexGridSizer *pTable, const w pTable->Add(pControl, 1, wxALL, 5); } -RefineDefMap::RefineDefMap(wxWindow *parent) : - wxDialog(parent, wxID_ANY, _("Refine Bad-pixel Map"), wxDefaultPosition, wxSize(900, 400), wxCAPTION | wxCLOSE_BOX), m_profileId(-1) +RefineDefMap::RefineDefMap(wxWindow *parent) + : wxDialog(parent, wxID_ANY, _("Refine Bad-pixel Map"), wxDefaultPosition, wxSize(900, 400), wxCAPTION | wxCLOSE_BOX) + , m_profileId(-1) { SetSize(wxSize(900, 400)); @@ -162,11 +164,13 @@ RefineDefMap::RefineDefMap(wxWindow *parent) : pHotSlider = new wxSlider(this, wxID_ANY, 0, 0, 100, wxPoint(-1, -1), wxSize(200, -1), wxSL_HORIZONTAL | wxSL_VALUE_LABEL); pHotSlider->Bind(wxEVT_SCROLL_CHANGED, &RefineDefMap::OnHotChange, this); pHotSlider->Bind(wxEVT_SCROLL_THUMBTRACK, &RefineDefMap::OnHotChange, this); - pHotSlider->SetToolTip(_("Move this slider to increase or decrease the number of pixels that will be treated as 'hot', then click on 'generate' to build and load the new bad-pixel map")); + pHotSlider->SetToolTip(_("Move this slider to increase or decrease the number of pixels that will be treated as 'hot', " + "then click on 'generate' to build and load the new bad-pixel map")); pColdSlider = new wxSlider(this, wxID_ANY, 0, 0, 100, wxPoint(-1, -1), wxSize(200, -1), wxSL_HORIZONTAL | wxSL_VALUE_LABEL); pColdSlider->Bind(wxEVT_SCROLL_CHANGED, &RefineDefMap::OnColdChange, this); pColdSlider->Bind(wxEVT_SCROLL_THUMBTRACK, &RefineDefMap::OnColdChange, this); - pColdSlider->SetToolTip(_("Move this slider to increase or decrease the number of pixels that will be treated as 'cold', then click on 'generate' to build and load the new bad-pixel map")); + pColdSlider->SetToolTip(_("Move this slider to increase or decrease the number of pixels that will be treated as 'cold', " + "then click on 'generate' to build and load the new bad-pixel map")); AddTableEntryPair(this, pAdjustmentGrid, _("Hot pixels"), pHotSlider); AddTableEntryPair(this, pAdjustmentGrid, _("Cold pixels"), pColdSlider); pAggressivenessGrp->Add(pAdjustmentGrid); @@ -180,21 +184,17 @@ RefineDefMap::RefineDefMap(wxWindow *parent) : pApplyBtn = new wxButton(this, wxID_ANY, _("Generate")); pApplyBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &RefineDefMap::OnGenerate, this); - pApplyBtn->SetToolTip(_("Use the current aggressiveness settings to build and load a new bad-pixel map; this will discard any manually added bad pixels")); + pApplyBtn->SetToolTip(_("Use the current aggressiveness settings to build and load a new bad-pixel map; this will discard " + "any manually added bad pixels")); pAddDefectBtn = new wxButton(this, wxID_ANY, _("Add Bad Pixel")); pAddDefectBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &RefineDefMap::OnAddDefect, this); - pAddDefectBtn->SetToolTip(_("Click on a bad pixel in the image display; then click on this button to add it to the in-use bad-pixel map")); - - pButtonSizer->Add( - pResetBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); - pButtonSizer->Add( - pApplyBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); - pButtonSizer->Add( - pAddDefectBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pAddDefectBtn->SetToolTip( + _("Click on a bad pixel in the image display; then click on this button to add it to the in-use bad-pixel map")); + + pButtonSizer->Add(pResetBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pButtonSizer->Add(pApplyBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pButtonSizer->Add(pAddDefectBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); pVSizer->Add(pButtonSizer, wxSizerFlags().Center().Border(wxALL, 10)); @@ -240,7 +240,7 @@ bool RefineDefMap::InitUI() if (!DefectMap::DefectMapExists(pConfig->GetCurrentProfileId(), false)) { if (RebuildMasterDarks()) - firstTime = true; // Need to get the UI built before finishing up + firstTime = true; // Need to get the UI built before finishing up } if (DefectMap::DefectMapExists(m_profileId, false) || firstTime) { @@ -253,7 +253,7 @@ bool RefineDefMap::InitUI() else { RestoreCameraMode(); - return false; // No master dark files to work with, user didn't build them + return false; // No master dark files to work with, user didn't build them } } @@ -297,7 +297,6 @@ void RefineDefMap::LoadFromProfile() GetBadPxCounts(); ShowStatus(_("Statistics completed..."), false); LoadPreview(); - } bool RefineDefMap::RebuildMasterDarks() @@ -351,10 +350,10 @@ void RefineDefMap::ApplyNewMap() pInfoGrid->SetCellValue(hotFactorLoc, wxString::Format("%d", pHotSlider->GetValue())); pInfoGrid->SetCellValue(coldFactorLoc, wxString::Format("%d", pColdSlider->GetValue())); pInfoGrid->SetCellValue(createTimeLoc, DefectMapTimeString()); - pStatsGrid->SetCellValue(manualPixelLoc, "0"); // Manual pixels will always be discarded + pStatsGrid->SetCellValue(manualPixelLoc, "0"); // Manual pixels will always be discarded pHotSlider->Enable(true); pColdSlider->Enable(true); - pFrame->SetDarkMenuState(); // Get enabled states straightened out + pFrame->SetDarkMenuState(); // Get enabled states straightened out } void RefineDefMap::OnGenerate(wxCommandEvent& evt) @@ -369,7 +368,7 @@ void RefineDefMap::OnGenerate(wxCommandEvent& evt) else { ShowStatus(_("Master dark frames NOT rebuilt"), false); - return; // Couldn't do what we were asked + return; // Couldn't do what we were asked } } ApplyNewMap(); @@ -382,7 +381,7 @@ wxString RefineDefMap::DefectMapTimeString() if (wxFileExists(dfFileName)) { wxDateTime when = wxFileModificationTime(dfFileName); - return(when.FormatDate() + " " + when.FormatTime()); + return (when.FormatDate() + " " + when.FormatTime()); } else return ""; @@ -405,7 +404,7 @@ void RefineDefMap::Recalc() if (manualPixelCount != 0) { manualPixelCount = 0; - pStatsGrid->SetCellValue(manualPixelLoc, "0"); // Manual pixels will always be discarded + pStatsGrid->SetCellValue(manualPixelLoc, "0"); // Manual pixels will always be discarded } GetBadPxCounts(); m_builder.BuildDefectMap(m_defectMap, false); @@ -432,7 +431,7 @@ void RefineDefMap::OnAddDefect(wxCommandEvent& evt) if (pFrame->pGuider->IsLocked()) { - wxPoint badspot((int)(pixelLoc.X + 0.5), (int)(pixelLoc.Y + 0.5)); + wxPoint badspot((int) (pixelLoc.X + 0.5), (int) (pixelLoc.Y + 0.5)); Debug.AddLine(wxString::Format("Current position returned as %.1f,%.1f", pixelLoc.X, pixelLoc.Y)); Debug.AddLine(wxString::Format("User adding bad pixel at %d,%d", badspot.x, badspot.y)); @@ -445,7 +444,7 @@ void RefineDefMap::OnAddDefect(wxCommandEvent& evt) { if (!pCurrMap->FindDefect(badspot)) { - pCurrMap->AddDefect(badspot); // Changes both in-memory instance and disk file + pCurrMap->AddDefect(badspot); // Changes both in-memory instance and disk file manualPixelCount++; pStatsGrid->SetCellValue(manualPixelLoc, wxString::Format("%d", manualPixelCount)); needLoadPreview = true; diff --git a/src/about_dialog.cpp b/src/about_dialog.cpp index 7c58e33c1..3f83fce3a 100644 --- a/src/about_dialog.cpp +++ b/src/about_dialog.cpp @@ -44,171 +44,173 @@ wxEND_EVENT_TABLE(); // clang-format on AboutDialog::AboutDialog() - : wxDialog(pFrame, wxID_ANY, wxString::Format(_("About %s"), APPNAME), - wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) + : wxDialog( + pFrame, wxID_ANY, wxString::Format(_("About %s"), APPNAME), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) { SetBackgroundColour(*wxWHITE); wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL); - #include "icons/phd2_64.png.h" +#include "icons/phd2_64.png.h" wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_64)); wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, phd2); wxFileSystem::AddHandler(new wxMemoryFSHandler); - wxMemoryFSHandler::AddFile("about.html", wxString::Format( - "" - "" - "%s %s
" - "
" - "PHD2 home - openphdguiding.org " - "" - "Source code on GitHub" - "
" - "" - "Project maintainers
" - "" - "" - "" - "" - "" - "
Andy GalassoBruce Waddington
" - "
" - "Past maintainers
" - "" - "" - "" - "" - "" - "
Craig StarkBret McKee
" - "
" - "Credits
" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "
Bernhard Reutner-FischerStefan ElsteGeoffrey HausheerJared WellmanJohn Wainwright
Sylvain GirardMax ChenCarsten PrzygodaHans LambermontDavid Ault
Markus WieczorekLinkageRobin GloverPatrick ChevalleyScott Edwards
Eiji KaneshigeKonstantin MenshikoffJakub BartasJavier ROleh Malyi
Tsung-Chi WuRaffi EnficiaudSabin FotaDylan O'DonnellKatsuhiro Kojima
Simon TaylorHallgeir HolienLaurent SchmitzAtushi SakauchiGiorgio Mazzacurati
Günter ScholzRay GralakKhalefa AlgadiDavid C. PartridgeMatteo Ghellere
normaEdgar D. KlenskeBernhard SchölkopfPhilipp HennigStephan Wenninger
Wagner TrindadeCyril RichardMattia VergaIván ZabalaKen Self
Alex HelmsRandy PufahlJasem MutlaqThomas StiborLudovic Pollet
Paweł PleskaczyńskinabePlaPhilip PeakeManuel RosalesMarcel Greter
Miquel RecachaMario NicotraGerry RobertsAnthony HinsingerRadek Kaczorek
Sebastian GodeletStanislav HolubValerio FaiuoloPeter BerbeePaolo Stivanin
Paweł SojaToupTek Photonics Co., LtdJarno PaananenLeo ShatzNiels Rackwitz
Philipp WeberKirill M. Skorobogatov

" - "
" - "
" - "Copyright 2006-2013 Craig Stark
" - "Copyright 2009 Geoffrey Hausheer
" - "Copyright 2012-2013 Bret McKee
" - "Copyright 2013 Sylvain Girard
" - "Copyright 2013-2022 Andy Galasso
" - "Copyright 2013-2023 Bruce Waddington
" - "Copyright 2014 Hans Lambermont
" - "Copyright 2014 Robin Glover
" - "Copyright 2014-2017 Max Planck Society
" - "Copyright 2017 Ken Self
" - "Copyright 2019 Jasem Mutlaq
" - "
" - "
" - "The Predictive PEC guide algorithm is based on
" - "Gaussian Process Based Predictive Control
for Periodic Error Correction
" - "
" - "", APPNAME, FULLVER)); + wxMemoryFSHandler::AddFile("about.html", + wxString::Format("" + "" + "%s %s
" + "
" + "PHD2 home - openphdguiding.org " + "" + "Source code on GitHub" + "
" + "" + "Project maintainers
" + "" + "" + "" + "" + "" + "
Andy GalassoBruce Waddington
" + "
" + "Past maintainers
" + "" + "" + "" + "" + "" + "
Craig StarkBret McKee
" + "
" + "Credits
" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
Bernhard Reutner-FischerStefan ElsteGeoffrey HausheerJared WellmanJohn Wainwright
Sylvain GirardMax ChenCarsten PrzygodaHans LambermontDavid Ault
Markus WieczorekLinkageRobin GloverPatrick ChevalleyScott Edwards
Eiji KaneshigeKonstantin MenshikoffJakub BartasJavier ROleh Malyi
Tsung-Chi WuRaffi EnficiaudSabin FotaDylan O'DonnellKatsuhiro Kojima
Simon TaylorHallgeir HolienLaurent SchmitzAtushi SakauchiGiorgio Mazzacurati
Günter ScholzRay GralakKhalefa AlgadiDavid C. PartridgeMatteo Ghellere
normaEdgar D. KlenskeBernhard SchölkopfPhilipp HennigStephan Wenninger
Wagner TrindadeCyril RichardMattia VergaIván ZabalaKen Self
Alex HelmsRandy PufahlJasem MutlaqThomas StiborLudovic Pollet
Paweł PleskaczyńskinabePlaPhilip PeakeManuel RosalesMarcel Greter
Miquel RecachaMario NicotraGerry RobertsAnthony HinsingerRadek Kaczorek
Sebastian GodeletStanislav HolubValerio FaiuoloPeter BerbeePaolo Stivanin
Paweł SojaToupTek Photonics Co., LtdJarno PaananenLeo ShatzNiels Rackwitz
Philipp WeberKirill M. Skorobogatov

" + "
" + "
" + "Copyright 2006-2013 Craig Stark
" + "Copyright 2009 Geoffrey Hausheer
" + "Copyright 2012-2013 Bret McKee
" + "Copyright 2013 Sylvain Girard
" + "Copyright 2013-2022 Andy Galasso
" + "Copyright 2013-2023 Bruce Waddington
" + "Copyright 2014 Hans Lambermont
" + "Copyright 2014 Robin Glover
" + "Copyright 2014-2017 Max Planck Society
" + "Copyright 2017 Ken Self
" + "Copyright 2019 Jasem Mutlaq
" + "
" + "
" + "The Predictive PEC guide algorithm is based on
" + "Gaussian Process Based Predictive " + "Control
for Periodic Error Correction
" + "
" + "", + APPNAME, FULLVER)); wxHtmlWindow *pHtml; pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(640, 500), wxHW_SCROLLBAR_AUTO); pHtml->SetBorders(0); @@ -228,7 +230,7 @@ AboutDialog::~AboutDialog(void) wxMemoryFSHandler::RemoveFile("about.html"); } -void AboutDialog::OnLink(wxHtmlLinkEvent & event) +void AboutDialog::OnLink(wxHtmlLinkEvent& event) { wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref()); } diff --git a/src/about_dialog.h b/src/about_dialog.h index d6a7fed7e..27b88de02 100644 --- a/src/about_dialog.h +++ b/src/about_dialog.h @@ -35,15 +35,14 @@ #ifndef ABOUT_DIALOG_H_INCLUDED #define ABOUT_DIALOG_H_INCLUDED -class AboutDialog : - public wxDialog +class AboutDialog : public wxDialog { public: AboutDialog(void); ~AboutDialog(void); private: - void OnLink(wxHtmlLinkEvent & event); + void OnLink(wxHtmlLinkEvent& event); wxDECLARE_EVENT_TABLE(); }; diff --git a/src/advanced_dialog.cpp b/src/advanced_dialog.cpp index d292227db..5aa48570d 100644 --- a/src/advanced_dialog.cpp +++ b/src/advanced_dialog.cpp @@ -116,10 +116,10 @@ static void EnableValidators(wxWindow *win) EnableValidators(kid); } -AdvancedDialog::AdvancedDialog(MyFrame *pFrame) : - wxDialog(pFrame, wxID_ANY, _("Advanced Settings"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX), - m_tip(nullptr), - m_tipTimer(nullptr) +AdvancedDialog::AdvancedDialog(MyFrame *pFrame) + : wxDialog(pFrame, wxID_ANY, _("Advanced Settings"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) + , m_tip(nullptr) + , m_tipTimer(nullptr) { /* * The advanced dialog is made up of a number of "on the fly" generated panels that configure different things. @@ -160,9 +160,9 @@ AdvancedDialog::AdvancedDialog(MyFrame *pFrame) : #else m_pNotebook = new wxNotebook(this, wxID_ANY); #endif - m_pFrame = pFrame; // We get called before global var is initialized + m_pFrame = pFrame; // We get called before global var is initialized - wxSizerFlags sizer_flags = wxSizerFlags(0).Align(wxALIGN_TOP|wxALIGN_CENTER_HORIZONTAL).Border(wxALL,2).Expand(); + wxSizerFlags sizer_flags = wxSizerFlags(0).Align(wxALIGN_TOP | wxALIGN_CENTER_HORIZONTAL).Border(wxALL, 2).Expand(); // Build all the panels first - these are needed to create the various ConfigCtrlSets // Each panel gets a vertical sizer attached to it @@ -191,7 +191,7 @@ AdvancedDialog::AdvancedDialog(MyFrame *pFrame) : m_pDevicesSettingsPanel->SetSizer(pDevicesTabSizer); m_pNotebook->AddPage(m_pDevicesSettingsPanel, _("Other Devices")); - BuildCtrlSets(); // Populates the m_brainCtrls map with all UI controls + BuildCtrlSets(); // Populates the m_brainCtrls map with all UI controls // Pane contruction now pulls controls from the map and places them where they make sense to a user // Populate global pane @@ -222,12 +222,11 @@ AdvancedDialog::AdvancedDialog(MyFrame *pFrame) : wxSizer *bsz = CreateButtonSizer(wxOK | wxCANCEL); bsz->PrependStretchSpacer(); wxButton *helpbtn = new wxButton(this, wxID_ANY, _("Help")); -# include "icons/help22.png.h" +#include "icons/help22.png.h" wxBitmap help_bmp(wxBITMAP_PNG_FROM_DATA(help22)); helpbtn->SetBitmap(help_bmp, wxLEFT); - helpbtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, [this](wxCommandEvent& evt) { - ::pFrame->help->Display(HelpLink(m_pNotebook)); - }); + helpbtn->Bind( + wxEVT_COMMAND_BUTTON_CLICKED, [this](wxCommandEvent& evt) { ::pFrame->help->Display(HelpLink(m_pNotebook)); }); bsz->Prepend(helpbtn); pTopLevelSizer->Add(bsz, wxSizerFlags(0).Expand().Border(wxALL, 5)); SetSizerAndFit(pTopLevelSizer); @@ -243,7 +242,8 @@ AdvancedDialog::~AdvancedDialog() delete m_tipTimer; } -// Let a client(GearDialog) ask to preload the UI elements - prevents any visible delay when the AdvancedDialog is shown for the first time +// Let a client(GearDialog) ask to preload the UI elements - prevents any visible delay when the AdvancedDialog is shown for the +// first time void AdvancedDialog::Preload() { if (m_rebuildPanels) @@ -303,15 +303,15 @@ void AdvancedDialog::RebuildPanels() AddCameraPage(); - m_pGuiderPane->LayoutControls(m_pFrame->pGuider, m_brainCtrls); // Guider pane doesn't have specific device dependencies + m_pGuiderPane->LayoutControls(m_pFrame->pGuider, m_brainCtrls); // Guider pane doesn't have specific device dependencies m_pGuiderPane->Layout(); AddMountPage(); - AddAoPage(); // Will handle no AO case - AddRotatorPage(); // Will handle no Rotator case + AddAoPage(); // Will handle no AO case + AddRotatorPage(); // Will handle no Rotator case - if (m_pAOPane == nullptr && m_pRotatorPane == nullptr) // Dump the Other Devices tab if not needed + if (m_pAOPane == nullptr && m_pRotatorPane == nullptr) // Dump the Other Devices tab if not needed { int idx = m_pNotebook->FindPage(m_pDevicesSettingsPanel); if (idx != wxNOT_FOUND) @@ -328,7 +328,7 @@ void AdvancedDialog::RebuildPanels() GetSizer()->Fit(this); m_rebuildPanels = false; - ConfirmLayouts(); // maybe should be under compiletime option + ConfirmLayouts(); // maybe should be under compiletime option } // Needed by ConfigDialogCtrlSets to know what parent to use when creating a control @@ -346,7 +346,7 @@ wxWindow *AdvancedDialog::GetTabLocation(BRAIN_CTRL_IDS id) return m_pDevicesSettingsPanel; else { - assert(false); // Fundamental problem + assert(false); // Fundamental problem return nullptr; } } @@ -511,8 +511,7 @@ void AdvancedDialog::UnloadValues() // Any un-do ops need to be handled at the ConfigDialogPane level void AdvancedDialog::Undo() { - ConfigDialogPane *const panes[] = - { m_pGlobalPane, m_pGuiderPane, m_pCameraPane, m_pMountPane, m_pAOPane, m_pRotatorPane }; + ConfigDialogPane *const panes[] = { m_pGlobalPane, m_pGuiderPane, m_pCameraPane, m_pMountPane, m_pAOPane, m_pRotatorPane }; for (unsigned int i = 0; i < WXSIZEOF(panes); i++) { @@ -577,7 +576,6 @@ double AdvancedDialog::DetermineGuideSpeed() else minSpd = raSpd; sidRate = SiderealRateFromGuideSpeed(minSpd); - } } else @@ -595,22 +593,23 @@ double AdvancedDialog::DetermineGuideSpeed() } return sidRate; } -// Reacts to param changes in the AD that change the image scale. Calibration step-size is recalculated, calibration is cleared, MinMoves are set to defaults based on new image scale +// Reacts to param changes in the AD that change the image scale. Calibration step-size is recalculated, calibration is +// cleared, MinMoves are set to defaults based on new image scale void AdvancedDialog::MakeImageScaleAdjustments() { double guideSpeedX; Debug.Write("Image scale has changed via AD UI - step-size and algo adjustments will be made\n"); - Debug.Write(wxString::Format("New image scale properties: fl= %d, px= %.3fu, bin= %d\n", - pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), - pCamera->Binning)); + Debug.Write(wxString::Format("New image scale properties: fl= %d, px= %.3fu, bin= %d\n", pFrame->GetFocalLength(), + pCamera->GetCameraPixelSize(), pCamera->Binning)); // Determine a calibration step-size based on recommended distance and best estimator of mount guide speeds guideSpeedX = DetermineGuideSpeed(); int calibrationStep; - int recDistance = CalstepDialog::GetCalibrationDistance(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); + int recDistance = + CalstepDialog::GetCalibrationDistance(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); int oldStepSize = TheScope()->GetCalibrationDuration(); - CalstepDialog::GetCalibrationStepSize(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning, guideSpeedX, - CalstepDialog::DEFAULT_STEPS, 0, recDistance, nullptr, &calibrationStep); + CalstepDialog::GetCalibrationStepSize(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning, + guideSpeedX, CalstepDialog::DEFAULT_STEPS, 0, recDistance, nullptr, &calibrationStep); TheScope()->SetCalibrationDuration(calibrationStep); Debug.Write(wxString::Format("Cal step-size changed from %d ms to %d ms\n", oldStepSize, calibrationStep)); // Clear the calibration to force a new one and reset the min-move values @@ -621,7 +620,8 @@ void AdvancedDialog::MakeImageScaleAdjustments() pSecondaryMount->ClearCalibration(); Debug.Write("Calibrations cleared because of image scale change\n"); - double defMinMove = GuideAlgorithm::SmartDefaultMinMove(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); + double defMinMove = + GuideAlgorithm::SmartDefaultMinMove(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); Debug.Write(wxString::Format("Guide algo min moves reset to %.3fu\n", defMinMove)); pMount->GetXGuideAlgorithm()->SetMinMove(defMinMove); pMount->GetYGuideAlgorithm()->SetMinMove(defMinMove); @@ -660,7 +660,10 @@ size_t AdvancedDialog::FindPage(wxWindow *ctrl) struct ClearTipTimer : public wxTimer { wxTipWindow **m_w; - ClearTipTimer(wxTipWindow **w) : m_w(w) { } + ClearTipTimer(wxTipWindow **w) + : m_w(w) + { + } void Notify() override { if (*m_w) @@ -684,7 +687,10 @@ void AdvancedDialog::ShowInvalid(wxWindow *ctrl, const wxString& message) if (!m_tipTimer) m_tipTimer = new ClearTipTimer(&m_tip); - enum { TIP_TIMER_MILLISECONDS = 9000 }; + enum + { + TIP_TIMER_MILLISECONDS = 9000 + }; m_tipTimer->StartOnce(TIP_TIMER_MILLISECONDS); } diff --git a/src/advanced_dialog.h b/src/advanced_dialog.h index 9f75b1fa3..18fae66eb 100644 --- a/src/advanced_dialog.h +++ b/src/advanced_dialog.h @@ -43,7 +43,8 @@ class CameraConfigDialogPane; class GuiderConfigDialogPane; class wxTipWindow; -enum TAB_PAGES { +enum TAB_PAGES +{ AD_GLOBAL_PAGE, AD_GUIDER_PAGE, AD_CAMERA_PAGE, @@ -58,7 +59,7 @@ class AdvancedDialog : public wxDialog MyFrame *m_pFrame; wxBookCtrlBase *m_pNotebook; MyFrameConfigDialogPane *m_pGlobalPane; - Guider::GuiderConfigDialogPane* m_pGuiderPane; + Guider::GuiderConfigDialogPane *m_pGuiderPane; CameraConfigDialogPane *m_pCameraPane; Mount::MountConfigDialogPane *m_pMountPane; AOConfigDialogPane *m_pAOPane; @@ -82,7 +83,6 @@ class AdvancedDialog : public wxDialog bool m_imageScaleChanged; public: - static const double MIN_FOCAL_LENGTH; static const double MAX_FOCAL_LENGTH; @@ -103,7 +103,10 @@ class AdvancedDialog : public wxDialog bool Validate() override; void ShowInvalid(wxWindow *ctrl, const wxString& message); - void FlagImageScaleChange() { m_imageScaleChanged = true; } // Allows image scale adjustment to be made only once when AD is closed + void FlagImageScaleChange() + { + m_imageScaleChanged = true; + } // Allows image scale adjustment to be made only once when AD is closed int GetFocalLength(); void SetFocalLength(int val); double GetPixelSize(); @@ -111,7 +114,7 @@ class AdvancedDialog : public wxDialog int GetBinning(); void SetBinning(int binning); void MakeImageScaleAdjustments(); - Mount::MountConfigDialogPane* GetCurrentMountPane() { return m_pMountPane; } + Mount::MountConfigDialogPane *GetCurrentMountPane() { return m_pMountPane; } wxWindow *GetTabLocation(BRAIN_CTRL_IDS id); diff --git a/src/aui_controls.cpp b/src/aui_controls.cpp index eca856554..f14bb0472 100644 --- a/src/aui_controls.cpp +++ b/src/aui_controls.cpp @@ -1,37 +1,37 @@ /* -* aui_controls.cpp -* PHD Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2016 Bruce Waddington and Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * aui_controls.cpp + * PHD Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2016 Bruce Waddington and Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #include "aui_controls.h" @@ -39,15 +39,15 @@ #include #include -//#define ICON_DEV +// #define ICON_DEV #ifndef ICON_DEV -#include "icons/sb_led_green.png.h" -#include "icons/sb_led_yellow.png.h" -#include "icons/sb_led_red.png.h" -#include "icons/sb_arrow_left_16.png.h" -#include "icons/sb_arrow_right_16.png.h" -#include "icons/sb_arrow_up_16.png.h" -#include "icons/sb_arrow_down_16.png.h" +# include "icons/sb_led_green.png.h" +# include "icons/sb_led_yellow.png.h" +# include "icons/sb_led_red.png.h" +# include "icons/sb_arrow_left_16.png.h" +# include "icons/sb_arrow_right_16.png.h" +# include "icons/sb_arrow_up_16.png.h" +# include "icons/sb_arrow_down_16.png.h" #endif // clang-format off @@ -77,11 +77,15 @@ class SBPanel : public wxPanel { std::vector m_fieldOffsets; wxString m_overlayText; - std::unordered_set m_hidden; // controls that are hidden by the overlay text + std::unordered_set m_hidden; // controls that are hidden by the overlay text - enum { OVERLAY_HPADDING = 10 }; + enum + { + OVERLAY_HPADDING = 10 + }; - int OverlayWidth() const { + int OverlayWidth() const + { wxSize sz = GetTextExtent(m_overlayText); return OVERLAY_HPADDING + sz.GetWidth() + OVERLAY_HPADDING; } @@ -121,7 +125,7 @@ class SBStateIndicatorItem; class SBStateIndicators { - std::vector m_stateItems; + std::vector m_stateItems; SBPanel *m_parentPanel; public: @@ -149,8 +153,8 @@ class SBStateIndicatorItem wxString otherInfo; public: - SBStateIndicatorItem(SBPanel *panel, SBStateIndicators *container, - int indField, const wxString& indLabel, SBFieldTypes indType, std::vector& fldWidths); + SBStateIndicatorItem(SBPanel *panel, SBStateIndicators *container, int indField, const wxString& indLabel, + SBFieldTypes indType, std::vector& fldWidths); void PositionControl(); void UpdateState(); wxString GearToolTip(int quadState); @@ -188,25 +192,24 @@ class SBStarIndicators SBStarIndicators(SBPanel *panel, std::vector& fldWidths); void PositionControls(); void UpdateState(double MassPct, double SNR, bool Saturated); - }; // How this works: // PHDStatusBar is a child of wxStatusBar and is composed of various control groups - properties of the guide star, info about -// current guide commands, and state information about the current app session. Each group is managed by its own class, and that class -// is responsible for building, positioning, and updating its controls. The various controls are positioned (via the OnSize event) on top of the SBPanel that -// is the single underlying field in the base-class statusbar. The SBPanel class handles its own Paint event in order to render -// the borders and field separators the way we want. +// current guide commands, and state information about the current app session. Each group is managed by its own class, and +// that class is responsible for building, positioning, and updating its controls. The various controls are positioned (via the +// OnSize event) on top of the SBPanel that is the single underlying field in the base-class statusbar. The SBPanel class +// handles its own Paint event in order to render the borders and field separators the way we want. // ---------------------------------------------------------------------------- // SBPanel - parent control is the parent for all the status bar items // SBPanel::SBPanel(wxStatusBar *parent, const wxSize& panelSize) - : wxPanel(parent, wxID_ANY, wxDefaultPosition, panelSize) + : wxPanel(parent, wxID_ANY, wxDefaultPosition, panelSize) { m_fieldOffsets.reserve(12); int txtHeight; - parent->GetTextExtent("M", &emWidth, &txtHeight); // Horizontal spacer used by various controls + parent->GetTextExtent("M", &emWidth, &txtHeight); // Horizontal spacer used by various controls SetBackgroundStyle(wxBG_STYLE_PAINT); #ifdef __APPLE__ @@ -397,14 +400,15 @@ SBStarIndicators::SBStarIndicators(SBPanel *panel, std::vector& fldWidths) txtSNRLabel->Show(false); txtSNRValue->SetBackgroundColour(*wxBLACK); txtSNRValue->SetForegroundColour(*wxGREEN); - txtSNRValue->SetToolTip(_("Signal-to-noise ratio of guide star\nGreen means SNR >= 10\nYellow means 4 <= SNR < 10\nRed means SNR < 4")); + txtSNRValue->SetToolTip( + _("Signal-to-noise ratio of guide star\nGreen means SNR >= 10\nYellow means 4 <= SNR < 10\nRed means SNR < 4")); m_parentPanel = panel; } void SBStarIndicators::PositionControls() { - int fieldNum = (int)Field_Sat; + int fieldNum = (int) Field_Sat; wxPoint snrPos; wxPoint satPos; @@ -473,7 +477,7 @@ SBGuideIndicators::SBGuideIndicators(SBPanel *panel, std::vector& fldWidths arrowUp = wxBitmap(wxBITMAP_PNG_FROM_DATA(sb_arrow_up_16)); arrowDown = wxBitmap(wxBITMAP_PNG_FROM_DATA(sb_arrow_down_16)); #endif - wxColor fgColor(200, 200, 200); // reduced brightness + wxColor fgColor(200, 200, 200); // reduced brightness int guideAmtWidth; int txtHeight; panel->GetTextExtent("5555 ms, 555 px", &guideAmtWidth, &txtHeight); @@ -482,24 +486,26 @@ SBGuideIndicators::SBGuideIndicators(SBPanel *panel, std::vector& fldWidths bitmapRA = new wxStaticBitmap(panel, wxID_ANY, arrowLeft); wxSize bitmapSize = bitmapRA->GetSize(); bitmapRA->Show(false); - txtRaAmounts = new wxStaticText(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(guideAmtWidth, bitmapSize.y), wxALIGN_CENTER); + txtRaAmounts = new wxStaticText( + panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(guideAmtWidth, bitmapSize.y), wxALIGN_CENTER); txtRaAmounts->SetBackgroundColour(*wxBLACK); txtRaAmounts->SetForegroundColour(fgColor); - txtDecAmounts = new wxStaticText(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(guideAmtWidth, bitmapSize.y), wxALIGN_RIGHT); + txtDecAmounts = + new wxStaticText(panel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(guideAmtWidth, bitmapSize.y), wxALIGN_RIGHT); txtDecAmounts->SetBackgroundColour(*wxBLACK); txtDecAmounts->SetForegroundColour(fgColor); bitmapDec = new wxStaticBitmap(panel, wxID_ANY, arrowUp); bitmapDec->Show(false); m_parentPanel = panel; - // Since we don't want separators between the arrows and the text info, we lump the two together and treat them as one field for the purpose - // of positioning - fldWidths.push_back(bitmapSize.x + guideAmtWidth + 2 * panel->emWidth); // RA info - fldWidths.push_back(bitmapSize.x + guideAmtWidth + 2 * panel->emWidth); // Dec info + // Since we don't want separators between the arrows and the text info, we lump the two together and treat them as one field + // for the purpose of positioning + fldWidths.push_back(bitmapSize.x + guideAmtWidth + 2 * panel->emWidth); // RA info + fldWidths.push_back(bitmapSize.x + guideAmtWidth + 2 * panel->emWidth); // Dec info } void SBGuideIndicators::PositionControls() { - int fieldNum = (int)Field_RAInfo; + int fieldNum = (int) Field_RAInfo; int txtWidth; int txtHeight; wxPoint loc; @@ -511,7 +517,7 @@ void SBGuideIndicators::PositionControls() txtRaAmounts->SetPosition(raPosition); fieldNum++; - wxString txtSizer = wxString::Format(_("%d ms, %0.1f px"), 120, 4.38); + wxString txtSizer = wxString::Format(_("%d ms, %0.1f px"), 120, 4.38); m_parentPanel->GetTextExtent(txtSizer, &txtWidth, &txtHeight); wxPoint decPosition = m_parentPanel->FieldLoc(fieldNum); txtDecAmounts->SetPosition(decPosition); @@ -562,7 +568,8 @@ void SBGuideIndicators::UpdateState(int raDirection, int decDirection, double ra //------------------------------------------------------------------------------------------ // ---SBStateIndicatorItem - individual state indicators // -SBStateIndicatorItem::SBStateIndicatorItem(SBPanel *panel, SBStateIndicators *host, int indField, const wxString& indLabel, SBFieldTypes indType, std::vector& fldWidths) +SBStateIndicatorItem::SBStateIndicatorItem(SBPanel *panel, SBStateIndicators *host, int indField, const wxString& indLabel, + SBFieldTypes indType, std::vector& fldWidths) { m_type = indType; lastState = -2; @@ -575,7 +582,8 @@ SBStateIndicatorItem::SBStateIndicatorItem(SBPanel *panel, SBStateIndicators *ho // Use default positions for control creation - positioning is handled explicitly in PositionControls() if (indType != Field_Gear) { - ctrl = new wxStaticText(m_parentPanel, wxID_ANY, indLabel, wxDefaultPosition, wxSize(txtWidth + m_parentPanel->emWidth, -1), wxALIGN_CENTER); + ctrl = new wxStaticText(m_parentPanel, wxID_ANY, indLabel, wxDefaultPosition, + wxSize(txtWidth + m_parentPanel->emWidth, -1), wxALIGN_CENTER); fldWidths.push_back(txtWidth + 2 * m_parentPanel->emWidth); } else @@ -601,8 +609,8 @@ static int CalibrationQuadState(wxString *tip) { // For calib quad state: -1 => no cal, 0 => cal but no pointing compensation, 1 => golden - bool calibrated = (pMount || pSecondaryMount) && - (!pMount || pMount->IsCalibrated()) && (!pSecondaryMount || pSecondaryMount->IsCalibrated()); + bool calibrated = (pMount || pSecondaryMount) && (!pMount || pMount->IsCalibrated()) && + (!pSecondaryMount || pSecondaryMount->IsCalibrated()); if (!calibrated) { @@ -649,11 +657,12 @@ static wxString Join(const wxString& delim, const std::vector& vec) wxString buf; buf.reserve(l + delim.length() * (vec.size() - 1)); std::for_each(vec.begin(), vec.end(), - [&buf, &delim](const wxString& s) { - if (!buf.empty()) - buf += delim; - buf += s; - }); + [&buf, &delim](const wxString& s) + { + if (!buf.empty()) + buf += delim; + buf += s; + }); return buf; } @@ -664,7 +673,8 @@ void SBStateIndicatorItem::UpdateState() switch (m_type) { - case Field_Gear: { + case Field_Gear: + { std::vector MIAs; bool cameraOk = true; bool problems = false; @@ -732,7 +742,7 @@ void SBStateIndicatorItem::UpdateState() if (cameraOk) pic->SetIcon(container->icoYellowLed); else - pic->SetIcon(container->icoRedLed); // What good are we without a camera + pic->SetIcon(container->icoRedLed); // What good are we without a camera quadState = 0; otherInfo = Join(_(", "), MIAs); pic->SetToolTip(GearToolTip(quadState)); @@ -765,11 +775,12 @@ void SBStateIndicatorItem::UpdateState() break; - case Field_Calib: { + case Field_Calib: + { quadState = CalibrationQuadState(&cal_tooltip); lastState = -2; // force tool-tip update even if state did not change break; - } + } default: break; @@ -853,9 +864,10 @@ SBStateIndicators::SBStateIndicators(SBPanel *panel, std::vector& fldWidths led = wxBitmap(wxBITMAP_PNG_FROM_DATA(sb_led_red)); icoRedLed.CopyFromBitmap(led); #endif - for (int inx = (int)Field_Darks; inx <= (int)Field_Gear; inx++) + for (int inx = (int) Field_Darks; inx <= (int) Field_Gear; inx++) { - SBStateIndicatorItem *item = new SBStateIndicatorItem(m_parentPanel, this, inx, labels[inx - Field_Darks], (SBFieldTypes)(inx), fldWidths); + SBStateIndicatorItem *item = + new SBStateIndicatorItem(m_parentPanel, this, inx, labels[inx - Field_Darks], (SBFieldTypes) (inx), fldWidths); m_stateItems.push_back(item); item->UpdateState(); } @@ -883,7 +895,8 @@ void SBStateIndicators::UpdateState() } } -enum { +enum +{ SB_HEIGHT = 16 }; @@ -895,7 +908,7 @@ PHDStatusBar::PHDStatusBar(wxWindow *parent, long style) std::vector fieldWidths; // Set up the only field the wxStatusBar base class will know about - int widths[] = {-1}; + int widths[] = { -1 }; SetFieldsCount(1); SetStatusWidths(1, widths); @@ -907,10 +920,10 @@ PHDStatusBar::PHDStatusBar(wxWindow *parent, long style) // Build the leftmost text status field, the only field managed at this level m_Msg1 = new wxStaticText(m_ctrlPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(150, -1)); int txtWidth, txtHeight; - GetTextExtent(_("Selected star at (999.9, 999.9)"), &txtWidth, &txtHeight); // only care about the width + GetTextExtent(_("Selected star at (999.9, 999.9)"), &txtWidth, &txtHeight); // only care about the width m_Msg1->SetBackgroundColour(*wxBLACK); m_Msg1->SetForegroundColour(*wxWHITE); - fieldWidths.push_back(txtWidth); // Doesn't matter but we need to occupy the position in fieldWidths + fieldWidths.push_back(txtWidth); // Doesn't matter but we need to occupy the position in fieldWidths // Build the star status fields m_StarIndicators = new SBStarIndicators(m_ctrlPanel, fieldWidths); @@ -935,7 +948,7 @@ PHDStatusBar *PHDStatusBar::CreateInstance(wxWindow *parent, long style) // Destructor PHDStatusBar::~PHDStatusBar() { - this->DestroyChildren(); // any wxWidgets objects will be deleted + this->DestroyChildren(); // any wxWidgets objects will be deleted delete m_StateIndicators; delete m_GuideIndicators; delete m_StarIndicators; @@ -978,8 +991,8 @@ void PHDStatusBar::UpdateStarInfo(double SNR, bool Saturated) void PHDStatusBar::UpdateGuiderInfo(const GuideStepInfo& info) { - m_GuideIndicators->UpdateState(info.directionRA, info.directionDec, fabs(info.mountOffset.X), - info.durationRA, fabs(info.mountOffset.Y), info.durationDec); + m_GuideIndicators->UpdateState(info.directionRA, info.directionDec, fabs(info.mountOffset.X), info.durationRA, + fabs(info.mountOffset.Y), info.durationDec); } void PHDStatusBar::ClearGuiderInfo() diff --git a/src/aui_controls.h b/src/aui_controls.h index 6b0d2c709..43c1c46b2 100644 --- a/src/aui_controls.h +++ b/src/aui_controls.h @@ -1,37 +1,37 @@ /* -* aui_controls.h -* PHD Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2016-2017 Bruce Waddington and Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * aui_controls.h + * PHD Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2016-2017 Bruce Waddington and Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef _AUI_CONTROLS_H_ #define _AUI_CONTROLS_H_ @@ -85,4 +85,4 @@ class PHDToolBarArt : public wxAuiDefaultToolBarArt virtual wxAuiToolBarArt *Clone() { return new PHDToolBarArt(*this); } }; -#endif // AUI_CONTROLS_H +#endif // AUI_CONTROLS_H diff --git a/src/backlash_comp.cpp b/src/backlash_comp.cpp index bfb132a5b..94ca83b9c 100644 --- a/src/backlash_comp.cpp +++ b/src/backlash_comp.cpp @@ -1,45 +1,45 @@ /* -* backlash_comp.cpp -* PHD Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2015 Bruce Waddington and Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * backlash_comp.cpp + * PHD Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2015 Bruce Waddington and Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #include "backlash_comp.h" #include -static const unsigned int MIN_COMP_AMOUNT = 20; // min pulse in ms, must be small enough to effectively disable blc -static const unsigned int MAX_COMP_AMOUNT = 8000; // max pulse in ms +static const unsigned int MIN_COMP_AMOUNT = 20; // min pulse in ms, must be small enough to effectively disable blc +static const unsigned int MAX_COMP_AMOUNT = 8000; // max pulse in ms class CorrectionTuple { @@ -72,18 +72,15 @@ class BLCEvent stictionSeen = false; } - size_t InfoCount() const - { - return corrections.size(); - } + size_t InfoCount() const { return corrections.size(); } void AddEventInfo(long TimeSecs, double Amount, double minMove) { - // Correction[0] is the deflection that triggered the BLC in the first place. Correction[1] is the first delta after the pulse was issued, - // Correction[2] is the (optional) subsequent delta, needed to detect stiction + // Correction[0] is the deflection that triggered the BLC in the first place. Correction[1] is the first delta after + // the pulse was issued, Correction[2] is the (optional) subsequent delta, needed to detect stiction if (InfoCount() < 3) { - corrections.push_back(CorrectionTuple(TimeSecs, Amount)); // Regardless of size relative to min-move + corrections.push_back(CorrectionTuple(TimeSecs, Amount)); // Regardless of size relative to min-move if (fabs(Amount) > minMove) { if (InfoCount() == 2) @@ -92,19 +89,17 @@ class BLCEvent initialUndershoot = true; else initialOvershoot = true; - } else { if (InfoCount() == 3) { - stictionSeen = Amount < 0 && corrections[1].miss > 0; // 2nd follow-on miss was an over-shoot + stictionSeen = Amount < 0 && corrections[1].miss > 0; // 2nd follow-on miss was an over-shoot } } } } } - }; // Basic operation @@ -135,15 +130,17 @@ class BLCHistory double avgInitialMiss; double avgStictionAmount; - RecentStats() : shortCount(0), longCount(0), stictionCount(0), avgInitialMiss(0), avgStictionAmount(0) + RecentStats() + : shortCount(0) + , longCount(0) + , stictionCount(0) + , avgInitialMiss(0) + , avgStictionAmount(0) { } }; - bool WindowOpen() const - { - return windowOpen; - } + bool WindowOpen() const { return windowOpen; } BLCHistory() { @@ -152,10 +149,7 @@ class BLCHistory timeBase = wxGetCurrentTime(); } - static void LogStatus(const wxString& Msg) - { - Debug.Write(wxString::Format("BLC: %s\n", Msg)); - } + static void LogStatus(const wxString& Msg) { Debug.Write(wxString::Format("BLC: %s\n", Msg)); } void CloseWindow() { @@ -180,9 +174,9 @@ class BLCHistory bool added = false; if (blcIndex >= 0 && blcEvents[blcIndex].InfoCount() < ENTRY_CAPACITY) { - blcEvents[blcIndex].AddEventInfo(When-timeBase, Amt, MinMove); + blcEvents[blcIndex].AddEventInfo(When - timeBase, Amt, MinMove); added = true; - //LogStatus("Deflection entry added for event " + std::to_string(blcIndex)); + // LogStatus("Deflection entry added for event " + std::to_string(blcIndex)); } else { @@ -231,7 +225,7 @@ class BLCHistory } // Stats over some number of recent events, returns the average initial miss - double GetStats(int numEvents, RecentStats* Results) const + double GetStats(int numEvents, RecentStats *Results) const { int bottom = std::max(0, blcIndex - (numEvents - 1)); double sum = 0; @@ -267,7 +261,7 @@ class BLCHistory return Results->avgInitialMiss; } - bool AdjustmentNeeded(double miss, double minMove, double yRate, double* correction) + bool AdjustmentNeeded(double miss, double minMove, double yRate, double *correction) { bool adjust = false; const BLCEvent *currEvent; @@ -278,22 +272,23 @@ class BLCHistory { avgInitMiss = GetStats(HISTORY_DEPTH, &stats); currEvent = &blcEvents[blcIndex]; - wxString deflections = " Deflections: 0=" + std::to_string(currEvent->corrections[0].miss) + ", 1:" + - wxString(std::to_string(currEvent->corrections[1].miss)); + wxString deflections = " Deflections: 0=" + std::to_string(currEvent->corrections[0].miss) + + ", 1:" + wxString(std::to_string(currEvent->corrections[1].miss)); if (currEvent->InfoCount() > 2) deflections += ", 2:" + std::to_string(currEvent->corrections[2].miss); - LogStatus(wxString::Format("History state: CurrMiss=%0.2f, AvgInitMiss=%0.2f, ShCount=%d, LgCount=%d, SticCount=%d, %s", - miss, stats.avgInitialMiss, stats.shortCount, stats.longCount, stats.stictionCount, deflections)); + LogStatus( + wxString::Format("History state: CurrMiss=%0.2f, AvgInitMiss=%0.2f, ShCount=%d, LgCount=%d, SticCount=%d, %s", + miss, stats.avgInitialMiss, stats.shortCount, stats.longCount, stats.stictionCount, deflections)); } else return false; - if (fabs(miss) >= minMove) // Most recent miss was big enough to look at + if (fabs(miss) >= minMove) // Most recent miss was big enough to look at { int corr; - corr = (int)(floor(abs(avgInitMiss) / yRate) + 0.5); // unsigned correction value + corr = (int) (floor(abs(avgInitMiss) / yRate) + 0.5); // unsigned correction value if (miss > 0) - // UNDER-SHOOT------------------------------- + // UNDER-SHOOT------------------------------- { if (avgInitMiss > 0) { @@ -307,7 +302,7 @@ class BLCHistory else { // Check for over-shoot history - if (stats.longCount >= 2) // 2 or more over-shoots in window + if (stats.longCount >= 2) // 2 or more over-shoots in window LogStatus("Under-shoot; no adjustment because of over-shoot history"); else { @@ -328,15 +323,15 @@ class BLCHistory } } else - // OVER-SHOOT, miss < 0-------------------------------------- + // OVER-SHOOT, miss < 0-------------------------------------- { std::string msg = ""; if (currEvent->stictionSeen) { - if (stats.stictionCount > 1) // Seeing and low min-move can look like stiction, don't over-react + if (stats.stictionCount > 1) // Seeing and low min-move can look like stiction, don't over-react { msg = "Over-shoot, stiction seen, "; - double stictionCorr = (int)(floor(abs(stats.avgStictionAmount) / yRate) + 0.5); + double stictionCorr = (int) (floor(abs(stats.avgStictionAmount) / yRate) + 0.5); *correction = -stictionCorr; RemoveOldestStictions(1); adjust = true; @@ -394,8 +389,8 @@ BacklashComp::BacklashComp(Scope *scope) SetCompValues(lastAmt, lastFloor, lastCeiling); m_lastDirection = NONE; if (m_compActive) - Debug.Write(wxString::Format("BLC: Enabled with correction = %d ms, Floor = %d, Ceiling = %d, %s\n", - m_pulseWidth, m_adjustmentFloor, m_adjustmentCeiling, m_fixedSize ? "Fixed" : "Adjustable")); + Debug.Write(wxString::Format("BLC: Enabled with correction = %d ms, Floor = %d, Ceiling = %d, %s\n", m_pulseWidth, + m_adjustmentFloor, m_adjustmentCeiling, m_fixedSize ? "Fixed" : "Adjustable")); else Debug.Write("BLC: Backlash compensation is disabled\n"); } @@ -415,7 +410,7 @@ int BacklashComp::GetBacklashPulseMinValue() return MIN_COMP_AMOUNT; } -void BacklashComp::GetBacklashCompSettings(int* pulseWidth, int* floor, int* ceiling) const +void BacklashComp::GetBacklashCompSettings(int *pulseWidth, int *floor, int *ceiling) const { *pulseWidth = m_pulseWidth; *floor = m_adjustmentFloor; @@ -427,7 +422,7 @@ void BacklashComp::GetBacklashCompSettings(int* pulseWidth, int* floor, int* cei void BacklashComp::SetCompValues(int requestedSize, int floor, int ceiling) { m_pulseWidth = wxMax(0, wxMin(requestedSize, MAX_COMP_AMOUNT)); - if (floor > m_pulseWidth || floor < MIN_COMP_AMOUNT) // Coming from GA or user input makes no sense + if (floor > m_pulseWidth || floor < MIN_COMP_AMOUNT) // Coming from GA or user input makes no sense m_adjustmentFloor = MIN_COMP_AMOUNT; else m_adjustmentFloor = floor; @@ -448,8 +443,8 @@ void BacklashComp::SetBacklashPulseWidth(int ms, int floor, int ceiling) int oldBLC = m_pulseWidth; SetCompValues(ms, floor, ceiling); pFrame->NotifyGuidingParam("Backlash comp amount", m_pulseWidth); - Debug.Write(wxString::Format("BLC: Comp pulse set to %d ms, Floor = %d ms, Ceiling = %d ms, %s\n", - m_pulseWidth, m_adjustmentFloor, m_adjustmentCeiling, m_fixedSize ? "Fixed" : "Adjustable")); + Debug.Write(wxString::Format("BLC: Comp pulse set to %d ms, Floor = %d ms, Ceiling = %d ms, %s\n", m_pulseWidth, + m_adjustmentFloor, m_adjustmentCeiling, m_fixedSize ? "Fixed" : "Adjustable")); if (abs(m_pulseWidth - oldBLC) > 100) { m_pHistory->ClearHistory(); @@ -473,7 +468,8 @@ void BacklashComp::EnableBacklashComp(bool enable) m_compActive = enable; pConfig->Profile.SetBoolean("/" + m_pScope->GetMountClassName() + "/BacklashCompEnabled", m_compActive); - Debug.Write(wxString::Format("BLC: Backlash comp %s, Comp pulse = %d ms\n", m_compActive ? "enabled" : "disabled", m_pulseWidth)); + Debug.Write( + wxString::Format("BLC: Backlash comp %s, Comp pulse = %d ms\n", m_compActive ? "enabled" : "disabled", m_pulseWidth)); } void BacklashComp::ResetBLCState() @@ -514,15 +510,15 @@ void BacklashComp::TrackBLCResults(unsigned int moveOptions, double yRawOffset) // An earlier BLC was applied and we're tracking follow-up results - // Record the history even if residual error is zero. Sign convention has nothing to do with N or S direction - only whether we - // needed more correction (+) or less (-) + // Record the history even if residual error is zero. Sign convention has nothing to do with N or S direction - only whether + // we needed more correction (+) or less (-) GUIDE_DIRECTION dir = yRawOffset > 0.0 ? DOWN : UP; double yDistance = fabs(yRawOffset); double miss; if (dir == m_lastDirection) - miss = yDistance; // + => we needed more of the same, under-shoot + miss = yDistance; // + => we needed more of the same, under-shoot else - miss = -yDistance; // over-shoot + miss = -yDistance; // over-shoot double minMove = fmax(m_pScope->GetYGuideAlgorithm()->GetMinMove(), 0.); // Algo w/ no min-move returns -1 @@ -597,11 +593,14 @@ void BacklashComp::ApplyBacklashComp(unsigned int moveOptions, double yGuideDist class BacklashGraph : public wxDialog { public: - BacklashGraph(wxDialog *parent, const std::vector &northSteps, const std::vector &southSteps, int PulseSize); - wxBitmap CreateGraph(int graphicWidth, int graphicHeight, const std::vector &northSteps, const std::vector &southSteps, int PulseSize); + BacklashGraph( + wxDialog *parent, const std::vector& northSteps, const std::vector& southSteps, int PulseSize); + wxBitmap CreateGraph(int graphicWidth, int graphicHeight, const std::vector& northSteps, + const std::vector& southSteps, int PulseSize); }; -BacklashGraph::BacklashGraph(wxDialog *parent, const std::vector &northSteps, const std::vector &southSteps, int PulseSize) +BacklashGraph::BacklashGraph( + wxDialog *parent, const std::vector& northSteps, const std::vector& southSteps, int PulseSize) : wxDialog(parent, wxID_ANY, wxGetTranslation(_("Backlash Results")), wxDefaultPosition, wxSize(500, 400)) { // Just but a big button area for the graph with a button below it @@ -612,14 +611,13 @@ BacklashGraph::BacklashGraph(wxDialog *parent, const std::vector &northS vSizer->Add(graph, 0, wxALIGN_CENTER_HORIZONTAL | wxALL | wxFIXED_MINSIZE, 5); // ok button because we're modal - vSizer->Add( - CreateButtonSizer(wxOK), - wxSizerFlags(0).Expand().Border(wxALL, 10)); + vSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10)); SetSizerAndFit(vSizer); } -wxBitmap BacklashGraph::CreateGraph(int bmpWidth, int bmpHeight, const std::vector &northSteps, const std::vector &southSteps, int PulseSize) +wxBitmap BacklashGraph::CreateGraph( + int bmpWidth, int bmpHeight, const std::vector& northSteps, const std::vector& southSteps, int PulseSize) { wxMemoryDC dc; wxBitmap bmp(bmpWidth, bmpHeight, -1); @@ -665,7 +663,7 @@ wxBitmap BacklashGraph::CreateGraph(int bmpWidth, int bmpHeight, const std::vect // Since we get mount coordinates, north steps will always be in ascending order numNorth = northSteps.size(); northInc = (northSteps.at(numNorth - 1) - northSteps.at(0)) / numNorth; - numSouth = southSteps.size(); // May not be the same as numNorth if some sort of problem occurred + numSouth = southSteps.size(); // May not be the same as numNorth if some sort of problem occurred dc.SelectObject(bmp); dc.SetBackground(*wxBLACK_BRUSH); @@ -675,7 +673,7 @@ wxBitmap BacklashGraph::CreateGraph(int bmpWidth, int bmpHeight, const std::vect // Bottom and top labels xOrigin = graphWindowWidth / 2; - yOrigin = graphWindowHeight + 40; // Leave room at the top for labels and such + yOrigin = graphWindowHeight + 40; // Leave room at the top for labels and such dc.SetTextForeground(idealColor); dc.DrawText(_("Ideal"), 0.7 * graphWindowWidth, bmpHeight - 25); dc.SetTextForeground(decColor); @@ -692,8 +690,8 @@ wxBitmap BacklashGraph::CreateGraph(int bmpWidth, int bmpHeight, const std::vect } // Draw the axes dc.SetPen(axisPen); - dc.DrawLine(0, yOrigin, graphWindowWidth, yOrigin); // x - dc.DrawLine(xOrigin, yOrigin, xOrigin, 0); // y + dc.DrawLine(0, yOrigin, graphWindowWidth, yOrigin); // x + dc.DrawLine(xOrigin, yOrigin, xOrigin, 0); // y // Draw the north steps dc.SetPen(decPen); @@ -708,7 +706,8 @@ wxBitmap BacklashGraph::CreateGraph(int bmpWidth, int bmpHeight, const std::vect // Draw the south steps for (int i = 0; i < numSouth; i++) { - dc.DrawCircle(wxPoint((i + numNorth) * xScaleFactor, round(yOrigin - (southSteps.at(i) - minDec) * yScaleFactor)), ptRadius); + dc.DrawCircle( + wxPoint((i + numNorth) * xScaleFactor, round(yOrigin - (southSteps.at(i) - minDec) * yScaleFactor)), ptRadius); } // Now show an ideal south recovery line @@ -718,7 +717,8 @@ wxBitmap BacklashGraph::CreateGraph(int bmpWidth, int bmpHeight, const std::vect double peakSouth = southSteps.at(0); for (int i = 1; i <= numNorth; i++) { - wxPoint where = wxPoint((i + numNorth)* xScaleFactor, round(yOrigin - (peakSouth - i * northInc - minDec) * yScaleFactor)); + wxPoint where = + wxPoint((i + numNorth) * xScaleFactor, round(yOrigin - (peakSouth - i * northInc - minDec) * yScaleFactor)); dc.DrawCircle(where, ptRadius); } @@ -732,7 +732,7 @@ BacklashTool::BacklashTool() { m_scope = TheScope(); - m_lastDecGuideRate = GetLastDecGuideRate(); // -1 if we aren't calibrated + m_lastDecGuideRate = GetLastDecGuideRate(); // -1 if we aren't calibrated if (m_lastDecGuideRate > 0) m_bltState = BLT_STATE_INITIALIZE; else @@ -747,10 +747,7 @@ BacklashTool::BacklashTool() m_backlashExemption = false; } -BacklashTool::~BacklashTool() -{ - -} +BacklashTool::~BacklashTool() { } bool BacklashTool::IsGraphable() { @@ -792,15 +789,13 @@ void BacklashTool::StopMeasurement() static bool OutOfRoom(const wxSize& frameSize, double camX, double camY, int margin) { - return camX < margin || - camY < margin || - camX >= frameSize.GetWidth() - margin || - camY >= frameSize.GetHeight() - margin; + return camX < margin || camY < margin || camX >= frameSize.GetWidth() - margin || camY >= frameSize.GetHeight() - margin; } -// Measure the apparent backlash by looking at the first south moves, looking to see when the mount moves consistently at the expected rate -// Goal is to establish a good seed value for backlash compensation, not to accurately measure the hardware performance -BacklashTool::MeasurementResults BacklashTool::ComputeBacklashPx(double* bltPx, int* bltMs, double* northRate) +// Measure the apparent backlash by looking at the first south moves, looking to see when the mount moves consistently at the +// expected rate Goal is to establish a good seed value for backlash compensation, not to accurately measure the hardware +// performance +BacklashTool::MeasurementResults BacklashTool::ComputeBacklashPx(double *bltPx, int *bltMs, double *northRate) { double expectedAmount; double expectedMagnitude; @@ -817,16 +812,20 @@ BacklashTool::MeasurementResults BacklashTool::ComputeBacklashPx(double* bltPx, if (m_northBLSteps.size() > 3) { // figure out the drift-related corrections - double driftAmtPx = m_driftPerSec * (m_msmtEndTime - m_msmtStartTime) / 1000; // amount of drift in px for entire north measurement period + double driftAmtPx = m_driftPerSec * (m_msmtEndTime - m_msmtStartTime) / + 1000; // amount of drift in px for entire north measurement period int stepCount = m_northStats.GetCount(); northDelta = m_northStats.GetSum(); - nRate = fabs((northDelta - driftAmtPx) / (stepCount * m_pulseWidth)); // drift-corrected empirical measure of north rate + nRate = fabs((northDelta - driftAmtPx) / (stepCount * m_pulseWidth)); // drift-corrected empirical measure of north rate driftPxPerFrame = driftAmtPx / stepCount; - Debug.Write(wxString::Format("BLT: Drift correction of %0.2f px applied to total north moves of %0.2f px, %0.3f px/frame\n", driftAmtPx, northDelta, driftPxPerFrame)); + Debug.Write( + wxString::Format("BLT: Drift correction of %0.2f px applied to total north moves of %0.2f px, %0.3f px/frame\n", + driftAmtPx, northDelta, driftPxPerFrame)); Debug.Write(wxString::Format("BLT: Empirical north rate = %.2f px/s \n", nRate * 1000)); - // Compute an expected movement of 90% of the median delta north moves (px). Use the 90% tolerance to accept situations where the south rate - // never matches the north rate yet the mount is moving consistently. Allow smoothing for odd mounts that produce sequences of short-long-short-long... + // Compute an expected movement of 90% of the median delta north moves (px). Use the 90% tolerance to accept situations + // where the south rate never matches the north rate yet the mount is moving consistently. Allow smoothing for odd + // mounts that produce sequences of short-long-short-long... expectedAmount = 0.9 * m_northStats.GetMedian(); expectedMagnitude = fabs(expectedAmount); int goodSouthMoves = 0; @@ -834,25 +833,29 @@ BacklashTool::MeasurementResults BacklashTool::ComputeBacklashPx(double* bltPx, bool smoothing = false; for (int step = 1; step < m_southBLSteps.size(); step++) { - double southMove = m_southBLSteps[step] - m_southBLSteps[step-1]; + double southMove = m_southBLSteps[step] - m_southBLSteps[step - 1]; earlySouthMoves += southMove; - if (southMove < 0 && (fabs(southMove) >= expectedMagnitude || fabs(southMove + lastSouthMove / 2.0) > expectedMagnitude)) // Big enough move and in the correct (south) direction + if (southMove < 0 && + (fabs(southMove) >= expectedMagnitude || + fabs(southMove + lastSouthMove / 2.0) > + expectedMagnitude)) // Big enough move and in the correct (south) direction { if (fabs(southMove) < expectedMagnitude) smoothing = true; goodSouthMoves++; - // We want two consecutive south moves that meet or exceed the expected magnitude. This sidesteps situations where the mount shows a "false start" south + // We want two consecutive south moves that meet or exceed the expected magnitude. This sidesteps situations + // where the mount shows a "false start" south if (goodSouthMoves == 2) { if (smoothing) Debug.Write("BLT: Smoothing applied to south data points\n"); // bl = sum(expected moves) - sum(actual moves) - (drift correction for that period) - blPx = step * expectedMagnitude - fabs(earlySouthMoves - step * driftPxPerFrame); // drift-corrected backlash amount + blPx = step * expectedMagnitude - + fabs(earlySouthMoves - step * driftPxPerFrame); // drift-corrected backlash amount if (blPx * nRate < -200) - rslt = MEASUREMENT_SANITY; // large negative number - else - if (blPx >= 0.7 * northDelta) - rslt = MEASUREMENT_TOO_FEW_NORTH; // bl large compared to total north moves + rslt = MEASUREMENT_SANITY; // large negative number + else if (blPx >= 0.7 * northDelta) + rslt = MEASUREMENT_TOO_FEW_NORTH; // bl large compared to total north moves else rslt = MEASUREMENT_VALID; if (blPx < 0) @@ -877,7 +880,7 @@ BacklashTool::MeasurementResults BacklashTool::ComputeBacklashPx(double* bltPx, rslt = MEASUREMENT_TOO_FEW_NORTH; // Update the ref variables *bltPx = blPx; - *bltMs = (int)(blPx / nRate); + *bltMs = (int) (blPx / nRate); *northRate = nRate; return rslt; } @@ -896,9 +899,9 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) if (m_bltState != BLT_STATE_INITIALIZE) { decDelta = currMountLocation.Y - m_markerPoint.Y; - m_cumClearingDistance += decDelta; // use signed value - //if (m_bltState == BLT_STATE_CLEAR_NORTH) // DEBUG ONLY - // decDelta = fakeDeltas[wxMin(m_stepCount, 7)]; + m_cumClearingDistance += decDelta; // use signed value + // if (m_bltState == BLT_STATE_CLEAR_NORTH) // DEBUG ONLY + // decDelta = fakeDeltas[wxMin(m_stepCount, 7)]; } Debug.Write("BLT: Entering DecMeasurementStep, state = " + std::to_string(m_bltState) + "\n"); switch (m_bltState) @@ -909,19 +912,21 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) m_startingPoint = currMountLocation; // Compute pulse size for clearing backlash - just use the last known guide rate if (m_lastDecGuideRate <= 0) - m_lastDecGuideRate = GetLastDecGuideRate(); // try it again, maybe the user has since calibrated + m_lastDecGuideRate = GetLastDecGuideRate(); // try it again, maybe the user has since calibrated if (m_lastDecGuideRate > 0) { - m_pulseWidth = BACKLASH_EXPECTED_DISTANCE * 1.25 / m_lastDecGuideRate; // px/px_per_ms, bump it to sidestep near misses + m_pulseWidth = + BACKLASH_EXPECTED_DISTANCE * 1.25 / m_lastDecGuideRate; // px/px_per_ms, bump it to sidestep near misses m_acceptedMoves = 0; m_lastClearRslt = 0; m_cumClearingDistance = 0; m_backlashExemption = false; m_Rslt = MEASUREMENT_VALID; - // Get this state machine in synch with the guider state machine - let it drive us, starting with backlash clearing step + // Get this state machine in synch with the guider state machine - let it drive us, starting with backlash + // clearing step m_bltState = BLT_STATE_CLEAR_NORTH; m_scope->SetGuidingEnabled(true); - pFrame->pGuider->EnableMeasurementMode(true); // Measurement results now come to us + pFrame->pGuider->EnableMeasurementMode(true); // Measurement results now come to us } else { @@ -937,7 +942,8 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) { // Get things moving with the first clearing pulse Debug.Write(wxString::Format("BLT starting North backlash clearing using pulse width of %d," - " looking for moves >= %d px\n", m_pulseWidth, BACKLASH_EXPECTED_DISTANCE)); + " looking for moves >= %d px\n", + m_pulseWidth, BACKLASH_EXPECTED_DISTANCE)); pFrame->ScheduleAxisMove(m_scope, NORTH, m_pulseWidth, MOVEOPTS_CALIBRATION_MOVE); m_stepCount = 1; m_lastStatus = wxString::Format(_("Clearing North backlash, step %d"), m_stepCount); @@ -946,40 +952,45 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) } if (fabs(decDelta) >= BACKLASH_EXPECTED_DISTANCE) { - if (m_acceptedMoves == 0 || (m_lastClearRslt * decDelta) > 0) // Just starting or still moving in same direction + if (m_acceptedMoves == 0 || (m_lastClearRslt * decDelta) > 0) // Just starting or still moving in same direction { m_acceptedMoves++; Debug.Write(wxString::Format("BLT accepted clearing move of %0.2f\n", decDelta)); } else { - m_acceptedMoves = 0; // Reset on a direction reversal + m_acceptedMoves = 0; // Reset on a direction reversal Debug.Write(wxString::Format("BLT rejected clearing move of %0.2f, direction reversal\n", decDelta)); } } else Debug.Write(wxString::Format("BLT backlash clearing move of %0.2f px was not large enough\n", decDelta)); - if (m_acceptedMoves < BACKLASH_MIN_COUNT) // More work to do + if (m_acceptedMoves < BACKLASH_MIN_COUNT) // More work to do { if (m_stepCount < MAX_CLEARING_STEPS) { if (fabs(m_cumClearingDistance) > BACKLASH_EXEMPTION_DISTANCE) { - // We moved the mount a substantial distance north but the individual moves were too small - probably a bad calibration, - // so let the user proceed with backlash measurement before we push the star too far - Debug.Write(wxString::Format("BLT: Cum backlash of %0.2f px is at least half of expected, continue with backlash measurement\n", m_cumClearingDistance)); + // We moved the mount a substantial distance north but the individual moves were too small - probably a + // bad calibration, so let the user proceed with backlash measurement before we push the star too far + Debug.Write(wxString::Format( + "BLT: Cum backlash of %0.2f px is at least half of expected, continue with backlash measurement\n", + m_cumClearingDistance)); m_backlashExemption = true; } else { - if (!OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels())) + if (!OutOfRoom( + pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels())) { pFrame->ScheduleAxisMove(m_scope, NORTH, m_pulseWidth, MOVEOPTS_CALIBRATION_MOVE); m_stepCount++; m_markerPoint = currMountLocation; m_lastClearRslt = decDelta; - m_lastStatus = wxString::Format(_("Clearing North backlash, step %d (up to limit of %d)"), m_stepCount, MAX_CLEARING_STEPS); - m_lastStatusDebug = wxString::Format("Clearing North backlash, step %d (up to limit of %d)", m_stepCount, MAX_CLEARING_STEPS); + m_lastStatus = wxString::Format( + _("Clearing North backlash, step %d (up to limit of %d)"), m_stepCount, MAX_CLEARING_STEPS); + m_lastStatusDebug = wxString::Format( + "Clearing North backlash, step %d (up to limit of %d)", m_stepCount, MAX_CLEARING_STEPS); Debug.Write(wxString::Format("BLT: %s, LastDecDelta = %0.2f px\n", m_lastStatusDebug, decDelta)); break; } @@ -989,22 +1000,25 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) { m_lastStatus = _("Could not clear North backlash - test failed"); m_Rslt = MEASUREMENT_BL_NOT_CLEARED; - throw (wxString("BLT: Could not clear north backlash")); + throw(wxString("BLT: Could not clear north backlash")); } } - if (m_acceptedMoves >= BACKLASH_MIN_COUNT || m_backlashExemption || OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels())) // Ok to go ahead with actual backlash measurement + if (m_acceptedMoves >= BACKLASH_MIN_COUNT || m_backlashExemption || + OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, + pFrame->pGuider->GetMaxMovePixels())) // Ok to go ahead with actual backlash measurement { m_bltState = BLT_STATE_STEP_NORTH; double totalBacklashCleared = m_stepCount * m_pulseWidth; - // Want to move the mount North at >=500 ms, regardless of image scale. But reduce pulse width if it would exceed 80% of the tracking rectangle - - // need to leave some room for seeing deflections and dec drift - m_pulseWidth = wxMax((int)NORTH_PULSE_SIZE, m_scope->GetCalibrationDuration()); - m_pulseWidth = wxMin(m_pulseWidth, (int)floor(0.7 * (double)pFrame->pGuider->GetMaxMovePixels() / m_lastDecGuideRate)); + // Want to move the mount North at >=500 ms, regardless of image scale. But reduce pulse width if it would + // exceed 80% of the tracking rectangle - need to leave some room for seeing deflections and dec drift + m_pulseWidth = wxMax((int) NORTH_PULSE_SIZE, m_scope->GetCalibrationDuration()); + m_pulseWidth = + wxMin(m_pulseWidth, (int) floor(0.7 * (double) pFrame->pGuider->GetMaxMovePixels() / m_lastDecGuideRate)); m_stepCount = 0; - // Move 50% more than the backlash we cleared or >=8 secs, whichever is greater. We want to leave plenty of room - // for giving South moves time to clear backlash and actually get moving + // Move 50% more than the backlash we cleared or >=8 secs, whichever is greater. We want to leave plenty of + // room for giving South moves time to clear backlash and actually get moving m_northPulseCount = wxMax((MAX_NORTH_PULSES + m_pulseWidth - 1) / m_pulseWidth, - totalBacklashCleared * 1.5 / m_pulseWidth); // Up to 8 secs + totalBacklashCleared * 1.5 / m_pulseWidth); // Up to 8 secs Debug.Write(wxString::Format("BLT: Starting North moves at Dec=%0.2f\n", currMountLocation.Y)); m_msmtStartTime = ::wxGetUTCTimeMillis().GetValue(); @@ -1012,10 +1026,13 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) } case BLT_STATE_STEP_NORTH: - if (m_stepCount < m_northPulseCount && !OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels())) + if (m_stepCount < m_northPulseCount && + !OutOfRoom(pCamera->FullSize, currentCamLoc.X, currentCamLoc.Y, pFrame->pGuider->GetMaxMovePixels())) { - m_lastStatus = wxString::Format(_("Moving North for %d ms, step %d / %d"), m_pulseWidth, m_stepCount + 1, m_northPulseCount); - m_lastStatusDebug = wxString::Format("Moving North for %d ms, step %d / %d", m_pulseWidth, m_stepCount + 1, m_northPulseCount); + m_lastStatus = wxString::Format( + _("Moving North for %d ms, step %d / %d"), m_pulseWidth, m_stepCount + 1, m_northPulseCount); + m_lastStatusDebug = + wxString::Format("Moving North for %d ms, step %d / %d", m_pulseWidth, m_stepCount + 1, m_northPulseCount); double deltaN; if (m_stepCount >= 1) { @@ -1025,9 +1042,10 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) else { deltaN = 0; - m_markerPoint = currMountLocation; // Marker point at start of Dec moves North + m_markerPoint = currMountLocation; // Marker point at start of Dec moves North } - Debug.Write(wxString::Format("BLT: %s, DecLoc = %0.2f, DeltaDec = %0.2f\n", m_lastStatusDebug, currMountLocation.Y, deltaN)); + Debug.Write(wxString::Format( + "BLT: %s, DecLoc = %0.2f, DeltaDec = %0.2f\n", m_lastStatusDebug, currMountLocation.Y, deltaN)); m_northBLSteps.push_back(currMountLocation.Y); pFrame->ScheduleAxisMove(m_scope, NORTH, m_pulseWidth, MOVEOPTS_CALIBRATION_MOVE); m_stepCount++; @@ -1043,15 +1061,18 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) deltaN = currMountLocation.Y - m_northBLSteps.back(); m_northStats.AddGuideInfo(m_stepCount, deltaN, 0); } - Debug.Write(wxString::Format("BLT: North pulses ended at Dec location %0.2f, TotalDecDelta=%0.2f px, LastDeltaDec = %0.2f\n", currMountLocation.Y, decDelta, deltaN)); + Debug.Write(wxString::Format( + "BLT: North pulses ended at Dec location %0.2f, TotalDecDelta=%0.2f px, LastDeltaDec = %0.2f\n", + currMountLocation.Y, decDelta, deltaN)); m_northBLSteps.push_back(currMountLocation.Y); if (m_stepCount < m_northPulseCount) { if (m_stepCount < 0.5 * m_northPulseCount) { - m_lastStatus = _("Star too close to edge for accurate measurement of backlash. Choose a star farther from the edge."); + m_lastStatus = _("Star too close to edge for accurate measurement of backlash. Choose a star farther " + "from the edge."); m_Rslt = MEASUREMENT_TOO_FEW_NORTH; - throw (wxString("BLT: Too few north moves")); + throw(wxString("BLT: Too few north moves")); } Debug.Write("BLT: North pulses truncated, too close to frame edge\n"); } @@ -1064,8 +1085,10 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) case BLT_STATE_STEP_SOUTH: if (m_stepCount < m_northPulseCount) { - m_lastStatus = wxString::Format(_("Moving South for %d ms, step %d / %d"), m_pulseWidth, m_stepCount + 1, m_northPulseCount); - m_lastStatusDebug = wxString::Format("Moving South for %d ms, step %d / %d", m_pulseWidth, m_stepCount + 1, m_northPulseCount); + m_lastStatus = wxString::Format( + _("Moving South for %d ms, step %d / %d"), m_pulseWidth, m_stepCount + 1, m_northPulseCount); + m_lastStatusDebug = + wxString::Format("Moving South for %d ms, step %d / %d", m_pulseWidth, m_stepCount + 1, m_northPulseCount); Debug.Write(wxString::Format("BLT: %s, DecLoc = %0.2f\n", m_lastStatusDebug, currMountLocation.Y)); m_southBLSteps.push_back(currMountLocation.Y); pFrame->ScheduleAxisMove(m_scope, SOUTH, m_pulseWidth, MOVEOPTS_CALIBRATION_MOVE); @@ -1092,25 +1115,26 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) { case MEASUREMENT_SANITY: m_lastStatus = _("Dec movements too erratic - test failed"); - throw (wxString("BLT: Calculation failed sanity check")); + throw(wxString("BLT: Calculation failed sanity check")); break; case MEASUREMENT_TOO_FEW_NORTH: - // Don't throw an exception - the test was completed but the bl result is not accurate - handle it in the GA UI + // Don't throw an exception - the test was completed but the bl result is not accurate - handle it in + // the GA UI break; case MEASUREMENT_TOO_FEW_SOUTH: m_lastStatus = _("Mount never established consistent south moves - test failed"); - throw (wxString("BLT: Too few acceptable south moves")); + throw(wxString("BLT: Too few acceptable south moves")); break; default: - break; + break; } } double sigmaPx; double sigmaMs; GetBacklashSigma(&sigmaPx, &sigmaMs); - Debug.Write(wxString::Format("BLT: Trial backlash amount is %0.2f px, %d ms, sigma = %0.1f px\n", m_backlashResultPx, m_backlashResultMs, - sigmaPx)); + Debug.Write(wxString::Format("BLT: Trial backlash amount is %0.2f px, %d ms, sigma = %0.1f px\n", + m_backlashResultPx, m_backlashResultMs, sigmaPx)); if (m_backlashResultMs > 0) { // Don't push the guide star outside the tracking region @@ -1118,16 +1142,19 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) { m_lastStatus = wxString::Format(_("Issuing test backlash correction of %d ms"), m_backlashResultMs); Debug.Write(m_lastStatus + "\n"); - // This should put us back roughly to where we issued the big North pulse unless the backlash is very large + // This should put us back roughly to where we issued the big North pulse unless the backlash is very + // large pFrame->ScheduleAxisMove(m_scope, SOUTH, m_backlashResultMs, MOVEOPTS_CALIBRATION_MOVE); m_stepCount++; break; } else { - int maxFrameMove = (int)floor((double)0.8 * pFrame->pGuider->GetMaxMovePixels() / m_northRate); - Debug.Write(wxString::Format("BLT: Clearing pulse is very large, issuing max S move of %d\n", maxFrameMove)); - pFrame->ScheduleAxisMove(m_scope, SOUTH, maxFrameMove, MOVEOPTS_CALIBRATION_MOVE); // One more pulse to cycle the state machine + int maxFrameMove = (int) floor((double) 0.8 * pFrame->pGuider->GetMaxMovePixels() / m_northRate); + Debug.Write( + wxString::Format("BLT: Clearing pulse is very large, issuing max S move of %d\n", maxFrameMove)); + pFrame->ScheduleAxisMove(m_scope, SOUTH, maxFrameMove, + MOVEOPTS_CALIBRATION_MOVE); // One more pulse to cycle the state machine m_stepCount = 0; // Can't fine-tune the pulse size, just try to restore the star to < MaxMove of error m_bltState = BLT_STATE_RESTORE; @@ -1140,29 +1167,33 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) m_stepCount = 0; // fall through, no need for test pulse } - } // See how close we came, maybe fine-tune a bit if (m_bltState == BLT_STATE_TEST_CORRECTION) { - Debug.Write(wxString::Format("BLT: Trial backlash pulse resulted in net DecDelta = %0.2f px, Dec Location %0.2f\n", decDelta, currMountLocation.Y)); - tol = TRIAL_TOLERANCE_AS / pFrame->GetCameraPixelScale(); // tolerance in units of px - if (fabs(decDelta) > tol) // decDelta = (current - markerPoint) + Debug.Write( + wxString::Format("BLT: Trial backlash pulse resulted in net DecDelta = %0.2f px, Dec Location %0.2f\n", + decDelta, currMountLocation.Y)); + tol = TRIAL_TOLERANCE_AS / pFrame->GetCameraPixelScale(); // tolerance in units of px + if (fabs(decDelta) > tol) // decDelta = (current - markerPoint) { - double pulse_delta = fabs(currMountLocation.Y - m_endSouth.Y); // How far we moved with the test pulse - double target_delta = fabs(m_markerPoint.Y - m_endSouth.Y); // How far we needed to go - if ((m_endSouth.Y - m_markerPoint.Y) * decDelta < 0) // Sign change, went too far + double pulse_delta = fabs(currMountLocation.Y - m_endSouth.Y); // How far we moved with the test pulse + double target_delta = fabs(m_markerPoint.Y - m_endSouth.Y); // How far we needed to go + if ((m_endSouth.Y - m_markerPoint.Y) * decDelta < 0) // Sign change, went too far { - //m_backlashResultMs *= target_delta / pulse_delta; - Debug.Write(wxString::Format("BLT: Nominal backlash value over-shot by %0.2f X\n", target_delta / pulse_delta)); + // m_backlashResultMs *= target_delta / pulse_delta; + Debug.Write( + wxString::Format("BLT: Nominal backlash value over-shot by %0.2f X\n", target_delta / pulse_delta)); } else { - Debug.Write(wxString::Format("BLT: Nominal backlash value under-shot by %0.2f X\n", target_delta / pulse_delta)); + Debug.Write(wxString::Format( + "BLT: Nominal backlash value under-shot by %0.2f X\n", target_delta / pulse_delta)); } } else - Debug.Write(wxString::Format("BLT: Nominal backlash pulse resulted in final delta of %0.1f a-s\n", fabs(decDelta) * pFrame->GetCameraPixelScale())); + Debug.Write(wxString::Format("BLT: Nominal backlash pulse resulted in final delta of %0.1f a-s\n", + fabs(decDelta) * pFrame->GetCameraPixelScale())); } m_bltState = BLT_STATE_RESTORE; @@ -1171,16 +1202,19 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) // fall through case BLT_STATE_RESTORE: - // We could be a considerable distance from where we started, so get back close to the starting point without losing the star + // We could be a considerable distance from where we started, so get back close to the starting point without losing + // the star if (m_stepCount == 0) { - Debug.Write(wxString::Format("BLT: Starting Dec position at %0.2f, Ending Dec position at %0.2f\n", m_markerPoint.Y, currMountLocation.Y)); + Debug.Write(wxString::Format("BLT: Starting Dec position at %0.2f, Ending Dec position at %0.2f\n", + m_markerPoint.Y, currMountLocation.Y)); amt = fabs(currMountLocation.Y - m_startingPoint.Y); - if (amt > pFrame->pGuider->GetMaxMovePixels()) // Too big, try to move guide star closer to starting position + if (amt > pFrame->pGuider->GetMaxMovePixels()) // Too big, try to move guide star closer to starting position { - m_restoreCount = (int)floor((amt / m_northRate) / m_pulseWidth); - m_restoreCount = wxMin(m_restoreCount, 10); // Don't spend forever at it, something probably went wrong - Debug.Write(wxString::Format("BLT: Final restore distance is %0.1f px, approx %d steps\n", amt, m_restoreCount)); + m_restoreCount = (int) floor((amt / m_northRate) / m_pulseWidth); + m_restoreCount = wxMin(m_restoreCount, 10); // Don't spend forever at it, something probably went wrong + Debug.Write( + wxString::Format("BLT: Final restore distance is %0.1f px, approx %d steps\n", amt, m_restoreCount)); m_stepCount = 0; } else @@ -1203,9 +1237,9 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) m_lastStatus = _("Measurement complete"); CleanUp(); m_bltState = BLT_STATE_COMPLETED; - break; // This will cycle the guider state machine and get normal guiding going + break; // This will cycle the guider state machine and get normal guiding going - case BLT_STATE_COMPLETED: // Shouldn't happen + case BLT_STATE_COMPLETED: // Shouldn't happen break; case BLT_STATE_ABORTED: @@ -1213,12 +1247,12 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) Debug.Write("BLT: measurement process halted by user or by error\n"); CleanUp(); break; - } // end of switch on state + } // end of switch on state } catch (const wxString& msg) { POSSIBLY_UNUSED(msg); - Debug.Write(wxString::Format("BLT: Exception thrown in logical state %d\n", (int)m_bltState)); + Debug.Write(wxString::Format("BLT: Exception thrown in logical state %d\n", (int) m_bltState)); m_bltState = BLT_STATE_ABORTED; Debug.Write("BLT: " + m_lastStatus + "\n"); CleanUp(); @@ -1227,7 +1261,7 @@ void BacklashTool::DecMeasurementStep(const PHD_Point& currentCamLoc) Debug.Write("BLT: Exiting DecMeasurementStep\n"); } -void BacklashTool::GetBacklashSigma(double* SigmaPx, double* SigmaMs) +void BacklashTool::GetBacklashSigma(double *SigmaPx, double *SigmaMs) { if ((m_Rslt == MEASUREMENT_VALID || m_Rslt == BacklashTool::MEASUREMENT_TOO_FEW_NORTH) && m_northStats.GetCount() > 1) { @@ -1245,7 +1279,8 @@ void BacklashTool::GetBacklashSigma(double* SigmaPx, double* SigmaMs) } // Launch modal dlg to show backlash test -void BacklashTool::ShowGraph(wxDialog *pGA, const std::vector &northSteps, const std::vector &southSteps, int PulseSize) +void BacklashTool::ShowGraph( + wxDialog *pGA, const std::vector& northSteps, const std::vector& southSteps, int PulseSize) { BacklashGraph dlg(pGA, northSteps, southSteps, PulseSize); dlg.ShowModal(); @@ -1253,7 +1288,7 @@ void BacklashTool::ShowGraph(wxDialog *pGA, const std::vector &northStep void BacklashTool::CleanUp() { - m_scope->GetBacklashComp()->ResetBLCState(); // Normal guiding will start, don't want old BC state applied + m_scope->GetBacklashComp()->ResetBLCState(); // Normal guiding will start, don't want old BC state applied pFrame->pGuider->EnableMeasurementMode(false); Debug.Write("BLT: Cleanup completed\n"); } diff --git a/src/backlash_comp.h b/src/backlash_comp.h index 2c79d68b1..3bf7747e2 100644 --- a/src/backlash_comp.h +++ b/src/backlash_comp.h @@ -44,7 +44,7 @@ class BLCHistory; struct RunningStats { int count; - double currentSS; // Sum of squares + double currentSS; // Sum of squares double currentMean; RunningStats(); @@ -62,7 +62,7 @@ class BacklashTool int m_acceptedMoves; double m_lastClearRslt; double m_lastDecGuideRate; - double m_backlashResultPx; // units of pixels + double m_backlashResultPx; // units of pixels double m_cumClearingDistance; bool m_backlashExemption; int m_backlashResultMs; @@ -71,8 +71,8 @@ class BacklashTool PHD_Point m_startingPoint; PHD_Point m_markerPoint; PHD_Point m_endSouth; - wxString m_lastStatus; // Translated for UI - wxString m_lastStatusDebug; // Always English for debug log + wxString m_lastStatus; // Translated for UI + wxString m_lastStatusDebug; // Always English for debug log Scope *m_scope; std::vector m_northBLSteps; std::vector m_southBLSteps; @@ -96,7 +96,7 @@ class BacklashTool BLT_STATE_COMPLETED } m_bltState; - enum MeasurementConstants // To control the behavior of the measurement process + enum MeasurementConstants // To control the behavior of the measurement process { BACKLASH_MIN_COUNT = 3, BACKLASH_EXPECTED_DISTANCE = 4, @@ -104,7 +104,7 @@ class BacklashTool MAX_CLEARING_STEPS = 100, NORTH_PULSE_SIZE = 500, MAX_NORTH_PULSES = 8000, - TRIAL_TOLERANCE_AS = 2 // arc-secs + TRIAL_TOLERANCE_AS = 2 // arc-secs }; enum MeasurementResults @@ -117,10 +117,9 @@ class BacklashTool } m_Rslt; private: - MeasurementResults ComputeBacklashPx(double* bltPx, int* bltMs, double* northRate); + MeasurementResults ComputeBacklashPx(double *bltPx, int *bltMs, double *northRate); public: - BacklashTool(); ~BacklashTool(); void StartMeasurement(double DriftPerMin); @@ -132,11 +131,11 @@ class BacklashTool int GetBLTMsmtPulseSize() const { return m_pulseWidth; } double GetBacklashResultPx() const { return m_backlashResultPx; } int GetBacklashResultMs() const { return m_backlashResultMs; } - void GetBacklashSigma(double* SigmaPx, double* SigmaMs); + void GetBacklashSigma(double *SigmaPx, double *SigmaMs); bool GetBacklashExempted() const { return m_backlashExemption; } wxString GetLastStatus() const { return m_lastStatus; } void SetBacklashPulse(int amt); - void ShowGraph(wxDialog *pGA, const std::vector &northSteps, const std::vector &southSteps, int PulseSize); + void ShowGraph(wxDialog *pGA, const std::vector& northSteps, const std::vector& southSteps, int PulseSize); bool IsGraphable(); const std::vector& GetNorthSteps() const { return m_northBLSteps; } const std::vector& GetSouthSteps() const { return m_southBLSteps; } @@ -157,7 +156,6 @@ class BacklashComp void SetCompValues(int requestSize, int floor, int ceiling); public: - BacklashComp(Scope *scope); ~BacklashComp(); diff --git a/src/calibration_assistant.cpp b/src/calibration_assistant.cpp index c77d4ff80..4f01d99ff 100644 --- a/src/calibration_assistant.cpp +++ b/src/calibration_assistant.cpp @@ -1,46 +1,52 @@ /* -* calibration_assistant.cpp -* PHD Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2023 Bruce Waddington -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * calibration_assistant.cpp + * PHD Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2023 Bruce Waddington + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #include "calibration_assistant.h" #include "calstep_dialog.h" #include -enum {defBestDec = 0, defBestOffset = 5, textWrapPoint = 500, slewSettleTime = 2000}; +enum +{ + defBestDec = 0, + defBestOffset = 5, + textWrapPoint = 500, + slewSettleTime = 2000 +}; double const siderealSecsPerSec = 0.9973; -#define RateX(spd) (spd * 3600.0 / (15.0 * siderealSecsPerSec)) +#define RateX(spd) (spd * 3600.0 / (15.0 * siderealSecsPerSec)) class CalibrationAssistant : public wxDialog { @@ -73,8 +79,8 @@ class CalibrationAssistant : public wxDialog // Methods void ShowExplanationMsg(double dec); void ExplainResults(void); - bool GetCalibPositionRecommendations(int* HA, int* Dec) const; - void GetCustomLocation(int* PrefHA, int* PrefDec, bool* SingleSide, bool* UsingDefaults) const; + bool GetCalibPositionRecommendations(int *HA, int *Dec) const; + void GetCustomLocation(int *PrefHA, int *PrefDec, bool *SingleSide, bool *UsingDefaults) const; void InitializeUI(bool forceDefaults); void UpdateCurrentPosition(bool fromTimer); void ShowError(const wxString& msg, bool fatal); @@ -98,6 +104,7 @@ class CalibrationAssistant : public wxDialog ~CalibrationAssistant(); double GetCalibrationDec(); void LoadCustomPosition(int CustHA, int CustDec); + private: void PerformSanityChecks(void); GUIDER_STATE m_guiderState; @@ -108,10 +115,10 @@ class CalibrationAssistant : public wxDialog class CalAssistSanityDialog : public wxDialog { public: - CalAssistSanityDialog(CalibrationAssistant* Parent, const wxString& msg); + CalAssistSanityDialog(CalibrationAssistant *Parent, const wxString& msg); private: - CalibrationAssistant* m_parent; + CalibrationAssistant *m_parent; void OnRecal(wxCommandEvent& evt); void OnCancel(wxCommandEvent& evt); }; @@ -136,7 +143,7 @@ class CalCustomDialog : public wxDialog void OnTargetEast(wxCommandEvent& evt); public: - CalCustomDialog(CalibrationAssistant* Parent, int DefaultHA, int DefaultDec); + CalCustomDialog(CalibrationAssistant *Parent, int DefaultHA, int DefaultDec); }; // Utility function to add the pairs to a flexgrid @@ -147,10 +154,11 @@ static void AddTableEntryPair(wxWindow *parent, wxFlexGridSizer *pTable, const w pTable->Add(pControl, 1, wxALL, 5); } -static wxSpinCtrl *NewSpinnerInt(wxWindow *parent, const wxSize& size, int val, int minval, int maxval, int inc, - const wxString& tooltip) +static wxSpinCtrl *NewSpinnerInt( + wxWindow *parent, const wxSize& size, int val, int minval, int maxval, int inc, const wxString& tooltip) { - wxSpinCtrl *pNewCtrl = pFrame->MakeSpinCtrl(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, size, wxSP_ARROW_KEYS, minval, maxval, val, _("Exposure time")); + wxSpinCtrl *pNewCtrl = pFrame->MakeSpinCtrl( + parent, wxID_ANY, wxEmptyString, wxDefaultPosition, size, wxSP_ARROW_KEYS, minval, maxval, val, _("Exposure time")); pNewCtrl->SetValue(val); pNewCtrl->SetToolTip(tooltip); return pNewCtrl; @@ -164,26 +172,25 @@ static void MakeBold(wxControl *ctrl) } CalibrationAssistant::CalibrationAssistant() - : wxDialog(pFrame, wxID_ANY, _("Calibration Assistant"), - wxDefaultPosition, wxSize(700, -1), wxCAPTION | wxCLOSE_BOX), - m_sanityCheckDone(0), - m_justSlewed(0), - m_isSlewing(0), - m_monitoringCalibration(0), - m_calibrationActive(0) + : wxDialog(pFrame, wxID_ANY, _("Calibration Assistant"), wxDefaultPosition, wxSize(700, -1), wxCAPTION | wxCLOSE_BOX) + , m_sanityCheckDone(0) + , m_justSlewed(0) + , m_isSlewing(0) + , m_monitoringCalibration(0) + , m_calibrationActive(0) { - wxStaticBoxSizer* currSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Current Pointing Location")); - wxStaticBoxSizer* tgtSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Calibration Location")); - wxFlexGridSizer* currPosSizer = new wxFlexGridSizer(1, 5, 5, 15); - wxFlexGridSizer* targetPosSizer = new wxFlexGridSizer(1, 5, 5, 15); + wxStaticBoxSizer *currSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Current Pointing Location")); + wxStaticBoxSizer *tgtSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Calibration Location")); + wxFlexGridSizer *currPosSizer = new wxFlexGridSizer(1, 5, 5, 15); + wxFlexGridSizer *targetPosSizer = new wxFlexGridSizer(1, 5, 5, 15); m_pExplanation = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(680, -1), wxALIGN_LEFT); MakeBold(m_pExplanation); int textWidth = StringWidth(this, "000000000"); m_pCurrOffset = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(textWidth, -1)); m_pCurrDec = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(textWidth, -1)); - wxStaticBoxSizer* sizerCurrSOP = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Pointing")); + wxStaticBoxSizer *sizerCurrSOP = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Pointing")); m_pCurrWest = new wxRadioButton(this, wxID_ANY, _("West"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP); m_pCurrEast = new wxRadioButton(this, wxID_ANY, _("East")); sizerCurrSOP->Add(m_pCurrWest); @@ -197,12 +204,15 @@ CalibrationAssistant::CalibrationAssistant() MakeBold(m_pCurrOffset); int spinnerWidth = StringWidth(this, "0000"); - m_pTargetDec = NewSpinnerInt(this, wxSize(spinnerWidth, -1), 0, -50, 50, 5, _("Target declination for slew, as close to Dec = 0 as possible for your location (>=-20 and <= 20) recommended")); + m_pTargetDec = NewSpinnerInt(this, wxSize(spinnerWidth, -1), 0, -50, 50, 5, + _("Target declination for slew, as close to Dec = 0 as possible for your location (>=-20 and <= 20) recommended")); AddTableEntryPair(this, targetPosSizer, _("Declination"), m_pTargetDec); - m_pTargetOffset = NewSpinnerInt(this, wxSize(spinnerWidth, -1), 10, 5, 50, 5, _("Target offset from central meridian, in degrees; east or west based on 'Pointing' buttons (less than 15 degrees recommended)")); + m_pTargetOffset = NewSpinnerInt(this, wxSize(spinnerWidth, -1), 10, 5, 50, 5, + _("Target offset from central meridian, in degrees; east or west based on 'Pointing' buttons (less than 15 degrees " + "recommended)")); AddTableEntryPair(this, targetPosSizer, _("Meridian offset (degrees)"), m_pTargetOffset); - wxStaticBoxSizer* sizerTargetSOP = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Pointing")); + wxStaticBoxSizer *sizerTargetSOP = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Pointing")); m_pTargetWest = new wxRadioButton(this, wxID_ANY, _("West"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP); m_pTargetWest->SetToolTip(_("Scope on the east side of pier, pointing west")); m_pTargetWest->Bind(wxEVT_COMMAND_RADIOBUTTON_SELECTED, &CalibrationAssistant::OnTargetWest, this); @@ -214,33 +224,37 @@ CalibrationAssistant::CalibrationAssistant() targetPosSizer->Add(sizerTargetSOP); tgtSizer->Add(targetPosSizer); - wxBoxSizer* midBtnSizer = new wxBoxSizer(wxHORIZONTAL); + wxBoxSizer *midBtnSizer = new wxBoxSizer(wxHORIZONTAL); wxButton *pCustomBtn = new wxButton(this, wxID_ANY, _("Save custom values...")); - pCustomBtn->SetToolTip(_("Save a custom sky location if your site has restricted sky visibility and you can't calibrate at the recommended location")); + pCustomBtn->SetToolTip(_("Save a custom sky location if your site has restricted sky visibility and you can't calibrate at " + "the recommended location")); pCustomBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalibrationAssistant::OnCustom, this); wxButton *pLoadBtn = new wxButton(this, wxID_ANY, _("Load custom values")); - pLoadBtn->SetToolTip(_("Reload a previously saved custom location and displays its values in the 'Calibration Location' fields")); + pLoadBtn->SetToolTip( + _("Reload a previously saved custom location and displays its values in the 'Calibration Location' fields")); pLoadBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalibrationAssistant::OnLoadCustom, this); - wxButton* pRestoreBtn = new wxButton(this, wxID_ANY, _("Restore defaults")); + wxButton *pRestoreBtn = new wxButton(this, wxID_ANY, _("Restore defaults")); pRestoreBtn->SetToolTip(_("Restore the 'Calibration Location' fields to show the recommended pointing location")); pRestoreBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalibrationAssistant::OnRestore, this); midBtnSizer->Add(pLoadBtn, wxSizerFlags().Center().Border(wxALL, 20)); midBtnSizer->Add(pCustomBtn, wxSizerFlags().Center().Border(wxALL, 20)); midBtnSizer->Add(pRestoreBtn, wxSizerFlags().Center().Border(wxALL, 20)); - m_pMessage = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, 75), wxALIGN_CENTER_HORIZONTAL | wxST_NO_AUTORESIZE); + m_pMessage = new wxStaticText( + this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, 75), wxALIGN_CENTER_HORIZONTAL | wxST_NO_AUTORESIZE); MakeBold(m_pMessage); m_pWarning = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, -1), wxALIGN_CENTER_HORIZONTAL); MakeBold(m_pWarning); - wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); + wxBoxSizer *btnSizer = new wxBoxSizer(wxHORIZONTAL); m_pSlewBtn = new wxButton(this, wxID_ANY, _("Slew")); m_pSlewBtn->SetToolTip(_("Start a slew to the calibration location. BE SURE the scope can be safely slewed")); m_pSlewBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalibrationAssistant::OnSlew, this); m_pCalibrateBtn = new wxButton(this, wxID_ANY, _("Calibrate")); - m_pCalibrateBtn->SetToolTip(_("Start the PHD2 calibration. The Calibration Assistant window will remain open to monitor and assess results")); + m_pCalibrateBtn->SetToolTip( + _("Start the PHD2 calibration. The Calibration Assistant window will remain open to monitor and assess results")); m_pCalibrateBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalibrationAssistant::OnCalibrate, this); - wxButton* pCancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); + wxButton *pCancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); pCancelBtn->SetToolTip(_("Close the Calibration Assistant window. Any calibration currently underway will continue.")); pCancelBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalibrationAssistant::OnCancel, this); @@ -251,7 +265,7 @@ CalibrationAssistant::CalibrationAssistant() m_pExplainBtn = new wxButton(this, wxID_ANY, _("Explain")); m_pExplainBtn->SetToolTip(_("Show additional information about any calibration result that is less than 'good'")); m_pExplainBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalibrationAssistant::OnExplain, this); - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); vSizer->Add(m_pExplanation, wxSizerFlags().Center().Border(wxTop, 5).Border(wxLEFT, 20)); vSizer->Add(currSizer, wxSizerFlags().Center().Border(wxALL, 20)); vSizer->Add(tgtSizer, wxSizerFlags().Center()); @@ -261,7 +275,7 @@ CalibrationAssistant::CalibrationAssistant() vSizer->Add(m_pMessage, wxSizerFlags().Center().Border(wxTOP, 15)); vSizer->Add(btnSizer, wxSizerFlags().Center().Border(wxTOP, 5)); - m_pTimer = new wxTimer(this, wxID_ANY); // asynch updates to current position fields + m_pTimer = new wxTimer(this, wxID_ANY); // asynch updates to current position fields m_pTimer->SetOwner(this); this->Connect(wxEVT_TIMER, wxTimerEventHandler(CalibrationAssistant::OnTimer), NULL, this); this->Bind(wxEVT_CLOSE_WINDOW, &CalibrationAssistant::OnClose, this); @@ -282,7 +296,7 @@ CalibrationAssistant::~CalibrationAssistant() pFrame->pCalibrationAssistant = NULL; } -void CalibrationAssistant::GetCustomLocation(int* PrefHA, int* PrefDec, bool* SingleSide, bool* UsingDefaults) const +void CalibrationAssistant::GetCustomLocation(int *PrefHA, int *PrefDec, bool *SingleSide, bool *UsingDefaults) const { *PrefHA = pConfig->Profile.GetInt("/scope/CalSlew/TgtHA", defBestOffset); *PrefDec = pConfig->Profile.GetInt("/scope/CalSlew/TgtDec", defBestDec); @@ -305,7 +319,7 @@ void CalibrationAssistant::PerformSanityChecks(void) if (!pPointingSource->ValidGuideRates(raSpd, decSpd)) return; - CalAssistSanityDialog* sanityDlg; + CalAssistSanityDialog *sanityDlg; double minSpd; double sidRate; if (decSpd != -1) @@ -317,24 +331,25 @@ void CalibrationAssistant::PerformSanityChecks(void) { if (sidRate <= 0.2) msg = _("Your mount guide speed is too slow for effective calibration and guiding." - " Use the hand-controller or mount driver to increase the guide speed to at least 0.5x sidereal." - " Then click the 'Recalc' button so PHD2 can compute a correct calibration step-size."); + " Use the hand-controller or mount driver to increase the guide speed to at least 0.5x sidereal." + " Then click the 'Recalc' button so PHD2 can compute a correct calibration step-size."); else msg = _("Your mount guide speed is below the minimum recommended value of 0.5x sidereal." - " Use the hand-controller or mount driver to increase the guide speed to at least 0.5x sidereal." - " Then click the 'Recalc' button so PHD2 can compute a correct calibration step-size."); + " Use the hand-controller or mount driver to increase the guide speed to at least 0.5x sidereal." + " Then click the 'Recalc' button so PHD2 can compute a correct calibration step-size."); } else { - int recDistance = CalstepDialog::GetCalibrationDistance(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); + int recDistance = + CalstepDialog::GetCalibrationDistance(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); int currStepSize = TheScope()->GetCalibrationDuration(); int recStepSize; - CalstepDialog::GetCalibrationStepSize(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning, sidRate, - CalstepDialog::DEFAULT_STEPS, m_currentDec, recDistance, 0, &recStepSize); - if (fabs(1.0 - (double)currStepSize / (double)recStepSize) > 0.3) // Within 30% is good enough + CalstepDialog::GetCalibrationStepSize(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning, + sidRate, CalstepDialog::DEFAULT_STEPS, m_currentDec, recDistance, 0, &recStepSize); + if (fabs(1.0 - (double) currStepSize / (double) recStepSize) > 0.3) // Within 30% is good enough { msg = _("Your current calibration parameters can be adjusted for more accurate results." - " Click the 'Recalc' button to restore them to the default values."); + " Click the 'Recalc' button to restore them to the default values."); } } if (!msg.empty()) @@ -397,7 +412,6 @@ void CalibrationAssistant::TrackCalibration(GUIDER_STATE state) } case STATE_STOP: break; - } } @@ -460,7 +474,7 @@ void CalibrationAssistant::UpdateCurrentPosition(bool fromTimer) } // Return of 'true' means error occurred -bool CalibrationAssistant::GetCalibPositionRecommendations(int* HA, int* Dec) const +bool CalibrationAssistant::GetCalibPositionRecommendations(int *HA, int *Dec) const { double hourAngle; int bestDec; @@ -495,13 +509,13 @@ bool CalibrationAssistant::GetCalibPositionRecommendations(int* HA, int* Dec) co else if (lat >= 0.) { eqAltitude = 90.0 - lat; - if (eqAltitude < 30.) // far north location + if (eqAltitude < 30.) // far north location bestDec += 30. - eqAltitude; } else { eqAltitude = 90. + lat; - if (eqAltitude < 30.) // far south location + if (eqAltitude < 30.) // far south location bestDec -= (30. - eqAltitude); } *HA = bestOffset; @@ -523,7 +537,8 @@ void CalibrationAssistant::ShowExplanationMsg(double dec) wxString slewCond; wxString explanation = wxEmptyString; if (pPointingSource->CanSlew()) - slewCond = _("Use the 'slew' button to move the scope to within 20 degrees of Dec = 0 or as close to that as your site will allow."); + slewCond = _("Use the 'slew' button to move the scope to within 20 degrees of Dec = 0 or as close to that as your site " + "will allow."); else slewCond = _("Slew the scope to within 20 degrees of Dec = 0 or as close to that as your site will allow."); if (fabs(dec) > 80.) @@ -532,11 +547,13 @@ void CalibrationAssistant::ShowExplanationMsg(double dec) } else if (fabs(dec) > degrees(Scope::DEC_COMP_LIMIT)) { - explanation = _("If you calibrate within 30 degrees of the pole, you will need to recalibrate when you slew to a different target.") - + " " + slewCond; + explanation = _("If you calibrate within 30 degrees of the pole, you will need to recalibrate when you slew to a " + "different target.") + + " " + slewCond; } else if (fabs(dec) > 20.) - explanation = _("Calibration will be more accurate with the scope pointing closer to the celestial equator.") + " " + slewCond; + explanation = + _("Calibration will be more accurate with the scope pointing closer to the celestial equator.") + " " + slewCond; m_pExplanation->SetLabelText(explanation); m_pExplanation->Wrap(textWrapPoint); } @@ -575,7 +592,8 @@ void CalibrationAssistant::InitializeUI(bool forceDefaults) } else { - CalibrationAssistant::GetCustomLocation(&bestOffset, &bestDec, &singleSide, &usingDefaults); // Get any custom preferences if present + CalibrationAssistant::GetCustomLocation( + &bestOffset, &bestDec, &singleSide, &usingDefaults); // Get any custom preferences if present } ShowExplanationMsg(dec); @@ -583,9 +601,9 @@ void CalibrationAssistant::InitializeUI(bool forceDefaults) m_currentDec = dec; hourAngle = norm(lst - ra, -12.0, 12.0); - if (!usingDefaults) // Custom pointing position + if (!usingDefaults) // Custom pointing position { - if (singleSide) // Use specified E-W orientation + if (singleSide) // Use specified E-W orientation { if (bestOffset <= 0) m_pTargetEast->SetValue(true); @@ -594,7 +612,7 @@ void CalibrationAssistant::InitializeUI(bool forceDefaults) } else { - if (hourAngle <= 0) // Use same E-W orientation as current pointing position + if (hourAngle <= 0) // Use same E-W orientation as current pointing position m_pTargetEast->SetValue(true); else m_pTargetWest->SetValue(true); @@ -621,7 +639,7 @@ void CalibrationAssistant::InitializeUI(bool forceDefaults) ShowError(_("Mount can't report its pointing position"), true); return; } - } // end of default handling + } // end of default handling // Current position m_pCurrOffset->SetValue(wxString::Format("%.1f", abs(hourAngle * 15.0))); @@ -671,11 +689,13 @@ bool CalibrationAssistant::PerformSlew(double ra, double dec) { double ra, dec; SlewInBg(wxWindow *parent, double ra_, double dec_) - : RunInBg(parent, _("Slew"), _("Slewing...")), ra(ra_), dec(dec_) + : RunInBg(parent, _("Slew"), _("Slewing...")) + , ra(ra_) + , dec(dec_) { SetPopupDelay(100); } - bool Entry() //wxWidgets background thread method + bool Entry() // wxWidgets background thread method { bool err = pPointingSource->SlewToCoordinatesAsync(ra, dec); if (err) @@ -698,8 +718,10 @@ bool CalibrationAssistant::PerformSlew(double ra, double dec) }; SlewInBg bg(this, ra, dec); m_isSlewing = true; - // Additional 2-sec delays are used here because some mount controllers report slew-completions before the mount has completely stopped moving - for example with behind-the-scenes clearing of RA backlash - // Starting a calibration before everything has settled will produce a bad result. The forced delays are simply an extra safety margin to reduce the likelihood of this happening. + // Additional 2-sec delays are used here because some mount controllers report slew-completions before the mount has + // completely stopped moving - for example with behind-the-scenes clearing of RA backlash Starting a calibration before + // everything has settled will produce a bad result. The forced delays are simply an extra safety margin to reduce the + // likelihood of this happening. if (bg.Run()) { m_isSlewing = false; @@ -763,16 +785,17 @@ void CalibrationAssistant::OnSlew(wxCommandEvent& evt) m_pSlewBtn->Enable(false); m_pCalibrateBtn->Enable(false); m_meridianFlipping = (m_pWarning->GetLabelText().Length() > 0); - Debug.Write(wxString::Format("CalAsst: slew from ra %.2f, dec %.1f to ra %.2f, dec %.1f, M/F = %d\n", - cur_ra, cur_dec, slew_ra, decSlew, m_meridianFlipping)); - if (decSlew <= cur_dec || m_meridianFlipping) // scope will slew sky-south regardless of north or south hemisphere + Debug.Write(wxString::Format("CalAsst: slew from ra %.2f, dec %.1f to ra %.2f, dec %.1f, M/F = %d\n", cur_ra, cur_dec, + slew_ra, decSlew, m_meridianFlipping)); + if (decSlew <= cur_dec || m_meridianFlipping) // scope will slew sky-south regardless of north or south hemisphere { ShowStatus(_("Initial slew to approximate position")); if (!PerformSlew(slew_ra, decSlew - 1.0)) { ShowStatus(_("Final slew north to pre-clear Dec backlash")); if (!PerformSlew(slew_ra, decSlew)) - ShowStatus(_("Wait for tracking to stabilize, then click 'Calibrate' to start calibration or 'Cancel' to exit")); + ShowStatus( + _("Wait for tracking to stabilize, then click 'Calibrate' to start calibration or 'Cancel' to exit")); } } else @@ -796,11 +819,12 @@ static wxString VectorToString(const wxString& separator, const std::vectorLoadCalibrationDetails(&newDetails); // See if we already triggered a sanity check alert on this last calibration - acceptableRslt = (newDetails.lastIssue == CalibrationIssueType::CI_None || newDetails.lastIssue == CalibrationIssueType::CI_Different); + acceptableRslt = (newDetails.lastIssue == CalibrationIssueType::CI_None || + newDetails.lastIssue == CalibrationIssueType::CI_Different); - // RA/Dec rates should be related by cos(dec) but don't check if Dec is too high or Dec guiding is disabled. Also don't check if DecComp - // is disabled because a Sitech controller might be monkeying around with the apparent rates + // RA/Dec rates should be related by cos(dec) but don't check if Dec is too high or Dec guiding is disabled. Also don't + // check if DecComp is disabled because a Sitech controller might be monkeying around with the apparent rates if (newCal.declination != UNKNOWN_DECLINATION && newCal.yRate != CALIBRATION_RATE_UNCALIBRATED && fabs(newCal.declination) <= Scope::DEC_COMP_LIMIT && TheScope()->DecCompensationEnabled()) { double expectedRatio = cos(newCal.declination); - if (newDetails.raGuideSpeed > 0.) // for mounts that may have different guide speeds on RA and Dec axes + if (newDetails.raGuideSpeed > 0.) // for mounts that may have different guide speeds on RA and Dec axes speedRatio = newDetails.decGuideSpeed / newDetails.raGuideSpeed; else speedRatio = 1.0; actualRatio = newCal.xRate * speedRatio / newCal.yRate; ratesMeaningful = true; - debugVals += wxString::Format("Spds: %.1fX,%.1fX, ", RateX(newDetails.raGuideSpeed), RateX(newDetails.decGuideSpeed)) + - wxString::Format("Dec: %.1f, Rates: %.1f, %.1f, ", degrees(newCal.declination), RateX(newCal.xRate), RateX(newCal.yRate)); + debugVals += + wxString::Format("Spds: %.1fX,%.1fX, ", RateX(newDetails.raGuideSpeed), RateX(newDetails.decGuideSpeed)) + + wxString::Format( + "Dec: %.1f, Rates: %.1f, %.1f, ", degrees(newCal.declination), RateX(newCal.xRate), RateX(newCal.yRate)); } else debugVals += "Spds: N/A, "; - goodRslt = (newDetails.raStepCount >= 2 * CAL_ALERT_MINSTEPS || (newDetails.decStepCount >= 2 * CAL_ALERT_MINSTEPS && newDetails.decStepCount > 0)) && // Dec guiding might be disabled - (newDetails.raStepCount <= 30 || (newDetails.decStepCount <= 30 && newDetails.decStepCount > 0)); // Not too few, not too many + goodRslt = (newDetails.raStepCount >= 2 * CAL_ALERT_MINSTEPS || + (newDetails.decStepCount >= 2 * CAL_ALERT_MINSTEPS && + newDetails.decStepCount > 0)) && // Dec guiding might be disabled + (newDetails.raStepCount <= 30 || + (newDetails.decStepCount <= 30 && newDetails.decStepCount > 0)); // Not too few, not too many debugVals += wxString::Format("Steps: %d,%d, ", newDetails.raStepCount, newDetails.decStepCount); if (!goodRslt) reasons.push_back(_("Steps")); // Non-orthogonal RA/Dec axes. Values in Calibration structures are in radians - double nonOrtho = degrees(fabs(fabs(norm_angle(newCal.xAngle - newCal.yAngle)) - M_PI / 2.)); // Delta from the nearest multiple of 90 degrees + double nonOrtho = degrees( + fabs(fabs(norm_angle(newCal.xAngle - newCal.yAngle)) - M_PI / 2.)); // Delta from the nearest multiple of 90 degrees debugVals += wxString::Format("Ortho: %.2f, ", nonOrtho); if (nonOrtho > 5) { @@ -898,13 +929,15 @@ void CalibrationAssistant::EvaluateCalibration(void) else if (acceptableRslt) { { - ShowStatus(_("Calibration result was acceptable, guiding is active using the new calibration") + "\n" + evalWhy); + ShowStatus( + _("Calibration result was acceptable, guiding is active using the new calibration") + "\n" + evalWhy); Debug.Write("CalAsst: acceptable result, " + evalWhy + "\n"); } } else { - ShowStatus(_("Calibration result was poor, consider re-doing it while following all recommendations") + "\n" + evalWhy); + ShowStatus( + _("Calibration result was poor, consider re-doing it while following all recommendations") + "\n" + evalWhy); Debug.Write("CalAsst: poor result, " + evalWhy + "\n"); } } @@ -951,7 +984,7 @@ void CalibrationAssistant::OnCalibrate(wxCommandEvent& evt) if (pFrame->CaptureActive) pFrame->StopCapturing(); ShowStatus(_("Pre-clearing backlash")); - if (PerformSlew(m_currentRA, m_currentDec + 2.0 / 60.)) // Status messages generated are handled by PerformSlew + if (PerformSlew(m_currentRA, m_currentDec + 2.0 / 60.)) // Status messages generated are handled by PerformSlew return; } m_pSlewBtn->Enable(false); @@ -973,7 +1006,7 @@ void CalibrationAssistant::OnCalibrate(wxCommandEvent& evt) void CalibrationAssistant::ExplainResults() { - CalAssistExplanationDialog* dlg = new CalAssistExplanationDialog(m_lastResult); + CalAssistExplanationDialog *dlg = new CalAssistExplanationDialog(m_lastResult); dlg->ShowModal(); } @@ -1001,7 +1034,7 @@ void CalibrationAssistant::OnCancel(wxCommandEvent& evt) void CalibrationAssistant::OnExplain(wxCommandEvent& evt) { - //m_lastResult = "Steps, Rates, Orthogonality, Sky location, Incomplete"; + // m_lastResult = "Steps, Rates, Orthogonality, Sky location, Incomplete"; ExplainResults(); } void CalibrationAssistant::OnClose(wxCloseEvent& evt) @@ -1027,24 +1060,26 @@ void CalibrationAssistant::OnCustom(wxCommandEvent& evt) if (sideEast) ha = -ha; CalCustomDialog custDlg(this, ha, dec); - custDlg.ShowModal(); // Dialog handles the UI updates + custDlg.ShowModal(); // Dialog handles the UI updates } -CalCustomDialog::CalCustomDialog(CalibrationAssistant* Parent, int DefaultHA, int DefaultDec) - : wxDialog(pFrame, wxID_ANY, _("Save Customized Calibration Position"), - wxDefaultPosition, wxSize(474, -1), wxCAPTION | wxCLOSE_BOX) +CalCustomDialog::CalCustomDialog(CalibrationAssistant *Parent, int DefaultHA, int DefaultDec) + : wxDialog(pFrame, wxID_ANY, _("Save Customized Calibration Position"), wxDefaultPosition, wxSize(474, -1), + wxCAPTION | wxCLOSE_BOX) { m_Parent = Parent; - wxStaticBoxSizer* tgtSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Target Position")); - wxFlexGridSizer* targetPosSizer = new wxFlexGridSizer(1, 5, 5, 15); + wxStaticBoxSizer *tgtSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Target Position")); + wxFlexGridSizer *targetPosSizer = new wxFlexGridSizer(1, 5, 5, 15); int spinnerWidth = StringWidth(this, "0000"); - m_pTargetDec = NewSpinnerInt(this, wxSize(spinnerWidth, -1), DefaultDec, -50, 50, 5, _("Target declination for slew, as close to Dec = 0 as possible for your location")); + m_pTargetDec = NewSpinnerInt(this, wxSize(spinnerWidth, -1), DefaultDec, -50, 50, 5, + _("Target declination for slew, as close to Dec = 0 as possible for your location")); AddTableEntryPair(this, targetPosSizer, _("Declination"), m_pTargetDec); - m_pTargetOffset = NewSpinnerInt(this, wxSize(spinnerWidth, -1), abs(DefaultHA), 5, 50, 5, _("Target offset from central meridian, in degrees; east or west based on 'Pointing' buttons")); + m_pTargetOffset = NewSpinnerInt(this, wxSize(spinnerWidth, -1), abs(DefaultHA), 5, 50, 5, + _("Target offset from central meridian, in degrees; east or west based on 'Pointing' buttons")); AddTableEntryPair(this, targetPosSizer, _("Meridian offset (degrees)"), m_pTargetOffset); - wxStaticBoxSizer* sizerTargetSOP = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Pointing")); + wxStaticBoxSizer *sizerTargetSOP = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Pointing")); m_pTargetWest = new wxRadioButton(this, wxID_ANY, _("West"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP); m_pTargetWest->SetToolTip(_("Scope on the east side of pier, pointing west")); m_pTargetWest->Bind(wxEVT_COMMAND_RADIOBUTTON_SELECTED, &CalCustomDialog::OnTargetWest, this); @@ -1061,26 +1096,28 @@ CalCustomDialog::CalCustomDialog(CalibrationAssistant* Parent, int DefaultHA, in tgtSizer->Add(targetPosSizer); m_pEastWestOnly = new wxCheckBox(this, wxID_ANY, wxEmptyString); - m_pEastWestOnly->SetToolTip(_("Check this if calibration can only be done on a particular side of the meridian because of nearby obstructions")); + m_pEastWestOnly->SetToolTip( + _("Check this if calibration can only be done on a particular side of the meridian because of nearby obstructions")); if (m_pTargetWest->GetValue()) m_pEastWestOnly->SetLabelText(_("Western sky only")); else m_pEastWestOnly->SetLabelText(_("Eastern sky only")); - wxStaticText* pMessage = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, -1), wxALIGN_CENTER_HORIZONTAL); + wxStaticText *pMessage = + new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, -1), wxALIGN_CENTER_HORIZONTAL); pMessage->SetLabelText(_("If your site location requires a unique sky position for calibration, you can specify it here.")); pMessage->Wrap(textWrapPoint); MakeBold(pMessage); - wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); - wxButton* OkBtn = new wxButton(this, wxID_ANY, _("Ok")); + wxBoxSizer *btnSizer = new wxBoxSizer(wxHORIZONTAL); + wxButton *OkBtn = new wxButton(this, wxID_ANY, _("Ok")); OkBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalCustomDialog::OnOk, this); - wxButton* cancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); + wxButton *cancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); cancelBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalCustomDialog::OnCancel, this); btnSizer->Add(OkBtn, wxSizerFlags().Border(wxALL, 20)); btnSizer->Add(cancelBtn, wxSizerFlags().Border(wxALL, 20)); - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); vSizer->Add(tgtSizer, wxSizerFlags().Center()); vSizer->Add(m_pEastWestOnly, wxSizerFlags().Center().Border(wxTOP, 15)); vSizer->Add(pMessage, wxSizerFlags().Center().Border(wxTOP, 15)); @@ -1117,24 +1154,23 @@ void CalCustomDialog::OnTargetEast(wxCommandEvent& evt) m_pEastWestOnly->SetLabelText(_("Eastern sky only")); } -CalAssistSanityDialog::CalAssistSanityDialog(CalibrationAssistant* Parent, const wxString& msg) - : wxDialog(pFrame, wxID_ANY, _("Calibration Parameters Check"), - wxDefaultPosition, wxSize(600, -1), wxCAPTION | wxCLOSE_BOX) +CalAssistSanityDialog::CalAssistSanityDialog(CalibrationAssistant *Parent, const wxString& msg) + : wxDialog(pFrame, wxID_ANY, _("Calibration Parameters Check"), wxDefaultPosition, wxSize(600, -1), wxCAPTION | wxCLOSE_BOX) { m_parent = Parent; - wxStaticText* pMessage = new wxStaticText(this, wxID_ANY, msg, wxDefaultPosition, wxSize(600, -1), wxALIGN_LEFT); + wxStaticText *pMessage = new wxStaticText(this, wxID_ANY, msg, wxDefaultPosition, wxSize(600, -1), wxALIGN_LEFT); pMessage->Wrap(textWrapPoint); MakeBold(pMessage); - wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); - wxButton* pRecalBtn = new wxButton(this, wxID_ANY, _("Recalc")); + wxBoxSizer *btnSizer = new wxBoxSizer(wxHORIZONTAL); + wxButton *pRecalBtn = new wxButton(this, wxID_ANY, _("Recalc")); pRecalBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalAssistSanityDialog::OnRecal, this); - wxButton* cancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); + wxButton *cancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); cancelBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalAssistSanityDialog::OnCancel, this); btnSizer->Add(pRecalBtn, wxSizerFlags().Border(wxALL, 20)); btnSizer->Add(cancelBtn, wxSizerFlags().Border(wxALL, 20)); - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); vSizer->Add(pMessage, wxSizerFlags().Center().Border(wxTOP, 15).Border(wxLEFT, 20)); vSizer->Add(btnSizer, wxSizerFlags().Center().Border(wxTOP, 15)); @@ -1165,9 +1201,11 @@ void CalAssistSanityDialog::OnRecal(wxCommandEvent& evt) minSpd = raSpd; double sidrate = RateX(minSpd); int calibrationStep; - int recDistance = CalstepDialog::GetCalibrationDistance(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); - CalstepDialog::GetCalibrationStepSize(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning, sidrate, - CalstepDialog::DEFAULT_STEPS, m_parent->GetCalibrationDec(), recDistance, nullptr, &calibrationStep); + int recDistance = CalstepDialog::GetCalibrationDistance( + pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); + CalstepDialog::GetCalibrationStepSize(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning, + sidrate, CalstepDialog::DEFAULT_STEPS, m_parent->GetCalibrationDec(), recDistance, nullptr, + &calibrationStep); TheScope()->SetCalibrationDuration(calibrationStep); EndDialog(wxOK); } @@ -1176,26 +1214,25 @@ void CalAssistSanityDialog::OnRecal(wxCommandEvent& evt) } CalAssistExplanationDialog::CalAssistExplanationDialog(const wxString& Why) - : wxDialog(pFrame, wxID_ANY, _("Explanation of Results"), - wxDefaultPosition, wxSize(700, -1), wxCAPTION | wxCLOSE_BOX) + : wxDialog(pFrame, wxID_ANY, _("Explanation of Results"), wxDefaultPosition, wxSize(700, -1), wxCAPTION | wxCLOSE_BOX) { const int wrapPoint = 550; const int textHeight = 80; - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); - wxStaticText* pHeader = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(680, textHeight), wxALIGN_LEFT); + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); + wxStaticText *pHeader = + new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(680, textHeight), wxALIGN_LEFT); pHeader->SetLabelText(_("Assuming you have followed all the recommendations of the Calibration Assistant, " - "the information below can help you identify any remaining problems." - )); + "the information below can help you identify any remaining problems.")); vSizer->Add(pHeader, wxSizerFlags().Center().Border(wxALL, 10)); if (Why.Contains("Steps")) { - wxStaticBoxSizer* stepsGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Too Few Steps")); - wxStaticText* pSteps = new wxStaticText(stepsGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); - pSteps->SetLabelText(_( - "Calibration was completed with fewer than the desired number of steps. This is usually caused by " - "changes to binning, focal length, or mount guide speed without using the new-profile-wizard. " - "Run the wizard to restore the correct calibration parameters." - )); + wxStaticBoxSizer *stepsGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Too Few Steps")); + wxStaticText *pSteps = new wxStaticText( + stepsGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); + pSteps->SetLabelText( + _("Calibration was completed with fewer than the desired number of steps. This is usually caused by " + "changes to binning, focal length, or mount guide speed without using the new-profile-wizard. " + "Run the wizard to restore the correct calibration parameters.")); pSteps->Wrap(wrapPoint); stepsGrp->Add(pSteps, wxSizerFlags().Center().Border(wxALL, 5)); vSizer->Add(stepsGrp, wxSizerFlags().Center().Border(wxALL, 10)); @@ -1203,12 +1240,13 @@ CalAssistExplanationDialog::CalAssistExplanationDialog(const wxString& Why) if (Why.Contains("Rates")) { - wxStaticBoxSizer* ratesGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Unexpected Rates")); - wxStaticText* pRates = new wxStaticText(ratesGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); - pRates->SetLabelText(_( - "Measured RA and Dec movements on the camera sensor aren't related by the expected ratio (cos(dec)). This can be caused " - "by sustantial weight imbalance in Dec or physical resistance to movement because of cables or over-tight gear mesh." - )); + wxStaticBoxSizer *ratesGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Unexpected Rates")); + wxStaticText *pRates = new wxStaticText( + ratesGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); + pRates->SetLabelText(_("Measured RA and Dec movements on the camera sensor aren't related by the expected ratio " + "(cos(dec)). This can be caused " + "by sustantial weight imbalance in Dec or physical resistance to movement because of cables or " + "over-tight gear mesh.")); pRates->Wrap(wrapPoint); ratesGrp->Add(pRates, wxSizerFlags().Center().Border(wxALL, 5)); vSizer->Add(ratesGrp, wxSizerFlags().Center().Border(wxALL, 10)); @@ -1216,13 +1254,13 @@ CalAssistExplanationDialog::CalAssistExplanationDialog(const wxString& Why) if (Why.Contains("Orthogonality")) { - wxStaticBoxSizer* orthGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Orthogonality")); - wxStaticText* pOrtho = new wxStaticText(orthGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); - pOrtho->SetLabelText(_( - "The mount is wandering off-target on one axis while PHD2 is measuring movement on the other axis. " - "This can be caused by large periodic error in RA or polar alignment > 10 arc-min. If the orthogonality " - "error is very large, the mount is probably not guiding correctly." - )); + wxStaticBoxSizer *orthGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Orthogonality")); + wxStaticText *pOrtho = new wxStaticText( + orthGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); + pOrtho->SetLabelText( + _("The mount is wandering off-target on one axis while PHD2 is measuring movement on the other axis. " + "This can be caused by large periodic error in RA or polar alignment > 10 arc-min. If the orthogonality " + "error is very large, the mount is probably not guiding correctly.")); pOrtho->Wrap(wrapPoint); orthGrp->Add(pOrtho, wxSizerFlags().Center().Border(wxALL, 5)); vSizer->Add(orthGrp, wxSizerFlags().Center().Border(wxALL, 10)); @@ -1230,12 +1268,13 @@ CalAssistExplanationDialog::CalAssistExplanationDialog(const wxString& Why) if (Why.Contains("Sky location")) { - wxStaticBoxSizer* locationGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Sky Location")); - wxStaticText* pLocation = new wxStaticText(locationGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); - pLocation->SetLabelText(_( - "Calibration wasn't done with Dec in the range of -20 to +20. Outside that range, measurement errors may degrade the calibration accuracy. " - "If Dec is outside the range of -60 to +60, declination compensation will not work correctly." - )); + wxStaticBoxSizer *locationGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Sky Location")); + wxStaticText *pLocation = new wxStaticText( + locationGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); + pLocation->SetLabelText( + _("Calibration wasn't done with Dec in the range of -20 to +20. Outside that range, measurement errors may " + "degrade the calibration accuracy. " + "If Dec is outside the range of -60 to +60, declination compensation will not work correctly.")); pLocation->Wrap(wrapPoint); locationGrp->Add(pLocation, wxSizerFlags().Center().Border(wxALL, 5)); vSizer->Add(locationGrp, wxSizerFlags().Center().Border(wxALL, 10)); @@ -1243,19 +1282,20 @@ CalAssistExplanationDialog::CalAssistExplanationDialog(const wxString& Why) if (Why.Contains("Incomplete")) { - wxStaticBoxSizer* failGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Not Enough Movement")); - wxStaticText* pFail = new wxStaticText(failGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); - pFail->SetLabelText(_( - "If you saw an alert saying the guide star did not move enough, the mount may not be receiving or handling guide commands. " - "If you are using an ST-4 guide cable, try replacing it. Otherwise, use the Star-Cross and Manual Guide tools in PHD2 to help " - "isolate the mechanical problem." - )); + wxStaticBoxSizer *failGrp = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Not Enough Movement")); + wxStaticText *pFail = new wxStaticText( + failGrp->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(600, textHeight), wxALIGN_LEFT); + pFail->SetLabelText(_("If you saw an alert saying the guide star did not move enough, the mount may not be receiving " + "or handling guide commands. " + "If you are using an ST-4 guide cable, try replacing it. Otherwise, use the Star-Cross and " + "Manual Guide tools in PHD2 to help " + "isolate the mechanical problem.")); pFail->Wrap(wrapPoint); failGrp->Add(pFail, wxSizerFlags().Center().Border(wxALL, 5)); vSizer->Add(failGrp, wxSizerFlags().Center().Border(wxALL, 5)); } - wxButton* okBtn = new wxButton(this, wxID_OK, _("Ok")); + wxButton *okBtn = new wxButton(this, wxID_OK, _("Ok")); vSizer->Add(okBtn, wxSizerFlags().Center().Border(wxALL, 20)); SetAutoLayout(true); diff --git a/src/calibration_assistant.h b/src/calibration_assistant.h index 98376c0aa..705278c74 100644 --- a/src/calibration_assistant.h +++ b/src/calibration_assistant.h @@ -1,37 +1,37 @@ /* -* calibration_assistant.h -* PHD Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2023 Bruce Waddington -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * calibration_assistant.h + * PHD Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2023 Bruce Waddington + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef Calilbration_Assistant_h_included #define Calilbration_Assistant_h_included diff --git a/src/calreview_dialog.cpp b/src/calreview_dialog.cpp index f65e02883..8d0336e95 100644 --- a/src/calreview_dialog.cpp +++ b/src/calreview_dialog.cpp @@ -1,37 +1,37 @@ /* -* calreview_dialog.cpp -* PHD Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2015 Bruce Waddington -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * calreview_dialog.cpp + * PHD Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2015 Bruce Waddington + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #include "calreview_dialog.h" @@ -47,11 +47,9 @@ wxEND_EVENT_TABLE(); #define NA_STR _("N/A") #define CALREVIEW_BITMAP_SIZE 250 -CalReviewDialog::CalReviewDialog( ) -{ -} +CalReviewDialog::CalReviewDialog() { } -CalReviewDialog::CalReviewDialog(wxFrame* parent, const wxString& caption) +CalReviewDialog::CalReviewDialog(wxFrame *parent, const wxString& caption) { m_childDialog = false; Create(parent, caption); @@ -64,12 +62,12 @@ CalReviewDialog::~CalReviewDialog() } // Separated from constructor because derived classes may override functions used to populate the UI -bool CalReviewDialog::Create(wxWindow* parent, const wxString& caption, const wxWindowID& id, const wxPoint& pos, - const wxSize& size, long style) +bool CalReviewDialog::Create( + wxWindow *parent, const wxString& caption, const wxWindowID& id, const wxPoint& pos, const wxSize& size, long style) { - SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS); - wxDialog::Create( parent, id, caption, pos, size, style ); + SetExtraStyle(GetExtraStyle() | wxWS_EX_BLOCK_EVENTS); + wxDialog::Create(parent, id, caption, pos, size, style); CreateControls(); GetSizer()->Fit(this); @@ -80,13 +78,14 @@ bool CalReviewDialog::Create(wxWindow* parent, const wxString& caption, const wx void CalReviewDialog::CreateControls() { - CalReviewDialog* parent = this; - wxBoxSizer* topVSizer = new wxBoxSizer(wxVERTICAL); + CalReviewDialog *parent = this; + wxBoxSizer *topVSizer = new wxBoxSizer(wxVERTICAL); parent->SetSizer(topVSizer); - wxNotebook* calibNotebook = new wxNotebook(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNB_TOP); + wxNotebook *calibNotebook = new wxNotebook(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNB_TOP); - wxPanel* panelMount = new wxPanel(calibNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxTAB_TRAVERSAL); + wxPanel *panelMount = + new wxPanel(calibNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxTAB_TRAVERSAL); CreatePanel(panelMount, false); panelMount->SetBackgroundColour("BLACK"); @@ -95,22 +94,20 @@ void CalReviewDialog::CreateControls() // Build the AO panel only if an AO is configured if (pSecondaryMount) { - wxPanel* panelAO = new wxPanel(calibNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxTAB_TRAVERSAL); + wxPanel *panelAO = + new wxPanel(calibNotebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxTAB_TRAVERSAL); CreatePanel(panelAO, true); panelAO->SetBackgroundColour("BLACK"); calibNotebook->AddPage(panelAO, _("AO")); } - topVSizer->Add(calibNotebook, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); - AddButtons(this, topVSizer); // virtual function + topVSizer->Add(calibNotebook, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); + AddButtons(this, topVSizer); // virtual function } -// Base class version of buttons - subclasses can put their own buttons if needed. No buttons for the base class because it is non-modal - -// but the window close event is hooked in order to force a destroy() and null of the global pointer -void CalReviewDialog::AddButtons(CalReviewDialog* parentDialog, wxBoxSizer* parentVSizer) -{ - -} +// Base class version of buttons - subclasses can put their own buttons if needed. No buttons for the base class because it is +// non-modal - but the window close event is hooked in order to force a destroy() and null of the global pointer +void CalReviewDialog::AddButtons(CalReviewDialog *parentDialog, wxBoxSizer *parentVSizer) { } // Populate one of the panels in the wxNotebook void CalReviewDialog::CreatePanel(wxPanel *thisPanel, bool AO) @@ -148,11 +145,11 @@ void CalReviewDialog::CreatePanel(wxPanel *thisPanel, bool AO) // Done with left-hand side // Now put the data grid(s) on the right side thisPanel->SetForegroundColour("WHITE"); - CreateDataGrids(thisPanel, panelHSizer, AO); // Virtual function + CreateDataGrids(thisPanel, panelHSizer, AO); // Virtual function } // Base class version builds data grids showing last calibration details and calibration "context" -void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSizer, bool AO) +void CalReviewDialog::CreateDataGrids(wxPanel *parentPanel, wxSizer *parentHSizer, bool AO) { const double siderealSecondPerSec = 0.9973; const double siderealRate = 15.0 * siderealSecondPerSec; @@ -172,7 +169,7 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize Calibration calBaseline; mount->GetLastCalibration(&calBaseline); - wxBoxSizer* panelGridVSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *panelGridVSizer = new wxBoxSizer(wxVERTICAL); parentHSizer->Add(panelGridVSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); int row = 0; @@ -181,12 +178,13 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize bool validBaselineDeclination = calBaseline.declination != UNKNOWN_DECLINATION; // Build the upper frame and grid for data from the last calibration - wxStaticBox* staticBoxLastCal = new wxStaticBox(parentPanel, wxID_ANY, _("Last Mount Calibration")); + wxStaticBox *staticBoxLastCal = new wxStaticBox(parentPanel, wxID_ANY, _("Last Mount Calibration")); if (AO) staticBoxLastCal->SetLabelText(_("Last AO Calibration")); - wxStaticBoxSizer* calibFrame = new wxStaticBoxSizer(staticBoxLastCal, wxVERTICAL | wxEXPAND); + wxStaticBoxSizer *calibFrame = new wxStaticBoxSizer(staticBoxLastCal, wxVERTICAL | wxEXPAND); panelGridVSizer->Add(calibFrame, 0, wxALIGN_LEFT | wxALL, 5); - wxGrid* calGrid = new wxGrid(parentPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxHSCROLL | wxVSCROLL); + wxGrid *calGrid = + new wxGrid(parentPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxHSCROLL | wxVSCROLL); calGrid->SetColLabelSize(0); calGrid->SetRowLabelSize(0); if (!AO) @@ -225,8 +223,10 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize if (validDetails && calDetails.raGuideSpeed > 0.0) { - guideRaSiderealX = calDetails.raGuideSpeed * 3600.0 / siderealRate; // Degrees/sec to Degrees/hour, 15 degrees/hour is roughly sidereal rate - guideDecSiderealX = calDetails.decGuideSpeed * 3600.0 / siderealRate; // Degrees/sec to Degrees/hour, 15 degrees/hour is roughly sidereal rate + guideRaSiderealX = calDetails.raGuideSpeed * 3600.0 / + siderealRate; // Degrees/sec to Degrees/hour, 15 degrees/hour is roughly sidereal rate + guideDecSiderealX = calDetails.decGuideSpeed * 3600.0 / + siderealRate; // Degrees/sec to Degrees/hour, 15 degrees/hour is roughly sidereal rate } wxString ARCSECPERSEC(_("a-s/sec")); @@ -240,10 +240,12 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize else calGrid->SetCellValue(row, col++, _("X rate:")); if (validDetails) - calGrid->SetCellValue(row, col++, wxString::Format("%0.3f %s\n%0.3f %s", calBaseline.xRate * 1000 * calDetails.imageScale, ARCSECPERSEC, - calBaseline.xRate * 1000, PXPERSEC)); + calGrid->SetCellValue(row, col++, + wxString::Format("%0.3f %s\n%0.3f %s", calBaseline.xRate * 1000 * calDetails.imageScale, ARCSECPERSEC, + calBaseline.xRate * 1000, PXPERSEC)); else - calGrid->SetCellValue(row, col++, wxString::Format("%0.3f %s", calBaseline.xRate * 1000, PXPERSEC)); // just px/sec with no image scale data + calGrid->SetCellValue(row, col++, + wxString::Format("%0.3f %s", calBaseline.xRate * 1000, PXPERSEC)); // just px/sec with no image scale data if (!AO) calGrid->SetCellValue(row, col++, _("Dec rate:")); else @@ -251,10 +253,12 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize if (calBaseline.yRate != CALIBRATION_RATE_UNCALIBRATED) { if (validDetails) - calGrid->SetCellValue(row, col++, wxString::Format("%0.3f %s\n%0.3f %s", calBaseline.yRate * 1000 * calDetails.imageScale, ARCSECPERSEC, - calBaseline.yRate * 1000, PXPERSEC)); + calGrid->SetCellValue(row, col++, + wxString::Format("%0.3f %s\n%0.3f %s", calBaseline.yRate * 1000 * calDetails.imageScale, ARCSECPERSEC, + calBaseline.yRate * 1000, PXPERSEC)); else - calGrid->SetCellValue(row, col++, wxString::Format("%0.3f %s", calBaseline.yRate * 1000, PXPERSEC)); // just px/sec with no image scale data + calGrid->SetCellValue(row, col++, + wxString::Format("%0.3f %s", calBaseline.yRate * 1000, PXPERSEC)); // just px/sec with no image scale data } else calGrid->SetCellValue(row, col++, NA_STR); @@ -286,7 +290,7 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize row++; col = 0; calGrid->SetCellValue(row, col++, _("Binning:")); - calGrid->SetCellValue(row, col++, wxString::Format("%d", (int)calBaseline.binning)); + calGrid->SetCellValue(row, col++, wxString::Format("%d", (int) calBaseline.binning)); calGrid->SetCellValue(row, col++, _("Created:")); calGrid->SetCellValue(row, col++, validDetails ? calDetails.origTimestamp : _("Unknown")); @@ -295,22 +299,24 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize row++; col = 0; calGrid->SetCellValue(row, col++, _("Side of pier:")); - wxString side = calDetails.origPierSide == PIER_SIDE_EAST ? _("East") : - calDetails.origPierSide == PIER_SIDE_WEST ? _("West") : NA_STR; + wxString side = calDetails.origPierSide == PIER_SIDE_EAST ? _("East") + : calDetails.origPierSide == PIER_SIDE_WEST ? _("West") + : NA_STR; calGrid->SetCellValue(row, col++, side); } calGrid->AutoSize(); calibFrame->Add(calGrid, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); - if (!AO) // Don't put this mount-related data on the AO panel + if (!AO) // Don't put this mount-related data on the AO panel { // Build the upper frame and grid for configuration data - wxStaticBox* staticBoxMount = new wxStaticBox(parentPanel, wxID_ANY, _("Mount Configuration")); - wxStaticBoxSizer* configFrame = new wxStaticBoxSizer(staticBoxMount, wxVERTICAL); + wxStaticBox *staticBoxMount = new wxStaticBox(parentPanel, wxID_ANY, _("Mount Configuration")); + wxStaticBoxSizer *configFrame = new wxStaticBoxSizer(staticBoxMount, wxVERTICAL); panelGridVSizer->Add(configFrame, 0, wxALIGN_LEFT | wxALL, 5); - wxGrid* cfgGrid = new wxGrid(parentPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxHSCROLL | wxVSCROLL); + wxGrid *cfgGrid = + new wxGrid(parentPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER | wxHSCROLL | wxVSCROLL); row = 0; col = 0; cfgGrid->SetColLabelSize(0); @@ -330,21 +336,23 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize cfgGrid->SetCellValue(row, col++, _("Image scale:")); if (validDetails) { - wxString binning = wxString::Format(_("Binning: %d"), (int)calDetails.origBinning); // Always binning used in actual calibration + wxString binning = + wxString::Format(_("Binning: %d"), (int) calDetails.origBinning); // Always binning used in actual calibration cfgGrid->SetCellValue(row, col++, wxString::Format("%0.2f %s\n%s", calDetails.imageScale, ARCSECPERPX, binning)); } else cfgGrid->SetCellValue(row, col++, NA_STR); cfgGrid->SetCellValue(row, col++, _("Side-of-pier:")); - wxString sPierSide = calBaseline.pierSide == PIER_SIDE_EAST ? _("East") : - calBaseline.pierSide == PIER_SIDE_WEST ? _("West") : NA_STR; + wxString sPierSide = calBaseline.pierSide == PIER_SIDE_EAST ? _("East") + : calBaseline.pierSide == PIER_SIDE_WEST ? _("West") + : NA_STR; cfgGrid->SetCellValue(row, col++, _(sPierSide)); row++; col = 0; cfgGrid->SetCellValue(row, col++, _("RA Guide speed:")); - if (guideRaSiderealX != -1.0) // Do the RA guide setting + if (guideRaSiderealX != -1.0) // Do the RA guide setting { cfgGrid->SetCellValue(row, col++, wxString::Format(_("%0.2fx"), guideRaSiderealX)); } @@ -352,7 +360,7 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize cfgGrid->SetCellValue(row, col++, NA_STR); cfgGrid->SetCellValue(row, col++, _("Dec Guide speed:")); - if (guideDecSiderealX != -1.0) // Do the Dec guide setting + if (guideDecSiderealX != -1.0) // Do the Dec guide setting { cfgGrid->SetCellValue(row, col++, wxString::Format(_("%0.2fx"), guideDecSiderealX)); } @@ -370,15 +378,13 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize { if (fabs(calBaseline.yRate) > 0.00001 && fabs(calBaseline.xRate / calBaseline.yRate) <= 1.0) { - dec = acos(calBaseline.xRate / calBaseline.yRate); // RA_Rate = Dec_Rate * cos(dec) + dec = acos(calBaseline.xRate / calBaseline.yRate); // RA_Rate = Dec_Rate * cos(dec) decEstimated = true; } } cfgGrid->SetCellValue(row, col++, _("Declination")); - wxString decStr = decEstimated ? - Mount::DeclinationStrTr(dec, "%0.1f (est)") : - Mount::DeclinationStrTr(dec, "%0.1f"); + wxString decStr = decEstimated ? Mount::DeclinationStrTr(dec, "%0.1f (est)") : Mount::DeclinationStrTr(dec, "%0.1f"); cfgGrid->SetCellValue(row, col++, decStr); cfgGrid->SetCellValue(row, col++, _("Rotator position:")); @@ -393,7 +399,7 @@ void CalReviewDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize } } -#define IntPoint(RealPoint, scaler) wxPoint(wxRound(RealPoint.x * scaler), wxRound(RealPoint.y * scaler)) +#define IntPoint(RealPoint, scaler) wxPoint(wxRound(RealPoint.x *scaler), wxRound(RealPoint.y *scaler)) // Build the calibration "step" graph which will appear on the lefthand side of the panels wxBitmap CalReviewDialog::CreateGraph(bool AO) @@ -405,7 +411,7 @@ wxBitmap CalReviewDialog::CreateGraph(bool AO) if (!pSecondaryMount || AO) mount = pMount; else - mount = pSecondaryMount; // Mount tab, use mount details + mount = pSecondaryMount; // Mount tab, use mount details mount->LoadCalibrationDetails(&calDetails); @@ -425,7 +431,7 @@ wxBitmap CalReviewDialog::CreateGraph(bool AO) double scaleFactor; if (biggestVal > 0.0) - scaleFactor = ((CALREVIEW_BITMAP_SIZE - 5) / 2) / biggestVal; // Leave room for circular point + scaleFactor = ((CALREVIEW_BITMAP_SIZE - 5) / 2) / biggestVal; // Leave room for circular point else scaleFactor = 1.0; @@ -438,8 +444,8 @@ wxBitmap CalReviewDialog::CreateGraph(bool AO) memDC.SetPen(axisPen); // Draw the axes memDC.SetDeviceOrigin(wxCoord(CALREVIEW_BITMAP_SIZE / 2), wxCoord(CALREVIEW_BITMAP_SIZE / 2)); - memDC.DrawLine(-CALREVIEW_BITMAP_SIZE / 2, 0, CALREVIEW_BITMAP_SIZE / 2, 0); // x - memDC.DrawLine(0, -CALREVIEW_BITMAP_SIZE / 2, 0, CALREVIEW_BITMAP_SIZE / 2); // y + memDC.DrawLine(-CALREVIEW_BITMAP_SIZE / 2, 0, CALREVIEW_BITMAP_SIZE / 2, 0); // x + memDC.DrawLine(0, -CALREVIEW_BITMAP_SIZE / 2, 0, CALREVIEW_BITMAP_SIZE / 2); // y if (calDetails.raStepCount > 0) { @@ -455,20 +461,22 @@ wxBitmap CalReviewDialog::CreateGraph(bool AO) // Scale the points, then plot them individually for (int i = 0; i < (int) calDetails.raSteps.size(); i++) { - if (i == calDetails.raStepCount + 2) // Valid even for "single-step" calibration + if (i == calDetails.raStepCount + 2) // Valid even for "single-step" calibration { - memDC.SetPen(wxPen(raColor, 1)); // 1-pixel-thick outline - memDC.SetBrush(wxNullBrush); // Outline only for "return" data points + memDC.SetPen(wxPen(raColor, 1)); // 1-pixel-thick outline + memDC.SetBrush(wxNullBrush); // Outline only for "return" data points ptRadius = 3; } memDC.DrawCircle(IntPoint(calDetails.raSteps.at(i), scaleFactor), ptRadius); } // Show the line PHD2 will use for the rate memDC.SetPen(raPen); - if ((int)calDetails.raSteps.size() > calDetails.raStepCount) // New calib, includes return values - memDC.DrawLine(IntPoint(calDetails.raSteps.at(0), scaleFactor), IntPoint(calDetails.raSteps.at(calDetails.raStepCount), scaleFactor)); + if ((int) calDetails.raSteps.size() > calDetails.raStepCount) // New calib, includes return values + memDC.DrawLine(IntPoint(calDetails.raSteps.at(0), scaleFactor), + IntPoint(calDetails.raSteps.at(calDetails.raStepCount), scaleFactor)); else - memDC.DrawLine(IntPoint(calDetails.raSteps.at(0), scaleFactor), IntPoint(calDetails.raSteps.at(calDetails.raStepCount - 1), scaleFactor)); + memDC.DrawLine(IntPoint(calDetails.raSteps.at(0), scaleFactor), + IntPoint(calDetails.raSteps.at(calDetails.raStepCount - 1), scaleFactor)); } // Handle the Dec data @@ -478,24 +486,26 @@ wxBitmap CalReviewDialog::CreateGraph(bool AO) memDC.SetPen(decPen); memDC.SetBrush(decBrush); int ptRadius = 2; - if (calDetails.decStepCount > 0 && calDetails.decSteps.size() > 0) // redundant, protection against old bug + if (calDetails.decStepCount > 0 && calDetails.decSteps.size() > 0) // redundant, protection against old bug { for (int i = 0; i < (int) calDetails.decSteps.size(); i++) { if (i == calDetails.decStepCount + 2) { - memDC.SetPen(wxPen(decColor, 1)); // 1-pixel-thick outline - memDC.SetBrush(wxNullBrush); // Outline only for "return" data points + memDC.SetPen(wxPen(decColor, 1)); // 1-pixel-thick outline + memDC.SetBrush(wxNullBrush); // Outline only for "return" data points ptRadius = 3; } memDC.DrawCircle(IntPoint(calDetails.decSteps.at(i), scaleFactor), ptRadius); } // Show the line PHD2 will use for the rate memDC.SetPen(decPen); - if ((int)calDetails.decSteps.size() > calDetails.decStepCount) // New calib, includes return values - memDC.DrawLine(IntPoint(calDetails.decSteps.at(0), scaleFactor), IntPoint(calDetails.decSteps.at(calDetails.decStepCount), scaleFactor)); + if ((int) calDetails.decSteps.size() > calDetails.decStepCount) // New calib, includes return values + memDC.DrawLine(IntPoint(calDetails.decSteps.at(0), scaleFactor), + IntPoint(calDetails.decSteps.at(calDetails.decStepCount), scaleFactor)); else - memDC.DrawLine(IntPoint(calDetails.decSteps.at(0), scaleFactor), IntPoint(calDetails.decSteps.at(calDetails.decStepCount - 1), scaleFactor)); + memDC.DrawLine(IntPoint(calDetails.decSteps.at(0), scaleFactor), + IntPoint(calDetails.decSteps.at(calDetails.decStepCount - 1), scaleFactor)); } return bmp; @@ -519,24 +529,21 @@ void CalReviewDialog::OnCloseWindow(wxCloseEvent& event) } // Derived classes from CalibrationRestoreDialog -// Restore dialog is basically the same as 'Review' except for option to actually restore the old calibration data - plus, it's modal -CalRestoreDialog::CalRestoreDialog(wxFrame* parent, const wxString& caption) +// Restore dialog is basically the same as 'Review' except for option to actually restore the old calibration data - plus, it's +// modal +CalRestoreDialog::CalRestoreDialog(wxFrame *parent, const wxString& caption) { m_childDialog = true; Create(parent, caption); } -void CalRestoreDialog::AddButtons(CalReviewDialog* parentDialog, wxBoxSizer* parentVSizer) +void CalRestoreDialog::AddButtons(CalReviewDialog *parentDialog, wxBoxSizer *parentVSizer) { wxBoxSizer *pButtonSizer = new wxBoxSizer(wxHORIZONTAL); wxButton *pRestore = new wxButton(parentDialog, wxID_OK, _("Restore")); pRestore->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalRestoreDialog::OnRestore, this); - pButtonSizer->Add( - pRestore, - wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); - pButtonSizer->Add( - CreateButtonSizer(wxCANCEL), - wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); + pButtonSizer->Add(pRestore, wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); + pButtonSizer->Add(CreateButtonSizer(wxCANCEL), wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); parentVSizer->Add(pButtonSizer, wxSizerFlags(0).Center()); } @@ -549,8 +556,8 @@ void CalRestoreDialog::OnRestore(wxCommandEvent& event) } // CalSanity dialog may get launched as part of an 'alert' if the last calibration looked wonky - this one is non-modal -CalSanityDialog::CalSanityDialog(wxFrame *parent, const Calibration& oldParams, const CalibrationDetails& oldDetails, - CalibrationIssueType issue) +CalSanityDialog::CalSanityDialog( + wxFrame *parent, const Calibration& oldParams, const CalibrationDetails& oldDetails, CalibrationIssueType issue) { m_pScope = TheScope(); m_pScope->GetLastCalibration(&m_newParams); @@ -566,7 +573,7 @@ CalSanityDialog::CalSanityDialog(wxFrame *parent, const Calibration& oldParams, CalSanityDialog::~CalSanityDialog() { - pFrame->pCalSanityCheckDlg = NULL; // Clear the global pointer used to launch us + pFrame->pCalSanityCheckDlg = NULL; // Clear the global pointer used to launch us } static const int MESSAGE_HEIGHT = 100; @@ -585,24 +592,33 @@ void CalSanityDialog::BuildMessage(wxStaticText *pText, CalibrationIssueType ety { case CI_Steps: msg = _("The calibration was done with a very small number of steps, which can produce inaccurate results. " - "Consider reducing the size of the calibration step parameter until you see at least 8 steps in each direction. The 'calculator' " - "feature in the 'Mount' configuration tab can help you with this."); + "Consider reducing the size of the calibration step parameter until you see at least 8 steps in each " + "direction. The 'calculator' " + "feature in the 'Mount' configuration tab can help you with this."); break; case CI_Angle: - msg = wxString::Format(_("The RA and Declination angles computed in the calibration are questionable. Normally, " - "these angles will be nearly perpendicular, having an 'orthogonality error' of less than 10 degrees. In this calibration, your error was %s degrees, which " - "is often caused by poor polar alignment, large Dec backlash, or a large periodic error in RA."), m_newAngleDelta); + msg = + wxString::Format(_("The RA and Declination angles computed in the calibration are questionable. Normally, " + "these angles will be nearly perpendicular, having an 'orthogonality error' of less than 10 " + "degrees. In this calibration, your error was %s degrees, which " + "is often caused by poor polar alignment, large Dec backlash, or a large periodic error in RA."), + m_newAngleDelta); break; case CI_Different: - msg = wxString::Format(_("The most recent calibration produced results that are %s%% different from the previous calibration. If this is because " - "you changed equipment configurations, you may want to use different profiles. Doing so will allow you to switch back " - "and forth between configurations and still retain earlier settings and calibration results."), m_oldNewDifference); + msg = wxString::Format(_("The most recent calibration produced results that are %s%% different from the previous " + "calibration. If this is because " + "you changed equipment configurations, you may want to use different profiles. Doing so will " + "allow you to switch back " + "and forth between configurations and still retain earlier settings and calibration results."), + m_oldNewDifference); break; case CI_Rates: - msg = wxString::Format(_("The RA and Declination guiding rates differ by an unexpected amount. For your declination of %0.0f degrees, " - "the RA rate should be about %0.0f%% of the Dec rate. But your RA rate is %0.0f%% of the Dec rate. " - "This usually means one of the axis calibrations is incorrect and may result in poor guiding."), - degrees(m_newParams.declination), cos(m_newParams.declination) * 100.0, m_newParams.xRate / m_newParams.yRate * 100.0); + msg = wxString::Format( + _("The RA and Declination guiding rates differ by an unexpected amount. For your declination of %0.0f degrees, " + "the RA rate should be about %0.0f%% of the Dec rate. But your RA rate is %0.0f%% of the Dec rate. " + "This usually means one of the axis calibrations is incorrect and may result in poor guiding."), + degrees(m_newParams.declination), cos(m_newParams.declination) * 100.0, + m_newParams.xRate / m_newParams.yRate * 100.0); break; default: msg = wxString::Format("Just testing"); @@ -612,8 +628,9 @@ void CalSanityDialog::BuildMessage(wxStaticText *pText, CalibrationIssueType ety pText->Wrap(420); } -// Overridden method for building the data grids - these are substantially different from the CalReview base but the overall appearance and graph presence are the same -void CalSanityDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSizer, bool AO) +// Overridden method for building the data grids - these are substantially different from the CalReview base but the overall +// appearance and graph presence are the same +void CalSanityDialog::CreateDataGrids(wxPanel *parentPanel, wxSizer *parentHSizer, bool AO) { wxString raSteps = wxString::Format("%d", m_calDetails.raStepCount); wxString decSteps = wxString::Format("%d", m_calDetails.decStepCount); @@ -623,7 +640,7 @@ void CalSanityDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize double imageScale = m_calDetails.imageScale; bool oldValid = m_oldParams.isValid; - if (!AO) // AO calibration never triggers sanity check alerts, so don't show that data + if (!AO) // AO calibration never triggers sanity check alerts, so don't show that data { // Compute the orthogonality stuff m_newAngleDelta = wxString::Format("%0.1f", m_calDetails.orthoError); @@ -644,7 +661,8 @@ void CalSanityDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize wxStaticBoxSizer *pMsgGrp = new wxStaticBoxSizer(wxVERTICAL, parentPanel, _("Explanation")); // Explanation area - wxStaticText *pMsgArea = new wxStaticText(parentPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(450, -1), wxALIGN_LEFT | wxST_NO_AUTORESIZE); + wxStaticText *pMsgArea = new wxStaticText( + parentPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(450, -1), wxALIGN_LEFT | wxST_NO_AUTORESIZE); BuildMessage(pMsgArea, m_issue); pMsgArea->SetSizeHints(wxSize(450, MESSAGE_HEIGHT)); wxFont font = pMsgArea->GetFont(); @@ -667,7 +685,8 @@ void CalSanityDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize pGrid->SetCellValue(row, col++, raSteps); pGrid->SetCellValue(row, col++, _("Steps, Dec:")); pGrid->SetCellValue(row, col++, decSteps); - if (m_issue == CI_Steps){ + if (m_issue == CI_Steps) + { if (raSteps <= decSteps) HighlightCell(pGrid, row, 1); else @@ -691,7 +710,8 @@ void CalSanityDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize { pGrid->SetCellValue(row, col++, _("This declination rate:")); if (newDecRate != CALIBRATION_RATE_UNCALIBRATED) - pGrid->SetCellValue(row, col++, wxString::Format(_("%0.3f a-s/sec\n%0.3f px/sec"), newDecRate * 1000 * imageScale, newDecRate * 1000)); + pGrid->SetCellValue(row, col++, + wxString::Format(_("%0.3f a-s/sec\n%0.3f px/sec"), newDecRate * 1000 * imageScale, newDecRate * 1000)); else pGrid->SetCellValue(row, col++, NA_STR); pGrid->SetCellValue(row, col++, _("Previous declination rate:")); @@ -705,10 +725,12 @@ void CalSanityDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize else { pGrid->SetCellValue(row, col++, _("RA rate:")); - pGrid->SetCellValue(row, col++, wxString::Format(_("%0.3f a-s/sec\n%0.3f px/sec"), newRARate * 1000 * imageScale, newRARate * 1000)); + pGrid->SetCellValue(row, col++, + wxString::Format(_("%0.3f a-s/sec\n%0.3f px/sec"), newRARate * 1000 * imageScale, newRARate * 1000)); pGrid->SetCellValue(row, col++, _("Declination rate:")); if (newDecRate != CALIBRATION_RATE_UNCALIBRATED) - pGrid->SetCellValue(row, col++, wxString::Format(_("%0.3f a-s/sec\n%0.3f px/sec"), newDecRate * 1000 * imageScale, newDecRate * 1000)); + pGrid->SetCellValue(row, col++, + wxString::Format(_("%0.3f a-s/sec\n%0.3f px/sec"), newDecRate * 1000 * imageScale, newDecRate * 1000)); else pGrid->SetCellValue(row, col++, NA_STR); if (m_issue == CI_Rates) @@ -728,10 +750,9 @@ void CalSanityDialog::CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSize pVSizer->Add(m_pBlockThis, wxSizerFlags(0).Border(wxALL, 15)); parentHSizer->Add(pVSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); } - } -void CalSanityDialog::AddButtons(CalReviewDialog* parentDialog, wxBoxSizer* parentVSizer) +void CalSanityDialog::AddButtons(CalReviewDialog *parentDialog, wxBoxSizer *parentVSizer) { wxBoxSizer *pButtonSizer = new wxBoxSizer(wxHORIZONTAL); @@ -739,26 +760,19 @@ void CalSanityDialog::AddButtons(CalReviewDialog* parentDialog, wxBoxSizer* pare pIgnore->SetToolTip(_("Accept the calibration as being valid and continue guiding")); pIgnore->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalSanityDialog::OnIgnore, this); wxButton *pRecal = new wxButton(this, wxID_ANY, _("Discard calibration")); - pRecal->SetToolTip(_("Stop guiding and discard the most recent calibration. Calibration will be re-done the next time you start guiding")); + pRecal->SetToolTip(_( + "Stop guiding and discard the most recent calibration. Calibration will be re-done the next time you start guiding")); pRecal->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalSanityDialog::OnRecal, this); wxButton *pRestore = new wxButton(this, wxID_ANY, _("Restore old calibration")); pRestore->SetToolTip(_("Stop guiding, discard the most recent calibration, then load the previous (good) calibration")); pRestore->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalSanityDialog::OnRestore, this); pRestore->Enable(m_oldValid); - pButtonSizer->Add( - pIgnore, - wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); - pButtonSizer->Add( - pRecal, - wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); - pButtonSizer->Add( - pRestore, - wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); - - parentVSizer->Add( - pButtonSizer, - wxSizerFlags(0).Center()); + pButtonSizer->Add(pIgnore, wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); + pButtonSizer->Add(pRecal, wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); + pButtonSizer->Add(pRestore, wxSizerFlags(0).Align(0).Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); + + parentVSizer->Add(pButtonSizer, wxSizerFlags(0).Center()); } void CalSanityDialog::OnIgnore(wxCommandEvent& evt) diff --git a/src/calreview_dialog.h b/src/calreview_dialog.h index 95f4c15ec..a501f6300 100644 --- a/src/calreview_dialog.h +++ b/src/calreview_dialog.h @@ -1,63 +1,64 @@ /* -* calreview_dialog.h -* PHD Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2015 Bruce Waddington -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * calreview_dialog.h + * PHD Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2015 Bruce Waddington + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef _CALREVIEW_DIALOG_H_ -#define _CALREVIEW_DIALOG_H_ +# define _CALREVIEW_DIALOG_H_ -#include +# include -class CalReviewDialog: public wxDialog +class CalReviewDialog : public wxDialog { wxDECLARE_EVENT_TABLE(); public: /// Constructors - CalReviewDialog( ); - CalReviewDialog(wxFrame* parent, const wxString& caption = _("Review Calibration")); + CalReviewDialog(); + CalReviewDialog(wxFrame *parent, const wxString& caption = _("Review Calibration")); ~CalReviewDialog(); protected: /// Creation - bool Create(wxWindow* parent, const wxString& caption, const wxWindowID& id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxSize(400, 300), long style = wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxCLOSE_BOX); + bool Create(wxWindow *parent, const wxString& caption, const wxWindowID& id = wxID_ANY, + const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(400, 300), + long style = wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxCLOSE_BOX); /// Builds the controls and sizers with virtual functions for derived dialogs virtual void CreateControls(); - virtual void AddButtons(CalReviewDialog* parentDialog, wxBoxSizer* parentVSizer); - void CreatePanel(wxPanel* thisPanel, bool AO); - virtual void CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSizer, bool AO); + virtual void AddButtons(CalReviewDialog *parentDialog, wxBoxSizer *parentVSizer); + void CreatePanel(wxPanel *thisPanel, bool AO); + virtual void CreateDataGrids(wxPanel *parentPanel, wxSizer *parentHSizer, bool AO); wxBitmap CreateGraph(bool AO); void ShutDown(); void OnCloseWindow(wxCloseEvent& event); @@ -72,9 +73,10 @@ class CalRestoreDialog : public CalReviewDialog { public: - CalRestoreDialog(wxFrame* parent, const wxString& caption = _("Restore Calibration")); + CalRestoreDialog(wxFrame *parent, const wxString& caption = _("Restore Calibration")); + private: - virtual void AddButtons(CalReviewDialog* parentDialog, wxBoxSizer* parentVSizer); + virtual void AddButtons(CalReviewDialog *parentDialog, wxBoxSizer *parentVSizer); void OnRestore(wxCommandEvent& event); }; @@ -82,13 +84,14 @@ class CalRestoreDialog : public CalReviewDialog class CalSanityDialog : public CalReviewDialog { public: - CalSanityDialog(wxFrame* parent, const Calibration& oldParams, const CalibrationDetails& oldDetails, - CalibrationIssueType issue); + CalSanityDialog( + wxFrame *parent, const Calibration& oldParams, const CalibrationDetails& oldDetails, CalibrationIssueType issue); ~CalSanityDialog(); + private: - virtual void AddButtons(CalReviewDialog* parentDialog, wxBoxSizer* parentVSizer); - virtual void CreateDataGrids(wxPanel* parentPanel, wxSizer* parentHSizer, bool AO); + virtual void AddButtons(CalReviewDialog *parentDialog, wxBoxSizer *parentVSizer); + virtual void CreateDataGrids(wxPanel *parentPanel, wxSizer *parentHSizer, bool AO); void OnIgnore(wxCommandEvent& evt); void OnRecal(wxCommandEvent& evt); @@ -108,4 +111,4 @@ class CalSanityDialog : public CalReviewDialog Scope *m_pScope; }; #endif - // _CALREVIEW_DIALOG_H_ +// _CALREVIEW_DIALOG_H_ diff --git a/src/calstep_dialog.cpp b/src/calstep_dialog.cpp index b54cd6fe3..81ada27d3 100644 --- a/src/calstep_dialog.cpp +++ b/src/calstep_dialog.cpp @@ -51,14 +51,14 @@ static wxSpinCtrlDouble *NewSpinner(wxWindow *parent, int width, double val, double minval, double maxval, double inc) { - wxSpinCtrlDouble *pNewCtrl = pFrame->MakeSpinCtrlDouble(parent, wxID_ANY, _T("foo2"), wxPoint(-1, -1), - wxSize(width, -1), wxSP_ARROW_KEYS, minval, maxval, val, inc); + wxSpinCtrlDouble *pNewCtrl = pFrame->MakeSpinCtrlDouble( + parent, wxID_ANY, _T("foo2"), wxPoint(-1, -1), wxSize(width, -1), wxSP_ARROW_KEYS, minval, maxval, val, inc); pNewCtrl->SetDigits(2); return pNewCtrl; } -CalstepDialog::CalstepDialog(wxWindow *parent, int focalLength, double pixelSize, int binning) : - wxDialog(parent, wxID_ANY, _("Calibration Calculator"), wxDefaultPosition, wxSize(400, 500), wxCAPTION | wxCLOSE_BOX) +CalstepDialog::CalstepDialog(wxWindow *parent, int focalLength, double pixelSize, int binning) + : wxDialog(parent, wxID_ANY, _("Calibration Calculator"), wxDefaultPosition, wxSize(400, 500), wxCAPTION | wxCLOSE_BOX) { double dGuideRateDec = 0.0; // initialize to suppress compiler warning double dGuideRateRA = 0.0; // initialize to suppress compiler warning @@ -68,11 +68,11 @@ CalstepDialog::CalstepDialog(wxWindow *parent, int focalLength, double pixelSize // Get squared away with initial parameter values - start with values from the profile m_iNumSteps = pConfig->Profile.GetInt("/CalStepCalc/NumSteps", DEFAULT_STEPS); - m_dDeclination = pConfig->Profile.GetDouble ("/CalStepCalc/CalDeclination", 0.0); + m_dDeclination = pConfig->Profile.GetDouble("/CalStepCalc/CalDeclination", 0.0); m_iFocalLength = focalLength; m_fPixelSize = pixelSize; m_binning = binning; - m_fGuideSpeed = (float) pConfig->Profile.GetDouble ("/CalStepCalc/GuideSpeed", Scope::DEFAULT_MOUNT_GUIDE_SPEED); + m_fGuideSpeed = (float) pConfig->Profile.GetDouble("/CalStepCalc/GuideSpeed", Scope::DEFAULT_MOUNT_GUIDE_SPEED); m_calibrationDistance = pConfig->Profile.GetInt("/scope/CalibrationDistance", DEFAULT_DISTANCE); // Now improve on Dec and guide speed if mount/pointing info is available @@ -81,7 +81,8 @@ CalstepDialog::CalstepDialog(wxWindow *parent, int focalLength, double pixelSize if (!pPointingSource->GetGuideRates(&dGuideRateRA, &dGuideRateDec)) { if (dGuideRateRA >= dGuideRateDec) - m_fGuideSpeed = dGuideRateRA * 3600.0 / (15.0 * dSiderealSecondPerSec); // Degrees/sec to Degrees/hour, 15 degrees/hour is roughly sidereal rate + m_fGuideSpeed = dGuideRateRA * 3600.0 / + (15.0 * dSiderealSecondPerSec); // Degrees/sec to Degrees/hour, 15 degrees/hour is roughly sidereal rate else m_fGuideSpeed = dGuideRateDec * 3600.0 / (15.0 * dSiderealSecondPerSec); @@ -104,21 +105,21 @@ CalstepDialog::CalstepDialog(wxWindow *parent, int focalLength, double pixelSize m_pInputGroupBox = new wxStaticBoxSizer(wxVERTICAL, this, _("Input Parameters")); textWidth = StringWidth(this, "00000"); m_pPixelSize = NewSpinner(this, textWidth, m_fPixelSize, MIN_PIXELSIZE, MAX_PIXELSIZE, 0.1); - m_pPixelSize->GetSize(&spinnerWidth, &spinnerHeight); // Get sizing info from spinner, which will be largest + m_pPixelSize->GetSize(&spinnerWidth, &spinnerHeight); // Get sizing info from spinner, which will be largest // Focal length - any positive int - wxIntegerValidator valFocalLength (&m_iFocalLength, 0); + wxIntegerValidator valFocalLength(&m_iFocalLength, 0); valFocalLength.SetRange(0, wxINT32_MAX); - m_pFocalLength = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(spinnerWidth, - -1), 0, valFocalLength); + m_pFocalLength = + new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(spinnerWidth, -1), 0, valFocalLength); m_pFocalLength->Enable(!pFrame->CaptureActive); m_pFocalLength->Bind(wxEVT_TEXT, &CalstepDialog::OnText, this); - AddTableEntry (m_pInputTableSizer, _("Focal length, mm"), m_pFocalLength, _("Guide scope focal length")); + AddTableEntry(m_pInputTableSizer, _("Focal length, mm"), m_pFocalLength, _("Guide scope focal length")); // Pixel size m_pPixelSize->Enable(!pFrame->CaptureActive); m_pPixelSize->Bind(wxEVT_SPINCTRLDOUBLE, &CalstepDialog::OnSpinCtrlDouble, this); - AddTableEntry (m_pInputTableSizer, _("Pixel size, microns"), m_pPixelSize, _("Guide camera pixel size")); + AddTableEntry(m_pInputTableSizer, _("Pixel size, microns"), m_pPixelSize, _("Guide camera pixel size")); // binning wxArrayString opts; @@ -134,32 +135,37 @@ CalstepDialog::CalstepDialog(wxWindow *parent, int focalLength, double pixelSize // Guide speed m_pGuideSpeed = NewSpinner(this, textWidth, m_fGuideSpeed, MIN_GUIDESPEED, MAX_GUIDESPEED, 0.25); m_pGuideSpeed->Bind(wxEVT_SPINCTRLDOUBLE, &CalstepDialog::OnSpinCtrlDouble, this); - AddTableEntry (m_pInputTableSizer, _("Guide speed, n.nn x sidereal"), m_pGuideSpeed, - /* xgettext:no-c-format */ _("Guide speed, multiple of sidereal rate; if your mount's guide speed is 50% sidereal rate, enter 0.5." - " NOTE: Changing this setting has no effect on the guide speed used by the mount - that must be changed via driver UI or hand-controller.")); + AddTableEntry(m_pInputTableSizer, _("Guide speed, n.nn x sidereal"), m_pGuideSpeed, + /* xgettext:no-c-format */ + _("Guide speed, multiple of sidereal rate; if your mount's guide speed is 50% sidereal rate, enter 0.5." + " NOTE: Changing this setting has no effect on the guide speed used by the mount - that must be changed via driver " + "UI or hand-controller.")); // Number of steps m_pNumSteps = NewSpinner(this, textWidth, m_iNumSteps, MIN_STEPS, MAX_STEPS, 1); - m_pNumSteps->SetDigits (0); + m_pNumSteps->SetDigits(0); m_pNumSteps->Bind(wxEVT_SPINCTRLDOUBLE, &CalstepDialog::OnSpinCtrlDouble, this); - AddTableEntry (m_pInputTableSizer, _("Calibration steps"), m_pNumSteps, - wxString::Format(_("Targeted number of steps in each direction. The default value (%d) works fine for most setups."), (int) DEFAULT_STEPS)); + AddTableEntry(m_pInputTableSizer, _("Calibration steps"), m_pNumSteps, + wxString::Format(_("Targeted number of steps in each direction. The default value (%d) works fine for most setups."), + (int) DEFAULT_STEPS)); // Distance for calibration (arcsec) m_pDistance = NewSpinner(this, textWidth, m_calibrationDistance, MIN_DISTANCE, MAX_DISTANCE, 1.0); m_pDistance->SetDigits(0); m_pDistance->Bind(wxEVT_SPINCTRLDOUBLE, &CalstepDialog::OnSpinCtrlDouble, this); AddTableEntry(m_pInputTableSizer, _("Calibration distance, px"), m_pDistance, - wxString::Format(_("Targeted distance in each direction. The default value (%d) works fine for most setups."), (int) DEFAULT_DISTANCE)); + wxString::Format(_("Targeted distance in each direction. The default value (%d) works fine for most setups."), + (int) DEFAULT_DISTANCE)); // Calibration declination m_pDeclination = NewSpinner(this, textWidth, m_dDeclination, MIN_DECLINATION, MAX_DECLINATION, 5.0); m_pDeclination->SetDigits(0); m_pDeclination->Bind(wxEVT_SPINCTRLDOUBLE, &CalstepDialog::OnSpinCtrlDouble, this); - AddTableEntry (m_pInputTableSizer, _("Calibration declination, degrees"), m_pDeclination, _("Approximate declination where you will do calibration")); + AddTableEntry(m_pInputTableSizer, _("Calibration declination, degrees"), m_pDeclination, + _("Approximate declination where you will do calibration")); // Button for doing a 'reset' - wxButton* pResetButton = new wxButton(this, wxID_DEFAULT, _("Reset")); + wxButton *pResetButton = new wxButton(this, wxID_DEFAULT, _("Reset")); pResetButton->SetToolTip(_("Reset the calibration parameters to defaults")); pResetButton->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CalstepDialog::OnReset, this); m_pInputTableSizer->Add(pResetButton, 1, wxALL, 5); @@ -168,35 +174,32 @@ CalstepDialog::CalstepDialog(wxWindow *parent, int focalLength, double pixelSize m_pOutputGroupBox = new wxStaticBoxSizer(wxVERTICAL, this, _("Computed Values")); m_status = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE_HORIZONTAL); - m_pImageScale = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(spinnerWidth, - -1)); + m_pImageScale = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(spinnerWidth, -1)); m_pImageScale->Enable(false); - AddTableEntry (m_pOutputTableSizer, _("Image scale, arc-sec/px"), m_pImageScale, ""); + AddTableEntry(m_pOutputTableSizer, _("Image scale, arc-sec/px"), m_pImageScale, ""); m_pRslt = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(spinnerWidth, -1)); - AddTableEntry (m_pOutputTableSizer, _("Calibration step, ms"), m_pRslt, ""); + AddTableEntry(m_pOutputTableSizer, _("Calibration step, ms"), m_pRslt, ""); // Add the tables to the panel, centered - m_pInputGroupBox->Add (m_pInputTableSizer, 0, wxALL, 10); - m_pOutputGroupBox->Add (m_pOutputTableSizer, 0, wxALL, 10); + m_pInputGroupBox->Add(m_pInputTableSizer, 0, wxALL, 10); + m_pOutputGroupBox->Add(m_pOutputTableSizer, 0, wxALL, 10); m_pVSizer->Add(m_status, 1, wxALL, 5); - m_pVSizer->Add (m_pInputGroupBox, wxSizerFlags().Center().Border(wxALL, 10)); - m_pVSizer->Add (m_pOutputGroupBox, wxSizerFlags().Center().Border(wxRIGHT|wxLEFT|wxBOTTOM, 10)); + m_pVSizer->Add(m_pInputGroupBox, wxSizerFlags().Center().Border(wxALL, 10)); + m_pVSizer->Add(m_pOutputGroupBox, wxSizerFlags().Center().Border(wxRIGHT | wxLEFT | wxBOTTOM, 10)); // ok/cancel buttons - m_pVSizer->Add( - CreateButtonSizer(wxOK | wxCANCEL), - wxSizerFlags(0).Expand().Border(wxALL, 10) ); + m_pVSizer->Add(CreateButtonSizer(wxOK | wxCANCEL), wxSizerFlags(0).Expand().Border(wxALL, 10)); - SetSizerAndFit (m_pVSizer); + SetSizerAndFit(m_pVSizer); } // Utility function to add the tuples to the grid including tool-tips -void CalstepDialog::AddTableEntry (wxFlexGridSizer *pTable, const wxString& label, wxWindow *pControl, const wxString& toolTip) +void CalstepDialog::AddTableEntry(wxFlexGridSizer *pTable, const wxString& label, wxWindow *pControl, const wxString& toolTip) { - wxStaticText *pLabel = new wxStaticText(this, wxID_ANY, label + _(": "),wxPoint(-1,-1),wxSize(-1,-1)); - pTable->Add (pLabel, 1, wxALL, 5); - pTable->Add (pControl, 1, wxALL, 5); - pControl->SetToolTip (toolTip); + wxStaticText *pLabel = new wxStaticText(this, wxID_ANY, label + _(": "), wxPoint(-1, -1), wxSize(-1, -1)); + pTable->Add(pLabel, 1, wxALL, 5); + pTable->Add(pControl, 1, wxALL, 5); + pControl->SetToolTip(toolTip); } // the recommended calibration distance is 20 arc-seconds or 25 pixels, whichever is greater @@ -227,13 +230,13 @@ void CalstepDialog::GetCalibrationStepSize(int FocalLength, double PixelSize, in double Declination, int distance, double *pImageScale, int *pStepSize) { double ImageScale = MyFrame::GetPixelScale(PixelSize, FocalLength, binning); // arc-sec per pixel - double totalDuration = (double) distance * ImageScale / (15.0 * GuideSpeed); // 15 arc-sec/sec is sidereal rate - double Pulse = totalDuration / DesiredSteps * 1000.0; // milliseconds at DEC=0 - double MaxPulse = totalDuration / MIN_STEPS * 1000.0; // max pulse size to still get MIN steps - Pulse = wxMin(MaxPulse, Pulse / cos(radians(Declination))); // UI forces abs(Dec) <= 60 degrees + double totalDuration = (double) distance * ImageScale / (15.0 * GuideSpeed); // 15 arc-sec/sec is sidereal rate + double Pulse = totalDuration / DesiredSteps * 1000.0; // milliseconds at DEC=0 + double MaxPulse = totalDuration / MIN_STEPS * 1000.0; // max pulse size to still get MIN steps + Pulse = wxMin(MaxPulse, Pulse / cos(radians(Declination))); // UI forces abs(Dec) <= 60 degrees if (pImageScale) *pImageScale = ImageScale; - *pStepSize = (int) ceil(Pulse / 50.0) * 50; // round up to nearest 50 ms, too-small pulses can lead to calibration problems + *pStepSize = (int) ceil(Pulse / 50.0) * 50; // round up to nearest 50 ms, too-small pulses can lead to calibration problems } void CalstepDialog::OnText(wxCommandEvent& evt) @@ -263,7 +266,7 @@ void CalstepDialog::DoRecalc(void) if (this->Validate() && this->TransferDataFromWindow()) { m_fPixelSize = m_pPixelSize->GetValue(); - m_pPixelSize->SetValue(m_fPixelSize); // For European locales, '.' -> ',' on output + m_pPixelSize->SetValue(m_fPixelSize); // For European locales, '.' -> ',' on output m_binning = m_binningChoice->GetSelection() + 1; m_fGuideSpeed = m_pGuideSpeed->GetValue(); m_pGuideSpeed->SetValue(m_fGuideSpeed); @@ -284,16 +287,16 @@ void CalstepDialog::DoRecalc(void) m_status->SetLabel(wxEmptyString); // Spin controls enforce numeric ranges - GetCalibrationStepSize(m_iFocalLength, m_fPixelSize, m_binning, m_fGuideSpeed, m_iNumSteps, - m_dDeclination, m_calibrationDistance, &m_fImageScale, &m_iStepSize); + GetCalibrationStepSize(m_iFocalLength, m_fPixelSize, m_binning, m_fGuideSpeed, m_iNumSteps, m_dDeclination, + m_calibrationDistance, &m_fImageScale, &m_iStepSize); m_bValidResult = true; } if (m_bValidResult) { - m_pImageScale->SetValue (wxString::Format ("%.2f", m_fImageScale)); - m_pRslt->SetValue (wxString::Format ("%3d", m_iStepSize)); + m_pImageScale->SetValue(wxString::Format("%.2f", m_fImageScale)); + m_pRslt->SetValue(wxString::Format("%3d", m_iStepSize)); } else { @@ -327,6 +330,4 @@ bool CalstepDialog::GetResults(int *focalLength, double *pixelSize, int *binning return false; } -CalstepDialog::~CalstepDialog(void) -{ -} +CalstepDialog::~CalstepDialog(void) { } diff --git a/src/calstep_dialog.h b/src/calstep_dialog.h index f94b664b1..023a7fbc6 100644 --- a/src/calstep_dialog.h +++ b/src/calstep_dialog.h @@ -39,7 +39,6 @@ class CalstepDialog : public wxDialog { private: - // wx UI controls wxBoxSizer *m_pVSizer; wxFlexGridSizer *m_pInputTableSizer; @@ -72,8 +71,11 @@ class CalstepDialog : public wxDialog void OnReset(wxCommandEvent& evt); public: - - enum { DEFAULT_STEPS = 12, DEFAULT_DISTANCE = 25 }; + enum + { + DEFAULT_STEPS = 12, + DEFAULT_DISTANCE = 25 + }; static const double DEFAULT_GUIDESPEED; CalstepDialog(wxWindow *parent, int focalLength, double pixelSize, int binning); @@ -81,8 +83,8 @@ class CalstepDialog : public wxDialog bool GetResults(int *focalLength, double *pixelSize, int *binning, int *stepSize, int *distance); static int GetCalibrationDistance(int focalLength, double pixelSize, int binning); - static void GetCalibrationStepSize(int focalLength, double pixelSize, int binning, double guideSpeed, - int desiredSteps, double declination, int distance, double *imageScale, int *stepSize); + static void GetCalibrationStepSize(int focalLength, double pixelSize, int binning, double guideSpeed, int desiredSteps, + double declination, int distance, double *imageScale, int *stepSize); private: void OnText(wxCommandEvent& evt); diff --git a/src/cam_INovaPLC.cpp b/src/cam_INovaPLC.cpp index cd29edaf5..44d010685 100644 --- a/src/cam_INovaPLC.cpp +++ b/src/cam_INovaPLC.cpp @@ -33,19 +33,19 @@ */ #include "phd.h" -#if defined (INOVA_PLC) -#include "camera.h" -#include "image_math.h" -#include "cam_INovaPLC.h" -#include "DSCAMAPI.h" +#if defined(INOVA_PLC) +# include "camera.h" +# include "image_math.h" +# include "cam_INovaPLC.h" +# include "DSCAMAPI.h" CameraINovaPLC::CameraINovaPLC() { Connected = FALSE; - Name=_T("i-Nova PLC-M"); - FullSize = wxSize(1280,1024); // Current size of a full frame - m_hasGuideOutput = true; // Do we have an ST4 port? - HasGainControl = true; // Can we adjust gain? + Name = _T("i-Nova PLC-M"); + FullSize = wxSize(1280, 1024); // Current size of a full frame + m_hasGuideOutput = true; // Do we have an ST4 port? + HasGainControl = true; // Can we adjust gain? } wxByte CameraINovaPLC::BitsPerPixel() @@ -61,10 +61,10 @@ bool CameraINovaPLC::Connect(const wxString& camId) DSCameraSetDataWide(true); DSCameraSetAeState(false); // Turn off auto-exposure - DSCameraGetRowTime(&RowTime); // Figure the row-time in microseconds -- this lets me figure the actual exp time - RawData = new unsigned short[1280*1024]; + DSCameraGetRowTime(&RowTime); // Figure the row-time in microseconds -- this lets me figure the actual exp time + RawData = new unsigned short[1280 * 1024]; - Connected = true; // Set global flag for being connected + Connected = true; // Set global flag for being connected return false; } @@ -92,20 +92,22 @@ bool CameraINovaPLC::ST4PulseGuideScope(int direction, int duration) bit1 - DEC+ bit2 - DEC- bit3 - RA-*/ - switch (direction) { - case WEST: - dircode = 0x01; - break; - case NORTH: - dircode = 0x02; - break; - case SOUTH: - dircode = 0x04; - break; - case EAST: - dircode = 0x08; - break; - default: return true; // bad direction passed in + switch (direction) + { + case WEST: + dircode = 0x01; + break; + case NORTH: + dircode = 0x02; + break; + case SOUTH: + dircode = 0x04; + break; + case EAST: + dircode = 0x08; + break; + default: + return true; // bad direction passed in } DSCameraSetGuidingPort(dircode); WorkerThread::MilliSleep(duration); @@ -117,7 +119,7 @@ bool CameraINovaPLC::Disconnect() { Connected = false; DSCameraUnInit(); - delete [] RawData; + delete[] RawData; return false; } @@ -127,33 +129,39 @@ bool CameraINovaPLC::Capture(int duration, usImage& img, int options, const wxRe int ysize = FullSize.GetHeight(); DS_CAMERA_STATUS rval; int ntries = 1; - if (img.Init(FullSize)) { + if (img.Init(FullSize)) + { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } int ExpDur = pFrame->RequestedExposureDuration(); - if (duration != ExpDur) { // reset the exp time - and pause -- we have had a change here from the current value + if (duration != ExpDur) + { // reset the exp time - and pause -- we have had a change here from the current value rval = DSCameraSetExposureTime(ExpDur * 1000 / RowTime); wxMilliSleep(100); } rval = DSCameraGrabFrame((BYTE *) RawData); - while (rval != STATUS_OK) { + while (rval != STATUS_OK) + { ntries++; rval = DSCameraGrabFrame((BYTE *) RawData); - //pFrame->StatusMsg(wxString::Format("%d %d",ntries,rval)); - if (ntries > 30) { + // pFrame->StatusMsg(wxString::Format("%d %d",ntries,rval)); + if (ntries > 30) + { pFrame->Alert("Timeout capturing frames - >30 bad in a row"); return true; } } - for (unsigned int i = 0; i > 8) | (RawData[i] << 8); + for (unsigned int i = 0; i < xsize * ysize; i++) + { + img.ImageData[i] = (RawData[i] >> 8) | (RawData[i] << 8); } - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return false; } diff --git a/src/cam_KWIQGuider.cpp b/src/cam_KWIQGuider.cpp index 56c6e24b9..8e0902671 100644 --- a/src/cam_KWIQGuider.cpp +++ b/src/cam_KWIQGuider.cpp @@ -37,16 +37,17 @@ #ifdef KWIQGUIDER_CAMERA -#include "cam_KWIQGuider.h" -#include "camera.h" +# include "cam_KWIQGuider.h" +# include "camera.h" -#include +# include using namespace KWIQ; class CameraKWIQGuider : public GuideCamera { KWIQ::KWIQGuider *KWIQguider; + public: CameraKWIQGuider(); bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; @@ -63,9 +64,9 @@ CameraKWIQGuider::CameraKWIQGuider() { Connected = false; Name = _T("KWIQGuider (KWIQGuider)"); - FullSize = wxSize(1280, 1024); // Current size of a full frame - m_hasGuideOutput = true; // Do we have an ST4 port? - HasGainControl = true; // Can we adjust gain? + FullSize = wxSize(1280, 1024); // Current size of a full frame + m_hasGuideOutput = true; // Do we have an ST4 port? + HasGainControl = true; // Can we adjust gain? KWIQguider = new KWIQGuider(); } @@ -80,7 +81,7 @@ bool CameraKWIQGuider::Connect(const wxString& camId) if (!KWIQguider->Connect()) return CamConnectFailed(_("Could not connect to KWIQGuider")); - Connected = true; // Set global flag for being connected + Connected = true; // Set global flag for being connected return false; } @@ -93,20 +94,22 @@ bool CameraKWIQGuider::Disconnect() bool CameraKWIQGuider::ST4PulseGuideScope(int direction, int duration) { - switch (direction) { - case WEST: - KWIQguider->Guide(guide_west, duration); - break; - case NORTH: - KWIQguider->Guide(guide_north, duration); - break; - case SOUTH: - KWIQguider->Guide(guide_south, duration); - break; - case EAST: - KWIQguider->Guide(guide_east, duration); - break; - default: return true; // bad direction passed in + switch (direction) + { + case WEST: + KWIQguider->Guide(guide_west, duration); + break; + case NORTH: + KWIQguider->Guide(guide_north, duration); + break; + case SOUTH: + KWIQguider->Guide(guide_south, duration); + break; + case EAST: + KWIQguider->Guide(guide_east, duration); + break; + default: + return true; // bad direction passed in } wxMilliSleep(duration + 10); @@ -119,23 +122,26 @@ bool CameraKWIQGuider::Capture(int duration, usImage& img, int options, const wx int xsize = FullSize.GetWidth(); int ysize = FullSize.GetHeight(); - if (img.Init(xsize,ysize)) { + if (img.Init(xsize, ysize)) + { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } - KWIQguider->SetGain((int)(GuideCameraGain / 24)); -// KWIQguider->SetGain((int)(GuideCameraGain / 7)); // Won't exceed 15, not < 1 + KWIQguider->SetGain((int) (GuideCameraGain / 24)); + // KWIQguider->SetGain((int)(GuideCameraGain / 7)); // Won't exceed 15, not < 1 struct raw_image *raw = KWIQguider->Expose(duration); - for (unsigned int i = 0; i < raw->width * raw->height; i++) { + for (unsigned int i = 0; i < raw->width * raw->height; i++) + { img.ImageData[i] = (unsigned short) raw->data[i]; } KWIQguider->FreeRawImage(raw); - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return false; } diff --git a/src/cam_LELXUSBWebcam.cpp b/src/cam_LELXUSBWebcam.cpp index be9fdc735..757a4292a 100644 --- a/src/cam_LELXUSBWebcam.cpp +++ b/src/cam_LELXUSBWebcam.cpp @@ -38,19 +38,21 @@ #if defined(LE_LXUSB_CAMERA) -#include "cam_LELXUSBWebcam.h" -#include "cam_wdm_base.h" -#include "cameras/ShoestringLXUSB_DLL.h" +# include "cam_LELXUSBWebcam.h" +# include "cam_wdm_base.h" +# include "cameras/ShoestringLXUSB_DLL.h" class CameraLELxUsbWebcam : public CameraLEWebcam { bool m_isOpen; + public: CameraLELxUsbWebcam(); virtual ~CameraLELxUsbWebcam(); bool Connect(const wxString& camId) override; bool Disconnect() override; + private: virtual bool LEControl(int actions); }; @@ -178,15 +180,15 @@ bool CameraLELxUsbWebcam::LEControl(int actions) if (actions & LECAMERA_LED_OFF) { - ledState = LXUSB_LED_OFF_RED; + ledState = LXUSB_LED_OFF_RED; } else if (actions & LECAMERA_LED_RED) { - ledState = LXUSB_LED_ON_RED; + ledState = LXUSB_LED_ON_RED; } else if (actions & LECAMERA_LED_GREEN) { - ledState = LXUSB_LED_ON_GREEN; + ledState = LXUSB_LED_ON_GREEN; } LXUSB_SetAll(frame1State, frame2State, shutterState, ampState, ledState); diff --git a/src/cam_LEParallelWebcam.cpp b/src/cam_LEParallelWebcam.cpp index 6c4f5076d..b5a616901 100644 --- a/src/cam_LEParallelWebcam.cpp +++ b/src/cam_LEParallelWebcam.cpp @@ -38,14 +38,15 @@ #if defined(LE_PARALLEL_CAMERA) -#include "cam_LEParallelWebcam.h" -#include "cam_wdm_base.h" +# include "cam_LEParallelWebcam.h" +# include "cam_wdm_base.h" class CameraLEParallelWebcam : public CameraLEWebcam { private: virtual bool LEControl(int actions); ParallelPort *m_pParallelPort; + public: CameraLEParallelWebcam(); virtual ~CameraLEParallelWebcam(); @@ -61,7 +62,7 @@ void _stdcall Out32(short PortAddress, short data); CameraLEParallelWebcam::CameraLEParallelWebcam(void) : CameraLEWebcam() { - Name=_T("Parallel LE Webcam"); + Name = _T("Parallel LE Webcam"); m_pParallelPort = NULL; } @@ -155,10 +156,10 @@ bool CameraLEParallelWebcam::LEControl(int actions) enum { - PARALLEL_BIT_TRANSFER = 1, - PARALLEL_BIT_UNUSED = 2, + PARALLEL_BIT_TRANSFER = 1, + PARALLEL_BIT_UNUSED = 2, PARALLEL_BIT_AMPLIFIER = 4, - PARALLEL_BIT_SHUTTER = 8 + PARALLEL_BIT_SHUTTER = 8 }; BYTE bitsToClear = 0; diff --git a/src/cam_LESerialWebcam.cpp b/src/cam_LESerialWebcam.cpp index 839d882dd..812183e37 100644 --- a/src/cam_LESerialWebcam.cpp +++ b/src/cam_LESerialWebcam.cpp @@ -38,8 +38,8 @@ #if defined(LE_SERIAL_CAMERA) -#include "cam_LESerialWebcam.h" -#include "cam_wdm_base.h" +# include "cam_LESerialWebcam.h" +# include "cam_wdm_base.h" class CameraLESerialWebcam : public CameraLEWebcam { @@ -55,24 +55,24 @@ class CameraLESerialWebcam : public CameraLEWebcam CameraLESerialWebcam(); virtual ~CameraLESerialWebcam(); - bool Connect(const wxString& camId) override; - bool Disconnect() override; - void ShowPropertyDialog() override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + void ShowPropertyDialog() override; private: bool LEControl(int actions); }; -#define LE_MASK_DTR 1 -#define LE_MASK_RTS 2 -//#define LE_INIT_DTR 4 -//#define LE_INIT_RTS 8 -#define LE_EXPO_DTR 16 -#define LE_EXPO_RTS 32 -#define LE_AMP_DTR 64 -#define LE_AMP_RTS 128 +# define LE_MASK_DTR 1 +# define LE_MASK_RTS 2 +// #define LE_INIT_DTR 4 +// #define LE_INIT_RTS 8 +# define LE_EXPO_DTR 16 +# define LE_EXPO_RTS 32 +# define LE_AMP_DTR 64 +# define LE_AMP_RTS 128 -#define LE_DEFAULT (LE_MASK_DTR | LE_MASK_RTS | /*LE_INIT_DTR | LE_INIT_RTS |*/ LE_EXPO_RTS | LE_AMP_DTR) +# define LE_DEFAULT (LE_MASK_DTR | LE_MASK_RTS | /*LE_INIT_DTR | LE_INIT_RTS |*/ LE_EXPO_RTS | LE_AMP_DTR) CameraLESerialWebcam::CameraLESerialWebcam(void) : CameraLEWebcam() @@ -98,8 +98,9 @@ bool CameraLESerialWebcam::Connect(const wxString& camId) m_UseAmp = pConfig->Profile.GetBoolean("/camera/serialLEWebcam/UseAmp", false); m_signalConfig = pConfig->Profile.GetInt("/camera/serialLEWebcam/SignalConfig", LE_DEFAULT); - m_Expo = (m_signalConfig & (LE_EXPO_DTR | LE_EXPO_RTS) ^ (LE_MASK_DTR | LE_MASK_RTS)) ? m_InvertedLogic : !m_InvertedLogic ; - m_Amp = (m_signalConfig & (LE_AMP_DTR | LE_AMP_RTS) ^ (LE_MASK_DTR | LE_MASK_RTS)) ? m_InvertedLogic : !m_InvertedLogic ; + m_Expo = + (m_signalConfig & (LE_EXPO_DTR | LE_EXPO_RTS) ^ (LE_MASK_DTR | LE_MASK_RTS)) ? m_InvertedLogic : !m_InvertedLogic; + m_Amp = (m_signalConfig & (LE_AMP_DTR | LE_AMP_RTS) ^ (LE_MASK_DTR | LE_MASK_RTS)) ? m_InvertedLogic : !m_InvertedLogic; m_pSerialPort = SerialPort::SerialPortFactory(); if (!m_pSerialPort) @@ -113,7 +114,7 @@ bool CameraLESerialWebcam::Connect(const wxString& camId) throw ERROR_INFO("LESerialWebcamClass::Connect: serial port connect failed"); } - //pConfig->Profile.SetString("/camera/serialLEWebcam/serialport", serialPorts[resp]); + // pConfig->Profile.SetString("/camera/serialLEWebcam/serialport", serialPorts[resp]); if (CameraLEWebcam::Connect(camId)) { @@ -254,7 +255,7 @@ struct LEWebcamDialog : public wxDialog wxCheckBox *m_pLEAmpRTS; wxCheckBox *m_pInvertedLogic; wxCheckBox *m_pUseAmp; - CVVidCapture* m_pVidCap; + CVVidCapture *m_pVidCap; void OnDefaults(wxCommandEvent& evt); void OnVidCapClick(wxCommandEvent& evt); @@ -274,8 +275,8 @@ void LEWebcamDialog::OnDefaults(wxCommandEvent& evt) m_pLEMaskDTR->SetValue(def & LE_MASK_DTR ? true : false); m_pLEMaskRTS->SetValue(def & LE_MASK_RTS ? true : false); - //m_pLEInitDTR->SetValue(def & LE_INIT_DTR ? true : false); - //m_pLEInitRTS->SetValue(def & LE_INIT_RTS ? true : false); + // m_pLEInitDTR->SetValue(def & LE_INIT_DTR ? true : false); + // m_pLEInitRTS->SetValue(def & LE_INIT_RTS ? true : false); m_pLEExpoDTR->SetValue(def & LE_EXPO_DTR ? true : false); m_pLEExpoRTS->SetValue(def & LE_EXPO_RTS ? true : false); m_pLEAmpDTR->SetValue(def & LE_AMP_DTR ? true : false); @@ -313,15 +314,14 @@ LEWebcamDialog::LEWebcamDialog(wxWindow *parent, CVVidCapture *vc) if (serialPorts.IsEmpty()) { - wxMessageBox(_("No serial ports found"),_("Error"), wxOK | wxICON_ERROR); + wxMessageBox(_("No serial ports found"), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("No Serial port found"); } wxString lastSerialPort = pConfig->Profile.GetString("/camera/serialLEWebcam/serialport", ""); int resp = serialPorts.Index(lastSerialPort); - m_pPortNum = new wxChoice(this, wxID_ANY,wxDefaultPosition, - wxDefaultSize, serialPorts ); + m_pPortNum = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, serialPorts); m_pPortNum->SetSelection(resp); pHSizer->Add(m_pPortNum, wxSizerFlags().Border(wxRIGHT | wxLEFT, 10).Expand()); @@ -347,13 +347,13 @@ LEWebcamDialog::LEWebcamDialog(wxWindow *parent, CVVidCapture *vc) m_pLEMaskRTS->SetValue(signal_config & LE_MASK_RTS ? true : false); pSignalSizer->Add(m_pLEMaskRTS, wxSizerFlags().Center()); - //pSignalSizer->Add(new wxStaticText(this, wxID_ANY, _T("LE Init"))); - //m_pLEInitDTR = new wxCheckBox(this, wxID_ANY, _T("")); - //m_pLEInitDTR->SetValue(signal_config & LE_INIT_DTR ? true : false); - //pSignalSizer->Add(m_pLEInitDTR, wxSizerFlags().Center()); - //m_pLEInitRTS = new wxCheckBox(this, wxID_ANY, _T("")); - //m_pLEInitRTS->SetValue(signal_config & LE_INIT_RTS ? true : false); - //pSignalSizer->Add(m_pLEInitRTS, wxSizerFlags().Center()); + // pSignalSizer->Add(new wxStaticText(this, wxID_ANY, _T("LE Init"))); + // m_pLEInitDTR = new wxCheckBox(this, wxID_ANY, _T("")); + // m_pLEInitDTR->SetValue(signal_config & LE_INIT_DTR ? true : false); + // pSignalSizer->Add(m_pLEInitDTR, wxSizerFlags().Center()); + // m_pLEInitRTS = new wxCheckBox(this, wxID_ANY, _T("")); + // m_pLEInitRTS->SetValue(signal_config & LE_INIT_RTS ? true : false); + // pSignalSizer->Add(m_pLEInitRTS, wxSizerFlags().Center()); pSignalSizer->Add(new wxStaticText(this, wxID_ANY, _T("LE Expo"))); m_pLEExpoDTR = new wxCheckBox(this, wxID_ANY, _T("")); @@ -389,7 +389,7 @@ LEWebcamDialog::LEWebcamDialog(wxWindow *parent, CVVidCapture *vc) if (m_pVidCap) { wxButton *pBtnVidCap = new wxButton(this, wxID_CONVERT, _("Webcam settings")); - pHSizer ->Add(pBtnVidCap, wxSizerFlags().Border(wxLEFT, 10)); + pHSizer->Add(pBtnVidCap, wxSizerFlags().Border(wxLEFT, 10)); } pVSizer->Add(pHSizer, wxSizerFlags().Border(wxALL, 10)); pVSizer->Add(CreateButtonSizer(wxOK | wxCANCEL), wxSizerFlags().Border(wxALL, 10)); @@ -408,21 +408,28 @@ void CameraLESerialWebcam::ShowPropertyDialog() { pConfig->Profile.SetString("/camera/serialLEWebcam/serialport", dlg.m_pPortNum->GetStringSelection()); - m_signalConfig = 0; - if (dlg.m_pLEMaskDTR->GetValue()) m_signalConfig |= LE_MASK_DTR; - if (dlg.m_pLEMaskRTS->GetValue()) m_signalConfig |= LE_MASK_RTS; - //if (dlg.m_pLEInitDTR->GetValue()) m_signalConfig |= LE_INIT_DTR; - //if (dlg.m_pLEInitRTS->GetValue()) m_signalConfig |= LE_INIT_RTS; - if (dlg.m_pLEExpoDTR->GetValue()) m_signalConfig |= LE_EXPO_DTR; - if (dlg.m_pLEExpoRTS->GetValue()) m_signalConfig |= LE_EXPO_RTS; - if (dlg.m_pLEAmpDTR->GetValue()) m_signalConfig |= LE_AMP_DTR; - if (dlg.m_pLEAmpRTS->GetValue()) m_signalConfig |= LE_AMP_RTS; + m_signalConfig = 0; + if (dlg.m_pLEMaskDTR->GetValue()) + m_signalConfig |= LE_MASK_DTR; + if (dlg.m_pLEMaskRTS->GetValue()) + m_signalConfig |= LE_MASK_RTS; + // if (dlg.m_pLEInitDTR->GetValue()) m_signalConfig |= LE_INIT_DTR; + // if (dlg.m_pLEInitRTS->GetValue()) m_signalConfig |= LE_INIT_RTS; + if (dlg.m_pLEExpoDTR->GetValue()) + m_signalConfig |= LE_EXPO_DTR; + if (dlg.m_pLEExpoRTS->GetValue()) + m_signalConfig |= LE_EXPO_RTS; + if (dlg.m_pLEAmpDTR->GetValue()) + m_signalConfig |= LE_AMP_DTR; + if (dlg.m_pLEAmpRTS->GetValue()) + m_signalConfig |= LE_AMP_RTS; m_InvertedLogic = dlg.m_pInvertedLogic->GetValue(); m_UseAmp = dlg.m_pUseAmp->GetValue(); - m_Expo = (m_signalConfig & (LE_EXPO_DTR | LE_EXPO_RTS) ^ (LE_MASK_DTR | LE_MASK_RTS)) ? m_InvertedLogic : !m_InvertedLogic ; - m_Amp = (m_signalConfig & (LE_AMP_DTR | LE_AMP_RTS) ^ (LE_MASK_DTR | LE_MASK_RTS)) ? m_InvertedLogic : !m_InvertedLogic ; + m_Expo = + (m_signalConfig & (LE_EXPO_DTR | LE_EXPO_RTS) ^ (LE_MASK_DTR | LE_MASK_RTS)) ? m_InvertedLogic : !m_InvertedLogic; + m_Amp = (m_signalConfig & (LE_AMP_DTR | LE_AMP_RTS) ^ (LE_MASK_DTR | LE_MASK_RTS)) ? m_InvertedLogic : !m_InvertedLogic; - pConfig->Profile.SetInt("/camera/serialLEWebcam/SignalConfig", m_signalConfig ); + pConfig->Profile.SetInt("/camera/serialLEWebcam/SignalConfig", m_signalConfig); pConfig->Profile.SetBoolean("/camera/serialLEWebcam/InvertedLogic", m_InvertedLogic); pConfig->Profile.SetBoolean("/camera/serialLEWebcam/UseAmp", m_UseAmp); diff --git a/src/cam_LESerialWebcam.h b/src/cam_LESerialWebcam.h index fd83f849e..8b1b378d7 100644 --- a/src/cam_LESerialWebcam.h +++ b/src/cam_LESerialWebcam.h @@ -45,4 +45,4 @@ class LESerialWebcamCameraFactory static GuideCamera *MakeLESerialWebcamCamera(); }; -#endif //CAM_LESERIALWEBCAM_H_INCLUDED +#endif // CAM_LESERIALWEBCAM_H_INCLUDED diff --git a/src/cam_LEwebcam.cpp b/src/cam_LEwebcam.cpp index 5b215f649..42b387c52 100644 --- a/src/cam_LEwebcam.cpp +++ b/src/cam_LEwebcam.cpp @@ -38,19 +38,17 @@ #if defined(LE_CAMERA) -#include "cam_wdm_base.h" +# include "cam_wdm_base.h" CameraLEWebcam::CameraLEWebcam(void) - : CameraWDM() + : CameraWDM() { Name = _T("Generic LE Webcam"); PropertyDialogType = PROPDLG_WHEN_CONNECTED; HasDelayParam = true; } -CameraLEWebcam::~CameraLEWebcam(void) -{ -} +CameraLEWebcam::~CameraLEWebcam(void) { } bool CameraLEWebcam::Connect(const wxString& camId) { @@ -99,12 +97,14 @@ bool CameraLEWebcam::Capture(int duration, usImage& img, int options, const wxRe else { // do the "amp on" part of the exposure - LEControl(LECAMERA_LED_GREEN | LECAMERA_SHUTTER_OPEN | LECAMERA_EXPOSURE_FIELD_A | LECAMERA_EXPOSURE_FIELD_B | LECAMERA_AMP_ON); + LEControl(LECAMERA_LED_GREEN | LECAMERA_SHUTTER_OPEN | LECAMERA_EXPOSURE_FIELD_A | LECAMERA_EXPOSURE_FIELD_B | + LECAMERA_AMP_ON); wxMilliSleep(ampOnTime); } // do the "amp off" part of the exposure. - LEControl(LECAMERA_LED_RED | LECAMERA_SHUTTER_OPEN | LECAMERA_EXPOSURE_FIELD_A | LECAMERA_EXPOSURE_FIELD_B | LECAMERA_AMP_OFF); + LEControl(LECAMERA_LED_RED | LECAMERA_SHUTTER_OPEN | LECAMERA_EXPOSURE_FIELD_A | LECAMERA_EXPOSURE_FIELD_B | + LECAMERA_AMP_OFF); wxMilliSleep(ampOffTime); // exposure complete - release the frame @@ -140,15 +140,15 @@ bool CameraLEWebcam::Capture(int duration, usImage& img, int options, const wxRe unsigned short *dptr2 = frame2.ImageData; unsigned short *dptr3 = frame3.ImageData; - UINT64 sum1=0; - UINT64 sum2=0; - UINT64 sum3=0; + UINT64 sum1 = 0; + UINT64 sum2 = 0; + UINT64 sum3 = 0; // we only use the data from the frame with the largest sum. // This is because we are not exactly sure when we will capture the "Long Exposure" // frame - for (unsigned int i = 0;i < frame1.NPixels; i++) + for (unsigned int i = 0; i < frame1.NPixels; i++) { sum1 += *dptr1++; sum2 += *dptr2++; diff --git a/src/cam_MeadeDSI.cpp b/src/cam_MeadeDSI.cpp index 643e98e52..2af7c0413 100644 --- a/src/cam_MeadeDSI.cpp +++ b/src/cam_MeadeDSI.cpp @@ -36,16 +36,16 @@ #ifdef MEADE_DSI_CAMERA -#include "camera.h" -#include "time.h" -#include "image_math.h" -#include "cam_MeadeDSI.h" +# include "camera.h" +# include "time.h" +# include "image_math.h" +# include "cam_MeadeDSI.h" -#if defined(__APPLE__) -# include -#endif +# if defined(__APPLE__) +# include +# endif -#include "DsiDevice.h" +# include "DsiDevice.h" class DsiDevice; @@ -57,21 +57,21 @@ class CameraDSI : public GuideCamera CameraDSI(); ~CameraDSI(); - bool CanSelectCamera() const override { return true; } - bool EnumCameras(wxArrayString& names, wxArrayString& ids) override; - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool HasNonGuiCapture() override; + bool CanSelectCamera() const override { return true; } + bool EnumCameras(wxArrayString& names, wxArrayString& ids) override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool HasNonGuiCapture() override; wxByte BitsPerPixel() override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - bool GetDevicePixelSize(double *devPixelSize) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + bool GetDevicePixelSize(double *devPixelSize) override; }; CameraDSI::CameraDSI() : MeadeCam(0) { Name = _T("Meade DSI"); - FullSize = wxSize(768,505); // CURRENTLY ULTRA-RAW + FullSize = wxSize(768, 505); // CURRENTLY ULTRA-RAW HasGainControl = true; } @@ -130,18 +130,25 @@ bool CameraDSI::Connect(const wxString& camId) } retval = !(MeadeCam->Open(DevNum)); -// wxMessageBox(wxString::Format("Color: %d\n%u x %u", -// MeadeCam->IsColor,MeadeCam->GetWidth(),MeadeCam->GetHeight())); - if (!retval) { - FullSize = wxSize(MeadeCam->GetWidth(),MeadeCam->GetHeight()); -// wxMessageBox(wxString::Format("%s\n%s (%d)\nColor: %d\n-II: %d\n%u x %u",MeadeCam->CcdName,MeadeCam->ModelName, MeadeCam->ModelNumber, -// MeadeCam->IsColor,MeadeCam->IsDsiII, FullSize.GetWidth(), FullSize.GetHeight()) + "\n" + MeadeCam->ErrorMessage); -// wxMessageBox(wxString::Format("%s\n%s (%d)\nColor: %d\n-USB2: %d\n%u x %u",MeadeCam->CcdName,MeadeCam->ModelName, MeadeCam->ModelNumber, -// MeadeCam->IsColor,MeadeCam->IsUSB2, FullSize.GetWidth(), FullSize.GetHeight()) + "\n" + MeadeCam->ErrorMessage); + // wxMessageBox(wxString::Format("Color: %d\n%u x %u", + // MeadeCam->IsColor,MeadeCam->GetWidth(),MeadeCam->GetHeight())); + if (!retval) + { + FullSize = wxSize(MeadeCam->GetWidth(), MeadeCam->GetHeight()); + // wxMessageBox(wxString::Format("%s\n%s (%d)\nColor: %d\n-II: %d\n%u x %u",MeadeCam->CcdName,MeadeCam->ModelName, + // MeadeCam->ModelNumber, + // MeadeCam->IsColor,MeadeCam->IsDsiII, FullSize.GetWidth(), FullSize.GetHeight()) + "\n" + + // MeadeCam->ErrorMessage); + // wxMessageBox(wxString::Format("%s\n%s (%d)\nColor: %d\n-USB2: %d\n%u x + // %u",MeadeCam->CcdName,MeadeCam->ModelName, MeadeCam->ModelNumber, + // MeadeCam->IsColor,MeadeCam->IsUSB2, FullSize.GetWidth(), FullSize.GetHeight()) + + // "\n" + MeadeCam->ErrorMessage); MeadeCam->Initialize(); MeadeCam->SetHighGain(true); - if (!MeadeCam->IsDsiIII) MeadeCam->SetDualExposureThreshold(501); - else MeadeCam->SetBinMode(1); + if (!MeadeCam->IsDsiIII) + MeadeCam->SetDualExposureThreshold(501); + else + MeadeCam->SetBinMode(1); MeadeCam->SetOffset(255); MeadeCam->SetFastReadoutSpeed(true); @@ -176,7 +183,7 @@ bool CameraDSI::GetDevicePixelSize(double *devPixelSize) else *devPixelSize = 7.5; - return false; // Pixel sizes are hard-coded + return false; // Pixel sizes are hard-coded } bool CameraDSI::Capture(int duration, usImage& img, int options, const wxRect& subframe) @@ -196,7 +203,7 @@ bool CameraDSI::Capture(int duration, usImage& img, int options, const wxRect& s // The AbortImage method does not appear to work with the DSI camera. If abort is called and the thread is terminated, the // pending image is still downloaded and PHD2 will crash -#if AbortActuallyWorks +# if AbortActuallyWorks CameraWatchdog watchdog(duration, GetTimeoutMs()); // wait for image to finish and d/l @@ -215,23 +222,26 @@ bool CameraDSI::Capture(int duration, usImage& img, int options, const wxRect& s return true; } } -#else // handle the pending image download, regardless +# else // handle the pending image download, regardless // We also need to prevent the thread from being killed when phd2 is closed WorkerThreadKillGuard _guard; - if (duration > 100) { + if (duration > 100) + { wxMilliSleep(duration - 100); // wait until near end of exposure, nicely } bool still_going = true; - while (still_going) { // wait for image to finish and d/l + while (still_going) + { // wait for image to finish and d/l wxMilliSleep(20); still_going = !(MeadeCam->ImageReady); } -#endif // end of waiting for the image +# endif // end of waiting for the image - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); if (options & CAPTURE_RECON) { @@ -239,7 +249,7 @@ bool CameraDSI::Capture(int duration, usImage& img, int options, const wxRect& s QuickLRecon(img); if (MeadeCam->IsDsiII) SquarePixels(img, 8.6, 8.3); - else if (!MeadeCam->IsDsiIII) // Original DSI + else if (!MeadeCam->IsDsiIII) // Original DSI SquarePixels(img, 9.6, 7.5); } diff --git a/src/cam_NebSBIG.cpp b/src/cam_NebSBIG.cpp index 67909d4d6..358001f99 100644 --- a/src/cam_NebSBIG.cpp +++ b/src/cam_NebSBIG.cpp @@ -35,16 +35,16 @@ #include "phd.h" #ifdef NEB_SBIG -#include "camera.h" -#include "time.h" -#include "image_math.h" -#include "cam_NebSBIG.h" -#include "socket_server.h" +# include "camera.h" +# include "time.h" +# include "image_math.h" +# include "cam_NebSBIG.h" +# include "socket_server.h" CameraNebSBIG::CameraNebSBIG() { Connected = false; - Name=_T("Nebulosity SBIG Guide chip"); + Name = _T("Nebulosity SBIG Guide chip"); } wxByte CameraNebSBIG::BitsPerPixel() @@ -56,8 +56,9 @@ bool CameraNebSBIG::Connect(const wxString& camId) { int xsize, ysize; bool retval = ServerSendCamConnect(xsize, ysize); - if (retval) return true; - FullSize = wxSize(xsize,ysize); + if (retval) + return true; + FullSize = wxSize(xsize, ysize); Connected = true; return false; } @@ -77,10 +78,10 @@ bool CameraNebSBIG::Capture(int duration, usImage& img, int options, const wxRec return true; } bool retval = ServerReqFrame(duration, img); - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return retval; - } bool CameraNebSBIG::ST4PulseGuideScope(int direction, int duration) diff --git a/src/cam_NebSBIG.h b/src/cam_NebSBIG.h index 925a16210..3f9af4e8f 100644 --- a/src/cam_NebSBIG.h +++ b/src/cam_NebSBIG.h @@ -40,12 +40,12 @@ class CameraNebSBIG : public GuideCamera { public: CameraNebSBIG(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool HasNonGuiCapture() override; - wxByte BitsPerPixel() override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - bool ST4PulseGuideScope(int direction, int duration) override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool HasNonGuiCapture() override; + wxByte BitsPerPixel() override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + bool ST4PulseGuideScope(int direction, int duration) override; }; #endif diff --git a/src/cam_OSPL130.cpp b/src/cam_OSPL130.cpp index c450266f0..2c464cf3f 100644 --- a/src/cam_OSPL130.cpp +++ b/src/cam_OSPL130.cpp @@ -13,9 +13,9 @@ #include "image_math.h" #include -#if defined (OS_PL130) -#include "cam_OSPL130.h" -#include "cameras/OSPL130API.h" +#if defined(OS_PL130) +# include "cam_OSPL130.h" +# include "cameras/OSPL130API.h" static bool DLLExists(const wxString& DLLName) { @@ -34,8 +34,8 @@ static bool DLLExists(const wxString& DLLName) CameraOpticstarPL130::CameraOpticstarPL130() { Connected = false; - Name=_T("Opticstar PL-130M"); - FullSize = wxSize(1280,1024); + Name = _T("Opticstar PL-130M"); + FullSize = wxSize(1280, 1024); m_hasGuideOutput = false; HasGainControl = false; Color = false; @@ -48,7 +48,7 @@ wxByte CameraOpticstarPL130::BitsPerPixel() bool CameraOpticstarPL130::Connect(const wxString& camId) { -// returns true on error + // returns true on error if (!DLLExists("OSPL130RT.dll")) return CamConnectFailed(_("Cannot find OSPL130RT.dll")); @@ -57,7 +57,7 @@ bool CameraOpticstarPL130::Connect(const wxString& camId) if (retval) return CamConnectFailed(_("Cannot init camera")); - //OSPL130_SetGain(6); + // OSPL130_SetGain(6); Connected = true; return false; } @@ -79,28 +79,32 @@ bool CameraOpticstarPL130::Capture(int duration, usImage& img, int options, cons DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } - if (OSPL130_Capture(mode,duration)) { + if (OSPL130_Capture(mode, duration)) + { pFrame->Alert(_("Cannot start exposure")); return true; } - if (duration > 100) { + if (duration > 100) + { wxMilliSleep(duration - 100); // wait until near end of exposure, nicely wxGetApp().Yield(); -// if (Abort) { -// MeadeCam->AbortImage(); -// return true; -// } + // if (Abort) { + // MeadeCam->AbortImage(); + // return true; + // } } - while (still_going) { // wait for image to finish and d/l + while (still_going) + { // wait for image to finish and d/l wxMilliSleep(20); OSPL130_IsExposing(&still_going); wxGetApp().Yield(); } // Download - OSPL130_GetRawImage(0,0,FullSize.GetWidth(),FullSize.GetHeight(), (void *) img.ImageData); + OSPL130_GetRawImage(0, 0, FullSize.GetWidth(), FullSize.GetHeight(), (void *) img.ImageData); // byte swap - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); if (Color && (options & CAPTURE_RECON)) QuickLRecon(img); diff --git a/src/cam_OSPL130.h b/src/cam_OSPL130.h index 4b058c2f1..a25ffd3ad 100644 --- a/src/cam_OSPL130.h +++ b/src/cam_OSPL130.h @@ -36,15 +36,15 @@ class CameraOpticstarPL130 : public GuideCamera { - bool Color; + bool Color; public: CameraOpticstarPL130(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - wxByte BitsPerPixel() override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + wxByte BitsPerPixel() override; }; -#endif //OSPL130DEF +#endif // OSPL130DEF diff --git a/src/cam_StarShootDSCI.cpp b/src/cam_StarShootDSCI.cpp index 374a2edc4..92307bd24 100644 --- a/src/cam_StarShootDSCI.cpp +++ b/src/cam_StarShootDSCI.cpp @@ -35,18 +35,18 @@ #include "phd.h" #ifdef ORION_DSCI -#include "camera.h" -#include "image_math.h" -#include "cam_StarShootDSCI.h" +# include "camera.h" +# include "image_math.h" +# include "cam_StarShootDSCI.h" CameraStarShootDSCI::CameraStarShootDSCI() { Connected = false; Name = _T("StarShoot DSCI"); - FullSize = wxSize(782,582); // This is *after* squaring + FullSize = wxSize(782, 582); // This is *after* squaring HasGainControl = true; - RawX = 752; // Also re-set in connect routine + RawX = 752; // Also re-set in connect routine RawY = 582; XPixelSize = 6.5; YPixelSize = 6.25; @@ -69,7 +69,7 @@ bool CameraStarShootDSCI::Connect(const wxString& camId) { // returns true on error - CameraDLL = LoadLibrary(TEXT("DSCI")); // load the DLL + CameraDLL = LoadLibrary(TEXT("DSCI")); // load the DLL if (!CameraDLL) return CamConnectFailed(wxT("Can't find DSCI.dll")); @@ -77,59 +77,69 @@ bool CameraStarShootDSCI::Connect(const wxString& camId) // assign functions B_V_DLLFUNC OCP_openUSB = (B_V_DLLFUNC) GetProcAddress(CameraDLL, "openUSB"); - if (!OCP_openUSB) { + if (!OCP_openUSB) + { FreeLibrary(CameraDLL); return CamConnectFailed(_("Didn't find openUSB in DLL")); } bool retval = OCP_openUSB(); - if (!retval) { + if (!retval) + { FreeLibrary(CameraDLL); return true; } // Good to go, now get other functions B_V_DLLFUNC OCP_isUSB2 = (B_V_DLLFUNC) GetProcAddress(CameraDLL, "IsUSB20"); - if (!OCP_isUSB2) { + if (!OCP_isUSB2) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("Didn't find %s in DLL"), "IsUSB20")); } UI_V_DLLFUNC OCP_Width = (UI_V_DLLFUNC) GetProcAddress(CameraDLL, "CAM_Width"); - if (!OCP_Width) { + if (!OCP_Width) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("Didn't find %s in DLL"), "CAM_Width")); } UI_V_DLLFUNC OCP_Height = (UI_V_DLLFUNC) GetProcAddress(CameraDLL, "CAM_Height"); - if (!OCP_Height) { + if (!OCP_Height) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("Didn't find %s in DLL"), "CAM_Height")); } - OCP_sendEP1_1BYTE = (V_V_DLLFUNC)GetProcAddress(CameraDLL,"sendEP1_1BYTE"); - if (!OCP_sendEP1_1BYTE) { + OCP_sendEP1_1BYTE = (V_V_DLLFUNC) GetProcAddress(CameraDLL, "sendEP1_1BYTE"); + if (!OCP_sendEP1_1BYTE) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("Didn't find %s in DLL"), "sendEP1_1BYTE")); } - OCP_sendRegister = (OCPREGFUNC)GetProcAddress(CameraDLL,"sendRegister"); - if (!OCP_sendRegister) { + OCP_sendRegister = (OCPREGFUNC) GetProcAddress(CameraDLL, "sendRegister"); + if (!OCP_sendRegister) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("Didn't find %s in DLL"), "sendRegister")); } - OCP_Exposure = (B_I_DLLFUNC)GetProcAddress(CameraDLL,"CAM_Exposure"); - if (!OCP_Exposure) { + OCP_Exposure = (B_I_DLLFUNC) GetProcAddress(CameraDLL, "CAM_Exposure"); + if (!OCP_Exposure) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("Didn't find %s in DLL"), "CAM_Exposure")); } - OCP_Exposing = (B_V_DLLFUNC)GetProcAddress(CameraDLL,"CAM_Exposing"); - if (!OCP_Exposing) { + OCP_Exposing = (B_V_DLLFUNC) GetProcAddress(CameraDLL, "CAM_Exposing"); + if (!OCP_Exposing) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("Didn't find %s in DLL"), "CAM_Exposing")); } - OCP_ProcessedBuffer = (USP_V_DLLFUNC)GetProcAddress(CameraDLL,"CAM_ProcessedBuffer"); - if (!OCP_ProcessedBuffer) { + OCP_ProcessedBuffer = (USP_V_DLLFUNC) GetProcAddress(CameraDLL, "CAM_ProcessedBuffer"); + if (!OCP_ProcessedBuffer) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("Didn't find %s in DLL"), "CAM_ProcessedBuffer")); } @@ -154,19 +164,21 @@ bool CameraStarShootDSCI::Capture(int duration, usImage& img, int options, const unsigned char retval = 0; if (duration != lastdur) { - retval = OCP_sendRegister(duration,0,(unsigned char) (GuideCameraGain * 63 / 100),120,true,0,false,false,false,false,false,ampoff,false,false); + retval = OCP_sendRegister(duration, 0, (unsigned char) (GuideCameraGain * 63 / 100), 120, true, 0, false, false, false, + false, false, ampoff, false, false); lastdur = duration; } - if (retval) { + if (retval) + { pFrame->Alert(_("Problem sending register to StarShoot")); return true; } if (USB2) - retval = OCP_Exposure(1); // Start USB2 exposure + retval = OCP_Exposure(1); // Start USB2 exposure else - retval = OCP_Exposure(0); // Start USB1.1 exposure + retval = OCP_Exposure(0); // Start USB1.1 exposure if (!retval) { @@ -191,12 +203,12 @@ bool CameraStarShootDSCI::Capture(int duration, usImage& img, int options, const return true; } - const unsigned short *rawptr = OCP_ProcessedBuffer(); // Copy raw data in + const unsigned short *rawptr = OCP_ProcessedBuffer(); // Copy raw data in memcpy(img.ImageData, rawptr, img.NPixels * sizeof(unsigned short)); SubtractDark(img); QuickLRecon(img); - SquarePixels(img,XPixelSize,YPixelSize); + SquarePixels(img, XPixelSize, YPixelSize); return false; } diff --git a/src/cam_StarShootDSCI.h b/src/cam_StarShootDSCI.h index 545440810..159ff5e47 100644 --- a/src/cam_StarShootDSCI.h +++ b/src/cam_StarShootDSCI.h @@ -40,13 +40,13 @@ class CameraStarShootDSCI : public GuideCamera { - bool USB2; // Is it a USB2 connection? - int RawX; // Raw size of array + bool USB2; // Is it a USB2 connection? + int RawX; // Raw size of array int RawY; int lastdur; // duration last asked for -- if same, don't need to resend registers - float XPixelSize; // pixel dimensions - needed for squaring + float XPixelSize; // pixel dimensions - needed for squaring float YPixelSize; - HINSTANCE CameraDLL; // Handle to DLL + HINSTANCE CameraDLL; // Handle to DLL V_V_DLLFUNC OCP_sendEP1_1BYTE; OCPREGFUNC OCP_sendRegister; B_I_DLLFUNC OCP_Exposure; @@ -55,9 +55,9 @@ class CameraStarShootDSCI : public GuideCamera public: CameraStarShootDSCI(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; bool HasNonGuiCapture() override { return true; } wxByte BitsPerPixel() override; }; diff --git a/src/cam_altair.cpp b/src/cam_altair.cpp index 8a79b8daf..250443523 100644 --- a/src/cam_altair.cpp +++ b/src/cam_altair.cpp @@ -37,23 +37,25 @@ #ifdef ALTAIR -#include "cam_altair.h" -#include "altaircam.h" +# include "cam_altair.h" +# include "altaircam.h" -#ifdef __WINDOWS__ +# ifdef __WINDOWS__ struct SDKLib { HMODULE m_module; -#define SDK(f) \ - decltype(Altaircam_ ## f) *f; -#define SDK_OPT(f) SDK(f) -# include "cameras/altaircam_sdk.h" -#undef SDK -#undef SDK_OPT +# define SDK(f) decltype(Altaircam_##f) *f; +# define SDK_OPT(f) SDK(f) +# include "cameras/altaircam_sdk.h" +# undef SDK +# undef SDK_OPT - SDKLib() : m_module(nullptr) { } + SDKLib() + : m_module(nullptr) + { + } ~SDKLib() { Unload(); } bool _Load(LPCTSTR filename, const char *prefix) @@ -72,23 +74,27 @@ struct SDKLib try { -#define _GPA(f) \ - std::ostringstream os; \ - os << prefix << #f; \ - std::string name = os.str(); \ - f = reinterpret_cast(GetProcAddress(m_module, name.c_str())) -#define SDK(f) do { \ - _GPA(f); \ - if (!f) \ - throw name; \ - } while (false); -#define SDK_OPT(f) do { \ - _GPA(f); \ - } while (false); -# include "cameras/altaircam_sdk.h" -#undef SDK -#undef SDK_OPT -#undef _GPA +# define _GPA(f) \ + std::ostringstream os; \ + os << prefix << #f; \ + std::string name = os.str(); \ + f = reinterpret_cast(GetProcAddress(m_module, name.c_str())) +# define SDK(f) \ + do \ + { \ + _GPA(f); \ + if (!f) \ + throw name; \ + } while (false); +# define SDK_OPT(f) \ + do \ + { \ + _GPA(f); \ + } while (false); +# include "cameras/altaircam_sdk.h" +# undef SDK +# undef SDK_OPT +# undef _GPA } catch (const std::string& name) { @@ -102,15 +108,9 @@ struct SDKLib return true; } - bool Load() - { - return _Load(_T("altaircam.dll"), "Altaircam_"); - } + bool Load() { return _Load(_T("altaircam.dll"), "Altaircam_"); } - bool LoadLegacy() - { - return _Load(_T("AltairCam_legacy.dll"), "Toupcam_"); - } + bool LoadLegacy() { return _Load(_T("AltairCam_legacy.dll"), "Toupcam_"); } void Unload() { @@ -122,11 +122,14 @@ struct SDKLib } }; -#endif // __WINDOWS__ +# endif // __WINDOWS__ struct AltairCamera : public GuideCamera { - enum { MAX_DISCARD_FRAMES = 5 }; + enum + { + MAX_DISCARD_FRAMES = 5 + }; AltairCamType m_type; SDKLib m_sdk; @@ -187,9 +190,8 @@ AltairCameraDlg::AltairCameraDlg(wxWindow *parent) wxStaticBoxSizer *sbSizer3 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, _("Settings")), wxVERTICAL); wxBoxSizer *sizer1 = new wxBoxSizer(wxHORIZONTAL); - m_reduceRes = new wxCheckBox(this, wxID_ANY, - wxString::Format(_("Reduced Resolution (by ~%d%%)"), 20), - wxDefaultPosition, wxDefaultSize, 0); + m_reduceRes = new wxCheckBox( + this, wxID_ANY, wxString::Format(_("Reduced Resolution (by ~%d%%)"), 20), wxDefaultPosition, wxDefaultSize, 0); sizer1->Add(m_reduceRes, 0, wxALL, 5); sbSizer3->Add(sizer1); @@ -199,8 +201,9 @@ AltairCameraDlg::AltairCameraDlg(wxWindow *parent) int width = StringWidth(this, _T("00")); m_framesToDiscard = pFrame->MakeSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, AltairCamera::MAX_DISCARD_FRAMES, 0); - m_framesToDiscard->SetToolTip(_("Discard this many frames whan capturing starts. " - "Useful for preventing initial under-exposed frames interfering with automatic star selection.")); + m_framesToDiscard->SetToolTip( + _("Discard this many frames whan capturing starts. " + "Useful for preventing initial under-exposed frames interfering with automatic star selection.")); sizer2->Add(m_framesToDiscard, 0, wxALL, 5); sbSizer3->Add(sizer2); @@ -229,16 +232,16 @@ static int GetConfigDiscardFrames() } AltairCamera::AltairCamera(AltairCamType type) - : - m_type(type), - m_buffer(nullptr), - m_capturing(false) + : m_type(type) + , m_buffer(nullptr) + , m_capturing(false) { Name = _T("Altair Camera"); Connected = false; m_hasGuideOutput = true; HasSubframes = false; - HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to true later when the camera is connected + HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to + // true later when the camera is connected PropertyDialogType = PROPDLG_WHEN_DISCONNECTED; this->m_framesToDiscard = GetConfigDiscardFrames(); @@ -367,8 +370,7 @@ bool AltairCamera::Connect(const wxString& camIdArg) bool hasSkip = (pai->model->flag & ALTAIRCAM_FLAG_BINSKIP_SUPPORTED) != 0; m_isColor = (pai->model->flag & ALTAIRCAM_FLAG_MONO) == 0; - Debug.Write(wxString::Format("ALTAIR: isColor = %d, hasROI = %d, hasSkip = %d\n", - m_isColor, hasROI, hasSkip)); + Debug.Write(wxString::Format("ALTAIR: isColor = %d, hasROI = %d, hasSkip = %d\n", m_isColor, hasROI, hasSkip)); int width, height; if (FAILED(m_sdk.get_Resolution(m_handle, 0, &width, &height))) @@ -378,7 +380,8 @@ bool AltairCamera::Connect(const wxString& camIdArg) } delete[] m_buffer; - m_buffer = new unsigned char[width * height]; // new SDK has issues with some ROI functions needing full resolution buffer size + m_buffer = + new unsigned char[width * height]; // new SDK has issues with some ROI functions needing full resolution buffer size m_reduceResolution = pConfig->Profile.GetBoolean("/camera/Altair/ReduceResolution", false); if (hasROI && m_reduceResolution) @@ -415,7 +418,7 @@ bool AltairCamera::Connect(const wxString& camIdArg) m_sdk.put_Option(m_handle, ALTAIRCAM_OPTION_RAW, 1); -#if 0 +# if 0 // TODO: this is the initiailization code copied from cam_touptek.cpp // I was hoping this one of these might help with the problem of the first // frame exposure being very low, but it had no effect. Leaving these @@ -435,14 +438,13 @@ bool AltairCamera::Connect(const wxString& camIdArg) m_sdk.put_Option(m_handle, ALTAIRCAM_OPTION_FFC, 0); m_sdk.put_Option(m_handle, ALTAIRCAM_OPTION_DFC, 0); m_sdk.put_Option(m_handle, ALTAIRCAM_OPTION_SHARPENING, 0); -#endif +# endif m_sdk.put_AutoExpoEnable(m_handle, 0); m_frame = wxRect(FullSize); - Debug.Write(wxString::Format("Altair: frame (%d,%d)+(%d,%d)\n", - m_frame.x, m_frame.y, m_frame.width, m_frame.height)); + Debug.Write(wxString::Format("Altair: frame (%d,%d)+(%d,%d)\n", m_frame.x, m_frame.y, m_frame.width, m_frame.height)); if (hasROI && m_reduceResolution) { @@ -468,7 +470,7 @@ bool AltairCamera::GetDevicePixelSize(double *devPixelSize) return true; *devPixelSize = m_devicePixelSize; - return false; // Pixel size is known in any case + return false; // Pixel size is known in any case } void AltairCamera::ShowPropertyDialog() @@ -523,21 +525,21 @@ void __stdcall CameraCallback(unsigned int event, void *pCallbackCtx) } } -//static void flush_buffered_image(int cameraId, usImage& img) +// static void flush_buffered_image(int cameraId, usImage& img) //{ -// enum { NUM_IMAGE_BUFFERS = 2 }; // camera has 2 internal frame buffers +// enum { NUM_IMAGE_BUFFERS = 2 }; // camera has 2 internal frame buffers // -// // clear buffered frames if any +// // clear buffered frames if any // -// for (unsigned int num_cleared = 0; num_cleared < NUM_IMAGE_BUFFERS; num_cleared++) -// { -// ASI_ERROR_CODE status = ASIGetVideoData(cameraId, (unsigned char *) img.ImageData, img.NPixels * sizeof(unsigned short), 0); -// if (status != ASI_SUCCESS) -// break; // no more buffered frames +// for (unsigned int num_cleared = 0; num_cleared < NUM_IMAGE_BUFFERS; num_cleared++) +// { +// ASI_ERROR_CODE status = ASIGetVideoData(cameraId, (unsigned char *) img.ImageData, img.NPixels * sizeof(unsigned +// short), 0); if (status != ASI_SUCCESS) +// break; // no more buffered frames // -// Debug.Write(wxString::Format("Altair: getimagedata clearbuf %u ret %d\n", num_cleared + 1, status)); -// } -//} +// Debug.Write(wxString::Format("Altair: getimagedata clearbuf %u ret %d\n", num_cleared + 1, status)); +// } +// } bool AltairCamera::Capture(int duration, usImage& img, int options, const wxRect& subframe) { @@ -552,8 +554,7 @@ bool AltairCamera::Capture(int duration, usImage& img, int options, const wxRect long exposureUS = duration * 1000; unsigned int cur_exp; - if (m_sdk.get_ExpoTime(m_handle, &cur_exp) == 0 && - cur_exp != exposureUS) + if (m_sdk.get_ExpoTime(m_handle, &cur_exp) == 0 && cur_exp != exposureUS) { Debug.Write(wxString::Format("Altair: set CONTROL_EXPOSURE %d\n", exposureUS)); m_sdk.put_ExpoTime(m_handle, exposureUS); @@ -561,8 +562,7 @@ bool AltairCamera::Capture(int duration, usImage& img, int options, const wxRect long new_gain = cam_gain(m_minGain, m_maxGain, GuideCameraGain); unsigned short cur_gain; - if (m_sdk.get_ExpoAGain(m_handle, &cur_gain) == 0 && - new_gain != cur_gain) + if (m_sdk.get_ExpoAGain(m_handle, &cur_gain) == 0 && new_gain != cur_gain) { Debug.Write(wxString::Format("Altair: set CONTROL_GAIN %d%% %d\n", GuideCameraGain, new_gain)); m_sdk.put_ExpoAGain(m_handle, new_gain); @@ -601,11 +601,11 @@ bool AltairCamera::Capture(int duration, usImage& img, int options, const wxRect CameraWatchdog watchdog(duration, duration + GetTimeoutMs() + 10000); // total timeout is 2 * duration + 15s (typically) // do not wait here, as we will miss a frame most likely, leading to poor flow of frames. -// if (WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY) && -// (WorkerThread::TerminateRequested() || StopCapture())) -// { -// return true; -// } + // if (WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY) && + // (WorkerThread::TerminateRequested() || StopCapture())) + // { + // return true; + // } while (true) // PullImage retry loop { diff --git a/src/cam_ascom.cpp b/src/cam_ascom.cpp index 3cd5e9a0a..a726083f9 100644 --- a/src/cam_ascom.cpp +++ b/src/cam_ascom.cpp @@ -37,19 +37,19 @@ #if defined(ASCOM_CAMERA) -#include "camera.h" -#include "comdispatch.h" -#include "time.h" -#include "image_math.h" -#include -#include -#include -#include +# include "camera.h" +# include "comdispatch.h" +# include "time.h" +# include "image_math.h" +# include +# include +# include +# include -#include "cam_ascom.h" +# include "cam_ascom.h" -#include -#include +# include +# include class CameraASCOM : public GuideCamera { @@ -68,27 +68,25 @@ class CameraASCOM : public GuideCamera double m_driverPixelSize; public: - bool Color; CameraASCOM(const wxString& choice); ~CameraASCOM(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool HasNonGuiCapture() override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - void ShowPropertyDialog() override; - bool ST4PulseGuideScope(int direction, int duration) override; - wxByte BitsPerPixel() override; - bool GetDevicePixelSize(double *devPixelSize) override; - bool SetCoolerOn(bool on) override; - bool SetCoolerSetpoint(double temperature) override; - bool GetCoolerStatus(bool *on, double *setpoint, double *power, double *temperature) override; - bool GetSensorTemperature(double *temperature) override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool HasNonGuiCapture() override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + void ShowPropertyDialog() override; + bool ST4PulseGuideScope(int direction, int duration) override; + wxByte BitsPerPixel() override; + bool GetDevicePixelSize(double *devPixelSize) override; + bool SetCoolerOn(bool on) override; + bool SetCoolerSetpoint(double temperature) override; + bool GetCoolerStatus(bool *on, double *setpoint, double *power, double *temperature) override; + bool GetSensorTemperature(double *temperature) override; private: - bool Create(DispatchObj *obj, DispatchClass *cls); bool AbortExposure(); @@ -97,11 +95,8 @@ class CameraASCOM : public GuideCamera }; // Frequently used IDs -static DISPID dispid_setxbin, dispid_setybin, dispid_startx, dispid_starty, - dispid_numx, dispid_numy, - dispid_startexposure, dispid_abortexposure, dispid_stopexposure, - dispid_imageready, dispid_imagearray, - dispid_ispulseguiding, dispid_pulseguide, +static DISPID dispid_setxbin, dispid_setybin, dispid_startx, dispid_starty, dispid_numx, dispid_numy, dispid_startexposure, + dispid_abortexposure, dispid_stopexposure, dispid_imageready, dispid_imagearray, dispid_ispulseguiding, dispid_pulseguide, dispid_cooleron, dispid_coolerpower, dispid_ccdtemperature, dispid_setccdtemperature; inline static void LogExcep(HRESULT hr, const wxString& prefix, const EXCEPINFO& excep) @@ -125,20 +120,20 @@ static bool ASCOM_SetBin(IDispatch *cam, int binning, EXCEPINFO *excep) DISPPARAMS dispParms; dispParms.cArgs = 1; dispParms.rgvarg = rgvarg; - dispParms.cNamedArgs = 1; // PropPut kludge + dispParms.cNamedArgs = 1; // PropPut kludge dispParms.rgdispidNamedArgs = &dispidNamed; Variant vRes; HRESULT hr; - if (FAILED(hr = cam->Invoke(dispid_setxbin, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_setxbin, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "invoke setxbin", *excep); return true; } - if (FAILED(hr = cam->Invoke(dispid_setybin, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_setybin, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "invoke setybin", *excep); return true; @@ -158,39 +153,39 @@ static bool ASCOM_SetROI(IDispatch *cam, const wxRect& roi, EXCEPINFO *excep) DISPPARAMS dispParms; dispParms.cArgs = 1; dispParms.rgvarg = rgvarg; - dispParms.cNamedArgs = 1; // PropPut kludge + dispParms.cNamedArgs = 1; // PropPut kludge dispParms.rgdispidNamedArgs = &dispidNamed; Variant vRes; HRESULT hr; rgvarg[0].lVal = roi.GetLeft(); - if (FAILED(hr = cam->Invoke(dispid_startx, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_startx, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "set startx", *excep); return true; } rgvarg[0].lVal = roi.GetTop(); - if (FAILED(hr = cam->Invoke(dispid_starty, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_starty, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "set starty", *excep); return true; } rgvarg[0].lVal = roi.GetWidth(); - if (FAILED(hr = cam->Invoke(dispid_numx, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_numx, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "set numx", *excep); return true; } rgvarg[0].lVal = roi.GetHeight(); - if (FAILED(hr = cam->Invoke(dispid_numy, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_numy, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "set numy", *excep); return true; @@ -212,8 +207,8 @@ static bool ASCOM_AbortExposure(IDispatch *cam, EXCEPINFO *excep) Variant vRes; HRESULT hr; - if (FAILED(hr = cam->Invoke(dispid_abortexposure, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_abortexposure, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "invoke abortexposure", *excep); return true; @@ -235,8 +230,8 @@ static bool ASCOM_StopExposure(IDispatch *cam, EXCEPINFO *excep) Variant vRes; HRESULT hr; - if (FAILED(hr = cam->Invoke(dispid_stopexposure, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_stopexposure, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "invoke stopexposure", *excep); return true; @@ -251,7 +246,7 @@ static bool ASCOM_StartExposure(IDispatch *cam, double duration, bool dark, EXCE VARIANTARG rgvarg[2]; rgvarg[1].vt = VT_R8; - rgvarg[1].dblVal = duration; + rgvarg[1].dblVal = duration; rgvarg[0].vt = VT_BOOL; rgvarg[0].boolVal = dark ? VARIANT_FALSE : VARIANT_TRUE; @@ -264,8 +259,8 @@ static bool ASCOM_StartExposure(IDispatch *cam, double duration, bool dark, EXCE Variant vRes; HRESULT hr; - if (FAILED(hr = cam->Invoke(dispid_startexposure, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_startexposure, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "invoke startexposure", *excep); return true; @@ -287,8 +282,8 @@ static bool ASCOM_ImageReady(IDispatch *cam, bool *ready, EXCEPINFO *excep) Variant vRes; HRESULT hr; - if (FAILED(hr = cam->Invoke(dispid_imageready, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_imageready, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "invoke imageready", *excep); return true; @@ -298,8 +293,8 @@ static bool ASCOM_ImageReady(IDispatch *cam, bool *ready, EXCEPINFO *excep) return false; } -static bool ASCOM_Image(IDispatch *cam, usImage& img, bool is_subframe, const wxRect& roi, - wxSize *size, const wxSize& max_size, bool *swap_axes, EXCEPINFO *excep) +static bool ASCOM_Image(IDispatch *cam, usImage& img, bool is_subframe, const wxRect& roi, wxSize *size, const wxSize& max_size, + bool *swap_axes, EXCEPINFO *excep) { // returns true on error, false if OK @@ -312,8 +307,8 @@ static bool ASCOM_Image(IDispatch *cam, usImage& img, bool is_subframe, const wx Variant vRes; HRESULT hr; - if (FAILED(hr = cam->Invoke(dispid_imagearray, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, - &dispParms, &vRes, excep, nullptr))) + if (FAILED(hr = cam->Invoke( + dispid_imagearray, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &dispParms, &vRes, excep, nullptr))) { LogExcep(hr, "invoke imagearray", *excep); return true; @@ -328,7 +323,7 @@ static bool ASCOM_Image(IDispatch *cam, usImage& img, bool is_subframe, const wx SafeArrayGetLBound(rawarray, 2, &lbound2); long *rawdata; - hr = SafeArrayAccessData(rawarray, (void**)&rawdata); + hr = SafeArrayAccessData(rawarray, (void **) &rawdata); if (hr != S_OK) { hr = SafeArrayDestroyData(rawarray); @@ -340,8 +335,8 @@ static bool ASCOM_Image(IDispatch *cam, usImage& img, bool is_subframe, const wx if (!is_subframe && !*swap_axes && xsize < ysize && max_size.x > max_size.y) { - Debug.Write(wxString::Format("ASCOM camera: array axes are flipped (%dx%d) vs (%dx%d)\n", - xsize, ysize, max_size.x, max_size.y)); + Debug.Write(wxString::Format( + "ASCOM camera: array axes are flipped (%dx%d) vs (%dx%d)\n", xsize, ysize, max_size.x, max_size.y)); *swap_axes = true; } @@ -414,10 +409,12 @@ static bool ASCOM_IsMoving(IDispatch *cam) ExcepInfo excep; Variant vRes; - if (FAILED(hr = cam->Invoke(dispid_ispulseguiding, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &dispParms, &vRes, &excep, nullptr))) + if (FAILED(hr = cam->Invoke(dispid_ispulseguiding, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET, &dispParms, &vRes, + &excep, nullptr))) { LogExcep(hr, "invoke ispulseguiding", excep); - pFrame->Alert(ExcepMsg(_("ASCOM driver failed checking IsPulseGuiding. See the debug log for more information."), excep)); + pFrame->Alert( + ExcepMsg(_("ASCOM driver failed checking IsPulseGuiding. See the debug log for more information."), excep)); return false; } @@ -439,9 +436,7 @@ CameraASCOM::CameraASCOM(const wxString& choice) m_bitsPerPixel = 0; } -CameraASCOM::~CameraASCOM() -{ -} +CameraASCOM::~CameraASCOM() { } wxByte CameraASCOM::BitsPerPixel() { @@ -555,7 +550,10 @@ bool CameraASCOM::Connect(const wxString& camId) struct ConnectInBg : public ConnectCameraInBg { CameraASCOM *cam; - ConnectInBg(CameraASCOM *cam_) : cam(cam_) { } + ConnectInBg(CameraASCOM *cam_) + : cam(cam_) + { + } bool Entry() { GITObjRef dobj(cam->m_gitEntry); @@ -587,21 +585,27 @@ bool CameraASCOM::Connect(const wxString& camId) if (!driver.GetProp(&vRes, L"CanPulseGuide")) { Debug.AddLine(ExcepMsg("CanPulseGuide", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CanPulseGuide")); + return CamConnectFailed( + wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), + "CanPulseGuide")); } m_hasGuideOutput = ((vRes.boolVal != VARIANT_FALSE) ? true : false); if (!driver.GetProp(&vRes, L"CanAbortExposure")) { Debug.AddLine(ExcepMsg("CanAbortExposure", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CanAbortExposure")); + return CamConnectFailed( + wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), + "CanAbortExposure")); } m_canAbortExposure = vRes.boolVal != VARIANT_FALSE ? true : false; if (!driver.GetProp(&vRes, L"CanStopExposure")) { Debug.AddLine(ExcepMsg("CanStopExposure", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CanStopExposure")); + return CamConnectFailed( + wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), + "CanStopExposure")); } m_canStopExposure = vRes.boolVal != VARIANT_FALSE ? true : false; @@ -616,14 +620,16 @@ bool CameraASCOM::Connect(const wxString& camId) if (!driver.GetProp(&vRes, L"CameraXSize")) { Debug.AddLine(ExcepMsg("CameraXSize", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CameraXSize")); + return CamConnectFailed(wxString::Format( + _("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CameraXSize")); } m_maxSize.SetWidth((int) vRes.lVal); if (!driver.GetProp(&vRes, L"CameraYSize")) { Debug.AddLine(ExcepMsg("CameraYSize", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CameraYSize")); + return CamConnectFailed(wxString::Format( + _("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CameraYSize")); } m_maxSize.SetHeight((int) vRes.lVal); @@ -632,7 +638,7 @@ bool CameraASCOM::Connect(const wxString& camId) if (!driver.GetProp(&vRes, L"MaxADU")) { Debug.AddLine(ExcepMsg("MaxADU", driver.Excep())); - m_bitsPerPixel = 16; // assume 16 BPP + m_bitsPerPixel = 16; // assume 16 BPP } else { @@ -647,9 +653,8 @@ bool CameraASCOM::Connect(const wxString& camId) DriverVersion = vRes.iVal; } - if (DriverVersion > 1 && // We can check the color sensor status of the cam - driver.GetProp(&vRes, L"SensorType") && - vRes.iVal > 1) + if (DriverVersion > 1 && // We can check the color sensor status of the cam + driver.GetProp(&vRes, L"SensorType") && vRes.iVal > 1) { Color = true; } @@ -659,14 +664,16 @@ bool CameraASCOM::Connect(const wxString& camId) if (!driver.GetProp(&vRes, L"PixelSizeX")) { Debug.AddLine(ExcepMsg("PixelSizeX", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "PixelSizeX")); + return CamConnectFailed(wxString::Format( + _("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "PixelSizeX")); } m_driverPixelSize = vRes.dblVal; if (!driver.GetProp(&vRes, L"PixelSizeY")) { Debug.AddLine(ExcepMsg("PixelSizeY", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "PixelSizeY")); + return CamConnectFailed(wxString::Format( + _("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "PixelSizeY")); } m_driverPixelSize = wxMax(m_driverPixelSize, vRes.dblVal); @@ -690,14 +697,18 @@ bool CameraASCOM::Connect(const wxString& camId) if (!driver.GetProp(&vRes, L"CanSetCCDTemperature")) { Debug.AddLine(ExcepMsg("CanSetCCDTemperature", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CanSetCCDTemperature")); + return CamConnectFailed(wxString::Format( + _("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), + "CanSetCCDTemperature")); } m_canSetCoolerTemperature = vRes.boolVal != VARIANT_FALSE ? true : false; if (!driver.GetProp(&vRes, L"CanGetCoolerPower")) { Debug.AddLine(ExcepMsg("CanGetCoolerPower", driver.Excep())); - return CamConnectFailed(wxString::Format(_("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), "CanGetCoolerPower")); + return CamConnectFailed(wxString::Format( + _("ASCOM driver missing the %s property. Please report this error to your ASCOM driver provider."), + "CanGetCoolerPower")); } m_canGetCoolerPower = vRes.boolVal != VARIANT_FALSE ? true : false; } @@ -836,7 +847,8 @@ bool CameraASCOM::SetCoolerOn(bool on) if (!cam.PutProp(dispid_cooleron, on)) { Debug.AddLine(ExcepMsg(wxString::Format("ASCOM error turning camera cooler %s", on ? "on" : "off"), cam.Excep())); - pFrame->Alert(ExcepMsg(wxString::Format(_("ASCOM error turning camera cooler %s"), on ? _("on") : _("off")), cam.Excep())); + pFrame->Alert( + ExcepMsg(wxString::Format(_("ASCOM error turning camera cooler %s"), on ? _("on") : _("off")), cam.Excep())); return true; } @@ -1039,7 +1051,7 @@ bool CameraASCOM::Capture(int duration, usImage& img, int options, const wxRect& bool takeDark = HasShutter && ShutterClosed; // Start the exposure - if (ASCOM_StartExposure(cam.IDisp(), (double)duration / 1000.0, takeDark, &excep)) + if (ASCOM_StartExposure(cam.IDisp(), (double) duration / 1000.0, takeDark, &excep)) { Debug.AddLine(ExcepMsg("ASCOM_StartExposure failed", excep)); pFrame->Alert(ExcepMsg(_("ASCOM error -- Cannot start exposure with given parameters"), excep)); @@ -1058,7 +1070,7 @@ bool CameraASCOM::Capture(int duration, usImage& img, int options, const wxRect& } } - while (true) // wait for image to finish and d/l + while (true) // wait for image to finish and d/l { wxMilliSleep(20); bool ready; @@ -1071,8 +1083,7 @@ bool CameraASCOM::Capture(int duration, usImage& img, int options, const wxRect& } if (ready) break; - if (WorkerThread::InterruptRequested() && - (WorkerThread::TerminateRequested() || AbortExposure())) + if (WorkerThread::InterruptRequested() && (WorkerThread::TerminateRequested() || AbortExposure())) { return true; } @@ -1104,14 +1115,15 @@ bool CameraASCOM::ST4PulseGuideScope(int direction, int duration) if (!m_hasGuideOutput) return true; - if (!pMount || !pMount->IsConnected()) return false; + if (!pMount || !pMount->IsConnected()) + return false; GITObjRef cam(m_gitEntry); // Start the motion (which may stop on its own) VARIANTARG rgvarg[2]; rgvarg[1].vt = VT_I2; - rgvarg[1].iVal = direction; + rgvarg[1].iVal = direction; rgvarg[0].vt = VT_I4; rgvarg[0].lVal = (long) duration; @@ -1127,14 +1139,14 @@ bool CameraASCOM::ST4PulseGuideScope(int direction, int duration) Variant vRes; HRESULT hr; - if (FAILED(hr = cam.IDisp()->Invoke(dispid_pulseguide, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, - &dispParms, &vRes, &excep, nullptr))) + if (FAILED(hr = cam.IDisp()->Invoke( + dispid_pulseguide, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispParms, &vRes, &excep, nullptr))) { LogExcep(hr, "invoke pulseguide", excep); return true; } - if (watchdog.Time() < duration) // likely returned right away and not after move - enter poll loop + if (watchdog.Time() < duration) // likely returned right away and not after move - enter poll loop { while (ASCOM_IsMoving(cam.IDisp())) { diff --git a/src/cam_ascom.h b/src/cam_ascom.h index 45eeb0180..75fb40830 100644 --- a/src/cam_ascom.h +++ b/src/cam_ascom.h @@ -1,35 +1,35 @@ /* -* cam_ascom.h -* Open PHD Guiding -* -* Copyright (c) 2020 Andy Galasso. -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * cam_ascom.h + * Open PHD Guiding + * + * Copyright (c) 2020 Andy Galasso. + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef CAM_ASCOM_INCLUDED #define CAM_ASCOM_INCLUDED diff --git a/src/cam_atik16.cpp b/src/cam_atik16.cpp index 97c734d67..81379f8bb 100644 --- a/src/cam_atik16.cpp +++ b/src/cam_atik16.cpp @@ -35,13 +35,13 @@ #if defined(ATIK16) -#include "cam_atik16.h" -#include "camera.h" -#include "image_math.h" +# include "cam_atik16.h" +# include "camera.h" +# include "image_math.h" -#include +# include -#include "ArtemisHSCAPI.h" +# include "ArtemisHSCAPI.h" class CameraAtik16 : public GuideCamera { @@ -55,18 +55,18 @@ class CameraAtik16 : public GuideCamera ~CameraAtik16(); bool CanSelectCamera() const override { return true; } - bool EnumCameras(wxArrayString& names, wxArrayString& ids) override; - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool HasNonGuiCapture() override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; + bool EnumCameras(wxArrayString& names, wxArrayString& ids) override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool HasNonGuiCapture() override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; - bool ST4PulseGuideScope(int direction, int duration) override; - void ClearGuidePort(); - wxByte BitsPerPixel() override; + bool ST4PulseGuideScope(int direction, int duration) override; + void ClearGuidePort(); + wxByte BitsPerPixel() override; - bool Color; - bool HSModel; + bool Color; + bool HSModel; private: bool ST4HasNonGuiMove(); @@ -78,7 +78,7 @@ CameraAtik16::CameraAtik16(bool hsmodel, bool color) { Connected = false; Name = _T("Atik 16"); - FullSize = wxSize(1280,1024); + FullSize = wxSize(1280, 1024); m_hasGuideOutput = true; HasGainControl = true; Color = color; @@ -151,9 +151,10 @@ bool CameraAtik16::Connect(const wxString& camId) { // returns true on error - if (Cam_Handle) { + if (Cam_Handle) + { Debug.Write("Already connected\n"); - return false; // Already connected + return false; // Already connected } wxString err; if (!LoadDLL(&err)) @@ -173,7 +174,7 @@ bool CameraAtik16::Connect(const wxString& camId) Cam_Handle = ArtemisConnect(devnum); // Connect to first avail camera - if (!Cam_Handle) // Connection failed + if (!Cam_Handle) // Connection failed { return CamConnectFailed(wxString::Format(_("Atik camera connection failed - Driver version %d"), ArtemisAPIVersion())); } @@ -206,15 +207,15 @@ bool CameraAtik16::Connect(const wxString& camId) int NumTempSensors; int TECMin; int TECMax; - int level,setpoint; + int level, setpoint; TECFlags = TECMin = TECMax = level = setpoint = 0; - ArtemisTemperatureSensorInfo(Cam_Handle,0,&NumTempSensors); + ArtemisTemperatureSensorInfo(Cam_Handle, 0, &NumTempSensors); ArtemisCoolingInfo(Cam_Handle, &TECFlags, &level, &TECMin, &TECMax, &setpoint); if ((TECFlags & 0x04) && !(TECFlags & 0x08)) // On/off only, no setpoints - setpoint = 1; // Turn it on + setpoint = 1; // Turn it on else - setpoint = 10 * 100; // should be 10C + setpoint = 10 * 100; // should be 10C if (TECFlags & 0x02) // can be controlled ArtemisSetCooling(Cam_Handle, setpoint); @@ -232,29 +233,39 @@ bool CameraAtik16::Connect(const wxString& camId) bool CameraAtik16::ST4PulseGuideScope(int direction, int duration) { int axis; - //wxStopWatch swatch; + // wxStopWatch swatch; // Output pins are NC, Com, RA+(W), Dec+(N), Dec-(S), RA-(E) ?? http://www.starlight-xpress.co.uk/faq.htm - switch (direction) { -/* case WEST: axis = ARTEMIS_GUIDE_WEST; break; // 0111 0000 - case NORTH: axis = ARTEMIS_GUIDE_NORTH; break; // 1011 0000 - case SOUTH: axis = ARTEMIS_GUIDE_SOUTH; break; // 1101 0000 - case EAST: axis = ARTEMIS_GUIDE_EAST; break; // 1110 0000*/ - case WEST: axis = 2; break; // 0111 0000 - case NORTH: axis = 0; break; // 1011 0000 - case SOUTH: axis = 1; break; // 1101 0000 - case EAST: axis = 3; break; // 1110 0000 - default: return true; // bad direction passed in + switch (direction) + { + /* case WEST: axis = ARTEMIS_GUIDE_WEST; break; // 0111 0000 + case NORTH: axis = ARTEMIS_GUIDE_NORTH; break; // 1011 0000 + case SOUTH: axis = ARTEMIS_GUIDE_SOUTH; break; // 1101 0000 + case EAST: axis = ARTEMIS_GUIDE_EAST; break; // 1110 0000*/ + case WEST: + axis = 2; + break; // 0111 0000 + case NORTH: + axis = 0; + break; // 1011 0000 + case SOUTH: + axis = 1; + break; // 1101 0000 + case EAST: + axis = 3; + break; // 1110 0000 + default: + return true; // bad direction passed in } - //swatch.Start(); - ArtemisPulseGuide(Cam_Handle,axis,duration); // returns after pulse - //long t1 = swatch.Time(); - //wxMessageBox(wxString::Format("%ld",t1)); -/* ArtemisGuide(Cam_Handle,axis); - wxMilliSleep(duration); - ArtemisStopGuiding(Cam_Handle);*/ - //if (duration > 50) wxMilliSleep(duration - 50); // wait until it's mostly done - //wxMilliSleep(duration + 10); + // swatch.Start(); + ArtemisPulseGuide(Cam_Handle, axis, duration); // returns after pulse + // long t1 = swatch.Time(); + // wxMessageBox(wxString::Format("%ld",t1)); + /* ArtemisGuide(Cam_Handle,axis); + wxMilliSleep(duration); + ArtemisStopGuiding(Cam_Handle);*/ + // if (duration > 50) wxMilliSleep(duration - 50); // wait until it's mostly done + // wxMilliSleep(duration + 10); return false; } @@ -307,12 +318,14 @@ bool CameraAtik16::Capture(int duration, usImage& img, int options, const wxRect return true; } - wxRect frame; // raw subframe to meet camera subframe requirements, may be a superset of the requested subframe - unbinned coords - wxPoint subframePos; // position of PHD2 subframe within frame - binned coords + wxRect frame; // raw subframe to meet camera subframe requirements, may be a superset of the requested subframe - unbinned + // coords + wxPoint subframePos; // position of PHD2 subframe within frame - binned coords if (useSubframe) { - // Round height up to next multiple of 2 to workaround bug where the camera returns incorrect data when the subframe height is odd. + // Round height up to next multiple of 2 to workaround bug where the camera returns incorrect data when the subframe + // height is odd. int w = subframe.width * Binning; int x = subframe.x * Binning; if (w & 1) @@ -361,8 +374,7 @@ bool CameraAtik16::Capture(int duration, usImage& img, int options, const wxRect wxMilliSleep(100); else wxMilliSleep(30); - if (WorkerThread::InterruptRequested() && - (WorkerThread::TerminateRequested() || StopCapture(Cam_Handle))) + if (WorkerThread::InterruptRequested() && (WorkerThread::TerminateRequested() || StopCapture(Cam_Handle))) { return true; } diff --git a/src/cam_atik16.h b/src/cam_atik16.h index 641f54ffa..0283d6718 100644 --- a/src/cam_atik16.h +++ b/src/cam_atik16.h @@ -40,4 +40,4 @@ class AtikCameraFactory static GuideCamera *MakeAtikCamera(bool hsModel, bool color); }; -#endif //ATIK16DEF +#endif // ATIK16DEF diff --git a/src/cam_firewire.h b/src/cam_firewire.h index 9c9102b37..48099cd0f 100644 --- a/src/cam_firewire.h +++ b/src/cam_firewire.h @@ -35,37 +35,36 @@ #ifndef FIREWIREDEF #define FIREWIREDEF -#if defined (__APPLE__) -#include -#include -#elif defined (CLOSED_SOURCE) -#include "tisudshl.h" +#if defined(__APPLE__) +# include +# include +#elif defined(CLOSED_SOURCE) +# include "tisudshl.h" #endif class CameraFirewire : public GuideCamera { -#if defined (__APPLE__) +#if defined(__APPLE__) dc1394_t *m_dcContext; dc1394camera_t *camera; -#elif defined (CLOSED_SOURCE) - DShowLib::Grabber* m_pGrabber; +#elif defined(CLOSED_SOURCE) + DShowLib::Grabber *m_pGrabber; DShowLib::tFrameHandlerSinkPtr pSink; - DShowLib::tIVCDAbsoluteValuePropertyPtr m_pExposureAbs; - DShowLib::tIVCDRangePropertyPtr m_pGain; + DShowLib::tIVCDAbsoluteValuePropertyPtr m_pExposureAbs; + DShowLib::tIVCDRangePropertyPtr m_pGain; long GainMax; #endif public: - CameraFirewire(); ~CameraFirewire(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool HasNonGuiCapture() override; - wxByte BitsPerPixel() override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - void InitCapture() override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool HasNonGuiCapture() override; + wxByte BitsPerPixel() override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + void InitCapture() override; }; #endif diff --git a/src/cam_firewire_IC.cpp b/src/cam_firewire_IC.cpp index f05cc3ae9..b984e448b 100644 --- a/src/cam_firewire_IC.cpp +++ b/src/cam_firewire_IC.cpp @@ -34,27 +34,27 @@ #include "phd.h" -#if defined (__WINDOWS__) && defined (FIREWIRE_CAMERA) -#include "camera.h" -#include "time.h" -#include "image_math.h" -#include -#include -#include +#if defined(__WINDOWS__) && defined(FIREWIRE_CAMERA) +# include "camera.h" +# include "time.h" +# include "image_math.h" +# include +# include +# include // Deal with 8-bit vs. 16-bit?? // Take care of gain capability // Start stream in InitCapture()? -#include "cam_firewire.h" +# include "cam_firewire.h" using namespace _DSHOWLIB_NAMESPACE; CameraFirewire::CameraFirewire() { Connected = false; Name = _T("The Imaging Source"); - FullSize = wxSize(1280,1024); + FullSize = wxSize(1280, 1024); HasGainControl = true; m_hasGuideOutput = false; } @@ -64,9 +64,9 @@ wxByte CameraFirewire::BitsPerPixel() return 8; } -//CameraFirewire::~CameraFirewire () { -// ; -//} +// CameraFirewire::~CameraFirewire () { +// ; +// } bool CameraFirewire::Connect(const wxString& camId) { int CamNum, ModeNum; @@ -77,158 +77,273 @@ bool CameraFirewire::Connect(const wxString& camId) wxTextFile *debugfile; int debugstep = 0; - if (debug) { - debugfile = new wxTextFile(Debug.GetLogDir() + PATHSEPSTR + wxString::Format("PHD_debug_%ld.txt",wxGetLocalTime())); - if (debugfile->Exists()) debugfile->Open(); - else debugfile->Create(); + if (debug) + { + debugfile = new wxTextFile(Debug.GetLogDir() + PATHSEPSTR + wxString::Format("PHD_debug_%ld.txt", wxGetLocalTime())); + if (debugfile->Exists()) + debugfile->Open(); + else + debugfile->Create(); wxDateTime now = wxDateTime::Now(); debugfile->AddLine(wxString::Format("DEBUG %s %s -- ", APPNAME, FULLVER) + now.FormatDate() + now.FormatTime()); } - try { - if (debug) { debugfile->AddLine(wxString::Format("1: Init library")); debugfile->Write(); } + try + { + if (debug) + { + debugfile->AddLine(wxString::Format("1: Init library")); + debugfile->Write(); + } // Init the TIS library - if( ! DShowLib::InitLibrary( "ISB3200016679" ) ) { // license key check + if (!DShowLib::InitLibrary("ISB3200016679")) + { // license key check return CamConnectFailed(_("Cannot initialize ImageCapture library")); } - if (debug) { debugfile->AddLine(wxString::Format("2: Create grabber")); debugfile->Write(); } + if (debug) + { + debugfile->AddLine(wxString::Format("2: Create grabber")); + debugfile->Write(); + } m_pGrabber = new DShowLib::Grabber(); - if (debug) { debugfile->AddLine(wxString::Format("3: Find cameras")); debugfile->Write(); } + if (debug) + { + debugfile->AddLine(wxString::Format("3: Find cameras")); + debugfile->Write(); + } Grabber::tVidCapDevListPtr pVidCapDevList = m_pGrabber->getAvailableVideoCaptureDevices(); - if( pVidCapDevList == 0 || pVidCapDevList->empty() ) + if (pVidCapDevList == 0 || pVidCapDevList->empty()) return CamConnectFailed(_("No camera found")); int NCams = (int) pVidCapDevList->size(); - if (debug) { debugfile->AddLine(wxString::Format("4: Found %d cams",NCams)); debugfile->Write(); } + if (debug) + { + debugfile->AddLine(wxString::Format("4: Found %d cams", NCams)); + debugfile->Write(); + } // deal with > 1 cam CamNum = 0; - if (NCams > 1) { - for( Grabber::tVidCapDevList::iterator it = pVidCapDevList->begin(); - it != pVidCapDevList->end(); ++it ) { + if (NCams > 1) + { + for (Grabber::tVidCapDevList::iterator it = pVidCapDevList->begin(); it != pVidCapDevList->end(); ++it) + { Names.Add(it->toString()); } - CamNum = wxGetSingleChoiceIndex(_("Select Camera"),_("Camera"),Names); + CamNum = wxGetSingleChoiceIndex(_("Select Camera"), _("Camera"), Names); if (CamNum == -1) return true; } // Open camera - if (debug) { debugfile->AddLine(wxString::Format("5: Open Camera")); debugfile->Write(); } - retval = m_pGrabber->openDev( pVidCapDevList->at( CamNum ) ); + if (debug) + { + debugfile->AddLine(wxString::Format("5: Open Camera")); + debugfile->Write(); + } + retval = m_pGrabber->openDev(pVidCapDevList->at(CamNum)); if (!retval) return CamConnectFailed(_("Cannot open camera")); - if (debug) { debugfile->AddLine(wxString(pVidCapDevList->at(CamNum).toString())); debugfile->Write(); } + if (debug) + { + debugfile->AddLine(wxString(pVidCapDevList->at(CamNum).toString())); + debugfile->Write(); + } - if (debug) { debugfile->AddLine(wxString::Format("6: Get Video formats")); debugfile->Write(); } + if (debug) + { + debugfile->AddLine(wxString::Format("6: Get Video formats")); + debugfile->Write(); + } // Get video formats Grabber::tVidFmtListPtr pVidFmtList = m_pGrabber->getAvailableVideoFormats(); - if ((pVidFmtList == 0) || pVidFmtList->empty()) { + if ((pVidFmtList == 0) || pVidFmtList->empty()) + { m_pGrabber->closeDev(); return CamConnectFailed(_("Cannot get list of video modes")); } int NModes = pVidFmtList->size(); - if (debug) { debugfile->AddLine(wxString::Format("7: Found %d formats",NModes)); debugfile->Write(); } + if (debug) + { + debugfile->AddLine(wxString::Format("7: Found %d formats", NModes)); + debugfile->Write(); + } - // Names.Clear(); - // ModeNum = 0; + // Names.Clear(); + // ModeNum = 0; wxString Name; - // if (NModes > 1) { - ModeNum = -1; - int i = 0; - for( Grabber::tVidFmtList::iterator it = pVidFmtList->begin(); - it != pVidFmtList->end(); ++it, i++ ) { - // Names.Add(it->toString()); - Name = wxString(it->toString()); - if (debug) {debugfile->AddLine(wxString(it->toString())); debugfile->Write(); } - if (Name.Find("Y800") != wxNOT_FOUND) { - ModeNum = i; - break; - } + // if (NModes > 1) { + ModeNum = -1; + int i = 0; + for (Grabber::tVidFmtList::iterator it = pVidFmtList->begin(); it != pVidFmtList->end(); ++it, i++) + { + // Names.Add(it->toString()); + Name = wxString(it->toString()); + if (debug) + { + debugfile->AddLine(wxString(it->toString())); + debugfile->Write(); } - //ModeNum = wxGetSingleChoiceIndex(_T("Select Mode"),_T("Mode"),Names); - if (ModeNum == -1) { - return CamConnectFailed(_("Cannot find a Y800 mode")); + if (Name.Find("Y800") != wxNOT_FOUND) + { + ModeNum = i; + break; } - // } + } + // ModeNum = wxGetSingleChoiceIndex(_T("Select Mode"),_T("Mode"),Names); + if (ModeNum == -1) + { + return CamConnectFailed(_("Cannot find a Y800 mode")); + } + // } - if (debug) { debugfile->AddLine(wxString::Format("8: Set format %d",ModeNum)); debugfile->Write(); } + if (debug) + { + debugfile->AddLine(wxString::Format("8: Set format %d", ModeNum)); + debugfile->Write(); + } // Set the video format m_pGrabber->setVideoFormat(pVidFmtList->at(ModeNum)); // Set some more format things - if (debug) { debugfile->AddLine(wxString::Format("9: Set FPS")); debugfile->Write(); } - // retval = m_pGrabber->setFPS(7.5); // No need to run higher than this - // if (!retval) wxMessageBox (_T("Could not set to 7.5 FPS")); - if (debug) { debugfile->AddLine(wxString::Format("10: Turn off auto-exposure")); debugfile->Write(); } - retval = m_pGrabber->setProperty(CameraControl_Exposure,false); - if (!retval) { + if (debug) + { + debugfile->AddLine(wxString::Format("9: Set FPS")); + debugfile->Write(); + } + // retval = m_pGrabber->setFPS(7.5); // No need to run higher than this + // if (!retval) wxMessageBox (_T("Could not set to 7.5 FPS")); + if (debug) + { + debugfile->AddLine(wxString::Format("10: Turn off auto-exposure")); + debugfile->Write(); + } + retval = m_pGrabber->setProperty(CameraControl_Exposure, false); + if (!retval) + { return CamConnectFailed(_("Could not turn off auto-exposure")); } // Setup the frame handler - if (debug) { debugfile->AddLine(wxString::Format("11: Setup frame handler")); debugfile->Write(); } - pSink = FrameHandlerSink::create(eY800, 4 ); // not sure why I even need 4... - if (!pSink) { + if (debug) + { + debugfile->AddLine(wxString::Format("11: Setup frame handler")); + debugfile->Write(); + } + pSink = FrameHandlerSink::create(eY800, 4); // not sure why I even need 4... + if (!pSink) + { return CamConnectFailed(_("Cannot setup frame handler")); } - if (debug) { debugstep = 1; debugfile->AddLine(wxString::Format("12: Set snap mode")); debugfile->Write(); } - pSink->setSnapMode( true ); + if (debug) + { + debugstep = 1; + debugfile->AddLine(wxString::Format("12: Set snap mode")); + debugfile->Write(); + } + pSink->setSnapMode(true); - if (debug) { debugstep = 2; debugfile->AddLine(wxString::Format("12a: Setting SinkType")); debugfile->Write(); } + if (debug) + { + debugstep = 2; + debugfile->AddLine(wxString::Format("12a: Setting SinkType")); + debugfile->Write(); + } retval = m_pGrabber->setSinkType(pSink); - if (!retval) { + if (!retval) + { Debug.Write("cam_firewire_IC: Could not set sink type\n"); return CamConnectFailed(_("FireWire camera setup failed")); } // Get info I need - if (debug) { debugstep = 3; debugfile->AddLine(wxString::Format("12b: Getting name for mode %d",ModeNum)); debugfile->Write(); } + if (debug) + { + debugstep = 3; + debugfile->AddLine(wxString::Format("12b: Getting name for mode %d", ModeNum)); + debugfile->Write(); + } Name = wxString(pVidCapDevList->at(CamNum).toString()); - if (debug) { debugstep = 4; debugfile->AddLine(_T(" Name: " + Name)); debugfile->Write(); } - if (debug) { debugstep = 5; debugfile->AddLine(wxString::Format("12c: Getting size for mode %d",ModeNum)); debugfile->Write(); } + if (debug) + { + debugstep = 4; + debugfile->AddLine(_T(" Name: " + Name)); + debugfile->Write(); + } + if (debug) + { + debugstep = 5; + debugfile->AddLine(wxString::Format("12c: Getting size for mode %d", ModeNum)); + debugfile->Write(); + } SIZE sz = pVidFmtList->at(ModeNum).getSize(); - if (debug) {debugstep = 6; debugfile->AddLine(_T("Size found - setting FullSize")); debugfile->Write(); } - FullSize = wxSize((int)sz.cx, (int)sz.cy); + if (debug) + { + debugstep = 6; + debugfile->AddLine(_T("Size found - setting FullSize")); + debugfile->Write(); + } + FullSize = wxSize((int) sz.cx, (int) sz.cy); - if (debug) { debugstep = 7; debugfile->AddLine(wxString::Format("Image: %d %d Camera: ",FullSize.GetWidth(),FullSize.GetHeight()) + Name); debugfile->Write(); } + if (debug) + { + debugstep = 7; + debugfile->AddLine(wxString::Format("Image: %d %d Camera: ", FullSize.GetWidth(), FullSize.GetHeight()) + Name); + debugfile->Write(); + } // Get the stream prepared, but don't start yet - going to start/stop on each frame grab - if (debug) { debugstep = 8; debugfile->AddLine(wxString::Format("13: Prepare Live")); debugfile->Write(); } + if (debug) + { + debugstep = 8; + debugfile->AddLine(wxString::Format("13: Prepare Live")); + debugfile->Write(); + } retval = m_pGrabber->prepareLive(false); // not using their renderer - if (!retval) { + if (!retval) + { return CamConnectFailed(_("Could not start Live view")); } // Get pointer to the exposure duration functin needed - if (debug) { debugfile->AddLine(wxString::Format("14: Get VCD properties")); debugfile->Write(); } + if (debug) + { + debugfile->AddLine(wxString::Format("14: Get VCD properties")); + debugfile->Write(); + } tIVCDPropertyItemsPtr pItems = m_pGrabber->getAvailableVCDProperties(); - if( pItems != 0 ) { - tIVCDPropertyItemPtr pExposureItem = pItems->findItem( VCDID_Exposure ); - tIVCDPropertyElementPtr pExposureValueElement = pExposureItem->findElement( VCDElement_Value ); - if (pExposureValueElement != 0) { + if (pItems != 0) + { + tIVCDPropertyItemPtr pExposureItem = pItems->findItem(VCDID_Exposure); + tIVCDPropertyElementPtr pExposureValueElement = pExposureItem->findElement(VCDElement_Value); + if (pExposureValueElement != 0) + { pExposureValueElement->getInterfacePtr(m_pExposureAbs); - if (m_pExposureAbs == 0) { + if (m_pExposureAbs == 0) + { pFrame->Alert(_("Warning - cannot directly control exposure duration - running in auto-exposure")); - m_pGrabber->setProperty(CameraControl_Exposure,true); + m_pGrabber->setProperty(CameraControl_Exposure, true); } else m_pExposureAbs->setValue(0.2); } - tIVCDPropertyItemPtr pGainItem = pItems->findItem( VCDID_Gain ); - tIVCDPropertyElementPtr pGainValueElement = pGainItem->findElement( VCDElement_Value ); - if (pGainValueElement != 0) { + tIVCDPropertyItemPtr pGainItem = pItems->findItem(VCDID_Gain); + tIVCDPropertyElementPtr pGainValueElement = pGainItem->findElement(VCDElement_Value); + if (pGainValueElement != 0) + { pGainValueElement->getInterfacePtr(m_pGain); - if (m_pGain == 0) { + if (m_pGain == 0) + { pFrame->Alert(_T("Warning - cannot directly control gain - running in auto-gain")); - // m_pGrabber->setProperty(CameraControl_Exposure,true); + // m_pGrabber->setProperty(CameraControl_Exposure,true); } - else { + else + { GainMax = m_pGain->getRangeMax(); long lval = (long) GuideCameraGain * GainMax / 100; if (lval > m_pGain->getRangeMax()) @@ -241,11 +356,22 @@ bool CameraFirewire::Connect(const wxString& camId) } } } // try - catch (...) { - if (debug) { debugfile->AddLine(wxString::Format("Failed at %d",debugstep)); debugfile->Write(); debugfile->Close(); } - return CamConnectFailed(wxString::Format(_("Fatal error at step %d connecting to TIS camera"),debugstep)); + catch (...) + { + if (debug) + { + debugfile->AddLine(wxString::Format("Failed at %d", debugstep)); + debugfile->Write(); + debugfile->Close(); + } + return CamConnectFailed(wxString::Format(_("Fatal error at step %d connecting to TIS camera"), debugstep)); + } + if (debug) + { + debugfile->Write(); + debugfile->Close(); + delete debugfile; } - if (debug) {debugfile->Write(); debugfile->Close(); delete debugfile; } Connected = true; return false; } @@ -262,7 +388,8 @@ bool CameraFirewire::Disconnect() void CameraFirewire::InitCapture() { // Set gain - if (m_pGain != 0) { + if (m_pGain != 0) + { long lval = (long) GuideCameraGain * GainMax / 100; if (lval > m_pGain->getRangeMax()) lval = m_pGain->getRangeMax(); @@ -287,13 +414,15 @@ bool CameraFirewire::Capture(int duration, usImage& img, int options, const wxRe } unsigned short *dataptr = img.ImageData; - if ((duration != programmed_dur) && (m_pExposureAbs != 0)) { + if ((duration != programmed_dur) && (m_pExposureAbs != 0)) + { m_pExposureAbs->setValue(duration / 1000.0); programmed_dur = duration; } bool retval = m_pGrabber->startLive(false); - if (!retval) { + if (!retval) + { pFrame->Alert(_("Could not start video stream")); return true; } @@ -302,20 +431,23 @@ bool CameraFirewire::Capture(int duration, usImage& img, int options, const wxRe // grab the next frame - Error err = pSink->snapImages( 1,15000 ); - if (err.getVal() == eTIMEOUT_PREMATURLY_ELAPSED) { + Error err = pSink->snapImages(1, 15000); + if (err.getVal() == eTIMEOUT_PREMATURLY_ELAPSED) + { wxMilliSleep(200); - err = pSink->snapImages( 1,15000 ); + err = pSink->snapImages(1, 15000); } - if (err.getVal() == eTIMEOUT_PREMATURLY_ELAPSED) { + if (err.getVal() == eTIMEOUT_PREMATURLY_ELAPSED) + { wxMilliSleep(200); - err = pSink->snapImages( 1,15000 ); + err = pSink->snapImages(1, 15000); } if (err.isError()) { - DisconnectWithAlert(wxString::Format(_("Error capturing image: %d (%d) %s"), - (int) err.getVal(), (int) eTIMEOUT_PREMATURLY_ELAPSED, wxString(err.c_str())), NO_RECONNECT); + DisconnectWithAlert(wxString::Format(_("Error capturing image: %d (%d) %s"), (int) err.getVal(), + (int) eTIMEOUT_PREMATURLY_ELAPSED, wxString(err.c_str())), + NO_RECONNECT); return true; } unsigned char *imgptr = (unsigned char *) pSink->getLastAcqMemBuffer()->getPtr(); @@ -323,19 +455,20 @@ bool CameraFirewire::Capture(int duration, usImage& img, int options, const wxRe for (unsigned int i = 0; i < img.NPixels; i++, dataptr++, imgptr++) *dataptr = (unsigned short) *imgptr; -/* if (dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_WAIT, &vframe)!=DC1394_SUCCESS) { - DisconnectWithAlert(_("Cannot get a frame from the queue")); - return true; - } - imgptr = vpFrame->image; - for (unsigned int i = 0; i < img.NPixels; i++, dataptr++, imgptr++) - *dataptr = (unsigned short) *imgptr; - dc1394_capture_enqueue(camera, vframe); // release this frame - */ + /* if (dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_WAIT, &vframe)!=DC1394_SUCCESS) { + DisconnectWithAlert(_("Cannot get a frame from the queue")); + return true; + } + imgptr = vpFrame->image; + for (unsigned int i = 0; i < img.NPixels; i++, dataptr++, imgptr++) + *dataptr = (unsigned short) *imgptr; + dc1394_capture_enqueue(camera, vframe); // release this frame + */ m_pGrabber->suspendLive(); - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return false; } diff --git a/src/cam_firewire_OSX.cpp b/src/cam_firewire_OSX.cpp index 023d1f9fa..8f8c7f713 100644 --- a/src/cam_firewire_OSX.cpp +++ b/src/cam_firewire_OSX.cpp @@ -34,11 +34,11 @@ #if defined(__APPLE__) && defined(FIREWIRE_CAMERA) -#include "phd.h" -#include "camera.h" -#include "time.h" -#include "image_math.h" -#include +# include "phd.h" +# include "camera.h" +# include "time.h" +# include "image_math.h" +# include // Deal with 8-bit vs. 16-bit?? // Take care of gain capability @@ -46,26 +46,28 @@ bool DCAM_flush_mode = true; bool DCAM_start_stop_mode = true; -#include "cam_firewire.h" +# include "cam_firewire.h" -CameraFirewire::CameraFirewire() : m_dcContext(0), camera(0) +CameraFirewire::CameraFirewire() + : m_dcContext(0) + , camera(0) { Connected = false; -// HaveBPMap = false; -// NBadPixels=-1; - Name=_T("The Imaging Source Firewire"); - FullSize = wxSize(1280,1024); + // HaveBPMap = false; + // NBadPixels=-1; + Name = _T("The Imaging Source Firewire"); + FullSize = wxSize(1280, 1024); HasGainControl = true; m_hasGuideOutput = false; } CameraFirewire::~CameraFirewire() { - if(m_dcContext) - { - dc1394_free(m_dcContext); - m_dcContext = 0; - } + if (m_dcContext) + { + dc1394_free(m_dcContext); + m_dcContext = 0; + } } wxByte CameraFirewire::BitsPerPixel() @@ -79,36 +81,40 @@ bool CameraFirewire::Connect(const wxString& camId) uint32_t i; dc1394video_mode_t vidmode; - if(m_dcContext == 0) + if (m_dcContext == 0) { m_dcContext = dc1394_new(); } - if(m_dcContext == 0) + if (m_dcContext == 0) { return CamConnectFailed(_("Error looking for Firewire / IEEE1394 cameras (internal error)")); } dc1394camera_list_t *cameras; err = dc1394_camera_enumerate(m_dcContext, &cameras); - if (err != DC1394_SUCCESS) { // && (err != DC1394_NO_CAMERA)) { + if (err != DC1394_SUCCESS) + { // && (err != DC1394_NO_CAMERA)) { return CamConnectFailed(_("Error looking for Firewire / IEEE1394 cameras")); } - if (cameras->num == 0) { + if (cameras->num == 0) + { return CamConnectFailed(_("No Firewire / IEEE1394 camera found")); } // Choose camera CamNum = 0; - if (cameras->num > 1) { + if (cameras->num > 1) + { wxArrayString CamNames; - for (i=0; inum; i++) + for (i = 0; i < cameras->num; i++) { dc1394camera_t *current_camera = dc1394_camera_new(m_dcContext, cameras->ids[i].guid); CamNames.Add(wxString(current_camera->model)); dc1394_camera_free(current_camera); } - CamNum = wxGetSingleChoiceIndex(_T("Select Firewire camera"),("Camera name"),CamNames); - if (CamNum == -1) { + CamNum = wxGetSingleChoiceIndex(_T("Select Firewire camera"), ("Camera name"), CamNames); + if (CamNum == -1) + { dc1394_camera_free_list(cameras); return true; } @@ -124,28 +130,33 @@ bool CameraFirewire::Connect(const wxString& camId) // Get the highest-res mono mode uint32_t w, h, max; dc1394video_modes_t video_modes; - dc1394_video_get_supported_modes(camera,&video_modes); + dc1394_video_get_supported_modes(camera, &video_modes); dc1394color_coding_t coding; bool HaveValid = false; - w=h=max=0; - for (i=0; i max) { - max = w*h; + w = h = max = 0; + for (i = 0; i < video_modes.num; i++) + { + dc1394_get_image_size_from_video_mode(camera, video_modes.modes[i], &w, &h); + dc1394_get_color_coding_from_video_mode(camera, video_modes.modes[i], &coding); + if (coding == DC1394_COLOR_CODING_MONO8) + { + if ((w * h) > max) + { + max = w * h; HaveValid = true; vidmode = video_modes.modes[i]; } } } - if (!HaveValid) { + if (!HaveValid) + { dc1394_camera_free(camera); return CamConnectFailed(_("Cannot find a suitable monochrome video mode")); } - if (dc1394_video_set_framerate(camera,DC1394_FRAMERATE_7_5)) { + if (dc1394_video_set_framerate(camera, DC1394_FRAMERATE_7_5)) + { dc1394_camera_free(camera); return CamConnectFailed(_("Cannot set frame rate to 7.5 FPS")); } @@ -154,10 +165,11 @@ bool CameraFirewire::Connect(const wxString& camId) dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400); // Engage video mode - dc1394_video_set_mode(camera,vidmode); + dc1394_video_set_mode(camera, vidmode); // Setup DMA buffers for capture - if (dc1394_capture_setup(camera,4,DC1394_CAPTURE_FLAGS_DEFAULT)) { + if (dc1394_capture_setup(camera, 4, DC1394_CAPTURE_FLAGS_DEFAULT)) + { dc1394_camera_free(camera); return CamConnectFailed(_("Cannot setup DMA buffers")); } @@ -166,66 +178,71 @@ bool CameraFirewire::Connect(const wxString& camId) long t1; // Startup transmission to make sure we can do so swatch.Start(); - if (dc1394_video_set_transmission(camera, DC1394_ON) != DC1394_SUCCESS) { + if (dc1394_video_set_transmission(camera, DC1394_ON) != DC1394_SUCCESS) + { dc1394_camera_free(camera); return CamConnectFailed(_("Cannot start transmission")); } dc1394switch_t status = DC1394_OFF; - for (i=0; i<5; i++) { + for (i = 0; i < 5; i++) + { wxMilliSleep(50); dc1394_video_get_transmission(camera, &status); - if (status != DC1394_OFF) break; + if (status != DC1394_OFF) + break; } t1 = swatch.Time(); - if (i==5) { + if (i == 5) + { dc1394_camera_free(camera); return CamConnectFailed(_("Transmission failed to start")); } -// dc1394_video_set_transmission(camera, DC1394_OFF); // turn it back off for now + // dc1394_video_set_transmission(camera, DC1394_OFF); // turn it back off for now -// dc1394_feature_set_value(camera,DC1394_FEATURE_EXPOSURE,0); // turn off auto-exposure + // dc1394_feature_set_value(camera,DC1394_FEATURE_EXPOSURE,0); // turn off auto-exposure -/* wxMilliSleep(500); - dc1394video_frame_t *vframe; + /* wxMilliSleep(500); + dc1394video_frame_t *vframe; - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); - dc1394_capture_enqueue(camera, vframe); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); - dc1394_capture_enqueue(camera, vframe); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); - dc1394_capture_enqueue(camera, vframe); -*/ + dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); + dc1394_capture_enqueue(camera, vframe); + dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); + dc1394_capture_enqueue(camera, vframe); + dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); + dc1394_capture_enqueue(camera, vframe); + */ // Setup my params - dc1394_get_image_size_from_video_mode(camera,vidmode,&w,&h); - FullSize = wxSize((int)w, (int)h); + dc1394_get_image_size_from_video_mode(camera, vidmode, &w, &h); + FullSize = wxSize((int) w, (int) h); Name = wxString(camera->model); -// wxMessageBox(Name + wxString::Format(" - %d x %d - %ld ms",FullSize.GetWidth(),FullSize.GetHeight(),t1)); -// dc1394feature_info_t feature; + // wxMessageBox(Name + wxString::Format(" - %d x %d - %ld ms",FullSize.GetWidth(),FullSize.GetHeight(),t1)); + // dc1394feature_info_t feature; // set shutter speed mode - dc1394bool_t Present; - dc1394_feature_has_absolute_control(camera,DC1394_FEATURE_SHUTTER,&Present); - if (Present != DC1394_TRUE) { + dc1394bool_t Present; + dc1394_feature_has_absolute_control(camera, DC1394_FEATURE_SHUTTER, &Present); + if (Present != DC1394_TRUE) + { pFrame->Alert("Cannot use absolute values to set exposures. Exposure durations will not be controlled properly"); } dc1394_feature_set_mode(camera, DC1394_FEATURE_SHUTTER, DC1394_FEATURE_MODE_MANUAL); - dc1394_feature_set_absolute_control(camera,DC1394_FEATURE_SHUTTER,DC1394_ON); - dc1394_feature_set_absolute_value(camera,DC1394_FEATURE_SHUTTER,1.0); + dc1394_feature_set_absolute_control(camera, DC1394_FEATURE_SHUTTER, DC1394_ON); + dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_SHUTTER, 1.0); // Set gain to manual control - dc1394_feature_set_mode(camera,DC1394_FEATURE_GAIN,DC1394_FEATURE_MODE_MANUAL); + dc1394_feature_set_mode(camera, DC1394_FEATURE_GAIN, DC1394_FEATURE_MODE_MANUAL); if (DCAM_start_stop_mode) dc1394_video_set_transmission(camera, DC1394_OFF); -/* int ans = wxMessageBox("Enable flushing of buffer on each capture?",_T("Flush mode?"),wxYES_NO); - if (ans == wxYES) - DCAM_flush_mode = true; - else - DCAM_flush_mode = false; -*/ + /* int ans = wxMessageBox("Enable flushing of buffer on each capture?",_T("Flush mode?"),wxYES_NO); + if (ans == wxYES) + DCAM_flush_mode = true; + else + DCAM_flush_mode = false; + */ Connected = true; return false; } @@ -237,15 +254,16 @@ void CameraFirewire::InitCapture() uint32_t Max; uint32_t NewVal; - dc1394_feature_get_boundaries(camera,DC1394_FEATURE_GAIN,&Min,&Max); + dc1394_feature_get_boundaries(camera, DC1394_FEATURE_GAIN, &Min, &Max); NewVal = GuideCameraGain * (Max - Min) / 100 + Min; - dc1394_feature_set_value(camera,DC1394_FEATURE_GAIN, NewVal); + dc1394_feature_set_value(camera, DC1394_FEATURE_GAIN, NewVal); } bool CameraFirewire::Disconnect() { - if (camera) { - dc1394_video_set_transmission(camera,DC1394_OFF); + if (camera) + { + dc1394_video_set_transmission(camera, DC1394_OFF); dc1394_camera_free(camera); camera = 0; } @@ -261,8 +279,10 @@ bool CameraFirewire::Capture(int duration, usImage& img, int options, const wxRe int xsize = FullSize.GetWidth(); int ysize = FullSize.GetHeight(); - if (img.NPixels != (unsigned int)(xsize * ysize)) { - if (img.Init(xsize, ysize)) { + if (img.NPixels != (unsigned int) (xsize * ysize)) + { + if (img.Init(xsize, ysize)) + { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } @@ -270,94 +290,106 @@ bool CameraFirewire::Capture(int duration, usImage& img, int options, const wxRe swatch.Start(); unsigned short *dataptr = img.ImageData; - if (DCAM_start_stop_mode) { + if (DCAM_start_stop_mode) + { dc1394_video_set_transmission(camera, DC1394_ON); dc1394switch_t status = DC1394_OFF; - for (int i=0; i<5; i++) { + for (int i = 0; i < 5; i++) + { wxMilliSleep(10); dc1394_video_get_transmission(camera, &status); - if (status != DC1394_OFF) break; + if (status != DC1394_OFF) + break; } } // Dequeue any existing -/* dc1394_video_set_transmission(camera,DC1394_OFF); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &frame); - if (pFrame->frames_behind) dc1394_capture_enqueue(camera, frame); - while (pFrame->frames_behind) { + /* dc1394_video_set_transmission(camera,DC1394_OFF); dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &frame); - dc1394_capture_enqueue(camera, frame); - }*/ - if (duration != programmed_dur) { - dc1394_feature_set_absolute_value(camera,DC1394_FEATURE_SHUTTER,(float) (duration) / 1000.0); + if (pFrame->frames_behind) dc1394_capture_enqueue(camera, frame); + while (pFrame->frames_behind) { + dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &frame); + dc1394_capture_enqueue(camera, frame); + }*/ + if (duration != programmed_dur) + { + dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_SHUTTER, (float) (duration) / 1000.0); programmed_dur = duration; } dc1394video_frame_t *vframe = nullptr; // Flush - if (DCAM_flush_mode) { + if (DCAM_flush_mode) + { vframe = nullptr; - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &vframe); - if (vframe) dc1394_capture_enqueue(camera, vframe); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &vframe); - if (vframe) dc1394_capture_enqueue(camera, vframe); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &vframe); - if (vframe) dc1394_capture_enqueue(camera, vframe); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &vframe); - if (vframe) dc1394_capture_enqueue(camera, vframe); + dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_POLL, &vframe); + if (vframe) + dc1394_capture_enqueue(camera, vframe); + dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_POLL, &vframe); + if (vframe) + dc1394_capture_enqueue(camera, vframe); + dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_POLL, &vframe); + if (vframe) + dc1394_capture_enqueue(camera, vframe); + dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_POLL, &vframe); + if (vframe) + dc1394_capture_enqueue(camera, vframe); } /* while (vframe && vpFrame->frames_behind) { - pFrame->StatusMsg(wxString::Format("%d %d %d", (int) vpFrame->size[0], (int) vpFrame->image_bytes, (int) vpFrame->frames_behind)); - dc1394_capture_enqueue(camera, vframe); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &vframe); + pFrame->StatusMsg(wxString::Format("%d %d %d", (int) vpFrame->size[0], (int) vpFrame->image_bytes, (int) + vpFrame->frames_behind)); dc1394_capture_enqueue(camera, vframe); dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, + &vframe); }*/ -/* dc1394_video_set_transmission(camera, DC1394_ON); - dc1394switch_t status = DC1394_OFF; - for (i=0; i<5; i++) { - wxMilliSleep(50); - dc1394_video_get_transmission(camera, &status); - if (status != DC1394_OFF) break; - }*/ + /* dc1394_video_set_transmission(camera, DC1394_ON); + dc1394switch_t status = DC1394_OFF; + for (i=0; i<5; i++) { + wxMilliSleep(50); + dc1394_video_get_transmission(camera, &status); + if (status != DC1394_OFF) break; + }*/ -/* - // Grab a short frame - err = dc1394_feature_set_absolute_value(camera,DC1394_FEATURE_SHUTTER,0.001); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); - dc1394_capture_enqueue(camera, vframe); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); - dc1394_capture_enqueue(camera, vframe); - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); - dc1394_capture_enqueue(camera, vframe); - -*/ - -/* wxMilliSleep(duration - 20); - // Flush - vframe = NULL; - dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &vframe); - if (vframe) dc1394_capture_enqueue(camera, vframe); - while (vframe) { + /* + // Grab a short frame + err = dc1394_feature_set_absolute_value(camera,DC1394_FEATURE_SHUTTER,0.001); + dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); + dc1394_capture_enqueue(camera, vframe); + dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); + dc1394_capture_enqueue(camera, vframe); + dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_WAIT, &vframe); + dc1394_capture_enqueue(camera, vframe); + + */ + + /* wxMilliSleep(duration - 20); + // Flush + vframe = NULL; dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &vframe); if (vframe) dc1394_capture_enqueue(camera, vframe); - } -*/ + while (vframe) { + dc1394_capture_dequeue(camera,DC1394_CAPTURE_POLICY_POLL, &vframe); + if (vframe) dc1394_capture_enqueue(camera, vframe); + } + */ // grab the next frame - if (dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_WAIT, &vframe) != DC1394_SUCCESS) { + if (dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_WAIT, &vframe) != DC1394_SUCCESS) + { DisconnectWithAlert(_("Cannot get a frame from the queue"), NO_RECONNECT); return true; } unsigned char *imgptr = vframe->image; -// pFrame->StatusMsg(wxString::Format("%d %d %d",(int) vpFrame->frames_behind, (int) vpFrame->size[0], (int) vpFrame->size[1])); + // pFrame->StatusMsg(wxString::Format("%d %d %d",(int) vpFrame->frames_behind, (int) vpFrame->size[0], (int) + // vpFrame->size[1])); for (unsigned int i = 0; i < img.NPixels; i++, dataptr++, imgptr++) *dataptr = (unsigned short) *imgptr; - dc1394_capture_enqueue(camera, vframe); // release this frame -// pFrame->StatusMsg(wxString::Format("Behind: %lu Pos: %lu",vpFrame->frames_behind,vpFrame->id)); - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + dc1394_capture_enqueue(camera, vframe); // release this frame + // pFrame->StatusMsg(wxString::Format("Behind: %lu Pos: %lu",vpFrame->frames_behind,vpFrame->id)); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); if (DCAM_start_stop_mode) dc1394_video_set_transmission(camera, DC1394_OFF); diff --git a/src/cam_indi.cpp b/src/cam_indi.cpp index 59ef5ff9a..698b4753d 100644 --- a/src/cam_indi.cpp +++ b/src/cam_indi.cpp @@ -38,160 +38,159 @@ #ifdef INDI_CAMERA -#include "cam_indi.h" -#include "camera.h" -#include "config_indi.h" -#include "image_math.h" -#include "indi_gui.h" -#include +# include "cam_indi.h" +# include "camera.h" +# include "config_indi.h" +# include "image_math.h" +# include "indi_gui.h" +# include -#include -#include +# include +# include class CapturedFrame { - public: - void *m_data; - size_t m_size; - char m_format[MAXINDIBLOBFMT]; +public: + void *m_data; + size_t m_size; + char m_format[MAXINDIBLOBFMT]; - CapturedFrame() - { - m_data = nullptr; - m_size = 0; - m_format[0] = 0; - } + CapturedFrame() + { + m_data = nullptr; + m_size = 0; + m_format[0] = 0; + } - ~CapturedFrame() - { -#ifdef INDI_SHARED_BLOB_SUPPORT - IDSharedBlobFree(m_data); -#else - free(m_data); -#endif - } + ~CapturedFrame() + { +# ifdef INDI_SHARED_BLOB_SUPPORT + IDSharedBlobFree(m_data); +# else + free(m_data); +# endif + } - // Take ownership of this blob's data, so INDI won't overwrite/free the memory - void steal(IBLOB *bp) - { - m_data = bp->blob; - m_size = bp->size; - strncpy(m_format, bp->format, MAXINDIBLOBFMT); + // Take ownership of this blob's data, so INDI won't overwrite/free the memory + void steal(IBLOB *bp) + { + m_data = bp->blob; + m_size = bp->size; + strncpy(m_format, bp->format, MAXINDIBLOBFMT); - bp->blob = nullptr; - bp->size = 0; - } + bp->blob = nullptr; + bp->size = 0; + } }; class CameraINDI : public GuideCamera, public INDI::BaseClient { - private: - ISwitchVectorProperty *connection_prop; - INumberVectorProperty *expose_prop; - INumberVectorProperty *frame_prop; - INumber *frame_x; - INumber *frame_y; - INumber *frame_width; - INumber *frame_height; - ISwitchVectorProperty *frame_type_prop; - INumberVectorProperty *ccdinfo_prop; - INumberVectorProperty *binning_prop; - INumber *binning_x; - INumber *binning_y; - ISwitchVectorProperty *video_prop; - ITextVectorProperty *camera_port; - INDI::BaseDevice camera_device; - INumberVectorProperty *pulseGuideNS_prop; - INumber *pulseN_prop; - INumber *pulseS_prop; - INumberVectorProperty *pulseGuideEW_prop; - INumber *pulseE_prop; - INumber *pulseW_prop; - - wxMutex sync_lock; - wxCondition sync_cond; - bool guide_active; - GuideAxis guide_active_axis; - - IndiGui *m_gui; - - wxMutex m_lastFrame_lock; - wxCondition m_lastFrame_cond; - CapturedFrame *m_lastFrame; - - usImage *StackImg; - int StackFrames; - volatile bool stacking; // TODO: use a wxCondition to signal completion - bool has_blob; - bool has_old_videoprop; - bool first_frame; - volatile bool modal; - bool ready; - wxByte m_bitsPerPixel; - double PixSize; - double PixSizeX; - double PixSizeY; - wxRect m_maxSize; - wxByte m_curBinning; - bool HasBayer; - long INDIport; - wxString INDIhost; - wxString INDICameraName; - long INDICameraCCD; - wxString INDICameraCCDCmd; - wxString INDICameraBlobName; - bool INDICameraForceVideo; - bool INDICameraForceExposure; - wxRect m_roi; - - bool ConnectToDriver(RunInBg *ctx); - void SetCCDdevice(); - void ClearStatus(); - void CheckState(); - void CameraDialog(); - void CameraSetup(); - bool ReadFITS(CapturedFrame *cf, usImage& img, bool takeSubframe, const wxRect& subframe); - bool StackStream(CapturedFrame *cf); - void SendBinning(); - - // Update the last frame, discarding any missed frame - void updateLastFrame(IBLOB *bp); - - // Wait until a frame was acquired, for limited amout of time. - // If non null is returned, caller is responsible for deletion - CapturedFrame *waitFrame(unsigned long waitTime); - - protected: - void newDevice(INDI::BaseDevice dp) override; - void removeDevice(INDI::BaseDevice dp) override; - void newProperty(INDI::Property property) override; - void updateProperty(INDI::Property property) override; - void removeProperty(INDI::Property property) override {} - void newMessage(INDI::BaseDevice dp, int messageID) override; - void serverConnected() override; - void serverDisconnected(int exit_code) override; - - public: - CameraINDI(); - ~CameraINDI(); - bool Connect(const wxString& camId) override; - bool Disconnect() override; - bool HasNonGuiCapture() override; - wxByte BitsPerPixel() override; - bool GetDevicePixelSize(double *pixSize) override; - void ShowPropertyDialog() override; - - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - - bool ST4PulseGuideScope(int direction, int duration) override; - bool ST4HasNonGuiMove() override; +private: + ISwitchVectorProperty *connection_prop; + INumberVectorProperty *expose_prop; + INumberVectorProperty *frame_prop; + INumber *frame_x; + INumber *frame_y; + INumber *frame_width; + INumber *frame_height; + ISwitchVectorProperty *frame_type_prop; + INumberVectorProperty *ccdinfo_prop; + INumberVectorProperty *binning_prop; + INumber *binning_x; + INumber *binning_y; + ISwitchVectorProperty *video_prop; + ITextVectorProperty *camera_port; + INDI::BaseDevice camera_device; + INumberVectorProperty *pulseGuideNS_prop; + INumber *pulseN_prop; + INumber *pulseS_prop; + INumberVectorProperty *pulseGuideEW_prop; + INumber *pulseE_prop; + INumber *pulseW_prop; + + wxMutex sync_lock; + wxCondition sync_cond; + bool guide_active; + GuideAxis guide_active_axis; + + IndiGui *m_gui; + + wxMutex m_lastFrame_lock; + wxCondition m_lastFrame_cond; + CapturedFrame *m_lastFrame; + + usImage *StackImg; + int StackFrames; + volatile bool stacking; // TODO: use a wxCondition to signal completion + bool has_blob; + bool has_old_videoprop; + bool first_frame; + volatile bool modal; + bool ready; + wxByte m_bitsPerPixel; + double PixSize; + double PixSizeX; + double PixSizeY; + wxRect m_maxSize; + wxByte m_curBinning; + bool HasBayer; + long INDIport; + wxString INDIhost; + wxString INDICameraName; + long INDICameraCCD; + wxString INDICameraCCDCmd; + wxString INDICameraBlobName; + bool INDICameraForceVideo; + bool INDICameraForceExposure; + wxRect m_roi; + + bool ConnectToDriver(RunInBg *ctx); + void SetCCDdevice(); + void ClearStatus(); + void CheckState(); + void CameraDialog(); + void CameraSetup(); + bool ReadFITS(CapturedFrame *cf, usImage& img, bool takeSubframe, const wxRect& subframe); + bool StackStream(CapturedFrame *cf); + void SendBinning(); + + // Update the last frame, discarding any missed frame + void updateLastFrame(IBLOB *bp); + + // Wait until a frame was acquired, for limited amout of time. + // If non null is returned, caller is responsible for deletion + CapturedFrame *waitFrame(unsigned long waitTime); + +protected: + void newDevice(INDI::BaseDevice dp) override; + void removeDevice(INDI::BaseDevice dp) override; + void newProperty(INDI::Property property) override; + void updateProperty(INDI::Property property) override; + void removeProperty(INDI::Property property) override { } + void newMessage(INDI::BaseDevice dp, int messageID) override; + void serverConnected() override; + void serverDisconnected(int exit_code) override; + +public: + CameraINDI(); + ~CameraINDI(); + bool Connect(const wxString& camId) override; + bool Disconnect() override; + bool HasNonGuiCapture() override; + wxByte BitsPerPixel() override; + bool GetDevicePixelSize(double *pixSize) override; + void ShowPropertyDialog() override; + + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + + bool ST4PulseGuideScope(int direction, int duration) override; + bool ST4HasNonGuiMove() override; }; CameraINDI::CameraINDI() - : - sync_cond(sync_lock), - m_lastFrame_cond(m_lastFrame_lock), - m_gui(nullptr) + : sync_cond(sync_lock) + , m_lastFrame_cond(m_lastFrame_lock) + , m_gui(nullptr) { m_lastFrame = nullptr; ClearStatus(); @@ -317,149 +316,144 @@ void CameraINDI::updateProperty(INDI::Property property) switch (property.getType()) { - case INDI_SWITCH: - { - auto svp = property.getSwitch(); + case INDI_SWITCH: + { + auto svp = property.getSwitch(); - if (INDIConfig::Verbose()) - Debug.Write(wxString::Format("INDI Camera Received Switch: %s = %i\n", svp->name, svp->sp->s)); + if (INDIConfig::Verbose()) + Debug.Write(wxString::Format("INDI Camera Received Switch: %s = %i\n", svp->name, svp->sp->s)); - if (strcmp(svp->name, "CONNECTION") == 0) + if (strcmp(svp->name, "CONNECTION") == 0) + { + ISwitch *connectswitch = IUFindSwitch(svp, "CONNECT"); + if (connectswitch->s == ISS_ON) { - ISwitch *connectswitch = IUFindSwitch(svp, "CONNECT"); - if (connectswitch->s == ISS_ON) - { - Connected = true; - CheckState(); - } - else - { - if (ready) - { - ClearStatus(); - - // call Disconnect in the main thread since that will - // want to join the INDI worker thread which is - // probably the current thread - - PhdApp::ExecInMainThread( - [this]() - { - DisconnectWithAlert(_("INDI camera disconnected"), NO_RECONNECT); - }); - } - } + Connected = true; + CheckState(); } - - } - break; - case INDI_NUMBER: - { - auto nvp = property.getNumber(); - - if (INDIConfig::Verbose()) + else { - if (strcmp(nvp->name, "CCD_EXPOSURE") == 0 ) - { - // rate limit this one, it's too noisy - static double s_lastval; - if (nvp->np->value > 0.0 && fabs(nvp->np->value - s_lastval) < 0.5) - return; - s_lastval = nvp->np->value; - } - std::ostringstream os; - for (int i = 0; i < nvp->nnp; i++) + if (ready) { - if (i) os << ','; - os << nvp->np[i].name << ':' << nvp->np[i].value; + ClearStatus(); + + // call Disconnect in the main thread since that will + // want to join the INDI worker thread which is + // probably the current thread + + PhdApp::ExecInMainThread([this]() { DisconnectWithAlert(_("INDI camera disconnected"), NO_RECONNECT); }); } - Debug.Write(wxString::Format("INDI Camera Received Number: %s = %s state = %s\n", nvp->name, os.str().c_str(), - property.getStateAsString())); } + } + } + break; + case INDI_NUMBER: + { + auto nvp = property.getNumber(); - if (nvp == ccdinfo_prop) + if (INDIConfig::Verbose()) + { + if (strcmp(nvp->name, "CCD_EXPOSURE") == 0) { - PixSize = IUFindNumber(ccdinfo_prop, "CCD_PIXEL_SIZE")->value; - PixSizeX = IUFindNumber(ccdinfo_prop, "CCD_PIXEL_SIZE_X")->value; - PixSizeY = IUFindNumber(ccdinfo_prop, "CCD_PIXEL_SIZE_Y")->value; - m_maxSize.x = IUFindNumber(ccdinfo_prop, "CCD_MAX_X")->value; - m_maxSize.y = IUFindNumber(ccdinfo_prop, "CCD_MAX_Y")->value; - // defer defining FullSize since it is not simply derivable from max size and binning - // no: FullSize = wxSize(m_maxSize.x / Binning, m_maxSize.y / Binning); - m_bitsPerPixel = IUFindNumber(ccdinfo_prop, "CCD_BITSPERPIXEL")->value; + // rate limit this one, it's too noisy + static double s_lastval; + if (nvp->np->value > 0.0 && fabs(nvp->np->value - s_lastval) < 0.5) + return; + s_lastval = nvp->np->value; } - else if (nvp == binning_prop) + std::ostringstream os; + for (int i = 0; i < nvp->nnp; i++) { - MaxBinning = wxMin(binning_x->max, binning_y->max); - m_curBinning = wxMin(binning_x->value, binning_y->value); - if (Binning > MaxBinning) - Binning = MaxBinning; - // defer defining FullSize since it is not simply derivable from max size and binning - // no: FullSize = wxSize(m_maxSize.x / Binning, m_maxSize.y / Binning); + if (i) + os << ','; + os << nvp->np[i].name << ':' << nvp->np[i].value; } - else if (nvp == pulseGuideEW_prop || nvp == pulseGuideNS_prop) + Debug.Write(wxString::Format( + "INDI Camera Received Number: %s = %s state = %s\n", nvp->name, os.str().c_str(), property.getStateAsString())); + } + + if (nvp == ccdinfo_prop) + { + PixSize = IUFindNumber(ccdinfo_prop, "CCD_PIXEL_SIZE")->value; + PixSizeX = IUFindNumber(ccdinfo_prop, "CCD_PIXEL_SIZE_X")->value; + PixSizeY = IUFindNumber(ccdinfo_prop, "CCD_PIXEL_SIZE_Y")->value; + m_maxSize.x = IUFindNumber(ccdinfo_prop, "CCD_MAX_X")->value; + m_maxSize.y = IUFindNumber(ccdinfo_prop, "CCD_MAX_Y")->value; + // defer defining FullSize since it is not simply derivable from max size and binning + // no: FullSize = wxSize(m_maxSize.x / Binning, m_maxSize.y / Binning); + m_bitsPerPixel = IUFindNumber(ccdinfo_prop, "CCD_BITSPERPIXEL")->value; + } + else if (nvp == binning_prop) + { + MaxBinning = wxMin(binning_x->max, binning_y->max); + m_curBinning = wxMin(binning_x->value, binning_y->value); + if (Binning > MaxBinning) + Binning = MaxBinning; + // defer defining FullSize since it is not simply derivable from max size and binning + // no: FullSize = wxSize(m_maxSize.x / Binning, m_maxSize.y / Binning); + } + else if (nvp == pulseGuideEW_prop || nvp == pulseGuideNS_prop) + { + bool notify = false; { - bool notify = false; + wxMutexLocker lck(sync_lock); + if (guide_active && nvp->s != IPS_BUSY && + ((guide_active_axis == GUIDE_RA && nvp == pulseGuideEW_prop) || + (guide_active_axis == GUIDE_DEC && nvp == pulseGuideNS_prop))) { - wxMutexLocker lck(sync_lock); - if (guide_active && nvp->s != IPS_BUSY && - ((guide_active_axis == GUIDE_RA && nvp == pulseGuideEW_prop) || - (guide_active_axis == GUIDE_DEC && nvp == pulseGuideNS_prop))) - { - guide_active = false; - notify = true; - } - else if (!guide_active && nvp->s == IPS_BUSY) - { - guide_active = true; - guide_active_axis = nvp == pulseGuideEW_prop ? GUIDE_RA : GUIDE_DEC; - } + guide_active = false; + notify = true; + } + else if (!guide_active && nvp->s == IPS_BUSY) + { + guide_active = true; + guide_active_axis = nvp == pulseGuideEW_prop ? GUIDE_RA : GUIDE_DEC; } - if (notify) - sync_cond.Broadcast(); } + if (notify) + sync_cond.Broadcast(); } - break; - case INDI_TEXT: - { - auto tvp = property.getText(); - - if (INDIConfig::Verbose()) - Debug.Write(wxString::Format("INDI Camera Received Text: %s = %s\n", tvp->name, tvp->tp->text)); + } + break; + case INDI_TEXT: + { + auto tvp = property.getText(); - } - break; - case INDI_BLOB: - { - // we go here every time a new blob is available - // this is normally the image from the camera + if (INDIConfig::Verbose()) + Debug.Write(wxString::Format("INDI Camera Received Text: %s = %s\n", tvp->name, tvp->tp->text)); + } + break; + case INDI_BLOB: + { + // we go here every time a new blob is available + // this is normally the image from the camera - auto bvp = property.getBLOB(); - auto bp = bvp->at(0); + auto bvp = property.getBLOB(); + auto bp = bvp->at(0); - if (INDIConfig::Verbose()) - Debug.Write(wxString::Format("INDI Camera Received BLOB %s len=%d size=%d\n", bp->name, bp->bloblen, bp->size)); + if (INDIConfig::Verbose()) + Debug.Write(wxString::Format("INDI Camera Received BLOB %s len=%d size=%d\n", bp->name, bp->bloblen, bp->size)); - if (expose_prop && !INDICameraForceVideo) + if (expose_prop && !INDICameraForceVideo) + { + if (bp->name == INDICameraBlobName) { - if (bp->name == INDICameraBlobName) - { - updateLastFrame(bp); - } + updateLastFrame(bp); } - else if (video_prop) + } + else if (video_prop) + { + if (modal && !stacking) { - if (modal && !stacking) - { - CapturedFrame cf; - cf.steal(bp); - StackStream(&cf); - } + CapturedFrame cf; + cf.steal(bp); + StackStream(&cf); } } + } + break; + default: break; - default: - break; } } @@ -494,10 +488,10 @@ void CameraINDI::newProperty(INDI::Property property) // set option to receive blob and messages for the selected CCD setBLOBMode(B_ALSO, INDICameraName.mb_str(wxConvUTF8), INDICameraBlobName.mb_str(wxConvUTF8)); -#ifdef INDI_SHARED_BLOB_SUPPORT +# ifdef INDI_SHARED_BLOB_SUPPORT // Allow faster mode provided we don't modify the blob content or free/realloc it enableDirectBlobAccess(INDICameraName.mb_str(wxConvUTF8), INDICameraBlobName.mb_str(wxConvUTF8)); -#endif +# endif } } else if (PropName == INDICameraCCDCmd + "EXPOSURE" && Proptype == INDI_NUMBER) @@ -637,7 +631,10 @@ bool CameraINDI::Connect(const wxString& camId) struct ConnectInBg : public ConnectCameraInBg { CameraINDI *cam; - ConnectInBg(CameraINDI *cam_) : cam(cam_) { } + ConnectInBg(CameraINDI *cam_) + : cam(cam_) + { + } bool Entry() { // Wait for driver to establish a device connection @@ -655,7 +652,6 @@ bool CameraINDI::Connect(const wxString& camId) // We need to return FALSE if we are successful return !cam->Connected; - } }; @@ -847,18 +843,11 @@ void CameraINDI::SetCCDdevice() bool CameraINDI::ReadFITS(CapturedFrame *frame, usImage& img, bool takeSubframe, const wxRect& subframe) { - fitsfile *fptr; // FITS file pointer - int status = 0; // CFITSIO status value MUST be initialized to zero! + fitsfile *fptr; // FITS file pointer + int status = 0; // CFITSIO status value MUST be initialized to zero! // load blob to CFITSIO - if (fits_open_memfile(&fptr, - "", - READONLY, - &frame->m_data, - &frame->m_size, - 0, - nullptr, - &status)) + if (fits_open_memfile(&fptr, "", READONLY, &frame->m_data, &frame->m_size, 0, nullptr, &status)) { pFrame->Alert(_("Unsupported type or read error loading FITS file")); return true; @@ -897,7 +886,7 @@ bool CameraINDI::ReadFITS(CapturedFrame *frame, usImage& img, bool takeSubframe, return true; } - long fpixel[3] = {1, 1, 1}; + long fpixel[3] = { 1, 1, 1 }; if (takeSubframe) { @@ -970,7 +959,8 @@ bool CameraINDI::StackStream(CapturedFrame *cf) if (cf->m_size != StackImg->NPixels) { - Debug.Write(wxString::Format("INDI Camera: discarding blob with size %d, expected %u\n", cf->m_size, StackImg->NPixels)); + Debug.Write( + wxString::Format("INDI Camera: discarding blob with size %d, expected %u\n", cf->m_size, StackImg->NPixels)); return true; } @@ -1113,11 +1103,11 @@ bool CameraINDI::Capture(int duration, usImage& img, int options, const wxRect& // try to use video stream instead of exposure // See: http://www.indilib.org/forum/ccds-dslrs/3078-v4l2-ccd-exposure-property.html // TODO : check if an updated INDI v4l2 driver offer a better solution - pFrame->Alert(wxString::Format(_("Camera %s, exposure error. Trying to use streaming instead."), - INDICameraName)); + pFrame->Alert( + wxString::Format(_("Camera %s, exposure error. Trying to use streaming instead."), INDICameraName)); INDICameraForceVideo = true; first_frame = false; - return Capture(duration, img, options, subframeArg); + return Capture(duration, img, options, subframeArg); } else { @@ -1230,7 +1220,7 @@ bool CameraINDI::Capture(int duration, usImage& img, int options, const wxRect& modal = false; } - if (WorkerThread::StopRequested() || WorkerThread::TerminateRequested()) + if (WorkerThread::StopRequested() || WorkerThread::TerminateRequested()) { // Stop video streaming when Stop button is pressed or exiting the program v_on->s = ISS_OFF; @@ -1287,14 +1277,14 @@ bool CameraINDI::ST4PulseGuideScope(int direction, int duration) { switch (direction) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - break; - default: - Debug.Write("INDI Camera error CameraINDI::Guide NONE\n"); - return true; + case EAST: + case WEST: + case NORTH: + case SOUTH: + break; + default: + Debug.Write("INDI Camera error CameraINDI::Guide NONE\n"); + return true; } if (!pulseGuideNS_prop || !pulseGuideEW_prop) @@ -1322,26 +1312,26 @@ bool CameraINDI::ST4PulseGuideScope(int direction, int duration) switch (direction) { - case EAST: - pulseE_prop->value = duration; - pulseW_prop->value = 0; - sendNewNumber(pulseGuideEW_prop); - break; - case WEST: - pulseE_prop->value = 0; - pulseW_prop->value = duration; - sendNewNumber(pulseGuideEW_prop); - break; - case NORTH: - pulseN_prop->value = duration; - pulseS_prop->value = 0; - sendNewNumber(pulseGuideNS_prop); - break; - case SOUTH: - pulseN_prop->value = 0; - pulseS_prop->value = duration; - sendNewNumber(pulseGuideNS_prop); - break; + case EAST: + pulseE_prop->value = duration; + pulseW_prop->value = 0; + sendNewNumber(pulseGuideEW_prop); + break; + case WEST: + pulseE_prop->value = 0; + pulseW_prop->value = duration; + sendNewNumber(pulseGuideEW_prop); + break; + case NORTH: + pulseN_prop->value = duration; + pulseS_prop->value = 0; + sendNewNumber(pulseGuideNS_prop); + break; + case SOUTH: + pulseN_prop->value = 0; + pulseS_prop->value = duration; + sendNewNumber(pulseGuideNS_prop); + break; } if (INDIConfig::Verbose()) diff --git a/src/cam_ioptron.cpp b/src/cam_ioptron.cpp index 40ae79dc6..ffeb385d5 100644 --- a/src/cam_ioptron.cpp +++ b/src/cam_ioptron.cpp @@ -36,17 +36,14 @@ #if defined(IOPTRON_CAMERA) -#include "cam_ioptron.h" -#include "cam_wdm_base.h" -#include "CVPlatform.h" +# include "cam_ioptron.h" +# include "cam_wdm_base.h" +# include "CVPlatform.h" class IoptronCamera : public CameraWDM { public: - IoptronCamera() - { - m_rawYUY2 = true; - } + IoptronCamera() { m_rawYUY2 = true; } bool CanSelectCamera() const override { // TODO: we could probably hanlde multiple cameras, but would need 2 cameras to test @@ -157,15 +154,13 @@ bool IoptronCamera::SelectDeviceAndMode(SelectionContext ctx) CVVidCapture::VIDCAP_MODE modeInfo; if (CVSUCCESS(vc.get()->GetModeInfo(i, modeInfo))) { - if (modeInfo.XRes == 640 && modeInfo.YRes == 960 && - modeInfo.InputFormat == VIDCAP_FORMAT_YUY2) + if (modeInfo.XRes == 640 && modeInfo.YRes == 960 && modeInfo.InputFormat == VIDCAP_FORMAT_YUY2) { if (m_deviceMode == -1) m_deviceMode = i; } - Debug.Write(wxString::Format("IOPTRON: mode %d: %dx%d (%s) %d fps %s\n", i, modeInfo.XRes, - modeInfo.YRes, vc.get()->GetFormatModeName(modeInfo.InputFormat), - modeInfo.EstFrameRate, i == m_deviceMode ? "<<<<" : "")); + Debug.Write(wxString::Format("IOPTRON: mode %d: %dx%d (%s) %d fps %s\n", i, modeInfo.XRes, modeInfo.YRes, + vc.get()->GetFormatModeName(modeInfo.InputFormat), modeInfo.EstFrameRate, i == m_deviceMode ? "<<<<" : "")); } else Debug.Write(wxString::Format("IOPTRON: mode %d: GetModeInfo failed, skipped\n", i)); diff --git a/src/cam_moravian.cpp b/src/cam_moravian.cpp index b5a1eda6d..617a6faa1 100644 --- a/src/cam_moravian.cpp +++ b/src/cam_moravian.cpp @@ -1,42 +1,42 @@ /* -* cam_moravian.cpp -* PHD2 Guiding -* -* Copyright (c) 2020 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * cam_moravian.cpp + * PHD2 Guiding + * + * Copyright (c) 2020 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #ifdef MORAVIAN_CAMERA -#include "cam_moravian.h" +# include "cam_moravian.h" // #include "gxeth.h" TODO - ethernet camera support -#include "gxusb.h" +# include "gxusb.h" static std::vector __ids; @@ -50,7 +50,7 @@ static std::vector _get_ids() Debug.Write("MVN: begin enumerate\n"); __ids.clear(); gXusb::Enumerate(_enum_cb); - Debug.Write(wxString::Format("MVN: enumerate found %u\n", (unsigned int)__ids.size())); // MSVC barfs on %zu + Debug.Write(wxString::Format("MVN: enumerate found %u\n", (unsigned int) __ids.size())); // MSVC barfs on %zu return __ids; } @@ -58,7 +58,10 @@ struct MCam { gXusb::CCamera *m_cam; - MCam() : m_cam(nullptr) { } + MCam() + : m_cam(nullptr) + { + } ~MCam() { @@ -143,10 +146,7 @@ struct MCam return dflt; } - wxString Serial() - { - return StrParam(gspCameraSerial, wxString::Format("ID%d", IntParam(gipCameraId, 1))); - } + wxString Serial() { return StrParam(gspCameraSerial, wxString::Format("ID%d", IntParam(gipCameraId, 1))); } float GetValue(gXusb::CARDINAL idx, float dflt = 0.f) { @@ -269,10 +269,7 @@ struct MCam return ok; } - wxSize ChipSize() - { - return wxSize(IntParam(gipChipW), IntParam(gipChipD)); - } + wxSize ChipSize() { return wxSize(IntParam(gipChipW), IntParam(gipChipD)); } bool CaptureSync(void *buf, unsigned int size, unsigned int duration, wxByte bpp, const wxRect& frame) { @@ -280,13 +277,13 @@ struct MCam gXusb::BOOLEAN ok; if (bpp == 8) { - ok = gXusb::GetImageExposure8b(m_cam, exp, false, frame.GetLeft(), frame.GetTop(), frame.GetWidth(), frame.GetHeight(), - size, buf); + ok = gXusb::GetImageExposure8b( + m_cam, exp, false, frame.GetLeft(), frame.GetTop(), frame.GetWidth(), frame.GetHeight(), size, buf); } else { - ok = gXusb::GetImageExposure16b(m_cam, exp, false, frame.GetLeft(), frame.GetTop(), frame.GetWidth(), frame.GetHeight(), - size, buf); + ok = gXusb::GetImageExposure16b( + m_cam, exp, false, frame.GetLeft(), frame.GetTop(), frame.GetWidth(), frame.GetHeight(), size, buf); } if (!ok) Debug.Write(wxString::Format("MVN: CaptureSync: %s\n", LastError())); @@ -336,7 +333,7 @@ class MoravianCamera : public GuideCamera unsigned int m_curGain; void *m_buffer; size_t m_buffer_size; - wxByte m_bpp; // bits per pixel: 8 or 16 + wxByte m_bpp; // bits per pixel: 8 or 16 MCam m_cam; bool m_canGuide; int m_maxGain; @@ -370,15 +367,15 @@ class MoravianCamera : public GuideCamera }; MoravianCamera::MoravianCamera() - : - m_buffer(nullptr) + : m_buffer(nullptr) { Name = _T("Moravian Camera"); PropertyDialogType = PROPDLG_WHEN_DISCONNECTED; Connected = false; m_hasGuideOutput = false; // updated when connected HasSubframes = true; - HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to true later when the camera is connected + HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to + // true later when the camera is connected m_defaultGainPct = 0; // TODO: what is a good default? GuideCamera::GetDefaultCameraGain(); int value = pConfig->Profile.GetInt("/camera/moravian/bpp", 16); m_bpp = value == 8 ? 8 : 16; @@ -432,8 +429,8 @@ MoravianCameraDlg::MoravianCameraDlg() wxBoxSizer *sizer5 = new wxBoxSizer(wxHORIZONTAL); - wxStaticText *staticText1 = new wxStaticText(sizer2->GetStaticBox(), wxID_ANY, _("Read Mode"), - wxDefaultPosition, wxDefaultSize, 0); + wxStaticText *staticText1 = + new wxStaticText(sizer2->GetStaticBox(), wxID_ANY, _("Read Mode"), wxDefaultPosition, wxDefaultSize, 0); staticText1->Wrap(-1); sizer5->Add(staticText1, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxTOP, 5); @@ -626,10 +623,8 @@ bool MoravianCamera::Connect(const wxString& camId) int flash_minor = m_cam.IntParam(gipFlashMinor); int flash_build = m_cam.IntParam(gipFlashBuild); - Debug.Write(wxString::Format("MVN: Driver %d.%d.%d | Firmware %d.%d.%d | Flash %d.%d.%d\n", - drv_major, drv_minor, drv_build, - fw_major, fw_minor, fw_build, - flash_major, flash_minor, flash_build)); + Debug.Write(wxString::Format("MVN: Driver %d.%d.%d | Firmware %d.%d.%d | Flash %d.%d.%d\n", drv_major, drv_minor, drv_build, + fw_major, fw_minor, fw_build, flash_major, flash_minor, flash_build)); Name = m_cam.StrParam(gspCameraDescription, _T("Moravian Camera")); @@ -663,8 +658,7 @@ bool MoravianCamera::Connect(const wxString& camId) m_hasGuideOutput = m_cam.BoolParam(gbpGuide); m_maxMoveMs = m_hasGuideOutput ? m_cam.IntParam(gipMaximalMoveTime) : 0; - Debug.Write(wxString::Format("MVN: CanPulseGuide: %s MaxMove: %d\n", - m_hasGuideOutput ? "yes" : "no", m_maxMoveMs)); + Debug.Write(wxString::Format("MVN: CanPulseGuide: %s MaxMove: %d\n", m_hasGuideOutput ? "yes" : "no", m_maxMoveMs)); bool rgb = m_cam.BoolParam(gbpRGB); bool cmy = m_cam.BoolParam(gbpCMY); @@ -713,8 +707,8 @@ bool MoravianCamera::Connect(const wxString& camId) m_maxGain = m_cam.IntParam(gipMaxGain); int default_gain = 0; // TODO: ask moravian m_defaultGainPct = gain_pct(0, m_maxGain, default_gain); - Debug.Write(wxString::Format("MVN: gain range = %d .. %d default = %ld (%d%%)\n", - 0, m_maxGain, default_gain, m_defaultGainPct)); + Debug.Write( + wxString::Format("MVN: gain range = %d .. %d default = %ld (%d%%)\n", 0, m_maxGain, default_gain, m_defaultGainPct)); unsigned int new_gain = cam_gain(0, m_maxGain, GuideCameraGain); Debug.Write(wxString::Format("MVN: set gain %d%% %d\n", GuideCameraGain, new_gain)); @@ -947,12 +941,26 @@ bool MoravianCamera::ST4PulseGuideScope(int direction, int duration) gXusb::INT16 radur, decdur; - switch (direction) { - case NORTH: radur = 0; decdur = +dur; break; - case SOUTH: radur = 0; decdur = -dur; break; - case EAST: radur = +dur; decdur = 0; break; - case WEST: radur = -dur; decdur = 0; break; - default: return true; + switch (direction) + { + case NORTH: + radur = 0; + decdur = +dur; + break; + case SOUTH: + radur = 0; + decdur = -dur; + break; + case EAST: + radur = +dur; + decdur = 0; + break; + case WEST: + radur = -dur; + decdur = 0; + break; + default: + return true; } if (!gXusb::MoveTelescope(m_cam, radur, decdur)) diff --git a/src/cam_moravian.h b/src/cam_moravian.h index 1731a3bef..b0f5e0678 100644 --- a/src/cam_moravian.h +++ b/src/cam_moravian.h @@ -1,35 +1,35 @@ /* -* cam_moravian.h -* PHD2 Guiding -* -* Copyright (c) 2020 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * cam_moravian.h + * PHD2 Guiding + * + * Copyright (c) 2020 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef CAM_MORAVIAN_INCLUDED #define CAM_MORAVIAN_INCLUDED diff --git a/src/cam_ogma.cpp b/src/cam_ogma.cpp index 4aed3d455..320f1161f 100644 --- a/src/cam_ogma.cpp +++ b/src/cam_ogma.cpp @@ -36,21 +36,21 @@ #if defined(OGMA_CAMERA) -#include "cam_ogma.h" -#include "ogmacam.h" +# include "cam_ogma.h" +# include "ogmacam.h" // Touptek API uses these Windows definitions even on non-Windows platforms -#ifndef S_OK -#define S_OK ((HRESULT)0L) -#define S_FALSE ((HRESULT)1L) -#endif +# ifndef S_OK +# define S_OK ((HRESULT) 0L) +# define S_FALSE ((HRESULT) 1L) +# endif struct OgmaCam { HOgmacam m_h; void *m_buffer; void *m_tmpbuf; - wxByte m_bpp; // bits per pixel: 8 or 16 + wxByte m_bpp; // bits per pixel: 8 or 16 bool m_isColor; bool m_hasGuideOutput; double m_devicePixelSize; @@ -65,13 +65,14 @@ struct OgmaCam wxMutex m_lock; wxCondition m_cond; - OgmaCam() : - m_h(nullptr), - m_buffer(nullptr), - m_tmpbuf(nullptr), - m_started(false), - m_cond(m_lock) - { } + OgmaCam() + : m_h(nullptr) + , m_buffer(nullptr) + , m_tmpbuf(nullptr) + , m_started(false) + , m_cond(m_lock) + { + } ~OgmaCam() { @@ -79,21 +80,15 @@ struct OgmaCam ::free(m_tmpbuf); } - int gain_pct(int val) const - { - return (val - m_minGain) * 100 / (m_maxGain - m_minGain); - } + int gain_pct(int val) const { return (val - m_minGain) * 100 / (m_maxGain - m_minGain); } - int cam_gain(int pct) const - { - return m_minGain + pct * (m_maxGain - m_minGain) / 100; - } + int cam_gain(int pct) const { return m_minGain + pct * (m_maxGain - m_minGain) / 100; } void StopCapture() { if (m_started) { - //Debug.Write("OGMA: stopcapture\n"); + // Debug.Write("OGMA: stopcapture\n"); HRESULT hr; if (FAILED(hr = Ogmacam_Stop(m_h))) Debug.Write(wxString::Format("OGMA: Ogmacam_Stop failed with status 0x%x\n", hr)); @@ -113,7 +108,7 @@ struct OgmaCam case OGMACAM_EVENT_NOFRAMETIMEOUT: case OGMACAM_EVENT_NOPACKETTIMEOUT: case OGMACAM_EVENT_TRIGGERFAIL: - //Debug.Write(wxString::Format("OGMA: cam event 0x%x\n", event)); + // Debug.Write(wxString::Format("OGMA: cam event 0x%x\n", event)); { wxMutexLocker lck(cam->m_lock); cam->m_captureResult = event; @@ -131,7 +126,7 @@ struct OgmaCam if (m_started) return; - //Debug.Write("OGMA: startcapture\n"); + // Debug.Write("OGMA: startcapture\n"); HRESULT hr; if (FAILED(hr = Ogmacam_StartPullModeWithCallback(m_h, &CamEventCb, this))) @@ -208,15 +203,9 @@ struct OgmaCam } } - bool SoftwareBinning() const - { - return m_isColor; - } + bool SoftwareBinning() const { return m_isColor; } - bool SetHwBinning(unsigned int binning) - { - return SetOption(OGMACAM_OPTION_BINNING, OgmacamBinning(binning)); - } + bool SetHwBinning(unsigned int binning) { return SetOption(OGMACAM_OPTION_BINNING, OgmacamBinning(binning)); } bool SetBinning(unsigned int binning) { @@ -261,7 +250,6 @@ class CameraOgma : public GuideCamera OgmaCam m_cam; public: - CameraOgma(); ~CameraOgma(); @@ -293,16 +281,15 @@ CameraOgma::CameraOgma() Connected = false; m_cam.m_hasGuideOutput = true; HasSubframes = true; - HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to true later when the camera is connected + HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to + // true later when the camera is connected m_cam.m_defaultGainPct = GuideCamera::GetDefaultCameraGain(); int value = pConfig->Profile.GetInt("/camera/ogma/bpp", 8); m_cam.m_bpp = value == 8 ? 8 : 16; MaxBinning = 4; } -CameraOgma::~CameraOgma() -{ -} +CameraOgma::~CameraOgma() { } bool CameraOgma::EnumCameras(wxArrayString& names, wxArrayString& ids) { @@ -376,8 +363,8 @@ bool CameraOgma::Connect(const wxString& camIdArg) HasCooler = (info->model->flag & OGMACAM_FLAG_TEC) != 0; m_cam.m_hasGuideOutput = (info->model->flag & OGMACAM_FLAG_ST4) != 0; - Debug.Write(wxString::Format("OGMA: isColor = %d, hasCooler = %d, hasST4 = %d\n", - m_cam.m_isColor, HasCooler, m_cam.m_hasGuideOutput)); + Debug.Write(wxString::Format( + "OGMA: isColor = %d, hasCooler = %d, hasST4 = %d\n", m_cam.m_isColor, HasCooler, m_cam.m_hasGuideOutput)); if (FAILED(Ogmacam_get_Resolution(m_cam.m_h, 0, &m_cam.m_maxSize.x, &m_cam.m_maxSize.y))) { @@ -444,7 +431,8 @@ bool CameraOgma::Connect(const wxString& camIdArg) m_cam.m_maxGain = maxGain; HasGainControl = maxGain > minGain; m_cam.m_defaultGainPct = m_cam.gain_pct(defaultGain); - Debug.Write(wxString::Format("OGMA: gain range %d .. %d, default = %d (%d%%)\n", minGain, maxGain, defaultGain, m_cam.m_defaultGainPct)); + Debug.Write(wxString::Format( + "OGMA: gain range %d .. %d, default = %d (%d%%)\n", minGain, maxGain, defaultGain, m_cam.m_defaultGainPct)); } else { @@ -469,14 +457,14 @@ bool CameraOgma::Connect(const wxString& camIdArg) m_cam.SetOption(OGMACAM_OPTION_RAW, 1); m_cam.SetOption(OGMACAM_OPTION_BITDEPTH, m_cam.m_bpp == 8 ? 0 : 1); m_cam.SetOption(OGMACAM_OPTION_LINEAR, 0); - //m_cam.SetOption(OGMACAM_OPTION_CURVE, 0); // resetting this one fails on all the cameras I have + // m_cam.SetOption(OGMACAM_OPTION_CURVE, 0); // resetting this one fails on all the cameras I have m_cam.SetOption(OGMACAM_OPTION_COLORMATIX, 0); m_cam.SetOption(OGMACAM_OPTION_WBGAIN, 0); - m_cam.SetOption(OGMACAM_OPTION_TRIGGER, 1); // software trigger + m_cam.SetOption(OGMACAM_OPTION_TRIGGER, 1); // software trigger m_cam.SetOption(OGMACAM_OPTION_AUTOEXP_POLICY, 0); // 0="Exposure Only" 1="Exposure Preferred" m_cam.SetOption(OGMACAM_OPTION_ROTATE, 0); m_cam.SetOption(OGMACAM_OPTION_UPSIDE_DOWN, 0); - //m_cam.SetOption(OGMACAM_OPTION_CG, 0); // "Conversion Gain" 0=LCG 1=HCG 2=HDR // setting this fails + // m_cam.SetOption(OGMACAM_OPTION_CG, 0); // "Conversion Gain" 0=LCG 1=HCG 2=HDR // setting this fails m_cam.SetOption(OGMACAM_OPTION_FFC, 0); m_cam.SetOption(OGMACAM_OPTION_DFC, 0); m_cam.SetOption(OGMACAM_OPTION_SHARPENING, 0); @@ -501,12 +489,8 @@ bool CameraOgma::Connect(const wxString& camIdArg) unsigned int fourcc, bpp; if (SUCCEEDED(hr = Ogmacam_get_RawFormat(m_cam.m_h, &fourcc, &bpp))) { - Debug.Write(wxString::Format("OGMA: raw format = %c%c%c%c bit depth = %u\n", - fourcc & 0xff, - (fourcc >> 8) & 0xff, - (fourcc >> 16) & 0xff, - fourcc >> 24, - bpp)); + Debug.Write(wxString::Format("OGMA: raw format = %c%c%c%c bit depth = %u\n", fourcc & 0xff, (fourcc >> 8) & 0xff, + (fourcc >> 16) & 0xff, fourcc >> 24, bpp)); } else Debug.Write(wxString::Format("OGMA: Ogmacam_get_RawFormat failed with status 0x%x\n", hr)); @@ -560,7 +544,7 @@ bool CameraOgma::Capture(int duration, usImage& img, int options, const wxRect& unsigned int const binning = m_cam.m_curBin; - wxRect roi; // un-binned coordinates + wxRect roi; // un-binned coordinates if (useSubframe) { @@ -605,7 +589,7 @@ bool CameraOgma::Capture(int duration, usImage& img, int options, const wxRect& m_cam.StartCapture(); - //Debug.Write("OGMA: capture: trigger\n"); + // Debug.Write("OGMA: capture: trigger\n"); if (FAILED(hr = Ogmacam_Trigger(m_cam.m_h, 1))) Debug.Write(wxString::Format("OGMA: Ogmacam_Trigger(1) failed with status 0x%x\n", hr)); @@ -658,7 +642,7 @@ bool CameraOgma::Capture(int duration, usImage& img, int options, const wxRect& return true; } - //Debug.Write("OGMA: capture: image ready\n"); + // Debug.Write("OGMA: capture: image ready\n"); void *buf; wxSize sz; @@ -724,7 +708,7 @@ bool CameraOgma::Capture(int duration, usImage& img, int options, const wxRect& } } - //Debug.Write("OGMA: capture: pull done\n"); + // Debug.Write("OGMA: capture: pull done\n"); if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); @@ -749,10 +733,14 @@ inline static int GetOgmacamDirection(int direction) switch (direction) { default: - case NORTH: return 0; - case EAST: return 2; - case WEST: return 3; - case SOUTH: return 1; + case NORTH: + return 0; + case EAST: + return 2; + case WEST: + return 3; + case SOUTH: + return 1; } } @@ -811,7 +799,7 @@ OgmaCameraDlg::OgmaCameraDlg() wxStdDialogButtonSizer *sdbSizer2 = new wxStdDialogButtonSizer(); wxButton *sdbSizer2OK = new wxButton(this, wxID_OK); - wxButton* sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); + wxButton *sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); sdbSizer2->AddButton(sdbSizer2OK); sdbSizer2->AddButton(sdbSizer2Cancel); sdbSizer2->Realize(); @@ -867,13 +855,13 @@ bool CameraOgma::SetCoolerOn(bool on) bool CameraOgma::SetCoolerSetpoint(double temperature) { - int val = (int)(temperature * 10.); -#if defined(OGMACAM_TEC_TARGET_MIN) + int val = (int) (temperature * 10.); +# if defined(OGMACAM_TEC_TARGET_MIN) val = wxMax(val, OGMACAM_TEC_TARGET_MIN); -#endif -#if defined(OGMACAM_TEC_TARGET_MAX) +# endif +# if defined(OGMACAM_TEC_TARGET_MAX) val = wxMin(val, OGMACAM_TEC_TARGET_MAX); -#endif +# endif return m_cam.SetOption(OGMACAM_OPTION_TECTARGET, val) ? false : true; } @@ -893,8 +881,7 @@ bool CameraOgma::GetCoolerStatus(bool *on, double *setpoint, double *power, doub else err = true; - if (m_cam.GetOption(OGMACAM_OPTION_TEC_VOLTAGE, &vcur) && - m_cam.GetOption(OGMACAM_OPTION_TEC_VOLTAGE_MAX, &vmax) && + if (m_cam.GetOption(OGMACAM_OPTION_TEC_VOLTAGE, &vcur) && m_cam.GetOption(OGMACAM_OPTION_TEC_VOLTAGE_MAX, &vmax) && vmax > 0) { *power = vcur * 100.0 / vmax; diff --git a/src/cam_opencv.cpp b/src/cam_opencv.cpp index c0466d478..f8115e1eb 100644 --- a/src/cam_opencv.cpp +++ b/src/cam_opencv.cpp @@ -38,14 +38,14 @@ #ifdef OPENCV_CAMERA -#include "cam_opencv.h" +# include "cam_opencv.h" -#include +# include CameraOpenCV::CameraOpenCV(int devNumber) { Connected = false; - Name=_T("OpenCV"); + Name = _T("OpenCV"); FullSize = wxSize(640, 480); m_hasGuideOutput = false; pCapDev = NULL; @@ -98,7 +98,8 @@ bool CameraOpenCV::Connect(const wxString& camId) bError = true; } - return bError;; + return bError; + ; } bool CameraOpenCV::Disconnect() @@ -172,4 +173,4 @@ bool CameraOpenCV::Capture(int duration, usImage& img, int options, const wxRect return bError; } -#endif // OPENCV_CAMERA +#endif // OPENCV_CAMERA diff --git a/src/cam_opencv.h b/src/cam_opencv.h index fa843afd9..7505278a3 100644 --- a/src/cam_opencv.h +++ b/src/cam_opencv.h @@ -41,7 +41,7 @@ class CameraOpenCV : public GuideCamera { - int DeviceNum; + int DeviceNum; protected: cv::VideoCapture *pCapDev; @@ -50,11 +50,11 @@ class CameraOpenCV : public GuideCamera CameraOpenCV(int devNumber); ~CameraOpenCV(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - bool HasNonGuiCapture() override { return true; } - wxByte BitsPerPixel() override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + bool HasNonGuiCapture() override { return true; } + wxByte BitsPerPixel() override; }; -#endif //CAM_OPENCV_H_INCLUDED +#endif // CAM_OPENCV_H_INCLUDED diff --git a/src/cam_openssag.cpp b/src/cam_openssag.cpp index ca088870d..86c9e40be 100644 --- a/src/cam_openssag.cpp +++ b/src/cam_openssag.cpp @@ -36,12 +36,12 @@ #ifdef OPENSSAG_CAMERA -#include "camera.h" -#include "image_math.h" -#include "cam_openssag.h" +# include "camera.h" +# include "image_math.h" +# include "cam_openssag.h" -#include -#include +# include +# include using namespace OpenSSAG; @@ -71,9 +71,9 @@ CameraOpenSSAG::CameraOpenSSAG() { Connected = false; Name = _T("StarShoot Autoguider (OpenSSAG)"); - FullSize = wxSize(1280,1024); // Current size of a full frame - m_hasGuideOutput = true; // Do we have an ST4 port? - HasGainControl = true; // Can we adjust gain? + FullSize = wxSize(1280, 1024); // Current size of a full frame + m_hasGuideOutput = true; // Do we have an ST4 port? + HasGainControl = true; // Can we adjust gain? PropertyDialogType = PROPDLG_WHEN_DISCONNECTED; ssag = new SSAG(); @@ -115,7 +115,12 @@ bool CameraOpenSSAG::Connect(const wxString& camId) { SSAG *ssag; int vid, pid; - ConnectInBg(SSAG *ssag_, int vid_, int pid_) : ssag(ssag_), vid(vid_), pid(pid_) { } + ConnectInBg(SSAG *ssag_, int vid_, int pid_) + : ssag(ssag_) + , vid(vid_) + , pid(pid_) + { + } bool Entry() { bool err = !ssag->Connect(true, vid, pid); @@ -131,27 +136,29 @@ bool CameraOpenSSAG::Connect(const wxString& camId) return CamConnectFailed(_("Could not connect to StarShoot Autoguider")); } - Connected = true; // Set global flag for being connected + Connected = true; // Set global flag for being connected return false; } bool CameraOpenSSAG::ST4PulseGuideScope(int direction, int duration) { - switch (direction) { - case WEST: - ssag->Guide(guide_west, duration); - break; - case NORTH: - ssag->Guide(guide_north, duration); - break; - case SOUTH: - ssag->Guide(guide_south, duration); - break; - case EAST: - ssag->Guide(guide_east, duration); - break; - default: return true; // bad direction passed in + switch (direction) + { + case WEST: + ssag->Guide(guide_west, duration); + break; + case NORTH: + ssag->Guide(guide_north, duration); + break; + case SOUTH: + ssag->Guide(guide_south, duration); + break; + case EAST: + ssag->Guide(guide_east, duration); + break; + default: + return true; // bad direction passed in } wxMilliSleep(duration + 10); @@ -174,7 +181,7 @@ bool CameraOpenSSAG::Capture(int duration, usImage& img, int options, const wxRe return true; } - ssag->SetGain((int)(GuideCameraGain / 24)); + ssag->SetGain((int) (GuideCameraGain / 24)); struct raw_image *raw = ssag->Expose(duration); if (!raw) @@ -183,13 +190,15 @@ bool CameraOpenSSAG::Capture(int duration, usImage& img, int options, const wxRe return true; } - for (unsigned int i = 0; i < raw->width * raw->height; i++) { + for (unsigned int i = 0; i < raw->width * raw->height; i++) + { img.ImageData[i] = (unsigned short) raw->data[i]; } ssag->FreeRawImage(raw); - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return false; } @@ -231,7 +240,8 @@ PropertiesDlg::PropertiesDlg(wxWindow *parent) wxBoxSizer *sz0 = new wxBoxSizer(wxVERTICAL); wxWindow *label = new wxStaticText(this, wxID_ANY, _("Loader VID:")); - m_vid = new wxTextCtrl(this, wxID_ANY, wxString::Format("0x%04x", vid), wxDefaultPosition, wxSize(TextWidth(this, "0x88888"), -1)); + m_vid = new wxTextCtrl( + this, wxID_ANY, wxString::Format("0x%04x", vid), wxDefaultPosition, wxSize(TextWidth(this, "0x88888"), -1)); m_vid->SetToolTip(wxString::Format(_("SSAG Loader USB Vendor ID. Default = 0x%04x"), default_loader_vid)); wxSizer *sz1 = new wxBoxSizer(wxHORIZONTAL); @@ -241,7 +251,8 @@ PropertiesDlg::PropertiesDlg(wxWindow *parent) sz0->Add(sz1, 1, wxEXPAND, 5); label = new wxStaticText(this, wxID_ANY, _("Loader PID:")); - m_pid = new wxTextCtrl(this, wxID_ANY, wxString::Format("0x%04x", pid), wxDefaultPosition, wxSize(TextWidth(this, "0x88888"), -1)); + m_pid = new wxTextCtrl( + this, wxID_ANY, wxString::Format("0x%04x", pid), wxDefaultPosition, wxSize(TextWidth(this, "0x88888"), -1)); m_pid->SetToolTip(wxString::Format(_("SSAG Loader USB Product ID. Default = 0x%04x"), default_loader_pid)); sz1 = new wxBoxSizer(wxHORIZONTAL); @@ -270,8 +281,7 @@ void CameraOpenSSAG::ShowPropertyDialog() if (dlg.ShowModal() == wxID_OK) { long vid, pid; - if (dlg.m_vid->GetValue().ToLong(&vid, 0) && - dlg.m_pid->GetValue().ToLong(&pid, 0)) + if (dlg.m_vid->GetValue().ToLong(&vid, 0) && dlg.m_pid->GetValue().ToLong(&pid, 0)) { SetLoaderVidPid(vid, pid); } diff --git a/src/cam_openssag.h b/src/cam_openssag.h index 6bd929f88..50ddd64d6 100644 --- a/src/cam_openssag.h +++ b/src/cam_openssag.h @@ -35,13 +35,15 @@ #ifndef CAM_OPENSSAG_H_INCLUDED #define CAM_OPENSSAG_H_INCLUDED -namespace OpenSSAG { - class SSAG; +namespace OpenSSAG +{ +class SSAG; } class CameraOpenSSAG : public GuideCamera { OpenSSAG::SSAG *ssag; + public: CameraOpenSSAG(); ~CameraOpenSSAG(); diff --git a/src/cam_qguide.cpp b/src/cam_qguide.cpp index 550f6ed80..dd69bc692 100644 --- a/src/cam_qguide.cpp +++ b/src/cam_qguide.cpp @@ -34,24 +34,27 @@ #include "phd.h" -#if defined (QGUIDE) +#if defined(QGUIDE) -#include "camera.h" -#include "time.h" -#include "image_math.h" +# include "camera.h" +# include "time.h" +# include "image_math.h" -#include -#include -//wxTextFile *qglogfile; +# include +# include +// wxTextFile *qglogfile; -int ushort_compare (const void * a, const void * b) { - if ( *(unsigned short *)a > *(unsigned short *)b ) return 1; - if ( *(unsigned short *)a < *(unsigned short *)b ) return -1; - return 0; +int ushort_compare(const void *a, const void *b) +{ + if (*(unsigned short *) a > *(unsigned short *) b) + return 1; + if (*(unsigned short *) a < *(unsigned short *) b) + return -1; + return 0; } -#define QGDEBUG 0 -#include "cam_qguide.h" +# define QGDEBUG 0 +# include "cam_qguide.h" // QHY CMOS guide camera version // Tom's driver @@ -59,7 +62,7 @@ CameraQGuider::CameraQGuider() { Connected = false; Name = _T("Q-Guider"); - FullSize = wxSize(1280,1024); + FullSize = wxSize(1280, 1024); m_hasGuideOutput = true; HasGainControl = true; } @@ -71,18 +74,18 @@ wxByte CameraQGuider::BitsPerPixel() bool CameraQGuider::Connect(const wxString& camId) { -// returns true on error -// CameraReset(); + // returns true on error + // CameraReset(); if (!openUSB(0)) return CamConnectFailed(_("No camera")); -// ClearGuidePort(); -// GuideCommand(0x0F,10); -// buffer = new unsigned char[1311744]; + // ClearGuidePort(); + // GuideCommand(0x0F,10); + // buffer = new unsigned char[1311744]; SETBUFFERMODE(0); Connected = true; -// qglogfile = new wxTextFile(Debug.GetLogDir() + PATHSEPSTR + _T("PHD_QGuide_log.txt")); - //qglogfile->AddLine(wxNow() + ": QGuide connected"); //qglogfile->Write(); + // qglogfile = new wxTextFile(Debug.GetLogDir() + PATHSEPSTR + _T("PHD_QGuide_log.txt")); + // qglogfile->AddLine(wxNow() + ": QGuide connected"); //qglogfile->Write(); return false; } @@ -91,41 +94,52 @@ bool CameraQGuider::ST4PulseGuideScope(int direction, int duration) int reg = 0; int dur = duration / 10; - //qglogfile->AddLine(wxString::Format("Sending guide dur %d",dur)); //qglogfile->Write(); - if (dur >= 255) dur = 254; // Max guide pulse is 2.54s -- 255 keeps it on always + // qglogfile->AddLine(wxString::Format("Sending guide dur %d",dur)); //qglogfile->Write(); + if (dur >= 255) + dur = 254; // Max guide pulse is 2.54s -- 255 keeps it on always // Output pins are NC, Com, RA+(W), Dec+(N), Dec-(S), RA-(E) ?? http://www.starlight-xpress.co.uk/faq.htm - switch (direction) { - case WEST: reg = 0x80; break; // 0111 0000 - case NORTH: reg = 0x40; break; // 1011 0000 - case SOUTH: reg = 0x20; break; // 1101 0000 - case EAST: reg = 0x10; break; // 1110 0000 - default: return true; // bad direction passed in + switch (direction) + { + case WEST: + reg = 0x80; + break; // 0111 0000 + case NORTH: + reg = 0x40; + break; // 1011 0000 + case SOUTH: + reg = 0x20; + break; // 1101 0000 + case EAST: + reg = 0x10; + break; // 1110 0000 + default: + return true; // bad direction passed in } - GuideCommand(reg,dur); - //if (duration > 50) wxMilliSleep(duration - 50); // wait until it's mostly done + GuideCommand(reg, dur); + // if (duration > 50) wxMilliSleep(duration - 50); // wait until it's mostly done WorkerThread::MilliSleep(duration + 10); - //qglogfile->AddLine("Done"); //qglogfile->Write(); + // qglogfile->AddLine("Done"); //qglogfile->Write(); return false; } void CameraQGuider::ClearGuidePort() { -// SendGuideCommand(DevName,0,0); + // SendGuideCommand(DevName,0,0); } void CameraQGuider::InitCapture() { -// CameraReset(); - ProgramCamera(0,0,1280,1024, (GuideCameraGain * 63 / 100) ); -// SetNoiseReduction(0); + // CameraReset(); + ProgramCamera(0, 0, 1280, 1024, (GuideCameraGain * 63 / 100)); + // SetNoiseReduction(0); } bool CameraQGuider::Disconnect() { closeUSB(); -// delete [] buffer; + // delete [] buffer; Connected = false; - //qglogfile->AddLine(wxNow() + ": Disconnecting"); //qglogfile->Write(); //qglogfile->Close(); + // qglogfile->AddLine(wxNow() + ": Disconnecting"); //qglogfile->Write(); //qglogfile->Close(); return false; } @@ -138,35 +152,35 @@ static bool StopExposure() bool CameraQGuider::Capture(int duration, usImage& img, int options, const wxRect& subframe) { -// Only does full frames still + // Only does full frames still unsigned short *dptr; bool firstimg = true; - //qglogfile->AddLine(wxString::Format("Capturing dur %d",duration)); //qglogfile->Write(); -// ThreadedExposure(10, buffer); - ProgramCamera(0,0,1280,1024, (GuideCameraGain * 63 / 100) ); + // qglogfile->AddLine(wxString::Format("Capturing dur %d",duration)); //qglogfile->Write(); + // ThreadedExposure(10, buffer); + ProgramCamera(0, 0, 1280, 1024, (GuideCameraGain * 63 / 100)); -/* ThreadedExposure(10, NULL); - while (isExposing()) - wxMilliSleep(10); -*/ - if (img.Init(FullSize)) { + /* ThreadedExposure(10, NULL); + while (isExposing()) + wxMilliSleep(10); + */ + if (img.Init(FullSize)) + { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } // ThreadedExposure(duration, buffer); ThreadedExposure(duration, NULL); - //qglogfile->AddLine("Exposure programmed"); //qglogfile->Write(); + // qglogfile->AddLine("Exposure programmed"); //qglogfile->Write(); CameraWatchdog watchdog(duration, GetTimeoutMs() + 1000); // typically 6 second timeout if (duration > 100) { // Shift to > duration - if (WorkerThread::MilliSleep(duration + 100) && - (WorkerThread::TerminateRequested() || StopExposure())) + if (WorkerThread::MilliSleep(duration + 100) && (WorkerThread::TerminateRequested() || StopExposure())) { return true; } @@ -175,8 +189,7 @@ bool CameraQGuider::Capture(int duration, usImage& img, int options, const wxRec while (isExposing()) { wxMilliSleep(200); - if (WorkerThread::InterruptRequested() && - (WorkerThread::TerminateRequested() || StopExposure())) + if (WorkerThread::InterruptRequested() && (WorkerThread::TerminateRequested() || StopExposure())) { return true; } @@ -187,16 +200,17 @@ bool CameraQGuider::Capture(int duration, usImage& img, int options, const wxRec } } - //qglogfile->AddLine("Exposure done"); //qglogfile->Write(); + // qglogfile->AddLine("Exposure done"); //qglogfile->Write(); -/* dptr = img.ImageData; - for (unsigned int i=0; i 65535) val = 65535; + if (val < 0) + val = 0; + else if (val > 65535) + val = 65535; *ptr2 = (unsigned short) val; } - } } #endif diff --git a/src/cam_qguide.h b/src/cam_qguide.h index 81bb74596..700e780ea 100644 --- a/src/cam_qguide.h +++ b/src/cam_qguide.h @@ -43,19 +43,19 @@ class CameraQGuider : public GuideCamera public: CameraQGuider(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - void InitCapture() override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + void InitCapture() override; - bool ST4PulseGuideScope(int direction, int duration) override; - void ClearGuidePort(); - bool HasNonGuiCapture() override { return true; } - bool ST4HasNonGuiMove() override { return true; } - wxByte BitsPerPixel() override; + bool ST4PulseGuideScope(int direction, int duration) override; + void ClearGuidePort(); + bool HasNonGuiCapture() override { return true; } + bool ST4HasNonGuiMove() override { return true; } + wxByte BitsPerPixel() override; private: void RemoveLines(usImage& img); }; -#endif //QGUIDEDEF +#endif // QGUIDEDEF diff --git a/src/cam_qhy.cpp b/src/cam_qhy.cpp index ced573ade..2e5c40b30 100644 --- a/src/cam_qhy.cpp +++ b/src/cam_qhy.cpp @@ -1,44 +1,44 @@ /* -* cam_qhy.cpp -* Open PHD Guiding -* -* Created by Andy Galasso. -* Copyright (c) 2015-2019 Andy Galasso. -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * cam_qhy.cpp + * Open PHD Guiding + * + * Created by Andy Galasso. + * Copyright (c) 2015-2019 Andy Galasso. + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #if defined(QHY_CAMERA) -#include "camera.h" -#include "cam_qhy.h" -#include "qhyccd.h" +# include "camera.h" +# include "cam_qhy.h" +# include "qhyccd.h" class Camera_QHY : public GuideCamera { @@ -57,7 +57,6 @@ class Camera_QHY : public GuideCamera wxByte m_bpp; public: - Camera_QHY(); ~Camera_QHY(); @@ -80,13 +79,13 @@ static bool s_qhySdkInitDone = false; static wxString GetQHYSDKVersion() { -#if defined (__APPLE__) +# if defined(__APPLE__) return "V7.4.16.4"; // FIXME - remove this when we update to the newer SDK that implements GetQHYCCDSDKVersion -#else +# else uint32_t YMDS[4] = {}; GetQHYCCDSDKVersion(&YMDS[0], &YMDS[1], &YMDS[2], &YMDS[3]); return wxString::Format("V20%02d%02d%02d_%d", YMDS[0], YMDS[1], YMDS[2], YMDS[3]); -#endif +# endif } static bool QHYSDKInit() @@ -103,20 +102,20 @@ static bool QHYSDKInit() long ll; if (wxGetEnv("QHY_LOG_LEVEL", &s) && s.ToLong(&ll)) lvl = static_cast(std::min(std::max(ll, 0L), 6L)); -#if !defined(__WINDOWS__) +# if !defined(__WINDOWS__) EnableQHYCCDLogFile(false); -#endif +# endif SetQHYCCDLogLevel(lvl); uint32_t ret; if ((ret = InitQHYCCDResource()) != 0) { - Debug.Write(wxString::Format("InitQHYCCDResource failed: %d\n", (int)ret)); + Debug.Write(wxString::Format("InitQHYCCDResource failed: %d\n", (int) ret)); return true; } -#if defined (__APPLE__) +# if defined(__APPLE__) Debug.Write("QHY: call OSXInitQHYCCDFirmwareArray()\n"); ret = OSXInitQHYCCDFirmwareArray(); Debug.Write(wxString::Format("QHY: OSXInitQHYCCDFirmwareArray() returns %d\n", ret)); @@ -134,7 +133,7 @@ static bool QHYSDKInit() } } // non-zero result indicates camera already has firmware -#endif +# endif s_qhySdkInitDone = true; return false; @@ -183,7 +182,10 @@ bool Camera_QHY::GetDevicePixelSize(double *devPixelSize) int Camera_QHY::GetDefaultCameraGain() { - enum { DefaultQHYCameraGain = 40 }; + enum + { + DefaultQHYCameraGain = 40 + }; return DefaultQHYCameraGain; } @@ -207,8 +209,9 @@ bool Camera_QHY::EnumCameras(wxArrayString& names, wxArrayString& ids) uint32_t ret = IsQHYCCDControlAvailable(h, CONTROL_ST4PORT); if (ret == QHYCCD_SUCCESS) st4 = true; - //CloseQHYCCD(h); // CloseQHYCCD() would proform a reset, so the other software that use QHY camera would be impacted. - // Do not call this,would not cause memory leak.The SDk has already process this. + // CloseQHYCCD(h); // CloseQHYCCD() would proform a reset, so the other software that use QHY camera would be + // impacted. + // Do not call this,would not cause memory leak.The SDk has already process this. } Debug.Write(wxString::Format("QHY cam [%d] %s avail %s st4 %s\n", i, camid, h ? "Yes" : "No", st4 ? "Yes" : "No")); if (st4) @@ -305,7 +308,8 @@ bool Camera_QHY::Connect(const wxString& camId) Debug.Write(wxString::Format("QHY: cam reports bayer type %d\n", bayer)); Color = false; - switch ((BAYER_ID)bayer) { + switch ((BAYER_ID) bayer) + { case BAYER_GB: case BAYER_GR: case BAYER_BG: @@ -314,13 +318,21 @@ bool Camera_QHY::Connect(const wxString& camId) } // check bin modes - CONTROL_ID modes[] = { CAM_BIN2X2MODE, CAM_BIN3X3MODE, CAM_BIN4X4MODE, }; - int bin[] = { 2, 3, 4, }; + CONTROL_ID modes[] = { + CAM_BIN2X2MODE, + CAM_BIN3X3MODE, + CAM_BIN4X4MODE, + }; + int bin[] = { + 2, + 3, + 4, + }; int maxBin = 1; for (int i = 0; i < WXSIZEOF(modes); i++) { ret = IsQHYCCDControlAvailable(m_camhandle, modes[i]); -#if 0 +# if 0 // FIXME- IsQHYCCDControlAvailable is supposed to return QHYCCD_ERROR_NOTSUPPORT for a // bin mode that is not supported, but in fact it returns QHYCCD_ERROR, so we cannot // distinguish "not supported" from "error". @@ -330,7 +342,7 @@ bool Camera_QHY::Connect(const wxString& camId) m_camhandle = 0; return CamConnectFailed(_("Failed to get camera bin info")); } -#endif +# endif if (ret == QHYCCD_SUCCESS) maxBin = bin[i]; else @@ -362,7 +374,7 @@ bool Camera_QHY::Connect(const wxString& camId) m_curGain = -1; m_curExposure = -1; - m_roi = wxRect(0, 0, FullSize.GetWidth(), FullSize.GetHeight()); // binned coordinates + m_roi = wxRect(0, 0, FullSize.GetWidth(), FullSize.GetHeight()); // binned coordinates Debug.Write(wxString::Format("QHY: call SetQHYCCDResolution roi = %d,%d\n", m_roi.width, m_roi.height)); ret = SetQHYCCDResolution(m_camhandle, 0, 0, m_roi.GetWidth(), m_roi.GetHeight()); @@ -388,10 +400,10 @@ static void StopCapture(qhyccd_handle *handle) bool Camera_QHY::Disconnect() { StopCapture(m_camhandle); -#if !defined(__APPLE__) +# if !defined(__APPLE__) // this crashes on macOS, but seems to work ok without it CloseQHYCCD(m_camhandle); -#endif +# endif m_camhandle = 0; Connected = false; delete[] RawBuffer; @@ -405,11 +417,20 @@ bool Camera_QHY::ST4PulseGuideScope(int direction, int duration) switch (direction) { - case NORTH: qdir = 1; break; - case SOUTH: qdir = 2; break; - case EAST: qdir = 0; break; - case WEST: qdir = 3; break; - default: return true; // bad direction passed in + case NORTH: + qdir = 1; + break; + case SOUTH: + qdir = 2; + break; + case EAST: + qdir = 0; + break; + case WEST: + qdir = 3; + break; + default: + return true; // bad direction passed in } if (duration > (uint16_t) (-1)) duration = (uint16_t) (-1); @@ -429,7 +450,7 @@ inline static int round_up(int v, int m) } // stopping capture causes problems on some cameras on Windows, disable it for now until we can test with a newer SDK -//#define CAN_STOP_CAPTURE +// #define CAN_STOP_CAPTURE bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& subframe) { @@ -459,7 +480,10 @@ bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& // Use a larger ROI around the subframe to avoid changing the ROI as the centroid // wobbles around. Changing the ROI introduces a lag of several seconds. // This also satifies the constraint that ROI width and height must be multiples of 4. - enum { PAD = 1 << 5 }; + enum + { + PAD = 1 << 5 + }; roi.SetLeft(round_down(subframe.GetLeft(), PAD)); roi.SetRight(round_up(subframe.GetRight() + 1, PAD) - 1); roi.SetTop(round_down(subframe.GetTop(), PAD)); @@ -475,7 +499,7 @@ bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& ret = SetQHYCCDBinMode(m_camhandle, Binning, Binning); if (ret != QHYCCD_SUCCESS) { - Debug.Write(wxString::Format("SetQHYCCDBinMode failed! ret = %d\n", (int)ret)); + Debug.Write(wxString::Format("SetQHYCCDBinMode failed! ret = %d\n", (int) ret)); } if (m_roi != roi) @@ -498,8 +522,8 @@ bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& } else { - Debug.Write(wxString::Format("SetQHYCCDResolution(%d,%d,%d,%d) failed! ret = %d\n", - roi.GetLeft(), roi.GetTop(), roi.GetWidth(), roi.GetHeight(), (int)ret)); + Debug.Write(wxString::Format("SetQHYCCDResolution(%d,%d,%d,%d) failed! ret = %d\n", roi.GetLeft(), roi.GetTop(), + roi.GetWidth(), roi.GetHeight(), (int) ret)); } } @@ -512,7 +536,7 @@ bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& } else { - Debug.Write(wxString::Format("QHY set exposure ret %d\n", (int)ret)); + Debug.Write(wxString::Format("QHY set exposure ret %d\n", (int) ret)); pFrame->Alert(_("Failed to set camera exposure")); } } @@ -529,7 +553,7 @@ bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& } else { - Debug.Write(wxString::Format("QHY set gain ret %d\n", (int)ret)); + Debug.Write(wxString::Format("QHY set gain ret %d\n", (int) ret)); pFrame->Alert(_("Failed to set camera gain")); } } @@ -537,17 +561,17 @@ bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& ret = ExpQHYCCDSingleFrame(m_camhandle); if (ret == QHYCCD_ERROR) { - Debug.Write(wxString::Format("QHY exp single frame ret %d\n", (int)ret)); + Debug.Write(wxString::Format("QHY exp single frame ret %d\n", (int) ret)); DisconnectWithAlert(_("QHY exposure failed"), NO_RECONNECT); return true; } -#ifdef CAN_STOP_CAPTURE +# ifdef CAN_STOP_CAPTURE if (WorkerThread::InterruptRequested()) { StopCapture(m_camhandle); return true; } -#endif +# endif if (ret == QHYCCD_SUCCESS) { Debug.Write(wxString::Format("QHY: 200ms delay needed\n")); @@ -555,7 +579,7 @@ bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& } if (ret == QHYCCD_READ_DIRECTLY) { - //Debug.Write("QHYCCD_READ_DIRECTLY\n"); + // Debug.Write("QHYCCD_READ_DIRECTLY\n"); } uint32_t w, h, bpp, channels; @@ -563,22 +587,22 @@ bool Camera_QHY::Capture(int duration, usImage& img, int options, const wxRect& if (ret != QHYCCD_SUCCESS || (bpp != 8 && bpp != 16)) { Debug.Write(wxString::Format("QHY get single frame ret %d bpp %u\n", ret, bpp)); -#ifdef CAN_STOP_CAPTURE +# ifdef CAN_STOP_CAPTURE StopCapture(m_camhandle); -#endif +# endif // users report that reconnecting the camera after this failure allows // them to resume guiding so we'll try to reconnect automatically DisconnectWithAlert(_("QHY get frame failed"), RECONNECT); return true; } -#ifdef CAN_STOP_CAPTURE +# ifdef CAN_STOP_CAPTURE if (WorkerThread::InterruptRequested()) { StopCapture(m_camhandle); return true; } -#endif +# endif if (useSubframe) { diff --git a/src/cam_qhy5.cpp b/src/cam_qhy5.cpp index 8c7e04114..09279cbac 100644 --- a/src/cam_qhy5.cpp +++ b/src/cam_qhy5.cpp @@ -32,39 +32,35 @@ * */ - #include "phd.h" #if defined(CAM_QHY5) -#include -#include "camera.h" -#include "image_math.h" +# include +# include "camera.h" +# include "image_math.h" -#include "cam_qhy5.h" +# include "cam_qhy5.h" -#define QHY5_MATRIX_WIDTH 1558 -#define QHY5_MATRIX_HEIGHT 1048 -#define QHY5_BUFFER_SIZE (QHY5_MATRIX_WIDTH * (QHY5_MATRIX_HEIGHT + 2)) +# define QHY5_MATRIX_WIDTH 1558 +# define QHY5_MATRIX_HEIGHT 1048 +# define QHY5_BUFFER_SIZE (QHY5_MATRIX_WIDTH * (QHY5_MATRIX_HEIGHT + 2)) -#define QHY5_IMAGE_WIDTH 1280 -#define QHY5_IMAGE_HEIGHT 1024 +# define QHY5_IMAGE_WIDTH 1280 +# define QHY5_IMAGE_HEIGHT 1024 -#define QHY5_VID 0x16c0 -#define QHY5_PID 0x296d -#define STORE_WORD_BE(var, val) *(var) = ((val) >> 8) & 0xff; *((var) + 1) = (val) & 0xff +# define QHY5_VID 0x16c0 +# define QHY5_PID 0x296d +# define STORE_WORD_BE(var, val) \ + *(var) = ((val) >> 8) & 0xff; \ + *((var) + 1) = (val) & 0xff static unsigned char reg[19]; -static int gain_lut[74] = {0x000, 0x004, 0x005, 0x006, 0x007, 0x008, 0x009, 0x00A, 0x00B, - 0x00C, 0x00D, 0x00E, 0x00F, 0x010, 0x011, 0x012, 0x013, 0x014, - 0x015, 0x016, 0x017, 0x018, 0x019, 0x01A, 0x01B, 0x01C, 0x01D, - 0x01E, 0x01F, 0x051, 0x052, 0x053, 0x054, 0x055, 0x056, 0x057, - 0x058, 0x059, 0x05A, 0x05B, 0x05C, 0x05D, 0x05E, 0x05F, 0x6CE, - 0x6CF, 0x6D0, 0x6D1, 0x6D2, 0x6D3, 0x6D4, 0x6D5, 0x6D6, 0x6D7, - 0x6D8, 0x6D9, 0x6DA, 0x6DB, 0x6DC, 0x6DD, 0x6DE, 0x6DF, 0x6E0, - 0x6E1, 0x6E2, 0x6E3, 0x6E4, 0x6E5, 0x6E6, 0x6E7, 0x6FC, 0x6FD, - 0x6FE, 0x6FF - }; +static int gain_lut[74] = { 0x000, 0x004, 0x005, 0x006, 0x007, 0x008, 0x009, 0x00A, 0x00B, 0x00C, 0x00D, 0x00E, 0x00F, 0x010, + 0x011, 0x012, 0x013, 0x014, 0x015, 0x016, 0x017, 0x018, 0x019, 0x01A, 0x01B, 0x01C, 0x01D, 0x01E, 0x01F, 0x051, 0x052, + 0x053, 0x054, 0x055, 0x056, 0x057, 0x058, 0x059, 0x05A, 0x05B, 0x05C, 0x05D, 0x05E, 0x05F, 0x6CE, 0x6CF, 0x6D0, 0x6D1, + 0x6D2, 0x6D3, 0x6D4, 0x6D5, 0x6D6, 0x6D7, 0x6D8, 0x6D9, 0x6DA, 0x6DB, 0x6DC, 0x6DD, 0x6DE, 0x6DF, 0x6E0, 0x6E1, 0x6E2, + 0x6E3, 0x6E4, 0x6E5, 0x6E6, 0x6E7, 0x6FC, 0x6FD, 0x6FE, 0x6FF }; static libusb_device_handle *m_handle = NULL; @@ -125,14 +121,14 @@ bool CameraQHY5::Connect(const wxString& camId) return true; } - if ( libusb_kernel_driver_active( m_handle, 0 ) ) - libusb_detach_kernel_driver( m_handle, 0 ); + if (libusb_kernel_driver_active(m_handle, 0)) + libusb_detach_kernel_driver(m_handle, 0); - libusb_set_configuration( m_handle, 1 ); - libusb_claim_interface( m_handle, 0 ); + libusb_set_configuration(m_handle, 1); + libusb_claim_interface(m_handle, 0); if (RawBuffer) - delete [] RawBuffer; + delete[] RawBuffer; RawBuffer = new unsigned char[QHY5_BUFFER_SIZE]; @@ -155,23 +151,23 @@ bool CameraQHY5::ST4PulseGuideScope(int direction, int duration) case WEST: reg = 0x80; dur[0] = duration; - break; // 0111 0000 + break; // 0111 0000 case NORTH: reg = 0x40; dur[1] = duration; - break; // 1011 0000 + break; // 1011 0000 case SOUTH: reg = 0x20; dur[1] = duration; - break; // 1101 0000 + break; // 1101 0000 case EAST: reg = 0x10; dur[0] = duration; - break; // 1110 0000 + break; // 1110 0000 default: return true; // bad direction passed in } - result = libusb_control_transfer(m_handle, 0x42, 0x10, 0, reg, (unsigned char *)dur, sizeof(dur), 5000); + result = libusb_control_transfer(m_handle, 0x42, 0x10, 0, reg, (unsigned char *) dur, sizeof(dur), 5000); wxMilliSleep(duration + 10); return result < 0 ? true : false; } @@ -179,22 +175,20 @@ bool CameraQHY5::ST4PulseGuideScope(int direction, int duration) void CameraQHY5::ClearGuidePort() { int16_t res = 0; - libusb_control_transfer(m_handle, 0xc2, 0x18, 0, 0, (unsigned char *)&res, sizeof(res), 5000); + libusb_control_transfer(m_handle, 0xc2, 0x18, 0, 0, (unsigned char *) &res, sizeof(res), 5000); } -void CameraQHY5::InitCapture() -{ -} +void CameraQHY5::InitCapture() { } bool CameraQHY5::Disconnect() { - libusb_release_interface( m_handle, 0 ); - libusb_close( m_handle ); + libusb_release_interface(m_handle, 0); + libusb_close(m_handle); m_handle = NULL; Connected = false; if (RawBuffer) - delete [] RawBuffer; + delete[] RawBuffer; RawBuffer = NULL; return false; @@ -202,20 +196,20 @@ bool CameraQHY5::Disconnect() bool CameraQHY5::Capture(int duration, usImage& img, int options, const wxRect& subframe) { -// Only does full frames still - //static int last_dur = 0; + // Only does full frames still + // static int last_dur = 0; static int last_gain = 60; static int first_time = 1; unsigned char *bptr; unsigned short *dptr; - int x, y; + int x, y; int xsize = FullSize.GetWidth(); int ysize = FullSize.GetHeight(); int op_height = FullSize.GetHeight(); - //bool firstimg = true; + // bool firstimg = true; unsigned char buffer[2]; // for debug purposes int offset, value, index; - int gain, gain_val, gain_lut_sz = (int)(sizeof(gain_lut) / sizeof(int)); + int gain, gain_val, gain_lut_sz = (int) (sizeof(gain_lut) / sizeof(int)); int ret, result; if (img.Init(xsize, ysize)) @@ -226,21 +220,21 @@ bool CameraQHY5::Capture(int duration, usImage& img, int options, const wxRect& if (GuideCameraGain != last_gain) { - op_height -= (op_height % 4); + op_height -= (op_height % 4); offset = (QHY5_MATRIX_HEIGHT - op_height) / 2; index = (QHY5_MATRIX_WIDTH * (op_height + 26)) >> 16; value = (QHY5_MATRIX_WIDTH * (op_height + 26)) & 0xffff; - gain = (int)(73. * (GuideCameraGain / 100.)); - if ( gain >= gain_lut_sz ) + gain = (int) (73. * (GuideCameraGain / 100.)); + if (gain >= gain_lut_sz) gain = gain_lut_sz - 1; - if ( gain < 0 ) + if (gain < 0) gain = 0; - gain_val = gain_lut[ gain ]; - STORE_WORD_BE(reg + 0, gain_val); - STORE_WORD_BE(reg + 2, gain_val); - STORE_WORD_BE(reg + 4, gain_val); - STORE_WORD_BE(reg + 6, gain_val); - STORE_WORD_BE(reg + 8, offset); + gain_val = gain_lut[gain]; + STORE_WORD_BE(reg + 0, gain_val); + STORE_WORD_BE(reg + 2, gain_val); + STORE_WORD_BE(reg + 4, gain_val); + STORE_WORD_BE(reg + 6, gain_val); + STORE_WORD_BE(reg + 8, offset); STORE_WORD_BE(reg + 10, 0); STORE_WORD_BE(reg + 12, op_height - 1); STORE_WORD_BE(reg + 14, 0x0521); @@ -271,7 +265,7 @@ bool CameraQHY5::Capture(int duration, usImage& img, int options, const wxRect& /* wait for exposure end */ wxMilliSleep(duration); - ret = libusb_bulk_transfer( m_handle, 0x82, RawBuffer, QHY5_BUFFER_SIZE, &result, 20000); + ret = libusb_bulk_transfer(m_handle, 0x82, RawBuffer, QHY5_BUFFER_SIZE, &result, 20000); if (ret < 0) { pFrame->Alert(_T("Failed to read image: libusb_bulk_transfer() failed.")); @@ -284,8 +278,8 @@ bool CameraQHY5::Capture(int duration, usImage& img, int options, const wxRect& return true; } - //bptr = RawBuffer; - // Load and crop from the 800 x 525 image that came in + // bptr = RawBuffer; + // Load and crop from the 800 x 525 image that came in dptr = img.ImageData; for (y = 0; y < ysize; y++) { @@ -296,7 +290,8 @@ bool CameraQHY5::Capture(int duration, usImage& img, int options, const wxRect& } } - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return false; } diff --git a/src/cam_qhy5.h b/src/cam_qhy5.h index 6f209e6a7..8090c8d7b 100644 --- a/src/cam_qhy5.h +++ b/src/cam_qhy5.h @@ -43,16 +43,16 @@ class CameraQHY5 : public GuideCamera public: CameraQHY5(); ~CameraQHY5(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - void InitCapture() override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + void InitCapture() override; - bool ST4PulseGuideScope(int direction, int duration) override; - bool ST4HasNonGuiMove() override { return true; } - bool HasNonGuiCapture() override { return true; } - void ClearGuidePort(); - wxByte BitsPerPixel() override; + bool ST4PulseGuideScope(int direction, int duration) override; + bool ST4HasNonGuiMove() override { return true; } + bool HasNonGuiCapture() override { return true; } + void ClearGuidePort(); + wxByte BitsPerPixel() override; }; #endif // QHY5IIIBASE_H_INCLUDED diff --git a/src/cam_sbig.cpp b/src/cam_sbig.cpp index d22b63838..38495debc 100644 --- a/src/cam_sbig.cpp +++ b/src/cam_sbig.cpp @@ -36,20 +36,20 @@ #if defined(SBIG) -#include "cam_sbig.h" -#include "camera.h" -#include "image_math.h" - -#include -#include - -#if defined (__APPLE__) -#include -#elif defined(__LINUX__) -#include -#else -#include "cameras/Sbigudrv.h" -#endif +# include "cam_sbig.h" +# include "camera.h" +# include "image_math.h" + +# include +# include + +# if defined(__APPLE__) +# include +# elif defined(__LINUX__) +# include +# else +# include "cameras/Sbigudrv.h" +# endif class CameraSBIG : public GuideCamera { @@ -85,7 +85,8 @@ static unsigned long bcd2long(unsigned long bcd) int digit; unsigned long val = 0; - do { + do + { pos -= 4; digit = (bcd >> pos) & 0xf; val = val * 10 + digit; @@ -99,8 +100,8 @@ CameraSBIG::CameraSBIG() { Connected = false; Name = _T("SBIG"); - //FullSize = wxSize(1280,1024); - //HasGainControl = true; + // FullSize = wxSize(1280,1024); + // HasGainControl = true; m_hasGuideOutput = true; m_useTrackingCCD = false; HasShutter = true; @@ -123,16 +124,18 @@ static bool _LoadDriver() { short err; -#if defined (__WINDOWS__) - __try { +# if defined(__WINDOWS__) + __try + { err = SBIGUnivDrvCommand(CC_OPEN_DRIVER, NULL, NULL); } - __except (EXCEPTION_EXECUTE_HANDLER) { + __except (EXCEPTION_EXECUTE_HANDLER) + { err = CE_DRIVER_NOT_FOUND; } -#else +# else err = SBIGUnivDrvCommand(CC_OPEN_DRIVER, NULL, NULL); -#endif +# endif return err == CE_NO_ERROR; } @@ -158,20 +161,19 @@ static bool SelectInterfaceAndDevice() interf.Add("USB"); interf.Add("Ethernet"); -#if defined (__WINDOWS__) +# if defined(__WINDOWS__) interf.Add("LPT 0x378"); interf.Add("LPT 0x278"); interf.Add("LPT 0x3BC"); -#else +# else interf.Add("USB1 direct"); interf.Add("USB2 direct"); interf.Add("USB3 direct"); -#endif +# endif int resp = pConfig->Profile.GetInt("/camera/sbig/interface", 0); - resp = wxGetSingleChoiceIndex(_("Select interface"), _("Interface"), interf, - NULL, wxDefaultCoord, wxDefaultCoord, true, wxCHOICE_WIDTH, wxCHOICE_HEIGHT, - resp); + resp = wxGetSingleChoiceIndex(_("Select interface"), _("Interface"), interf, NULL, wxDefaultCoord, wxDefaultCoord, true, + wxCHOICE_WIDTH, wxCHOICE_HEIGHT, resp); if (resp == -1) { @@ -185,7 +187,8 @@ static bool SelectInterfaceAndDevice() short err; - switch (resp) { + switch (resp) + { case 0: odp.deviceType = DEV_USB; QueryUSBResults2 usbp; @@ -207,10 +210,11 @@ static bool SelectInterfaceAndDevice() odp.deviceType = DEV_USB1 + i; } break; - case 1: { + case 1: + { odp.deviceType = DEV_ETH; - wxString IPstr = wxGetTextFromUser(_("IP address"), _("Enter IP address"), - pConfig->Profile.GetString("/camera/sbig/ipaddr", _T(""))); + wxString IPstr = wxGetTextFromUser( + _("IP address"), _("Enter IP address"), pConfig->Profile.GetString("/camera/sbig/ipaddr", _T(""))); Debug.Write(wxString::Format("SBIG: selected ipaddr %s\n", IPstr)); if (IPstr.length() == 0) return true; @@ -234,7 +238,7 @@ static bool SelectInterfaceAndDevice() odp.ipAddress = ip; break; } -#ifdef __WINDOWS__ +# ifdef __WINDOWS__ case 2: Debug.Write("SBIG: selected LPT1\n"); odp.deviceType = DEV_LPT1; @@ -250,7 +254,7 @@ static bool SelectInterfaceAndDevice() odp.deviceType = DEV_LPT3; odp.lptBaseAddress = 0x3BC; break; -#else +# else case 2: Debug.Write("SBIG: selected USB1\n"); odp.deviceType = DEV_USB1; @@ -263,7 +267,7 @@ static bool SelectInterfaceAndDevice() Debug.Write("SBIG: selected USB3\n"); odp.deviceType = DEV_USB3; break; -#endif +# endif } pConfig->Profile.SetInt("/camera/sbig/deviceType", odp.deviceType); @@ -406,7 +410,7 @@ bool CameraSBIG::Connect(const wxString& camId) err = SBIGUnivDrvCommand(CC_GET_CCD_INFO, &gcip, &gcir6); if (err == CE_NO_ERROR) { - IsColor = gcir6.ccdBits & 1; // b0 set indicates color CCD + IsColor = gcir6.ccdBits & 1; // b0 set indicates color CCD } } @@ -416,9 +420,10 @@ bool CameraSBIG::Connect(const wxString& camId) IsColor = true; } - Debug.Write(wxString::Format("SBIG: %s type=%u, UseTrackingCCD=%d, MaxBin = %hu, 1x1 size %d x %d, 2x2 size %d x %d IsColor %d\n", - gcir0.name, gcir0.cameraType, m_useTrackingCCD, MaxBinning, m_imageSize[0].x, m_imageSize[0].y, m_imageSize[1].x, m_imageSize[1].y, - IsColor)); + Debug.Write( + wxString::Format("SBIG: %s type=%u, UseTrackingCCD=%d, MaxBin = %hu, 1x1 size %d x %d, 2x2 size %d x %d IsColor %d\n", + gcir0.name, gcir0.cameraType, m_useTrackingCCD, MaxBinning, m_imageSize[0].x, m_imageSize[0].y, m_imageSize[1].x, + m_imageSize[1].y, IsColor)); Connected = true; return false; @@ -459,7 +464,8 @@ bool CameraSBIG::Capture(int duration, usImage& img, int options, const wxRect& FullSize = m_imageSize[Binning - 1]; - if (subframe.width <= 0 || subframe.height <= 0 || subframe.GetRight() >= FullSize.GetWidth() || subframe.GetBottom() >= FullSize.GetHeight()) + if (subframe.width <= 0 || subframe.height <= 0 || subframe.GetRight() >= FullSize.GetWidth() || + subframe.GetBottom() >= FullSize.GetHeight()) { TakeSubframe = false; } @@ -473,7 +479,7 @@ bool CameraSBIG::Capture(int duration, usImage& img, int options, const wxRect& if (m_useTrackingCCD) { - sep.ccd = CCD_TRACKING; + sep.ccd = CCD_TRACKING; sep.abgState = ABG_CLK_LOW7; eep.ccd = CCD_TRACKING; rlp.ccd = CCD_TRACKING; @@ -481,7 +487,7 @@ bool CameraSBIG::Capture(int duration, usImage& img, int options, const wxRect& } else { - sep.ccd = CCD_IMAGING; + sep.ccd = CCD_IMAGING; sep.abgState = ABG_LOW7; eep.ccd = CCD_IMAGING; rlp.ccd = CCD_IMAGING; @@ -490,8 +496,7 @@ bool CameraSBIG::Capture(int duration, usImage& img, int options, const wxRect& sep.exposureTime = (unsigned long) duration / 10; sep.openShutter = ShutterClosed ? SC_CLOSE_SHUTTER : SC_OPEN_SHUTTER; - sep.readoutMode = rlp.readoutMode = dlp.readoutMode = - Binning == 1 ? RM_1X1 : RM_2X2; + sep.readoutMode = rlp.readoutMode = dlp.readoutMode = Binning == 1 ? RM_1X1 : RM_2X2; if (TakeSubframe) { @@ -582,7 +587,7 @@ bool CameraSBIG::Capture(int duration, usImage& img, int options, const wxRect& SBIGUnivDrvCommand(CC_DUMP_LINES, &dlp, NULL); // set up to read the part of the lines we do want - rlp.pixelStart = subframe.x; + rlp.pixelStart = subframe.x; rlp.pixelLength = subframe.width; img.Clear(); @@ -600,7 +605,7 @@ bool CameraSBIG::Capture(int duration, usImage& img, int options, const wxRect& } else { - rlp.pixelStart = 0; + rlp.pixelStart = 0; rlp.pixelLength = (unsigned short) FullSize.GetWidth(); unsigned short *dataptr = img.ImageData; for (int y = 0; y < FullSize.GetHeight(); y++) @@ -628,28 +633,41 @@ bool CameraSBIG::ST4PulseGuideScope(int direction, int duration) ActivateRelayParams rp; rp.tXMinus = rp.tXPlus = rp.tYMinus = rp.tYPlus = 0; unsigned short dur = duration / 10; - switch (direction) { - case WEST: rp.tXMinus = dur; break; - case EAST: rp.tXPlus = dur; break; - case NORTH: rp.tYMinus = dur; break; - case SOUTH: rp.tYPlus = dur; break; + switch (direction) + { + case WEST: + rp.tXMinus = dur; + break; + case EAST: + rp.tXPlus = dur; + break; + case NORTH: + rp.tYMinus = dur; + break; + case SOUTH: + rp.tYPlus = dur; + break; } short err = SBIGUnivDrvCommand(CC_ACTIVATE_RELAY, &rp, NULL); - if (err != CE_NO_ERROR) return true; + if (err != CE_NO_ERROR) + return true; - if (duration > 60) wxMilliSleep(duration - 50); + if (duration > 60) + wxMilliSleep(duration - 50); QueryCommandStatusParams qcsp; qcsp.command = CC_ACTIVATE_RELAY; MountWatchdog watchdog(duration, 5000); - while (true) { // wait for pulse to finish + while (true) + { // wait for pulse to finish wxMilliSleep(10); QueryCommandStatusResults qcsr; err = SBIGUnivDrvCommand(CC_QUERY_COMMAND_STATUS, &qcsp, &qcsr); - if (err != CE_NO_ERROR) { + if (err != CE_NO_ERROR) + { pFrame->Alert(_("Cannot check SBIG relay status")); return true; } diff --git a/src/cam_sbigrotator.cpp b/src/cam_sbigrotator.cpp index 3e5f9d3d7..20b169001 100644 --- a/src/cam_sbigrotator.cpp +++ b/src/cam_sbigrotator.cpp @@ -36,8 +36,8 @@ #if defined(SBIG) && defined(SBIGROTATOR_CAMERA) -#include "cam_sbigrotator.h" -#include "cam_sbig.h" +# include "cam_sbigrotator.h" +# include "cam_sbig.h" class CameraSBIGRotator : public GuideCamera { @@ -80,7 +80,7 @@ bool CameraSBIGRotator::Connect(const wxString& camId) try { - wxString raAngle = wxGetTextFromUser(_("Enter RA Angle (in degrees)"),_("RA angle"), _T("0.0")); + wxString raAngle = wxGetTextFromUser(_("Enter RA Angle (in degrees)"), _("RA angle"), _T("0.0")); double temp; if (raAngle.length() == 0 || !raAngle.ToDouble(&temp)) @@ -95,8 +95,7 @@ bool CameraSBIGRotator::Connect(const wxString& camId) choices.Add(wxString::Format("Unmirrored (%.2f)", temp - 90)); choices.Add(wxString::Format("Mirrored (%.2f)", temp + 90)); - int idx = wxGetSingleChoiceIndex(_("Choose Dec Angle"), _("Dec Angle"), - choices); + int idx = wxGetSingleChoiceIndex(_("Choose Dec Angle"), _("Dec Angle"), choices); if (idx == -1) return true; @@ -151,7 +150,7 @@ bool CameraSBIGRotator::Capture(int duration, usImage& img, int options, const w return bError; } -bool CameraSBIGRotator::ST4PulseGuideScope (int direction, int duration) +bool CameraSBIGRotator::ST4PulseGuideScope(int direction, int duration) { return m_pSubcamera->ST4PulseGuideScope(direction, duration); } diff --git a/src/cam_sbigrotator.h b/src/cam_sbigrotator.h index 554dd6ed4..c021e40ff 100644 --- a/src/cam_sbigrotator.h +++ b/src/cam_sbigrotator.h @@ -33,7 +33,7 @@ */ #if defined(SBIG) && defined(SBIGROTATOR_CAMERA) && !defined(SBIGROTATOR_CAMERA_H_INCLUDED) -#define SBIGROTATOR_CAMERA_H_INCLUDED +# define SBIGROTATOR_CAMERA_H_INCLUDED class SBIGRotatorCameraFactory { @@ -41,4 +41,4 @@ class SBIGRotatorCameraFactory static GuideCamera *MakeSBIGRotatorCamera(); }; -#endif //defined(SBIGROTATOR_CAMERA_H_INCLUDED) and defined(SBIG) +#endif // defined(SBIGROTATOR_CAMERA_H_INCLUDED) and defined(SBIG) diff --git a/src/cam_skyraider.cpp b/src/cam_skyraider.cpp index 0ee8bc131..01a47b1a1 100644 --- a/src/cam_skyraider.cpp +++ b/src/cam_skyraider.cpp @@ -36,10 +36,10 @@ #if defined(SKYRAIDER_CAMERA) -#include "cam_skyraider.h" +# include "cam_skyraider.h" -#include "MallincamGuider/MallincamGuider.h" -#include "MallincamGuider/toupcam.h" +# include "MallincamGuider/MallincamGuider.h" +# include "MallincamGuider/toupcam.h" static bool verbose = true; @@ -74,22 +74,15 @@ struct SkyraiderCamera : public GuideCamera void FrameReady(); bool StopCapture(); - int gain_pct(int val) const - { - return (val - m_minGain) * 100 / (m_maxGain - m_minGain); - } + int gain_pct(int val) const { return (val - m_minGain) * 100 / (m_maxGain - m_minGain); } - int cam_gain(int pct) const - { - return m_minGain + pct * (m_maxGain - m_minGain) / 100; - } + int cam_gain(int pct) const { return m_minGain + pct * (m_maxGain - m_minGain) / 100; } }; -//#define USE_PUSH_MODE +// #define USE_PUSH_MODE -#ifdef USE_PUSH_MODE -static void __stdcall CameraPushDataCallback(const void *pData, const BITMAPINFOHEADER *pHeader, - BOOL bSnap, void *pCallbackCtx) +# ifdef USE_PUSH_MODE +static void __stdcall CameraPushDataCallback(const void *pData, const BITMAPINFOHEADER *pHeader, BOOL bSnap, void *pCallbackCtx) { if (pData) { @@ -97,7 +90,7 @@ static void __stdcall CameraPushDataCallback(const void *pData, const BITMAPINFO pCam->FrameReady(); } } -#else // USE_PUSH_MODE +# else // USE_PUSH_MODE static void __stdcall CameraCallback(unsigned nEvent, void *pCallbackCtx) { if (nEvent == MALLINCAM_EVENT_IMAGE) @@ -106,11 +99,11 @@ static void __stdcall CameraCallback(unsigned nEvent, void *pCallbackCtx) pCam->FrameReady(); } } -#endif // USE_PUSH_MODE +# endif // USE_PUSH_MODE SkyraiderCamera::SkyraiderCamera() - : m_buffer(nullptr), - m_capturing(false) + : m_buffer(nullptr) + , m_capturing(false) { Connected = false; Name = _T("MallinCam SkyRaider"); @@ -174,8 +167,8 @@ bool SkyraiderCamera::Connect(const wxString& camId) m_maxGain = max; HasGainControl = max > min; m_defaultGainPct = gain_pct(def); - Debug.Write(wxString::Format("SKYRAIDER: gain range %d .. %d, default = %d (%d%%)\n", - m_minGain, m_maxGain, def, m_defaultGainPct)); + Debug.Write(wxString::Format( + "SKYRAIDER: gain range %d .. %d, default = %d (%d%%)\n", m_minGain, m_maxGain, def, m_defaultGainPct)); } if (m_buffer) @@ -185,8 +178,8 @@ bool SkyraiderCamera::Connect(const wxString& camId) m_buffer = new unsigned char[FullSize.x * FullSize.y]; - //Mallincam_put_AutoExpoEnable(m_Guider.m_Hmallincam, 0); - //Toupcam_put_AutoExpoEnable(reinterpret_cast(m_Guider.m_Hmallincam), 0); + // Mallincam_put_AutoExpoEnable(m_Guider.m_Hmallincam, 0); + // Toupcam_put_AutoExpoEnable(reinterpret_cast(m_Guider.m_Hmallincam), 0); return false; } @@ -210,18 +203,16 @@ bool SkyraiderCamera::Capture(int duration, usImage& img, int options, const wxR int res = m_Guider.Mallincam_get_ExpoTime(m_Guider.m_Hmallincam, &cur_exp); if ((res == MC_SUCCESS) && (cur_exp != exposureUS)) { - Debug.Write(wxString::Format("SKYRAIDER: exposure value is %u, updating to %ld\n", - cur_exp, exposureUS)); + Debug.Write(wxString::Format("SKYRAIDER: exposure value is %u, updating to %ld\n", cur_exp, exposureUS)); res = m_Guider.Mallincam_put_ExpoTime(m_Guider.m_Hmallincam, exposureUS); } unsigned short new_gain = cam_gain(GuideCameraGain); unsigned short cur_gain; - if (m_Guider.Mallincam_get_ExpoAGain(m_Guider.m_Hmallincam, &cur_gain) == MC_SUCCESS && - new_gain != cur_gain) + if (m_Guider.Mallincam_get_ExpoAGain(m_Guider.m_Hmallincam, &cur_gain) == MC_SUCCESS && new_gain != cur_gain) { - Debug.Write(wxString::Format("SKYRAIDER: gain value is %hu (%d%%), updating to %hu (%d%%)\n", - cur_gain, gain_pct(cur_gain), new_gain, GuideCameraGain)); + Debug.Write(wxString::Format("SKYRAIDER: gain value is %hu (%d%%), updating to %hu (%d%%)\n", cur_gain, + gain_pct(cur_gain), new_gain, GuideCameraGain)); m_Guider.Mallincam_put_ExpoAGain(m_Guider.m_Hmallincam, new_gain); } @@ -230,21 +221,21 @@ bool SkyraiderCamera::Capture(int duration, usImage& img, int options, const wxR // get is current unsigned int width, height; -#if 0 // TODO: this is almost certainly required, but it was excluded for some reason and I have no way to test it +# if 0 // TODO: this is almost certainly required, but it was excluded for some reason and I have no way to test it while (SUCCEEDED(m_sdk.PullImage(m_handle, m_buffer, 8, &width, &height))) { } -#endif +# endif if (!m_capturing) { Debug.Write("SKYRAIDER: startcapture\n"); m_frameReady = false; -#ifdef USE_PUSH_MODE +# ifdef USE_PUSH_MODE m_Guider.Mallincam_StartPushMode(m_Guider.m_Hmallincam, CameraPushDataCallback, this); -#else +# else m_Guider.Mallincam_StartPullModeWithCallback(m_Guider.m_Hmallincam, CameraCallback, this); -#endif +# endif m_capturing = true; } @@ -252,28 +243,31 @@ bool SkyraiderCamera::Capture(int duration, usImage& img, int options, const wxR CameraWatchdog watchdog(duration, duration + GetTimeoutMs() + 10000); // total timeout is 2 * duration + 15s (typically) -// do not wait here, as we will miss a frame most likely, leading to poor flow of frames. -// if (WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY) && -// (WorkerThread::TerminateRequested() || StopCapture())) -// { -// return true; -// } + // do not wait here, as we will miss a frame most likely, leading to poor flow of frames. + // if (WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY) && + // (WorkerThread::TerminateRequested() || StopCapture())) + // { + // return true; + // } while (true) { if (m_frameReady) { - if (verbose) Debug.Write("SKYRAIDER: frame is ready, pull image\n"); + if (verbose) + Debug.Write("SKYRAIDER: frame is ready, pull image\n"); m_frameReady = false; int result = m_Guider.Mallincam_PullImage(m_Guider.m_Hmallincam, m_buffer, 8, &width, &height); - if (verbose) Debug.Write(wxString::Format("SKYRAIDER: pull image ret %d\n", res)); + if (verbose) + Debug.Write(wxString::Format("SKYRAIDER: pull image ret %d\n", res)); if (result == MC_SUCCESS) break; } WorkerThread::MilliSleep(poll, WorkerThread::INT_ANY); if (WorkerThread::InterruptRequested()) { - if (verbose) Debug.Write("SKYRAIDER: interrupt requested\n"); + if (verbose) + Debug.Write("SKYRAIDER: interrupt requested\n"); StopCapture(); return true; } @@ -289,7 +283,8 @@ bool SkyraiderCamera::Capture(int duration, usImage& img, int options, const wxR for (int i = 0; i < img.NPixels; i++) img.ImageData[i] = m_buffer[i]; - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return false; } @@ -307,7 +302,8 @@ bool SkyraiderCamera::StopCapture() void SkyraiderCamera::FrameReady() { - if (verbose) Debug.Write("SKYRAIDER: frameready callback\n"); + if (verbose) + Debug.Write("SKYRAIDER: frameready callback\n"); m_frameReady = true; } diff --git a/src/cam_sspiag.cpp b/src/cam_sspiag.cpp index db2838bce..ca0e0d6b6 100644 --- a/src/cam_sspiag.cpp +++ b/src/cam_sspiag.cpp @@ -32,10 +32,10 @@ * */ #include "phd.h" -#if defined (SSPIAG) -#include "camera.h" -#include "time.h" -#include "image_math.h" +#if defined(SSPIAG) +# include "camera.h" +# include "time.h" +# include "image_math.h" /* To-Do - Updating gain on the fly, esp. if also changing exposure duration? @@ -43,22 +43,22 @@ */ -#include "cam_sspiag.h" +# include "cam_sspiag.h" // Orion SS PI AG camera (aka QHY5V) -//extern "C" __declspec(dllexport) __stdcall void setDevName(PCHAR i); -typedef void (CALLBACK* Q5V_PCHAR)(char*); +// extern "C" __declspec(dllexport) __stdcall void setDevName(PCHAR i); +typedef void(CALLBACK *Q5V_PCHAR)(char *); Q5V_PCHAR Q5V_SetDevName; -//extern "C" __declspec(dllexport) __stdcall void getFullSizeImage(unsigned char *img); -//extern "C" __declspec(dllexport) __stdcall void RowNoiseReductionMethod(unsigned char i); -//extern "C" __declspec(dllexport) __stdcall void BlackCalibration(unsigned char i); //0= not enable 1=enable -//extern "C" __declspec(dllexport) __stdcall void RowNoiseConstant(unsigned char i); -typedef void (CALLBACK* Q5V_UPCHAR)(unsigned char*); +// extern "C" __declspec(dllexport) __stdcall void getFullSizeImage(unsigned char *img); +// extern "C" __declspec(dllexport) __stdcall void RowNoiseReductionMethod(unsigned char i); +// extern "C" __declspec(dllexport) __stdcall void BlackCalibration(unsigned char i); //0= not enable 1=enable +// extern "C" __declspec(dllexport) __stdcall void RowNoiseConstant(unsigned char i); +typedef void(CALLBACK *Q5V_UPCHAR)(unsigned char *); Q5V_UPCHAR Q5V_GetFullSizeImage; -//extern "C" __declspec(dllexport) __stdcall unsigned char openQHY5V(void); -typedef unsigned char (CALLBACK* Q5V_UC_V)(void); +// extern "C" __declspec(dllexport) __stdcall unsigned char openQHY5V(void); +typedef unsigned char(CALLBACK *Q5V_UC_V)(void); Q5V_UC_V Q5V_OpenQHY5V; /*extern "C" __declspec(dllexport) __stdcall void AGC_enable(int i); @@ -68,7 +68,7 @@ extern "C" __declspec(dllexport) __stdcall void LongExpMode(int i); extern "C" __declspec(dllexport) __stdcall void HighDynamic(int i); extern "C" __declspec(dllexport) __stdcall void BlackOffset(int i); */ -typedef void (CALLBACK* Q5V_INT)(int); +typedef void(CALLBACK *Q5V_INT)(int); Q5V_INT Q5V_AGC_Enable; Q5V_INT Q5V_AEC_Enable; Q5V_INT Q5V_BitCompanding; @@ -76,44 +76,44 @@ Q5V_INT Q5V_LongExpMode; Q5V_INT Q5V_HighDynamic; Q5V_INT Q5V_BlackOffset; -//extern "C" __declspec(dllexport) __stdcall void HighGainBoost(unsigned char i); -typedef void (CALLBACK* Q5V_UC)(unsigned char); +// extern "C" __declspec(dllexport) __stdcall void HighGainBoost(unsigned char i); +typedef void(CALLBACK *Q5V_UC)(unsigned char); Q5V_UC Q5V_HighGainBoost; Q5V_UC Q5V_RowNoiseReductionMethod; Q5V_UC Q5V_BlackCalibration; Q5V_UC Q5V_RowNoiseConstant; -//extern "C" __declspec(dllexport) __stdcall void setQHY5VGlobalGain(unsigned short i); -//extern "C" __declspec(dllexport) __stdcall void setTotalShutterWidth(unsigned short width); -typedef void (CALLBACK* Q5V_US)(unsigned short); +// extern "C" __declspec(dllexport) __stdcall void setQHY5VGlobalGain(unsigned short i); +// extern "C" __declspec(dllexport) __stdcall void setTotalShutterWidth(unsigned short width); +typedef void(CALLBACK *Q5V_US)(unsigned short); Q5V_US Q5V_SetQHY5VGlobalGain; Q5V_US Q5V_SetTotalShutterWidth; -//extern "C" __declspec(dllexport) __stdcall void RowNoiseReduction(int en,int useblacklevel,unsigned char darkpixels,unsigned char RowNoiseConstant); -//typedef void (CALLBACK* Q5V_ROWNR)(int, int, unsigned char, unsigned char); -//Q5V_ROWNR Q5V_RowNoiseReduction; +// extern "C" __declspec(dllexport) __stdcall void RowNoiseReduction(int en,int useblacklevel,unsigned char darkpixels,unsigned +// char RowNoiseConstant); typedef void (CALLBACK* Q5V_ROWNR)(int, int, unsigned char, unsigned char); Q5V_ROWNR +// Q5V_RowNoiseReduction; -//extern "C" __declspec(dllexport) __stdcall void ReadMode(int RowFlip,int ColumnFlip,int ShowDarkRows,int ShowDarkColumns); -typedef void (CALLBACK* Q5V_RMODE)(int, int, int, int); +// extern "C" __declspec(dllexport) __stdcall void ReadMode(int RowFlip,int ColumnFlip,int ShowDarkRows,int ShowDarkColumns); +typedef void(CALLBACK *Q5V_RMODE)(int, int, int, int); Q5V_RMODE Q5V_ReadMode; -//extern "C" __declspec(dllexport) __stdcall void setLongExpTime(unsigned long i); -typedef void (CALLBACK* Q5V_UL)(unsigned long); +// extern "C" __declspec(dllexport) __stdcall void setLongExpTime(unsigned long i); +typedef void(CALLBACK *Q5V_UL)(unsigned long); Q5V_UL Q5V_SetLongExpTime; -//extern "C" __declspec(dllexport) __stdcall void QHY5VInit(void); -typedef void (CALLBACK* Q5V_V)(void); +// extern "C" __declspec(dllexport) __stdcall void QHY5VInit(void); +typedef void(CALLBACK *Q5V_V)(void); Q5V_V Q5V_QHY5VInit; -//sendGuideCommand(PCHAR devname,unsigned char GuideCommand,unsigned char PulseTime);//for QHY5,QHY5V -typedef void (CALLBACK* Q5V_GUIDE) (char*, unsigned char, unsigned char); +// sendGuideCommand(PCHAR devname,unsigned char GuideCommand,unsigned char PulseTime);//for QHY5,QHY5V +typedef void(CALLBACK *Q5V_GUIDE)(char *, unsigned char, unsigned char); Q5V_GUIDE Q5V_SendGuideCommand; CameraSSPIAG::CameraSSPIAG() { Connected = false; Name = _T("StarShoot PIAG"); - FullSize = wxSize(752,480); + FullSize = wxSize(752, 480); m_hasGuideOutput = true; HasGainControl = true; RawBuffer = NULL; @@ -128,133 +128,155 @@ bool CameraSSPIAG::Connect(const wxString& camId) { // returns true on error CameraDLL = LoadLibrary(TEXT("astroDLLsspiag")); - if (CameraDLL == NULL) { + if (CameraDLL == NULL) + { return CamConnectFailed(_("Cannot load astroDLLsspiag.dll")); } - Q5V_SetDevName = (Q5V_PCHAR)GetProcAddress(CameraDLL,"setDevName"); - if (!Q5V_SetDevName) { + Q5V_SetDevName = (Q5V_PCHAR) GetProcAddress(CameraDLL, "setDevName"); + if (!Q5V_SetDevName) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "setDevName")); } - Q5V_GetFullSizeImage = (Q5V_UPCHAR)GetProcAddress(CameraDLL,"getFullSizeImage"); - if (!Q5V_GetFullSizeImage) { + Q5V_GetFullSizeImage = (Q5V_UPCHAR) GetProcAddress(CameraDLL, "getFullSizeImage"); + if (!Q5V_GetFullSizeImage) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "getFullSizeImage")); } - Q5V_RowNoiseReductionMethod = (Q5V_UC)GetProcAddress(CameraDLL,"RowNoiseReductionMethod"); - if (!Q5V_RowNoiseReductionMethod) { + Q5V_RowNoiseReductionMethod = (Q5V_UC) GetProcAddress(CameraDLL, "RowNoiseReductionMethod"); + if (!Q5V_RowNoiseReductionMethod) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "RowNoiseReductionMethod")); } - Q5V_BlackCalibration = (Q5V_UC)GetProcAddress(CameraDLL,"BlackCalibration"); - if (!Q5V_BlackCalibration) { + Q5V_BlackCalibration = (Q5V_UC) GetProcAddress(CameraDLL, "BlackCalibration"); + if (!Q5V_BlackCalibration) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "BlackCalibration")); } - Q5V_RowNoiseConstant = (Q5V_UC)GetProcAddress(CameraDLL,"RowNoiseConstant"); - if (!Q5V_RowNoiseConstant) { + Q5V_RowNoiseConstant = (Q5V_UC) GetProcAddress(CameraDLL, "RowNoiseConstant"); + if (!Q5V_RowNoiseConstant) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "RowNoiseConstant")); } - Q5V_OpenQHY5V = (Q5V_UC_V)GetProcAddress(CameraDLL,"openQHY5V"); - if (!Q5V_OpenQHY5V) { + Q5V_OpenQHY5V = (Q5V_UC_V) GetProcAddress(CameraDLL, "openQHY5V"); + if (!Q5V_OpenQHY5V) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "openQHY5V")); } - Q5V_AGC_Enable = (Q5V_INT)GetProcAddress(CameraDLL,"AGC_enable"); - if (!Q5V_AGC_Enable) { + Q5V_AGC_Enable = (Q5V_INT) GetProcAddress(CameraDLL, "AGC_enable"); + if (!Q5V_AGC_Enable) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "AGC_enable")); } - Q5V_AEC_Enable = (Q5V_INT)GetProcAddress(CameraDLL,"AEC_enable"); - if (!Q5V_AEC_Enable) { + Q5V_AEC_Enable = (Q5V_INT) GetProcAddress(CameraDLL, "AEC_enable"); + if (!Q5V_AEC_Enable) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "AEC_enable")); } - Q5V_BitCompanding = (Q5V_INT)GetProcAddress(CameraDLL,"bitCompanding"); - if (!Q5V_BitCompanding) { + Q5V_BitCompanding = (Q5V_INT) GetProcAddress(CameraDLL, "bitCompanding"); + if (!Q5V_BitCompanding) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "bitCompanding")); } - Q5V_LongExpMode = (Q5V_INT)GetProcAddress(CameraDLL,"LongExpMode"); - if (!Q5V_LongExpMode) { + Q5V_LongExpMode = (Q5V_INT) GetProcAddress(CameraDLL, "LongExpMode"); + if (!Q5V_LongExpMode) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "LongExpMode")); } - Q5V_HighDynamic = (Q5V_INT)GetProcAddress(CameraDLL,"HighDynamic"); - if (!Q5V_HighDynamic) { + Q5V_HighDynamic = (Q5V_INT) GetProcAddress(CameraDLL, "HighDynamic"); + if (!Q5V_HighDynamic) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "HighDynamic")); } - Q5V_BlackOffset = (Q5V_INT)GetProcAddress(CameraDLL,"BlackOffset"); - if (!Q5V_BlackOffset) { + Q5V_BlackOffset = (Q5V_INT) GetProcAddress(CameraDLL, "BlackOffset"); + if (!Q5V_BlackOffset) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "BlackOffset")); } - Q5V_HighGainBoost = (Q5V_UC)GetProcAddress(CameraDLL,"HighGainBoost"); - if (!Q5V_HighGainBoost) { + Q5V_HighGainBoost = (Q5V_UC) GetProcAddress(CameraDLL, "HighGainBoost"); + if (!Q5V_HighGainBoost) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "HighGainBoost")); } - Q5V_SetQHY5VGlobalGain = (Q5V_US)GetProcAddress(CameraDLL,"setQHY5VGlobalGain"); - if (!Q5V_SetQHY5VGlobalGain) { + Q5V_SetQHY5VGlobalGain = (Q5V_US) GetProcAddress(CameraDLL, "setQHY5VGlobalGain"); + if (!Q5V_SetQHY5VGlobalGain) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "setQHY5VGlobalGain")); } - Q5V_SetTotalShutterWidth = (Q5V_US)GetProcAddress(CameraDLL,"setTotalShutterWidth"); - if (!Q5V_SetTotalShutterWidth) { + Q5V_SetTotalShutterWidth = (Q5V_US) GetProcAddress(CameraDLL, "setTotalShutterWidth"); + if (!Q5V_SetTotalShutterWidth) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "setTotalShutterWidth")); } -/* Q5V_RowNoiseReduction = (Q5V_ROWNR)GetProcAddress(CameraDLL,"RowNoiseReduction"); - if (!Q5V_RowNoiseReduction) { - FreeLibrary(CameraDLL); - return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "RowNoiseReduction")); - }*/ - Q5V_ReadMode = (Q5V_RMODE)GetProcAddress(CameraDLL,"ReadMode"); - if (!Q5V_ReadMode) { + /* Q5V_RowNoiseReduction = (Q5V_ROWNR)GetProcAddress(CameraDLL,"RowNoiseReduction"); + if (!Q5V_RowNoiseReduction) { + FreeLibrary(CameraDLL); + return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "RowNoiseReduction")); + }*/ + Q5V_ReadMode = (Q5V_RMODE) GetProcAddress(CameraDLL, "ReadMode"); + if (!Q5V_ReadMode) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "ReadMode")); } - Q5V_SetLongExpTime = (Q5V_UL)GetProcAddress(CameraDLL,"setLongExpTime"); - if (!Q5V_SetLongExpTime) { + Q5V_SetLongExpTime = (Q5V_UL) GetProcAddress(CameraDLL, "setLongExpTime"); + if (!Q5V_SetLongExpTime) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "setLongExpTime")); } - Q5V_QHY5VInit = (Q5V_V)GetProcAddress(CameraDLL,"QHY5VInit"); - if (!Q5V_QHY5VInit) { + Q5V_QHY5VInit = (Q5V_V) GetProcAddress(CameraDLL, "QHY5VInit"); + if (!Q5V_QHY5VInit) + { FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("astroDLLsspiag.dll does not have %s"), "QHY5VInit")); } GenericDLL = LoadLibrary(TEXT("SSPIAGCAM.dll")); - if (GenericDLL == NULL) { + if (GenericDLL == NULL) + { FreeLibrary(CameraDLL); return CamConnectFailed(_("Cannot load SSPIAGCAM.dll")); } - Q5V_SendGuideCommand = (Q5V_GUIDE)GetProcAddress(GenericDLL,"sendGuideCommand"); - if (!Q5V_SendGuideCommand) { + Q5V_SendGuideCommand = (Q5V_GUIDE) GetProcAddress(GenericDLL, "sendGuideCommand"); + if (!Q5V_SendGuideCommand) + { FreeLibrary(GenericDLL); FreeLibrary(CameraDLL); return CamConnectFailed(wxString::Format(_("SSPIAGCAM.dll does not have %s"), "sendGuideCommand")); } Q5V_SetDevName("SSPIA-0"); - if (!Q5V_OpenQHY5V()) { + if (!Q5V_OpenQHY5V()) + { FreeLibrary(GenericDLL); FreeLibrary(CameraDLL); return CamConnectFailed(_("Failed to open the camera")); } if (RawBuffer) - delete [] RawBuffer; - RawBuffer = new unsigned char[856*500]; + delete[] RawBuffer; + RawBuffer = new unsigned char[856 * 500]; Q5V_QHY5VInit(); Q5V_GetFullSizeImage(RawBuffer); wxMilliSleep(100); Q5V_QHY5VInit(); Q5V_GetFullSizeImage(RawBuffer); - Q5V_ReadMode(0,0,1,1); + Q5V_ReadMode(0, 0, 1, 1); Q5V_GetFullSizeImage(RawBuffer); Q5V_BlackOffset(5); Q5V_GetFullSizeImage(RawBuffer); @@ -264,8 +286,8 @@ bool CameraSSPIAG::Connect(const wxString& camId) Q5V_GetFullSizeImage(RawBuffer); Q5V_RowNoiseReductionMethod(1); Q5V_GetFullSizeImage(RawBuffer); -// Q5V_HighGainBoost(255); -// Q5V_GetFullSizeImage(RawBuffer); + // Q5V_HighGainBoost(255); + // Q5V_GetFullSizeImage(RawBuffer); Q5V_AEC_Enable(0); Q5V_GetFullSizeImage(RawBuffer); Q5V_AGC_Enable(0); @@ -281,40 +303,51 @@ bool CameraSSPIAG::Connect(const wxString& camId) bool CameraSSPIAG::ST4PulseGuideScope(int direction, int duration) { -// Vend req 0xb5 (vendTXD) -// Buffer[0] = GuideCommand, Buffer[1]=PulseTime. + // Vend req 0xb5 (vendTXD) + // Buffer[0] = GuideCommand, Buffer[1]=PulseTime. int reg = 0; int dur = duration / 10; - if (dur >= 255) dur = 254; // Max guide pulse is 2.54s -- 255 keeps it on always + if (dur >= 255) + dur = 254; // Max guide pulse is 2.54s -- 255 keeps it on always // Output pins are NC, Com, RA+(W), Dec+(N), Dec-(S), RA-(E) ?? http://www.starlight-xpress.co.uk/faq.htm - switch (direction) { - case WEST: reg = 0x80; break; // 0111 0000 - case NORTH: reg = 0x40; break; // 1011 0000 - case SOUTH: reg = 0x20; break; // 1101 0000 - case EAST: reg = 0x10; break; // 1110 0000 - default: return true; // bad direction passed in + switch (direction) + { + case WEST: + reg = 0x80; + break; // 0111 0000 + case NORTH: + reg = 0x40; + break; // 1011 0000 + case SOUTH: + reg = 0x20; + break; // 1101 0000 + case EAST: + reg = 0x10; + break; // 1110 0000 + default: + return true; // bad direction passed in } - Q5V_SendGuideCommand("QHY5V-0", reg,dur); + Q5V_SendGuideCommand("QHY5V-0", reg, dur); WorkerThread::MilliSleep(duration + 10); return false; } void CameraSSPIAG::ClearGuidePort() { - Q5V_SendGuideCommand("QHY5V-0",0,0); + Q5V_SendGuideCommand("QHY5V-0", 0, 0); } void CameraSSPIAG::InitCapture() { - //Q5V_SetQHY5VGlobalGain(GuideCameraGain * 63 / 100); + // Q5V_SetQHY5VGlobalGain(GuideCameraGain * 63 / 100); } bool CameraSSPIAG::Disconnect() { - //closeUSB(); + // closeUSB(); if (RawBuffer) - delete [] RawBuffer; + delete[] RawBuffer; RawBuffer = NULL; FreeLibrary(CameraDLL); FreeLibrary(GenericDLL); @@ -324,29 +357,32 @@ bool CameraSSPIAG::Disconnect() bool CameraSSPIAG::Capture(int duration, usImage& img, int options, const wxRect& subframe) { -// Only does full frames still + // Only does full frames still static int last_dur = 0; static int last_gain = 60; unsigned char *bptr; unsigned short *dptr; - int x,y; + int x, y; int xsize = FullSize.GetWidth(); int ysize = FullSize.GetHeight(); -// bool firstimg = true; + // bool firstimg = true; - if (img.Init(FullSize)) { + if (img.Init(FullSize)) + { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } - if (duration != last_dur) { + if (duration != last_dur) + { Q5V_SetLongExpTime(duration); last_dur = duration; } - else if (GuideCameraGain != last_gain) { + else if (GuideCameraGain != last_gain) + { Q5V_SetQHY5VGlobalGain(GuideCameraGain * 63 / 100); last_gain = GuideCameraGain; -// Q5V_GetFullSizeImage(RawBuffer); + // Q5V_GetFullSizeImage(RawBuffer); } bptr = RawBuffer; @@ -354,17 +390,21 @@ bool CameraSSPIAG::Capture(int duration, usImage& img, int options, const wxRect // Load and crop from the 800 x 525 image that came in dptr = img.ImageData; - for (y=0; y +# include class CameraStarfish : public GuideCamera { @@ -54,48 +54,105 @@ class CameraStarfish : public GuideCamera public: CameraStarfish(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - void InitCapture() override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + void InitCapture() override; - bool ST4PulseGuideScope(int direction, int duration) override; + bool ST4PulseGuideScope(int direction, int duration) override; - bool HasNonGuiCapture() override { return true; } - bool ST4HasNonGuiMove() override { return true; } - wxByte BitsPerPixel() override; + bool HasNonGuiCapture() override { return true; } + bool ST4HasNonGuiMove() override { return true; } + wxByte BitsPerPixel() override; }; -#if defined (__WINDOWS__) -#define kIOReturnSuccess 0 +# if defined(__WINDOWS__) +# define kIOReturnSuccess 0 typedef int IOReturn; using namespace FcCamSpace; -void fcUsb_init(void) { FcCamFuncs::fcUsb_init(); } -void fcUsb_close(void) { FcCamFuncs::fcUsb_close(); } -void fcUsb_CloseCameraDriver(void) { FcCamFuncs::fcUsb_close(); } -int fcUsb_FindCameras(void) { return FcCamFuncs::fcUsb_FindCameras(); } -int fcUsb_cmd_setRegister(int camNum, UInt16 regAddress, UInt16 dataValue) { return FcCamFuncs::fcUsb_cmd_setRegister(camNum, regAddress, dataValue); } -UInt16 fcUsb_cmd_getRegister(int camNum, UInt16 regAddress) { return FcCamFuncs::fcUsb_cmd_getRegister(camNum, regAddress); } -int fcUsb_cmd_setIntegrationTime(int camNum, UInt32 theTime) { return FcCamFuncs::fcUsb_cmd_setIntegrationTime(camNum, theTime); } -int fcUsb_cmd_startExposure(int camNum) { return FcCamFuncs::fcUsb_cmd_startExposure(camNum); } -int fcUsb_cmd_abortExposure(int camNum) { return FcCamFuncs::fcUsb_cmd_abortExposure(camNum); } -UInt16 fcUsb_cmd_getState(int camNum) { return FcCamFuncs::fcUsb_cmd_getState(camNum); } -int fcUsb_cmd_setRoi(int camNum, UInt16 left, UInt16 top, UInt16 right, UInt16 bottom) { return FcCamFuncs::fcUsb_cmd_setRoi(camNum,left,top,right,bottom); } -int fcUsb_cmd_setRelay(int camNum, int whichRelay) { return FcCamFuncs::fcUsb_cmd_setRelay(camNum,whichRelay); } -int fcUsb_cmd_clearRelay(int camNum, int whichRelay) { return FcCamFuncs::fcUsb_cmd_clearRelay(camNum,whichRelay); } -int fcUsb_cmd_pulseRelay(int camNum, int whichRelay, int onMs, int offMs, bool repeats) { return FcCamFuncs::fcUsb_cmd_pulseRelay(camNum,whichRelay, onMs, offMs, repeats); } -int fcUsb_cmd_setTemperature(int camNum, SInt16 theTemp) { return FcCamFuncs::fcUsb_cmd_setTemperature(camNum,theTemp); } -bool fcUsb_cmd_getTECInPowerOK(int camNum) { return FcCamFuncs::fcUsb_cmd_getTECInPowerOK(camNum); } -int fcUsb_cmd_getRawFrame(int camNum, UInt16 numRows, UInt16 numCols, UInt16 *frameBuffer) { return FcCamFuncs::fcUsb_cmd_getRawFrame(camNum,numRows,numCols, frameBuffer); } -int fcUsb_cmd_setReadMode(int camNum, int DataXfrReadMode, int DataFormat) { return FcCamFuncs::fcUsb_cmd_setReadMode(camNum,DataXfrReadMode,DataFormat); } -bool fcUsb_haveCamera(void) { return FcCamFuncs::fcUsb_haveCamera(); } -#endif +void fcUsb_init(void) +{ + FcCamFuncs::fcUsb_init(); +} +void fcUsb_close(void) +{ + FcCamFuncs::fcUsb_close(); +} +void fcUsb_CloseCameraDriver(void) +{ + FcCamFuncs::fcUsb_close(); +} +int fcUsb_FindCameras(void) +{ + return FcCamFuncs::fcUsb_FindCameras(); +} +int fcUsb_cmd_setRegister(int camNum, UInt16 regAddress, UInt16 dataValue) +{ + return FcCamFuncs::fcUsb_cmd_setRegister(camNum, regAddress, dataValue); +} +UInt16 fcUsb_cmd_getRegister(int camNum, UInt16 regAddress) +{ + return FcCamFuncs::fcUsb_cmd_getRegister(camNum, regAddress); +} +int fcUsb_cmd_setIntegrationTime(int camNum, UInt32 theTime) +{ + return FcCamFuncs::fcUsb_cmd_setIntegrationTime(camNum, theTime); +} +int fcUsb_cmd_startExposure(int camNum) +{ + return FcCamFuncs::fcUsb_cmd_startExposure(camNum); +} +int fcUsb_cmd_abortExposure(int camNum) +{ + return FcCamFuncs::fcUsb_cmd_abortExposure(camNum); +} +UInt16 fcUsb_cmd_getState(int camNum) +{ + return FcCamFuncs::fcUsb_cmd_getState(camNum); +} +int fcUsb_cmd_setRoi(int camNum, UInt16 left, UInt16 top, UInt16 right, UInt16 bottom) +{ + return FcCamFuncs::fcUsb_cmd_setRoi(camNum, left, top, right, bottom); +} +int fcUsb_cmd_setRelay(int camNum, int whichRelay) +{ + return FcCamFuncs::fcUsb_cmd_setRelay(camNum, whichRelay); +} +int fcUsb_cmd_clearRelay(int camNum, int whichRelay) +{ + return FcCamFuncs::fcUsb_cmd_clearRelay(camNum, whichRelay); +} +int fcUsb_cmd_pulseRelay(int camNum, int whichRelay, int onMs, int offMs, bool repeats) +{ + return FcCamFuncs::fcUsb_cmd_pulseRelay(camNum, whichRelay, onMs, offMs, repeats); +} +int fcUsb_cmd_setTemperature(int camNum, SInt16 theTemp) +{ + return FcCamFuncs::fcUsb_cmd_setTemperature(camNum, theTemp); +} +bool fcUsb_cmd_getTECInPowerOK(int camNum) +{ + return FcCamFuncs::fcUsb_cmd_getTECInPowerOK(camNum); +} +int fcUsb_cmd_getRawFrame(int camNum, UInt16 numRows, UInt16 numCols, UInt16 *frameBuffer) +{ + return FcCamFuncs::fcUsb_cmd_getRawFrame(camNum, numRows, numCols, frameBuffer); +} +int fcUsb_cmd_setReadMode(int camNum, int DataXfrReadMode, int DataFormat) +{ + return FcCamFuncs::fcUsb_cmd_setReadMode(camNum, DataXfrReadMode, DataFormat); +} +bool fcUsb_haveCamera(void) +{ + return FcCamFuncs::fcUsb_haveCamera(); +} +# endif CameraStarfish::CameraStarfish() { Connected = false; Name = _T("Fishcamp Starfish"); - FullSize = wxSize(1280,1024); + FullSize = wxSize(1280, 1024); HasSubframes = true; HasGainControl = true; m_hasGuideOutput = true; @@ -109,26 +166,29 @@ wxByte CameraStarfish::BitsPerPixel() bool CameraStarfish::Connect(const wxString& camId) { -// returns true on error + // returns true on error wxBeginBusyCursor(); - if (!DriverLoaded) { - fcUsb_init(); // Init the driver + if (!DriverLoaded) + { + fcUsb_init(); // Init the driver DriverLoaded = true; } NCams = fcUsb_FindCameras(); wxEndBusyCursor(); if (NCams == 0) return true; - else { - CamNum = 1; // Assume just the one cam for now + else + { + CamNum = 1; // Assume just the one cam for now // set to polling mode and turn off black adjustment but turn on auto balancing of the offsets in the 2x2 matrix IOReturn rval = fcUsb_cmd_setReadMode(CamNum, fc_classicDataXfr, fc_16b_data); - if (rval != kIOReturnSuccess) return true; + if (rval != kIOReturnSuccess) + return true; if (fcUsb_cmd_getTECInPowerOK(CamNum)) - fcUsb_cmd_setTemperature(CamNum,10); + fcUsb_cmd_setTemperature(CamNum, 10); } - lastSubFrame = wxRect(wxSize(1, 1)); // To differentiate between full-frame "null" subframe + lastSubFrame = wxRect(wxSize(1, 1)); // To differentiate between full-frame "null" subframe Connected = true; return false; } @@ -145,18 +205,21 @@ void CameraStarfish::InitCapture() { // Set gain unsigned short Gain = (unsigned short) GuideCameraGain; - if (Gain < 25 ) { // Low noise 1x-4x in .125x mode maps on 0-24 - Gain = 8 + Gain; //103 + if (Gain < 25) + { // Low noise 1x-4x in .125x mode maps on 0-24 + Gain = 8 + Gain; // 103 } - else if (Gain < 57) { // 4.25x-8x in .25x steps maps onto 25-56 - Gain = 0x51 + (Gain - 25)/2; // 81-96 aka 0x51-0x60 + else if (Gain < 57) + { // 4.25x-8x in .25x steps maps onto 25-56 + Gain = 0x51 + (Gain - 25) / 2; // 81-96 aka 0x51-0x60 } - else { // 9x-15x in 1x steps maps onto 57-95 - Gain = 0x61 + (Gain - 57)/6; + else + { // 9x-15x in 1x steps maps onto 57-95 + Gain = 0x61 + (Gain - 57) / 6; } - if (Gain > 0x67) Gain = 0x67; - fcUsb_cmd_setRegister(CamNum,0x35,Gain); - + if (Gain > 0x67) + Gain = 0x67; + fcUsb_cmd_setRegister(CamNum, 0x35, Gain); } static bool StopExposure(int camNum) @@ -174,7 +237,8 @@ bool CameraStarfish::Capture(int duration, usImage& img, int options, const wxRe IOReturn rval; // init memory - if (img.Init(FullSize)) { + if (img.Init(FullSize)) + { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } @@ -200,17 +264,29 @@ bool CameraStarfish::Capture(int duration, usImage& img, int options, const wxRe // set ROI if something has changed if (lastSubFrame != subframe) { - rval = fcUsb_cmd_setRoi(CamNum, (unsigned short)xpos, (unsigned short)ypos, (unsigned short)(xpos + xsize - 1), (unsigned short)(ypos + ysize - 1)); - //Debug.AddLine(wxString::Format("Starfish: using %s", usingSubFrames ? " sub-frames" : " full frames")); - //Debug.AddLine(wxString::Format("Starfish: ROI set from {%d,%d} to {%d,%d)", xpos, ypos, xpos + xsize - 1, ypos + ysize - 1)); - if (rval != kIOReturnSuccess) { if (debug) pFrame->Alert(_T("Starfish Err 1")); return true; } + rval = fcUsb_cmd_setRoi(CamNum, (unsigned short) xpos, (unsigned short) ypos, (unsigned short) (xpos + xsize - 1), + (unsigned short) (ypos + ysize - 1)); + // Debug.AddLine(wxString::Format("Starfish: using %s", usingSubFrames ? " sub-frames" : " full frames")); + // Debug.AddLine(wxString::Format("Starfish: ROI set from {%d,%d} to {%d,%d)", xpos, ypos, xpos + xsize - 1, ypos + + // ysize - 1)); + if (rval != kIOReturnSuccess) + { + if (debug) + pFrame->Alert(_T("Starfish Err 1")); + return true; + } lastSubFrame = subframe; } // set duration fcUsb_cmd_setIntegrationTime(CamNum, (unsigned int) duration); rval = fcUsb_cmd_startExposure(CamNum); - if (rval != kIOReturnSuccess) { if (debug) pFrame->Alert(_T("Starfish Err 2")); return true; } + if (rval != kIOReturnSuccess) + { + if (debug) + pFrame->Alert(_T("Starfish Err 2")); + return true; + } CameraWatchdog watchdog(duration, GetTimeoutMs()); @@ -228,8 +304,7 @@ bool CameraStarfish::Capture(int duration, usImage& img, int options, const wxRe while (fcUsb_cmd_getState(CamNum) != 0) { wxMilliSleep(50); - if (WorkerThread::InterruptRequested() && - (WorkerThread::TerminateRequested() || StopExposure(CamNum))) + if (WorkerThread::InterruptRequested() && (WorkerThread::TerminateRequested() || StopExposure(CamNum))) { return true; } @@ -242,7 +317,7 @@ bool CameraStarfish::Capture(int duration, usImage& img, int options, const wxRe if (usingSubFrames) { - rval = fcUsb_cmd_getRawFrame(CamNum, (unsigned short)ysize, (unsigned short)xsize, subImage.ImageData); + rval = fcUsb_cmd_getRawFrame(CamNum, (unsigned short) ysize, (unsigned short) xsize, subImage.ImageData); // Transfer the subframe to the corresponding location in the full-size frame for (int y = 0; y < ysize; y++) { @@ -254,7 +329,7 @@ bool CameraStarfish::Capture(int duration, usImage& img, int options, const wxRe } else { - rval = fcUsb_cmd_getRawFrame(CamNum, (unsigned short)ysize, (unsigned short)xsize, img.ImageData); + rval = fcUsb_cmd_getRawFrame(CamNum, (unsigned short) ysize, (unsigned short) xsize, img.ImageData); } /* if (rval != kIOReturnSuccess) { @@ -262,15 +337,19 @@ bool CameraStarfish::Capture(int duration, usImage& img, int options, const wxRe //return true; }*/ - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return false; } -bool CameraStarfish::ST4PulseGuideScope(int direction, int duration) { +bool CameraStarfish::ST4PulseGuideScope(int direction, int duration) +{ - if (direction == WEST) direction = EAST; // my ENUM and theirs are flipped - else if (direction == EAST) direction = WEST; + if (direction == WEST) + direction = EAST; // my ENUM and theirs are flipped + else if (direction == EAST) + direction = WEST; if (fcUsb_cmd_pulseRelay(CamNum, direction, duration, 0, false) != kIOReturnSuccess) return true; diff --git a/src/cam_starfish.h b/src/cam_starfish.h index 6c8900fa2..cbfb011bf 100644 --- a/src/cam_starfish.h +++ b/src/cam_starfish.h @@ -40,4 +40,4 @@ class StarfishCameraFactory static GuideCamera *MakeStarfishCamera(); }; -#endif // CAM_STARFISH_INCLUDED +#endif // CAM_STARFISH_INCLUDED diff --git a/src/cam_svb.cpp b/src/cam_svb.cpp index 019b45b9b..89ae1ca77 100644 --- a/src/cam_svb.cpp +++ b/src/cam_svb.cpp @@ -1,46 +1,46 @@ /* -* cam_svb.cpp -* PHD2 Guiding -* -* Copyright (c) 2020 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * cam_svb.cpp + * PHD2 Guiding + * + * Copyright (c) 2020 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #ifdef SVB_CAMERA -#include "cam_svb.h" -#include "cameras/SVBCameraSDK.h" +# include "cam_svb.h" +# include "cameras/SVBCameraSDK.h" -#ifdef __WINDOWS__ -# include -# include -#endif +# ifdef __WINDOWS__ +# include +# include +# endif enum CaptureMode { @@ -55,7 +55,7 @@ class SVBCamera : public GuideCamera unsigned short m_prevBinning; void *m_buffer; size_t m_buffer_size; - wxByte m_bpp; // bits per pixel: 8 or 16 + wxByte m_bpp; // bits per pixel: 8 or 16 CaptureMode m_mode; bool m_capturing; int m_cameraId; @@ -90,15 +90,15 @@ class SVBCamera : public GuideCamera }; SVBCamera::SVBCamera() - : - m_buffer(nullptr) + : m_buffer(nullptr) { Name = _T("Svbony Camera"); PropertyDialogType = PROPDLG_WHEN_DISCONNECTED; Connected = false; m_hasGuideOutput = false; // updated when connected HasSubframes = true; - HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to true later when the camera is connected + HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to + // true later when the camera is connected m_defaultGainPct = GuideCamera::GetDefaultCameraGain(); int value = pConfig->Profile.GetInt("/camera/svb/bpp", 16); m_bpp = value == 8 ? 8 : 16; @@ -137,7 +137,7 @@ SVBCameraDlg::SVBCameraDlg() wxStdDialogButtonSizer *sdbSizer2 = new wxStdDialogButtonSizer(); wxButton *sdbSizer2OK = new wxButton(this, wxID_OK); - wxButton* sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); + wxButton *sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); sdbSizer2->AddButton(sdbSizer2OK); sdbSizer2->AddButton(sdbSizer2Cancel); sdbSizer2->Realize(); @@ -241,7 +241,8 @@ static int FindCamera(const wxString& camId, wxString *err) SVB_CAMERA_INFO info; if (SVBGetCameraInfo(&info, i) == SVB_SUCCESS) { - Debug.Write(wxString::Format("SVB: cam [%d] id %d %s S/N %s\n", i, info.CameraID, info.FriendlyName, info.CameraSN)); + Debug.Write( + wxString::Format("SVB: cam [%d] id %d %s S/N %s\n", i, info.CameraID, info.FriendlyName, info.CameraSN)); if (info.CameraSN == camId) { Debug.Write(wxString::Format("SVB: found matching camera at idx %d, id=%d\n", i, info.CameraID)); @@ -257,7 +258,8 @@ static int FindCamera(const wxString& camId, wxString *err) inline static int ImgTypeBits(SVB_IMG_TYPE t) { - switch (t) { + switch (t) + { case SVB_IMG_RAW8: case SVB_IMG_Y8: return 8; @@ -345,14 +347,13 @@ bool SVBCamera::Connect(const wxString& camId) } } - Debug.Write(wxString::Format("SVB: using mode BPP = %u, image type %d\n", (unsigned int)m_bpp, img_type)); + Debug.Write(wxString::Format("SVB: using mode BPP = %u, image type %d\n", (unsigned int) m_bpp, img_type)); if (img_type == SVB_IMG_END) { Disconnect(); return CamConnectFailed(wxString::Format(_("The camera does not support %s mode, try selecting %s mode"), - m_bpp == 8 ? _("8-bit") : _("16-bit"), - m_bpp == 8 ? _("16-bit") : _("8-bit"))); + m_bpp == 8 ? _("8-bit") : _("16-bit"), m_bpp == 8 ? _("16-bit") : _("8-bit"))); } m_mode = CM_VIDEO; @@ -471,8 +472,8 @@ bool SVBCamera::Connect(const wxString& camId) m_minGain = caps.MinValue; m_maxGain = caps.MaxValue; m_defaultGainPct = gain_pct(m_minGain, m_maxGain, caps.DefaultValue); - Debug.Write(wxString::Format("SVB: gain range = %d .. %d default = %ld (%d%%)\n", - m_minGain, m_maxGain, caps.DefaultValue, m_defaultGainPct)); + Debug.Write(wxString::Format("SVB: gain range = %d .. %d default = %ld (%d%%)\n", m_minGain, m_maxGain, + caps.DefaultValue, m_defaultGainPct)); } // fall through @@ -497,7 +498,6 @@ bool SVBCamera::Connect(const wxString& camId) break; } } - } m_frame = wxRect(FullSize); @@ -505,8 +505,7 @@ bool SVBCamera::Connect(const wxString& camId) SVBSetOutputImageType(m_cameraId, img_type); - SVBSetROIFormat(m_cameraId, m_frame.GetLeft(), m_frame.GetTop(), - m_frame.GetWidth(), m_frame.GetHeight(), Binning); + SVBSetROIFormat(m_cameraId, m_frame.GetLeft(), m_frame.GetTop(), m_frame.GetWidth(), m_frame.GetHeight(), Binning); return false; } @@ -569,7 +568,10 @@ inline static int round_up(int v, int m) static void flush_buffered_image(int cameraId, void *buf, size_t size) { - enum { NUM_IMAGE_BUFFERS = 2 }; // camera has 2 internal frame buffers + enum + { + NUM_IMAGE_BUFFERS = 2 + }; // camera has 2 internal frame buffers // clear buffered frames if any @@ -629,8 +631,7 @@ bool SVBCamera::Capture(int duration, usImage& img, int options, const wxRect& s long cur_exp; // The returned exposure value may differ from the requested exposure by several usecs, // so round the returned exposure to the nearest millisecond. - if (SVBGetControlValue(m_cameraId, SVB_EXPOSURE, &cur_exp, &tmp) == SVB_SUCCESS && - (cur_exp + 500) / 1000 != duration) + if (SVBGetControlValue(m_cameraId, SVB_EXPOSURE, &cur_exp, &tmp) == SVB_SUCCESS && (cur_exp + 500) / 1000 != duration) { Debug.Write(wxString::Format("SVB: set CONTROL_EXPOSURE %d\n", duration * 1000)); SVBSetControlValue(m_cameraId, SVB_EXPOSURE, duration * 1000, SVB_FALSE); @@ -638,8 +639,7 @@ bool SVBCamera::Capture(int duration, usImage& img, int options, const wxRect& s long new_gain = cam_gain(m_minGain, m_maxGain, GuideCameraGain); long cur_gain; - if (SVBGetControlValue(m_cameraId, SVB_GAIN, &cur_gain, &tmp) == SVB_SUCCESS && - new_gain != cur_gain) + if (SVBGetControlValue(m_cameraId, SVB_GAIN, &cur_gain, &tmp) == SVB_SUCCESS && new_gain != cur_gain) { Debug.Write(wxString::Format("SVB: set CONTROL_GAIN %d%% %d\n", GuideCameraGain, new_gain)); SVBSetControlValue(m_cameraId, SVB_GAIN, new_gain, SVB_FALSE); @@ -658,18 +658,17 @@ bool SVBCamera::Capture(int duration, usImage& img, int options, const wxRect& s { StopCapture(); - SVB_ERROR_CODE status = SVBSetROIFormat(m_cameraId, frame.GetLeft(), frame.GetTop(), - frame.GetWidth(), frame.GetHeight(), Binning); + SVB_ERROR_CODE status = + SVBSetROIFormat(m_cameraId, frame.GetLeft(), frame.GetTop(), frame.GetWidth(), frame.GetHeight(), Binning); if (status != SVB_SUCCESS) - Debug.Write(wxString::Format("SVB: setImageFormat(%d,%d,%d,%d,%hu) => %d\n", - frame.GetLeft(), frame.GetTop(), frame.GetWidth(), frame.GetHeight(), Binning, status)); + Debug.Write(wxString::Format("SVB: setImageFormat(%d,%d,%d,%d,%hu) => %d\n", frame.GetLeft(), frame.GetTop(), + frame.GetWidth(), frame.GetHeight(), Binning, status)); } int poll = wxMin(duration, 100); - unsigned char *const buffer = - m_bpp == 16 && !useSubframe ? (unsigned char *) img.ImageData : (unsigned char *) m_buffer; + unsigned char *const buffer = m_bpp == 16 && !useSubframe ? (unsigned char *) img.ImageData : (unsigned char *) m_buffer; if (m_mode == CM_VIDEO) { @@ -727,7 +726,10 @@ bool SVBCamera::Capture(int duration, usImage& img, int options, const wxRect& s SVBSendSoftTrigger(m_cameraId); - enum { GRACE_PERIOD_MS = 500 }; // recommended by Svbony + enum + { + GRACE_PERIOD_MS = 500 + }; // recommended by Svbony CameraWatchdog watchdog(duration, duration + GRACE_PERIOD_MS); if (duration > 100) @@ -815,7 +817,7 @@ bool SVBCamera::Capture(int duration, usImage& img, int options, const wxRect& s if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); if (m_isColor && Binning == 1 && (options & CAPTURE_RECON)) - QuickLRecon(img); + QuickLRecon(img); return false; } diff --git a/src/cam_svb.h b/src/cam_svb.h index 0f89a22c5..46d16dbcc 100644 --- a/src/cam_svb.h +++ b/src/cam_svb.h @@ -1,35 +1,35 @@ /* -* cam_svb.h -* PHD2 Guiding -* -* Copyright (c) 2020 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * cam_svb.h + * PHD2 Guiding + * + * Copyright (c) 2020 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef CAM_SVB_INCLUDED #define CAM_SVB_INCLUDED diff --git a/src/cam_sxv.cpp b/src/cam_sxv.cpp index 8e40b8881..c9659014d 100644 --- a/src/cam_sxv.cpp +++ b/src/cam_sxv.cpp @@ -35,24 +35,24 @@ #include "phd.h" -#if defined (SXV) +#if defined(SXV) -#include "cam_sxv.h" -#include "image_math.h" +# include "cam_sxv.h" +# include "image_math.h" -#include +# include -#if defined (__WINDOWS__) -# include "cameras/SXUSB.h" +# if defined(__WINDOWS__) +# include "cameras/SXUSB.h" typedef struct t_sxccd_params sxccd_params_t; typedef HANDLE sxccd_handle_t; -# define SXCCD_EXP_FLAGS_NOWIPE_FRAME CCD_EXP_FLAGS_NOWIPE_FRAME -# define SXCCD_EXP_FLAGS_FIELD_ODD CCD_EXP_FLAGS_FIELD_ODD -# define SXCCD_EXP_FLAGS_FIELD_BOTH CCD_EXP_FLAGS_FIELD_BOTH -#else -# include "cameras/SXMacLib.h" +# define SXCCD_EXP_FLAGS_NOWIPE_FRAME CCD_EXP_FLAGS_NOWIPE_FRAME +# define SXCCD_EXP_FLAGS_FIELD_ODD CCD_EXP_FLAGS_FIELD_ODD +# define SXCCD_EXP_FLAGS_FIELD_BOTH CCD_EXP_FLAGS_FIELD_BOTH +# else +# include "cameras/SXMacLib.h" typedef void *sxccd_handle_t; -#endif +# endif class CameraSXV : public GuideCamera { @@ -70,7 +70,6 @@ class CameraSXV : public GuideCamera double m_devicePixelSize; public: - CameraSXV(); ~CameraSXV(); @@ -92,7 +91,8 @@ class CameraSXV : public GuideCamera void InitFrameSizes(); }; -enum { +enum +{ SX_CMOS_GUIDER = 39, }; @@ -107,53 +107,141 @@ static wxString NameFromModel(int model) switch (model) { - case 0x05: m = "SX-H5"; break; - case 0x85: m = "SX-H5C"; break; - case 0x09: m = "SX-H9"; break; // this is almost certainly a Superstar - case 0x89: m = "SX-H9C"; break; - case 0x39: m = "SX-LS9"; break; - case 0x19: m = "SX-SX9"; break; - case 0x99: m = "SX-SX9C"; break; - case 0x10: m = "SX-H16"; break; - case 0x90: m = "SX-H16C"; break; - case 0x11: m = "SX-H17"; break; - case 0x91: m = "SX-H17C"; break; - case 0x12: m = "SX-H18"; break; - case 0x92: m = "SX-H18C"; break; - case 0x23: m = "SX-H35"; break; - case 0xB3: m = "SX-H35C"; break; - case 0x24: m = "SX-H36"; break; - case 0xB4: m = "SX-H36C"; break; - case 0x56: m = "SX-H674"; break; - case 0xB6: m = "SX-H674C"; break; - case 0x57: m = "SX-H694"; break; - case 0xB7: m = "SX-H694C"; break; - case 0x28: m = "SX-H814"; break; - case 0xA8: m = "SX-H814C"; break; - case 0x29: m = "SX-H834"; break; - case 0xA9: m = "SX-H834C"; break; - case 0x3B: m = "SX-H825"; break; - case 0xBB: m = "SX-H825C"; break; - case 0x3C: m = "SX-US825"; break; - case 0xBC: m = "SX-US825C"; break; - // interlaced models - case 0x45: m = "SX-MX5"; break; - case 0x84: m = "SX-MX5C"; break; - case 0x46: m = "SX-LX1"; break; - case 0x47: m = "SX-MX7"; break; - case 0xC7: m = "SX-MX7C"; break; - case 0x48: m = "SX-MX8"; break; - case 0xC8: m = "SX-MX8C"; break; - case 0x49: m = "SX-MX9"; break; - case 0x59: m = "SX-M25"; break; - case 0x5A: m = "SX-M26"; break; - // development models - case 0x0C: m = "SX-DEV1"; break; - case 0x0D: m = "SX-DEV2"; break; - case 0x0E: m = "SX-DEV3"; break; - case 0x0F: m = "SX-DEV4"; break; - - default: m = wxString::Format("SX Camera Model %d", model); break; + case 0x05: + m = "SX-H5"; + break; + case 0x85: + m = "SX-H5C"; + break; + case 0x09: + m = "SX-H9"; + break; // this is almost certainly a Superstar + case 0x89: + m = "SX-H9C"; + break; + case 0x39: + m = "SX-LS9"; + break; + case 0x19: + m = "SX-SX9"; + break; + case 0x99: + m = "SX-SX9C"; + break; + case 0x10: + m = "SX-H16"; + break; + case 0x90: + m = "SX-H16C"; + break; + case 0x11: + m = "SX-H17"; + break; + case 0x91: + m = "SX-H17C"; + break; + case 0x12: + m = "SX-H18"; + break; + case 0x92: + m = "SX-H18C"; + break; + case 0x23: + m = "SX-H35"; + break; + case 0xB3: + m = "SX-H35C"; + break; + case 0x24: + m = "SX-H36"; + break; + case 0xB4: + m = "SX-H36C"; + break; + case 0x56: + m = "SX-H674"; + break; + case 0xB6: + m = "SX-H674C"; + break; + case 0x57: + m = "SX-H694"; + break; + case 0xB7: + m = "SX-H694C"; + break; + case 0x28: + m = "SX-H814"; + break; + case 0xA8: + m = "SX-H814C"; + break; + case 0x29: + m = "SX-H834"; + break; + case 0xA9: + m = "SX-H834C"; + break; + case 0x3B: + m = "SX-H825"; + break; + case 0xBB: + m = "SX-H825C"; + break; + case 0x3C: + m = "SX-US825"; + break; + case 0xBC: + m = "SX-US825C"; + break; + // interlaced models + case 0x45: + m = "SX-MX5"; + break; + case 0x84: + m = "SX-MX5C"; + break; + case 0x46: + m = "SX-LX1"; + break; + case 0x47: + m = "SX-MX7"; + break; + case 0xC7: + m = "SX-MX7C"; + break; + case 0x48: + m = "SX-MX8"; + break; + case 0xC8: + m = "SX-MX8C"; + break; + case 0x49: + m = "SX-MX9"; + break; + case 0x59: + m = "SX-M25"; + break; + case 0x5A: + m = "SX-M26"; + break; + // development models + case 0x0C: + m = "SX-DEV1"; + break; + case 0x0D: + m = "SX-DEV2"; + break; + case 0x0E: + m = "SX-DEV3"; + break; + case 0x0F: + m = "SX-DEV4"; + break; + + default: + m = wxString::Format("SX Camera Model %d", model); + break; } if (model == 0x46) @@ -195,14 +283,15 @@ wxByte CameraSXV::BitsPerPixel() class SXCameraDlg : public wxDialog { public: - wxCheckBox* m_squarePixels; + wxCheckBox *m_squarePixels; SXCameraDlg(wxWindow *parent, wxWindowID id = wxID_ANY, const wxString& title = _("SX Camera Settings"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(268, 133), long style = wxDEFAULT_DIALOG_STYLE); ~SXCameraDlg() { } }; -SXCameraDlg::SXCameraDlg(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) +SXCameraDlg::SXCameraDlg( + wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) { SetSizeHints(wxDefaultSize, wxDefaultSize); @@ -214,9 +303,9 @@ SXCameraDlg::SXCameraDlg(wxWindow *parent, wxWindowID id, const wxString& title, sbSizer3->Add(m_squarePixels, 0, wxALL, 5); bSizer12->Add(sbSizer3, 1, wxEXPAND, 5); - wxStdDialogButtonSizer* sdbSizer2 = new wxStdDialogButtonSizer(); + wxStdDialogButtonSizer *sdbSizer2 = new wxStdDialogButtonSizer(); wxButton *sdbSizer2OK = new wxButton(this, wxID_OK); - wxButton* sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); + wxButton *sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); sdbSizer2->AddButton(sdbSizer2OK); sdbSizer2->AddButton(sdbSizer2Cancel); sdbSizer2->Realize(); @@ -269,7 +358,7 @@ void CameraSXV::InitFrameSizes() { FullSize.SetWidth(CCDParams.width / Binning); // This is the height after squaring pixels. - FullSize.SetHeight((int)floor((float)(CCDParams.height / Binning) * CCDParams.pix_height / CCDParams.pix_width)); + FullSize.SetHeight((int) floor((float) (CCDParams.height / Binning) * CCDParams.pix_height / CCDParams.pix_width)); } else { @@ -282,17 +371,17 @@ void CameraSXV::InitFrameSizes() m_darkFrameSize = FullSize; } - Debug.Write(wxString::Format("SXV: Bin = %hu, dark size = %dx%d, frame size = %dx%d\n", - Binning, m_darkFrameSize.x, m_darkFrameSize.y, FullSize.x, FullSize.y)); + Debug.Write(wxString::Format("SXV: Bin = %hu, dark size = %dx%d, frame size = %dx%d\n", Binning, m_darkFrameSize.x, + m_darkFrameSize.y, FullSize.x, FullSize.y)); } bool CameraSXV::Connect(const wxString& camId) { // returns true on error -#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) +# if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__) sxSetTimeoutMS(m_timeoutMs); -#endif +# endif long idx = -1; if (camId == DEFAULT_CAMERA_ID) @@ -338,7 +427,7 @@ bool CameraSXV::Connect(const wxString& camId) Name = NameFromModel(CameraModel); - if (CameraModel & 0x80) // color + if (CameraModel & 0x80) // color ColorSensor = true; else ColorSensor = false; @@ -396,12 +485,12 @@ bool CameraSXV::Connect(const wxString& camId) } Debug.AddLine("SX Camera: " + Name); - Debug.AddLine(wxString::Format("SX Camera Params: %u x %u (reported as %u x %u) PixSz: %.2f x %.2f; #Pix: %u Array color type: %u,%u Interlaced: %d Model: %u, Subype: %u, Porch: %u,%u %u,%u Extras: %u", - FullSize.GetWidth(), FullSize.GetHeight(), CCDParams.width, CCDParams.height, - CCDParams.pix_width, CCDParams.pix_height, FullSize.GetHeight() * FullSize.GetWidth(), - CCDParams.color_matrix, (int) ColorSensor, (int) Interlaced, - CameraModel, SubType, CCDParams.hfront_porch, CCDParams.hback_porch, CCDParams.vfront_porch, CCDParams.vback_porch, - CCDParams.extra_caps)); + Debug.AddLine(wxString::Format("SX Camera Params: %u x %u (reported as %u x %u) PixSz: %.2f x %.2f; #Pix: %u Array color " + "type: %u,%u Interlaced: %d Model: %u, Subype: %u, Porch: %u,%u %u,%u Extras: %u", + FullSize.GetWidth(), FullSize.GetHeight(), CCDParams.width, CCDParams.height, CCDParams.pix_width, CCDParams.pix_height, + FullSize.GetHeight() * FullSize.GetWidth(), CCDParams.color_matrix, (int) ColorSensor, (int) Interlaced, CameraModel, + SubType, CCDParams.hfront_porch, CCDParams.hback_porch, CCDParams.vfront_porch, CCDParams.vback_porch, + CCDParams.extra_caps)); if (!err) Connected = true; @@ -450,28 +539,35 @@ static bool InitImgCMOSGuider(usImage& img, const wxSize& FullSize, const unsign { int oddbias, evenbias; oddbias = evenbias = 0; - for (int x = 0; x < 16; x += 2) { // Figure the offsets for this line - oddbias += (int)*rawptr++; - evenbias += (int)*rawptr++; + for (int x = 0; x < 16; x += 2) + { // Figure the offsets for this line + oddbias += (int) *rawptr++; + evenbias += (int) *rawptr++; } - oddbias = oddbias / 8 - 1000; // Create avg and pre-build in the offset to keep off of the floor + oddbias = oddbias / 8 - 1000; // Create avg and pre-build in the offset to keep off of the floor evenbias = evenbias / 8 - 1000; - for (int x = 0; x < output_xsize; x += 2) { // Load value into new image array pulling out right bias - int val = (int)*rawptr++ - oddbias; - if (val < 0) val = 0; // Bounds check - else if (val > 65535) val = 65535; - *dataptr++ = (unsigned short)val; - val = (int)*rawptr++ - evenbias; - if (val < 0) val = 0; // Bounds check - else if (val > 65535) val = 65535; - *dataptr++ = (unsigned short)val; + for (int x = 0; x < output_xsize; x += 2) + { // Load value into new image array pulling out right bias + int val = (int) *rawptr++ - oddbias; + if (val < 0) + val = 0; // Bounds check + else if (val > 65535) + val = 65535; + *dataptr++ = (unsigned short) val; + val = (int) *rawptr++ - evenbias; + if (val < 0) + val = 0; // Bounds check + else if (val > 65535) + val = 65535; + *dataptr++ = (unsigned short) val; } } return false; } -static bool InitImgInterlacedInterp(usImage& img, const wxSize& FullSize, bool subframe, const wxRect& frame, const usImage& tmp) +static bool InitImgInterlacedInterp( + usImage& img, const wxSize& FullSize, bool subframe, const wxRect& frame, const usImage& tmp) { if (img.Init(FullSize)) return true; @@ -528,8 +624,8 @@ static bool InitImgInterlacedSquare(usImage& img, const wxSize& FullSize, bool s // xsize = number of columns (752) // ysize = number of rows read from camera (290) - float const pw = ccdparams.pix_width * binning; // bin1: 8.6, bin2: 17.2 - float const ph = ccdparams.pix_height; // reported value is for the binned pixel (16.6) + float const pw = ccdparams.pix_width * binning; // bin1: 8.6, bin2: 17.2 + float const ph = ccdparams.pix_height; // reported value is for the binned pixel (16.6) float const r0 = pw / ph; if (img.Init(FullSize)) @@ -561,7 +657,7 @@ static bool InitImgInterlacedSquare(usImage& img, const wxSize& FullSize, bool s { const unsigned short *src = raw + p0 * fullw + xofs; for (int x = 0; x < framew; x++) - *dst++ = (unsigned short)(r0 * (float) *src++); + *dst++ = (unsigned short) (r0 * (float) *src++); } else { @@ -570,7 +666,7 @@ static bool InitImgInterlacedSquare(usImage& img, const wxSize& FullSize, bool s const unsigned short *src0 = raw + p0 * fullw + xofs; const unsigned short *src1 = raw + p1 * fullw + xofs; for (int x = 0; x < framew; x++) - *dst++ = (unsigned short)(r0 * (float)*src0++ + r1 * (float)*src1++); + *dst++ = (unsigned short) (r0 * (float) *src0++ + r1 * (float) *src1++); } y0 = y1; @@ -581,8 +677,8 @@ static bool InitImgInterlacedSquare(usImage& img, const wxSize& FullSize, bool s return false; } -static bool InitImgProgressive(usImage& img, unsigned int xofs, unsigned int yofs, unsigned int xsize, - unsigned int ysize, bool subframe, const wxSize& FullSize, const unsigned short *raw) +static bool InitImgProgressive(usImage& img, unsigned int xofs, unsigned int yofs, unsigned int xsize, unsigned int ysize, + bool subframe, const wxSize& FullSize, const unsigned short *raw) { if (img.Init(FullSize)) return true; @@ -607,7 +703,7 @@ static bool InitImgProgressive(usImage& img, unsigned int xofs, unsigned int yof return false; } -inline static void swap(unsigned short *&a, unsigned short *&b) +inline static void swap(unsigned short *& a, unsigned short *& b) { unsigned short *tmp = a; a = b; @@ -625,9 +721,8 @@ static bool ClearPixels(sxccd_handle_t sxHandle, unsigned short flags) return true; } -static bool LatchPixels(sxccd_handle_t sxHandle, unsigned short flags, unsigned short xoffset, - unsigned short yoffset, unsigned short width, unsigned short height, unsigned short xbin, - unsigned short ybin) +static bool LatchPixels(sxccd_handle_t sxHandle, unsigned short flags, unsigned short xoffset, unsigned short yoffset, + unsigned short width, unsigned short height, unsigned short xbin, unsigned short ybin) { int ret = sxLatchPixels(sxHandle, flags, 0, xoffset, yoffset, width, height, xbin, ybin); if (ret == 0) @@ -638,9 +733,8 @@ static bool LatchPixels(sxccd_handle_t sxHandle, unsigned short flags, unsigned return true; } -static bool ExposePixels(sxccd_handle_t sxHandle, unsigned short flags, unsigned short xoffset, - unsigned short yoffset, unsigned short width, unsigned short height, unsigned short xbin, - unsigned short ybin, unsigned int msec) +static bool ExposePixels(sxccd_handle_t sxHandle, unsigned short flags, unsigned short xoffset, unsigned short yoffset, + unsigned short width, unsigned short height, unsigned short xbin, unsigned short ybin, unsigned int msec) { int ret = sxExposePixels(sxHandle, flags, 0, xoffset, yoffset, width, height, xbin, ybin, msec); if (ret == 0) @@ -677,7 +771,7 @@ bool CameraSXV::Capture(int duration, usImage& img, int options, const wxRect& s if (HasShutter && ShutterClosed) { - sxSetShutter(hCam, 1); // Close the shutter if needed + sxSetShutter(hCam, 1); // Close the shutter if needed wxMilliSleep(200); } @@ -721,7 +815,8 @@ bool CameraSXV::Capture(int duration, usImage& img, int options, const wxRect& s { if (SquarePixels) { - // incoming subframe coordinates are in squared pixel coordinate system, convert to camera pixel coordinates + // incoming subframe coordinates are in squared pixel coordinate system, convert to camera pixel + // coordinates float r = CCDParams.pix_width * (float) xbin / CCDParams.pix_height; unsigned int y0 = (unsigned int) floor(subframe.GetTop() * r); unsigned int y1 = (unsigned int) floor(subframe.GetBottom() * r); @@ -734,7 +829,7 @@ bool CameraSXV::Capture(int duration, usImage& img, int options, const wxRect& s { unsigned int y0 = (unsigned int) subframe.GetTop() / 2; // interpolation may require the next row - unsigned int y1 = (unsigned int)(subframe.GetBottom() + 1) / 2; + unsigned int y1 = (unsigned int) (subframe.GetBottom() + 1) / 2; if (y1 >= CCDParams.height) y1 = CCDParams.height - 1; yofs = y0; @@ -817,7 +912,7 @@ bool CameraSXV::Capture(int duration, usImage& img, int options, const wxRect& s // if (WorkerThread::InterruptRequested()) // return true; - if (!ReadPixels(hCam, RawData, nPixelsToRead)) // stop exposure and read but only the one frame + if (!ReadPixels(hCam, RawData, nPixelsToRead)) // stop exposure and read but only the one frame { DisconnectWithAlert(_("Lost connection to camera"), RECONNECT); return true; @@ -825,7 +920,7 @@ bool CameraSXV::Capture(int duration, usImage& img, int options, const wxRect& s if (HasShutter && ShutterClosed) { - sxSetShutter(hCam, 0); // Open it back up + sxSetShutter(hCam, 0); // Open it back up wxMilliSleep(200); } @@ -838,7 +933,8 @@ bool CameraSXV::Capture(int duration, usImage& img, int options, const wxRect& s if (IsCMOSGuider(CameraModel)) error = InitImgCMOSGuider(img, FullSize, RawData); else - error = InitImgProgressive(img, xofs / xbin, yofs / ybin, xsize / xbin, ysize / ybin, takeSubframe, FullSize, RawData); + error = + InitImgProgressive(img, xofs / xbin, yofs / ybin, xsize / xbin, ysize / ybin, takeSubframe, FullSize, RawData); if (error) { @@ -918,24 +1014,25 @@ bool CameraSXV::ST4PulseGuideScope(int direction, int duration) // North = 2 // South = 4 unsigned char dircmd = 0; - switch (direction) { - case WEST: - dircmd = (unsigned char) 1; - break; - case EAST: - dircmd = (unsigned char) 8; - break; - case NORTH: - dircmd = (unsigned char) 2; - break; - case SOUTH: - dircmd = (unsigned char) 4; - break; - } - sxSetSTAR2000(hCam,dircmd); + switch (direction) + { + case WEST: + dircmd = (unsigned char) 1; + break; + case EAST: + dircmd = (unsigned char) 8; + break; + case NORTH: + dircmd = (unsigned char) 2; + break; + case SOUTH: + dircmd = (unsigned char) 4; + break; + } + sxSetSTAR2000(hCam, dircmd); WorkerThread::MilliSleep(duration); dircmd = 0; - sxSetSTAR2000(hCam,dircmd); + sxSetSTAR2000(hCam, dircmd); return false; } diff --git a/src/cam_touptek.cpp b/src/cam_touptek.cpp index a5a746791..5d9e459ef 100644 --- a/src/cam_touptek.cpp +++ b/src/cam_touptek.cpp @@ -36,22 +36,22 @@ #if defined(TOUPTEK_CAMERA) -#include "cam_touptek.h" -#include "cameras/toupcam.h" -#include "image_math.h" +# include "cam_touptek.h" +# include "cameras/toupcam.h" +# include "image_math.h" // Touptek API uses these Windows definitions even on non-Windows platforms -#ifndef S_OK -#define S_OK ((HRESULT)0L) -#define S_FALSE ((HRESULT)1L) -#endif +# ifndef S_OK +# define S_OK ((HRESULT) 0L) +# define S_FALSE ((HRESULT) 1L) +# endif struct ToupCam { HToupCam m_h; void *m_buffer; void *m_tmpbuf; - wxByte m_bpp; // bits per pixel: 8 or 16 + wxByte m_bpp; // bits per pixel: 8 or 16 bool m_isColor; bool m_hasGuideOutput; double m_devicePixelSize; @@ -66,13 +66,14 @@ struct ToupCam wxMutex m_lock; wxCondition m_cond; - ToupCam() : - m_h(nullptr), - m_buffer(nullptr), - m_tmpbuf(nullptr), - m_started(false), - m_cond(m_lock) - { } + ToupCam() + : m_h(nullptr) + , m_buffer(nullptr) + , m_tmpbuf(nullptr) + , m_started(false) + , m_cond(m_lock) + { + } ~ToupCam() { @@ -80,21 +81,15 @@ struct ToupCam ::free(m_tmpbuf); } - int gain_pct(int val) const - { - return (val - m_minGain) * 100 / (m_maxGain - m_minGain); - } + int gain_pct(int val) const { return (val - m_minGain) * 100 / (m_maxGain - m_minGain); } - int cam_gain(int pct) const - { - return m_minGain + pct * (m_maxGain - m_minGain) / 100; - } + int cam_gain(int pct) const { return m_minGain + pct * (m_maxGain - m_minGain) / 100; } void StopCapture() { if (m_started) { - //Debug.Write("TOUPTEK: stopcapture\n"); + // Debug.Write("TOUPTEK: stopcapture\n"); HRESULT hr; if (FAILED(hr = Toupcam_Stop(m_h))) Debug.Write(wxString::Format("TOUPTEK: Toupcam_Stop failed with status 0x%x\n", hr)); @@ -114,7 +109,7 @@ struct ToupCam case TOUPCAM_EVENT_NOFRAMETIMEOUT: case TOUPCAM_EVENT_NOPACKETTIMEOUT: case TOUPCAM_EVENT_TRIGGERFAIL: - //Debug.Write(wxString::Format("TOUPTEK: cam event 0x%x\n", event)); + // Debug.Write(wxString::Format("TOUPTEK: cam event 0x%x\n", event)); { wxMutexLocker lck(cam->m_lock); cam->m_captureResult = event; @@ -132,7 +127,7 @@ struct ToupCam if (m_started) return; - //Debug.Write("TOUPTEK: startcapture\n"); + // Debug.Write("TOUPTEK: startcapture\n"); HRESULT hr; if (FAILED(hr = Toupcam_StartPullModeWithCallback(m_h, &CamEventCb, this))) @@ -209,15 +204,9 @@ struct ToupCam } } - bool SoftwareBinning() const - { - return m_isColor; - } + bool SoftwareBinning() const { return m_isColor; } - bool SetHwBinning(unsigned int binning) - { - return SetOption(TOUPCAM_OPTION_BINNING, ToupcamBinning(binning)); - } + bool SetHwBinning(unsigned int binning) { return SetOption(TOUPCAM_OPTION_BINNING, ToupcamBinning(binning)); } bool SetBinning(unsigned int binning) { @@ -262,7 +251,6 @@ class CameraToupTek : public GuideCamera ToupCam m_cam; public: - CameraToupTek(); ~CameraToupTek(); @@ -294,16 +282,15 @@ CameraToupTek::CameraToupTek() Connected = false; m_cam.m_hasGuideOutput = true; HasSubframes = true; - HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to true later when the camera is connected + HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to + // true later when the camera is connected m_cam.m_defaultGainPct = GuideCamera::GetDefaultCameraGain(); int value = pConfig->Profile.GetInt("/camera/ToupTek/bpp", 8); m_cam.m_bpp = value == 8 ? 8 : 16; MaxBinning = 4; } -CameraToupTek::~CameraToupTek() -{ -} +CameraToupTek::~CameraToupTek() { } bool CameraToupTek::EnumCameras(wxArrayString& names, wxArrayString& ids) { @@ -377,8 +364,8 @@ bool CameraToupTek::Connect(const wxString& camIdArg) HasCooler = (info->model->flag & TOUPCAM_FLAG_TEC) != 0; m_cam.m_hasGuideOutput = (info->model->flag & TOUPCAM_FLAG_ST4) != 0; - Debug.Write(wxString::Format("TOUPTEK: isColor = %d, hasCooler = %d, hasST4 = %d\n", - m_cam.m_isColor, HasCooler, m_cam.m_hasGuideOutput)); + Debug.Write(wxString::Format( + "TOUPTEK: isColor = %d, hasCooler = %d, hasST4 = %d\n", m_cam.m_isColor, HasCooler, m_cam.m_hasGuideOutput)); if (FAILED(Toupcam_get_Resolution(m_cam.m_h, 0, &m_cam.m_maxSize.x, &m_cam.m_maxSize.y))) { @@ -445,7 +432,8 @@ bool CameraToupTek::Connect(const wxString& camIdArg) m_cam.m_maxGain = maxGain; HasGainControl = maxGain > minGain; m_cam.m_defaultGainPct = m_cam.gain_pct(defaultGain); - Debug.Write(wxString::Format("TOUPTEK: gain range %d .. %d, default = %d (%d%%)\n", minGain, maxGain, defaultGain, m_cam.m_defaultGainPct)); + Debug.Write(wxString::Format( + "TOUPTEK: gain range %d .. %d, default = %d (%d%%)\n", minGain, maxGain, defaultGain, m_cam.m_defaultGainPct)); } else { @@ -470,14 +458,14 @@ bool CameraToupTek::Connect(const wxString& camIdArg) m_cam.SetOption(TOUPCAM_OPTION_RAW, 1); m_cam.SetOption(TOUPCAM_OPTION_BITDEPTH, m_cam.m_bpp == 8 ? 0 : 1); m_cam.SetOption(TOUPCAM_OPTION_LINEAR, 0); - //m_cam.SetOption(TOUPCAM_OPTION_CURVE, 0); // resetting this one fails on all the cameras I have + // m_cam.SetOption(TOUPCAM_OPTION_CURVE, 0); // resetting this one fails on all the cameras I have m_cam.SetOption(TOUPCAM_OPTION_COLORMATIX, 0); m_cam.SetOption(TOUPCAM_OPTION_WBGAIN, 0); - m_cam.SetOption(TOUPCAM_OPTION_TRIGGER, 1); // software trigger + m_cam.SetOption(TOUPCAM_OPTION_TRIGGER, 1); // software trigger m_cam.SetOption(TOUPCAM_OPTION_AUTOEXP_POLICY, 0); // 0="Exposure Only" 1="Exposure Preferred" m_cam.SetOption(TOUPCAM_OPTION_ROTATE, 0); m_cam.SetOption(TOUPCAM_OPTION_UPSIDE_DOWN, 0); - //m_cam.SetOption(TOUPCAM_OPTION_CG, 0); // "Conversion Gain" 0=LCG 1=HCG 2=HDR // setting this fails + // m_cam.SetOption(TOUPCAM_OPTION_CG, 0); // "Conversion Gain" 0=LCG 1=HCG 2=HDR // setting this fails m_cam.SetOption(TOUPCAM_OPTION_FFC, 0); m_cam.SetOption(TOUPCAM_OPTION_DFC, 0); m_cam.SetOption(TOUPCAM_OPTION_SHARPENING, 0); @@ -502,12 +490,8 @@ bool CameraToupTek::Connect(const wxString& camIdArg) unsigned int fourcc, bpp; if (SUCCEEDED(hr = Toupcam_get_RawFormat(m_cam.m_h, &fourcc, &bpp))) { - Debug.Write(wxString::Format("TOUPTEK: raw format = %c%c%c%c bit depth = %u\n", - fourcc & 0xff, - (fourcc >> 8) & 0xff, - (fourcc >> 16) & 0xff, - fourcc >> 24, - bpp)); + Debug.Write(wxString::Format("TOUPTEK: raw format = %c%c%c%c bit depth = %u\n", fourcc & 0xff, (fourcc >> 8) & 0xff, + (fourcc >> 16) & 0xff, fourcc >> 24, bpp)); } else Debug.Write(wxString::Format("TOUPTEK: Toupcam_get_RawFormat failed with status 0x%x\n", hr)); @@ -561,7 +545,7 @@ bool CameraToupTek::Capture(int duration, usImage& img, int options, const wxRec unsigned int const binning = m_cam.m_curBin; - wxRect roi; // un-binned coordinates + wxRect roi; // un-binned coordinates if (useSubframe) { @@ -606,7 +590,7 @@ bool CameraToupTek::Capture(int duration, usImage& img, int options, const wxRec m_cam.StartCapture(); - //Debug.Write("TOUPTEK: capture: trigger\n"); + // Debug.Write("TOUPTEK: capture: trigger\n"); if (FAILED(hr = Toupcam_Trigger(m_cam.m_h, 1))) Debug.Write(wxString::Format("TOUPTEK: Toupcam_Trigger(1) failed with status 0x%x\n", hr)); @@ -659,7 +643,7 @@ bool CameraToupTek::Capture(int duration, usImage& img, int options, const wxRec return true; } - //Debug.Write("TOUPTEK: capture: image ready\n"); + // Debug.Write("TOUPTEK: capture: image ready\n"); void *buf; wxSize sz; @@ -725,7 +709,7 @@ bool CameraToupTek::Capture(int duration, usImage& img, int options, const wxRec } } - //Debug.Write("TOUPTEK: capture: pull done\n"); + // Debug.Write("TOUPTEK: capture: pull done\n"); if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); @@ -750,10 +734,14 @@ inline static int GetToupcamDirection(int direction) switch (direction) { default: - case NORTH: return 0; - case EAST: return 2; - case WEST: return 3; - case SOUTH: return 1; + case NORTH: + return 0; + case EAST: + return 2; + case WEST: + return 3; + case SOUTH: + return 1; } } @@ -812,7 +800,7 @@ ToupTekCameraDlg::ToupTekCameraDlg() wxStdDialogButtonSizer *sdbSizer2 = new wxStdDialogButtonSizer(); wxButton *sdbSizer2OK = new wxButton(this, wxID_OK); - wxButton* sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); + wxButton *sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); sdbSizer2->AddButton(sdbSizer2OK); sdbSizer2->AddButton(sdbSizer2Cancel); sdbSizer2->Realize(); @@ -868,7 +856,7 @@ bool CameraToupTek::SetCoolerOn(bool on) bool CameraToupTek::SetCoolerSetpoint(double temperature) { - int val = (int)(temperature * 10.); + int val = (int) (temperature * 10.); val = wxMax(val, TOUPCAM_TEC_TARGET_MIN); val = wxMin(val, TOUPCAM_TEC_TARGET_MAX); @@ -890,8 +878,7 @@ bool CameraToupTek::GetCoolerStatus(bool *on, double *setpoint, double *power, d else err = true; - if (m_cam.GetOption(TOUPCAM_OPTION_TEC_VOLTAGE, &vcur) && - m_cam.GetOption(TOUPCAM_OPTION_TEC_VOLTAGE_MAX, &vmax) && + if (m_cam.GetOption(TOUPCAM_OPTION_TEC_VOLTAGE, &vcur) && m_cam.GetOption(TOUPCAM_OPTION_TEC_VOLTAGE_MAX, &vmax) && vmax > 0) { *power = vcur * 100.0 / vmax; diff --git a/src/cam_vfw.cpp b/src/cam_vfw.cpp index f7eb5cedc..c29a124b7 100644 --- a/src/cam_vfw.cpp +++ b/src/cam_vfw.cpp @@ -36,19 +36,20 @@ #ifdef VFW_CAMERA -#include "camera.h" -#include "time.h" -#include "image_math.h" -#include -//#include "vcapwin.h" -#include "cam_vfw.h" +# include "camera.h" +# include "time.h" +# include "image_math.h" +# include +// #include "vcapwin.h" +# include "cam_vfw.h" CameraVFW::CameraVFW() { Connected = false; Name = _T("Windows VFW"); - FullSize = wxSize(640,480); // should be overwritten - VFW_Window = NULL; Extra_Window=NULL; + FullSize = wxSize(640, 480); // should be overwritten + VFW_Window = NULL; + Extra_Window = NULL; PropertyDialogType = PROPDLG_WHEN_CONNECTED; HasDelayParam = false; HasPortNum = false; @@ -61,66 +62,76 @@ wxByte CameraVFW::BitsPerPixel() bool CameraVFW::Connect(const wxString& camId) { -// returns true on error -// bool retval; + // returns true on error + // bool retval; int ndevices, i, devicenum; wxSplitterWindow *dispwin; - wxVideoCaptureWindow* capwin; + wxVideoCaptureWindow *capwin; - if (!Extra_Window) { - dispwin = new wxSplitterWindow(pFrame->guider,-1); + if (!Extra_Window) + { + dispwin = new wxSplitterWindow(pFrame->guider, -1); Extra_Window = dispwin; } - else dispwin = Extra_Window; + else + dispwin = Extra_Window; - if (!VFW_Window) { - capwin = new wxVideoCaptureWindow(dispwin,WIN_VFW,wxPoint(0,0),wxSize(640,480)); + if (!VFW_Window) + { + capwin = new wxVideoCaptureWindow(dispwin, WIN_VFW, wxPoint(0, 0), wxSize(640, 480)); VFW_Window = capwin; } - else capwin = VFW_Window; + else + capwin = VFW_Window; dispwin->Show(false); - //capwin->Create(frame); + // capwin->Create(frame); ndevices = capwin->GetDeviceCount(); - if (ndevices == 0) return true; + if (ndevices == 0) + return true; devicenum = 1; - if (ndevices > 1) { // multiple found -- get one from user + if (ndevices > 1) + { // multiple found -- get one from user wxArrayString devnames; - for (i=0; iGetDeviceName(i)); - devicenum = wxGetSingleChoiceIndex(_("Select capture device"),_("Camera choice"),devnames); + devicenum = wxGetSingleChoiceIndex(_("Select capture device"), _("Camera choice"), devnames); if (devicenum == -1) return true; - else devicenum = devicenum + 1; + else + devicenum = devicenum + 1; } - if (capwin->DeviceConnect(devicenum-1) == false) // try to connect + if (capwin->DeviceConnect(devicenum - 1) == false) // try to connect return true; - if (VFW_Window->HasVideoFormatDialog()) { + if (VFW_Window->HasVideoFormatDialog()) + { VFW_Window->VideoFormatDialog(); -// int w,h,bpp; -// FOURCC fourcc; -// VFW_Window->GetVideoFormat( &w,&h, &bpp, &fourcc ); -// FullSize = wxSize(w,h); + // int w,h,bpp; + // FOURCC fourcc; + // VFW_Window->GetVideoFormat( &w,&h, &bpp, &fourcc ); + // FullSize = wxSize(w,h); } - int w,h,bpp; + int w, h, bpp; FOURCC fourcc; - capwin->GetVideoFormat( &w,&h, &bpp, &fourcc ); -// capwin->SetVideoFormat(640,480,-1,-1); - FullSize=wxSize(w,h); - pFrame->StatusMsg(wxString::Format("%d x %d mode activated",w,h)); + capwin->GetVideoFormat(&w, &h, &bpp, &fourcc); + // capwin->SetVideoFormat(640,480,-1,-1); + FullSize = wxSize(w, h); + pFrame->StatusMsg(wxString::Format("%d x %d mode activated", w, h)); Connected = true; return false; } -bool CameraVFW::Disconnect() { - if (VFW_Window->IsDeviceConnected()) { +bool CameraVFW::Disconnect() +{ + if (VFW_Window->IsDeviceConnected()) + { VFW_Window->DeviceDisconnect(); } Connected = false; VFW_Window = NULL; -// Extra_Window = NULL; + // Extra_Window = NULL; return false; } @@ -137,45 +148,50 @@ bool CameraVFW::Capture(int duration, usImage& img, int options, const wxRect& s wxStopWatch swatch; - //gNumFrames = 0; - if (img.Init(FullSize)) { + // gNumFrames = 0; + if (img.Init(FullSize)) + { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } img.Clear(); - swatch.Start(); //wxStartTimer(); - while (still_going) { + swatch.Start(); // wxStartTimer(); + while (still_going) + { VFW_Window->SnapshotTowxImage(); cap_img = VFW_Window->GetwxImage(); imgdata = cap_img.GetData(); dptr = img.ImageData; - for (unsigned int i = 0; i < img.NPixels; i++, dptr++, imgdata += 3) { - *dptr = *dptr + (unsigned short) (*imgdata + *(imgdata+1) + *(imgdata+2)); + for (unsigned int i = 0; i < img.NPixels; i++, dptr++, imgdata += 3) + { + *dptr = *dptr + (unsigned short) (*imgdata + *(imgdata + 1) + *(imgdata + 2)); } NFrames++; if ((swatch.Time() >= duration) && (NFrames > 2)) still_going = false; } - pFrame->StatusMsg(wxString::Format("%d frames",NFrames)); - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + pFrame->StatusMsg(wxString::Format("%d frames", NFrames)); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); return false; } -void CameraVFW::ShowPropertyDialog() { -// if (event.GetId() == ADV_BUTTON1) { -/* if (VFW_Window->HasVideoFormatDialog()) { - VFW_Window->VideoFormatDialog(); - int w,h,bpp; - FOURCC fourcc; - VFW_Window->GetVideoFormat( &w,&h, &bpp, &fourcc ); - FullSize = wxSize(w,h); - }*/ -// else { - if (VFW_Window->HasVideoSourceDialog()) VFW_Window->VideoSourceDialog(); -// } - +void CameraVFW::ShowPropertyDialog() +{ + // if (event.GetId() == ADV_BUTTON1) { + /* if (VFW_Window->HasVideoFormatDialog()) { + VFW_Window->VideoFormatDialog(); + int w,h,bpp; + FOURCC fourcc; + VFW_Window->GetVideoFormat( &w,&h, &bpp, &fourcc ); + FullSize = wxSize(w,h); + }*/ + // else { + if (VFW_Window->HasVideoSourceDialog()) + VFW_Window->VideoSourceDialog(); + // } } #endif diff --git a/src/cam_vfw.h b/src/cam_vfw.h index 92811efcd..703ef788c 100644 --- a/src/cam_vfw.h +++ b/src/cam_vfw.h @@ -40,15 +40,15 @@ class CameraVFW : public GuideCamera { wxVideoCaptureWindow *VFW_Window; - wxSplitterWindow *Extra_Window; + wxSplitterWindow *Extra_Window; public: CameraVFW(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - void ShowPropertyDialog() override; - wxByte BitsPerPixel() override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + void ShowPropertyDialog() override; + wxByte BitsPerPixel() override; }; #endif diff --git a/src/cam_wdm.cpp b/src/cam_wdm.cpp index 42ba42658..0087a6a96 100644 --- a/src/cam_wdm.cpp +++ b/src/cam_wdm.cpp @@ -39,16 +39,16 @@ #ifdef WDM_CAMERA -#include "cam_wdm_base.h" -#include "cam_wdm.h" -#include "CVPlatform.h" +# include "cam_wdm_base.h" +# include "cam_wdm.h" +# include "CVPlatform.h" CameraWDM::CameraWDM() { Connected = false; - Name = _T("Windows Camera"); // should get overwritten on connect - FullSize = wxSize(640, 480); // should get overwritten on connect - m_deviceNumber = -1; // Which WDM device connected + Name = _T("Windows Camera"); // should get overwritten on connect + FullSize = wxSize(640, 480); // should get overwritten on connect + m_deviceNumber = -1; // Which WDM device connected m_deviceMode = -1; PropertyDialogType = PROPDLG_WHEN_CONNECTED; HasDelayParam = false; @@ -174,7 +174,7 @@ bool CameraWDM::SelectDeviceAndMode(SelectionContext ctx) // Init the library if (CVFAILED(vidCap->Init())) { - wxMessageBox(_T("Error initializing WDM services"),_("Error"), wxOK | wxICON_ERROR); + wxMessageBox(_T("Error initializing WDM services"), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("CVFAILED(VidCap->Init())"); } inited = true; @@ -300,7 +300,7 @@ bool CameraWDM::Connect(const wxString& camId) // Init the library if (CVFAILED(m_pVidCap->Init())) { - wxMessageBox(_T("Error initializing WDM services"), _("Error"),wxOK | wxICON_ERROR); + wxMessageBox(_T("Error initializing WDM services"), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("CVFAILED(VidCap->Init())"); } @@ -323,7 +323,8 @@ bool CameraWDM::Connect(const wxString& camId) } else { - wxMessageBox(wxString::Format("Error connecting to WDM device #%d", m_deviceNumber), _("Error"), wxOK | wxICON_ERROR); + wxMessageBox( + wxString::Format("Error connecting to WDM device #%d", m_deviceNumber), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("Error connecting to WDM device"); } @@ -337,15 +338,13 @@ bool CameraWDM::Connect(const wxString& camId) CVVidCapture::VIDCAP_MODE modeInfo; if (CVFAILED(m_pVidCap->GetCurrentMode(modeInfo))) { - wxMessageBox(wxString::Format("Error probing video mode %d", m_deviceMode),_("Error"),wxOK | wxICON_ERROR); + wxMessageBox(wxString::Format("Error probing video mode %d", m_deviceMode), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("GetCurrentMode() failed"); } // RAW YUY2 format encodes two 8-bit greyscale pixels per pseudo-YUY2 value // so the width is twice the video mode's advertised width - FullSize = m_rawYUY2 ? - wxSize(modeInfo.XRes * 2, modeInfo.YRes) : - wxSize(modeInfo.XRes, modeInfo.YRes); + FullSize = m_rawYUY2 ? wxSize(modeInfo.XRes * 2, modeInfo.YRes) : wxSize(modeInfo.XRes, modeInfo.YRes); // Start the stream m_captureMode = NOT_CAPTURING; // Make sure we don't start saving yet diff --git a/src/cam_wdm_base.h b/src/cam_wdm_base.h index 7fd03dffb..476dcd904 100644 --- a/src/cam_wdm_base.h +++ b/src/cam_wdm_base.h @@ -64,8 +64,7 @@ class CameraWDM : public GuideCamera volatile int m_nFrames; volatile int m_nAttempts; usImage *m_stack; - volatile enum E_CAPTURE_MODE - { + volatile enum E_CAPTURE_MODE { NOT_CAPTURING = 0, STOP_CAPTURING, CAPTURE_ONE_FRAME, @@ -95,8 +94,9 @@ class CameraWDM : public GuideCamera bool OnCapture(const cbdata& p); protected: - enum SelectionContext { - CTX_SELECT, // selecting device and mode in response to camera selection button + enum SelectionContext + { + CTX_SELECT, // selecting device and mode in response to camera selection button CTX_CONNECT, // selecting device and mode in response to camera connect button }; virtual bool SelectDeviceAndMode(SelectionContext ctx); @@ -122,7 +122,6 @@ class CameraLEWebcam : public CameraWDM }; public: - CameraLEWebcam(); ~CameraLEWebcam(); diff --git a/src/cam_zwo.cpp b/src/cam_zwo.cpp index be2eb0af1..5bc76b4f7 100644 --- a/src/cam_zwo.cpp +++ b/src/cam_zwo.cpp @@ -1,54 +1,54 @@ /* -* cam_zwo.cpp -* PHD Guiding -* -* Created by Robin Glover. -* Copyright (c) 2014 Robin Glover. -* Copyright (c) 2017-2018 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * cam_zwo.cpp + * PHD Guiding + * + * Created by Robin Glover. + * Copyright (c) 2014 Robin Glover. + * Copyright (c) 2017-2018 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #ifdef ZWO_ASI -#include "cam_zwo.h" -#include "cameras/ASICamera2.h" +# include "cam_zwo.h" +# include "cameras/ASICamera2.h" -#ifdef __WINDOWS__ +# ifdef __WINDOWS__ -#ifdef OS_WINDOWS +# ifdef OS_WINDOWS // troubleshooting with the libusb definitions -# undef OS_WINDOWS -#endif +# undef OS_WINDOWS +# endif -# include -# include -#endif +# include +# include +# endif enum CaptureMode { @@ -63,7 +63,7 @@ class Camera_ZWO : public GuideCamera unsigned short m_prevBinning; void *m_buffer; size_t m_buffer_size; - wxByte m_bpp; // bits per pixel: 8 or 16 + wxByte m_bpp; // bits per pixel: 8 or 16 CaptureMode m_mode; bool m_capturing; int m_cameraId; @@ -105,15 +105,15 @@ class Camera_ZWO : public GuideCamera }; Camera_ZWO::Camera_ZWO() - : - m_buffer(nullptr) + : m_buffer(nullptr) { Name = _T("ZWO ASI Camera"); PropertyDialogType = PROPDLG_WHEN_DISCONNECTED; Connected = false; m_hasGuideOutput = true; HasSubframes = true; - HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to true later when the camera is connected + HasGainControl = true; // workaround: ok to set to false later, but brain dialog will crash if we start false then change to + // true later when the camera is connected m_defaultGainPct = GuideCamera::GetDefaultCameraGain(); int value = pConfig->Profile.GetInt("/camera/ZWO/bpp", 8); m_bpp = value == 8 ? 8 : 16; @@ -132,9 +132,7 @@ wxByte Camera_ZWO::BitsPerPixel() inline wxSize Camera_ZWO::BinnedFrameSize(unsigned int binning) { // ASI cameras require width % 8 == 0 and height % 2 == 0 - return wxSize( - (m_maxSize.x / binning) & ~(8U - 1), - (m_maxSize.y / binning) & ~(2U - 1)); + return wxSize((m_maxSize.x / binning) & ~(8U - 1), (m_maxSize.y / binning) & ~(2U - 1)); } struct ZWOCameraDlg : public wxDialog @@ -160,7 +158,7 @@ ZWOCameraDlg::ZWOCameraDlg() wxStdDialogButtonSizer *sdbSizer2 = new wxStdDialogButtonSizer(); wxButton *sdbSizer2OK = new wxButton(this, wxID_OK); - wxButton* sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); + wxButton *sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); sdbSizer2->AddButton(sdbSizer2OK); sdbSizer2->AddButton(sdbSizer2Cancel); sdbSizer2->Realize(); @@ -198,14 +196,14 @@ inline static int gain_pct(int minval, int maxval, int val) return (val - minval) * 100 / (maxval - minval); } -#ifdef __WINDOWS__ +# ifdef __WINDOWS__ -#if !defined(FACILITY_VISUALCPP) -# define FACILITY_VISUALCPP ((LONG)0x6d) -#endif -#ifndef VcppException -# define VcppException(sev,err) ((sev) | ((FACILITY_VISUALCPP)<<16) | (err)) -#endif +# if !defined(FACILITY_VISUALCPP) +# define FACILITY_VISUALCPP ((LONG) 0x6d) +# endif +# ifndef VcppException +# define VcppException(sev, err) ((sev) | ((FACILITY_VISUALCPP) << 16) | (err)) +# endif static LONG WINAPI DelayLoadDllExceptionFilter(PEXCEPTION_POINTERS pExcPointers, wxString *err) { @@ -214,7 +212,8 @@ static LONG WINAPI DelayLoadDllExceptionFilter(PEXCEPTION_POINTERS pExcPointers, switch (pExcPointers->ExceptionRecord->ExceptionCode) { - case VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND): { + case VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND): + { // ASICamera2.dll depends on the VC++ 2008 runtime, check for that HMODULE hm = LoadLibraryEx(_T("MSVCR90.DLL"), NULL, LOAD_LIBRARY_AS_DATAFILE); if (hm) @@ -223,7 +222,8 @@ static LONG WINAPI DelayLoadDllExceptionFilter(PEXCEPTION_POINTERS pExcPointers, *err = wxString::Format(_("Could not load DLL %s"), pdli->szDll); } else - *err = _("The ASI camera library requires the Microsoft Visual C++ 2008 Redistributable Package (x86), available at http://www.microsoft.com/en-us/download/details.aspx?id=29"); + *err = _("The ASI camera library requires the Microsoft Visual C++ 2008 Redistributable Package (x86), available " + "at http://www.microsoft.com/en-us/download/details.aspx?id=29"); break; } @@ -245,23 +245,25 @@ static LONG WINAPI DelayLoadDllExceptionFilter(PEXCEPTION_POINTERS pExcPointers, static bool DoTryLoadDll(wxString *err) { - __try { + __try + { ASIGetNumOfConnectedCameras(); return true; } - __except (DelayLoadDllExceptionFilter(GetExceptionInformation(), err)) { + __except (DelayLoadDllExceptionFilter(GetExceptionInformation(), err)) + { return false; } } -#else // __WINDOWS__ +# else // __WINDOWS__ static bool DoTryLoadDll(wxString *err) { return true; } -#endif // __WINDOWS__ +# endif // __WINDOWS__ static bool TryLoadDll(wxString *err) { @@ -536,7 +538,6 @@ bool Camera_ZWO::Connect(const wxString& camId) break; } } - } if (HasGainControl) @@ -693,7 +694,10 @@ inline static int round_up(int v, int m) static void flush_buffered_image(int cameraId, void *buf, size_t size) { - enum { NUM_IMAGE_BUFFERS = 2 }; // camera has 2 internal frame buffers + enum + { + NUM_IMAGE_BUFFERS = 2 + }; // camera has 2 internal frame buffers // clear buffered frames if any @@ -751,8 +755,7 @@ bool Camera_ZWO::Capture(int duration, usImage& img, int options, const wxRect& long exposureUS = duration * 1000; ASI_BOOL tmp; long cur_exp; - if (ASIGetControlValue(m_cameraId, ASI_EXPOSURE, &cur_exp, &tmp) == ASI_SUCCESS && - cur_exp != exposureUS) + if (ASIGetControlValue(m_cameraId, ASI_EXPOSURE, &cur_exp, &tmp) == ASI_SUCCESS && cur_exp != exposureUS) { Debug.Write(wxString::Format("ZWO: set CONTROL_EXPOSURE %d\n", exposureUS)); ASISetControlValue(m_cameraId, ASI_EXPOSURE, exposureUS, ASI_FALSE); @@ -760,8 +763,7 @@ bool Camera_ZWO::Capture(int duration, usImage& img, int options, const wxRect& long new_gain = cam_gain(m_minGain, m_maxGain, GuideCameraGain); long cur_gain; - if (ASIGetControlValue(m_cameraId, ASI_GAIN, &cur_gain, &tmp) == ASI_SUCCESS && - new_gain != cur_gain) + if (ASIGetControlValue(m_cameraId, ASI_GAIN, &cur_gain, &tmp) == ASI_SUCCESS && new_gain != cur_gain) { Debug.Write(wxString::Format("ZWO: set CONTROL_GAIN %d%% %d\n", GuideCameraGain, new_gain)); ASISetControlValue(m_cameraId, ASI_GAIN, new_gain, ASI_FALSE); @@ -780,9 +782,11 @@ bool Camera_ZWO::Capture(int duration, usImage& img, int options, const wxRect& { StopCapture(); - ASI_ERROR_CODE status = ASISetROIFormat(m_cameraId, frame.GetWidth(), frame.GetHeight(), Binning, m_bpp == 8 ? ASI_IMG_RAW8 : ASI_IMG_RAW16); + ASI_ERROR_CODE status = ASISetROIFormat( + m_cameraId, frame.GetWidth(), frame.GetHeight(), Binning, m_bpp == 8 ? ASI_IMG_RAW8 : ASI_IMG_RAW16); if (status != ASI_SUCCESS) - Debug.Write(wxString::Format("ZWO: setImageFormat(%d,%d,%hu) => %d\n", frame.GetWidth(), frame.GetHeight(), Binning, status)); + Debug.Write(wxString::Format( + "ZWO: setImageFormat(%d,%d,%hu) => %d\n", frame.GetWidth(), frame.GetHeight(), Binning, status)); } if (pos_change) @@ -794,8 +798,7 @@ bool Camera_ZWO::Capture(int duration, usImage& img, int options, const wxRect& int poll = wxMin(duration, 100); - unsigned char *const buffer = - m_bpp == 16 && !useSubframe ? (unsigned char *) img.ImageData : (unsigned char *) m_buffer; + unsigned char *const buffer = m_bpp == 16 && !useSubframe ? (unsigned char *) img.ImageData : (unsigned char *) m_buffer; if (m_mode == CM_VIDEO) { @@ -848,7 +851,8 @@ bool Camera_ZWO::Capture(int duration, usImage& img, int options, const wxRect& ASIStartExposure(m_cameraId, is_dark); - CameraWatchdog watchdog(duration, duration + GetTimeoutMs() + 10000); // total timeout is 2 * duration + 15s (typically) + CameraWatchdog watchdog( + duration, duration + GetTimeoutMs() + 10000); // total timeout is 2 * duration + 15s (typically) if (duration > 100) { @@ -987,7 +991,7 @@ bool Camera_ZWO::ST4PulseGuideScope(int direction, int duration) return false; } -void Camera_ZWO::ClearGuidePort() +void Camera_ZWO::ClearGuidePort() { ASIPulseGuideOff(m_cameraId, ASI_GUIDE_NORTH); ASIPulseGuideOff(m_cameraId, ASI_GUIDE_SOUTH); @@ -1000,10 +1004,13 @@ GuideCamera *ZWOCameraFactory::MakeZWOCamera() return new Camera_ZWO(); } -#if defined(__APPLE__) +# if defined(__APPLE__) // workaround link error for missing symbol ___exp10 from libASICamera2.a -#include -extern "C" double __exp10(double x) { return pow(10.0, x); } -#endif +# include +extern "C" double __exp10(double x) +{ + return pow(10.0, x); +} +# endif #endif // ZWO_ASI diff --git a/src/cam_zwo.h b/src/cam_zwo.h index e2abb5526..293709bae 100644 --- a/src/cam_zwo.h +++ b/src/cam_zwo.h @@ -1,37 +1,37 @@ /* -* cam_zwo.h -* PHD Guiding -* -* Created by Robin Glover. -* Copyright (c) 2014 Robin Glover -* Copyright (c) 2018 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * cam_zwo.h + * PHD Guiding + * + * Created by Robin Glover. + * Copyright (c) 2014 Robin Glover + * Copyright (c) 2018 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef CAM_ZWO_H_INCLUDED #define CAM_ZWO_H_INCLUDED diff --git a/src/camcal_import_dialog.cpp b/src/camcal_import_dialog.cpp index c0312a0e9..02bbf55c3 100644 --- a/src/camcal_import_dialog.cpp +++ b/src/camcal_import_dialog.cpp @@ -33,8 +33,8 @@ * */ -// Handles import of camera calibration files (dark library, bad-pix map files) from user-selected profile to the current profile -// Source profile choices are limited to camera data with compatible geometry +// Handles import of camera calibration files (dark library, bad-pix map files) from user-selected profile to the current +// profile Source profile choices are limited to camera data with compatible geometry #include "phd.h" #include "camcal_import_dialog.h" @@ -48,10 +48,10 @@ static void AddTableEntryPair(wxWindow *parent, wxFlexGridSizer *pTable, const w pTable->Add(pControl, 1, wxALL, 5); } -CamCalImportDialog::CamCalImportDialog(wxWindow *parent) : - wxDialog(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) +CamCalImportDialog::CamCalImportDialog(wxWindow *parent) + : wxDialog(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) { - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); SetTitle(wxString::Format(_("Import Darks to Profile %s"), pConfig->GetCurrentProfile())); @@ -59,11 +59,12 @@ CamCalImportDialog::CamCalImportDialog(wxWindow *parent) : m_profileNames = pConfig->ProfileNames(); // Start with the dark library - wxStaticBoxSizer* darksGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Dark Library")); + wxStaticBoxSizer *darksGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Dark Library")); - wxStaticText* darksLabel = new wxStaticText(this, wxID_STATIC, _("Choose the profile with the dark library you want to use:"), wxDefaultPosition, wxDefaultSize, 0); + wxStaticText *darksLabel = new wxStaticText( + this, wxID_STATIC, _("Choose the profile with the dark library you want to use:"), wxDefaultPosition, wxDefaultSize, 0); darksGroup->Add(darksLabel, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); - wxFlexGridSizer* drkGrid = new wxFlexGridSizer(2, 2, 0, 0); + wxFlexGridSizer *drkGrid = new wxFlexGridSizer(2, 2, 0, 0); wxArrayString drkChoices; drkChoices.Add(_("None")); @@ -72,7 +73,8 @@ CamCalImportDialog::CamCalImportDialog(wxWindow *parent) : if (drkChoices.Count() > 1) { - m_darksChoice = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, drkChoices, 0, wxDefaultValidator, _("Darks Profiles")); + m_darksChoice = new wxChoice( + this, wxID_ANY, wxDefaultPosition, wxDefaultSize, drkChoices, 0, wxDefaultValidator, _("Darks Profiles")); m_darksChoice->SetSelection(0); m_darksChoice->Bind(wxEVT_COMMAND_CHOICE_SELECTED, &CamCalImportDialog::OnDarkProfileChoice, this); AddTableEntryPair(this, drkGrid, _("Import from profile"), m_darksChoice); @@ -85,9 +87,10 @@ CamCalImportDialog::CamCalImportDialog(wxWindow *parent) : vSizer->Add(darksGroup, 0, wxALIGN_LEFT | wxALL, 10); // Now add the bad-pix map controls - wxStaticBoxSizer* bpmGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Bad-pixel Map")); + wxStaticBoxSizer *bpmGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Bad-pixel Map")); - wxStaticText* bpmLabel = new wxStaticText(this, wxID_STATIC, _("Choose the profile with the bad-pixel map you want to use:"), wxDefaultPosition, wxDefaultSize, 0); + wxStaticText *bpmLabel = new wxStaticText(this, wxID_STATIC, + _("Choose the profile with the bad-pixel map you want to use:"), wxDefaultPosition, wxDefaultSize, 0); bpmGroup->Add(bpmLabel, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 10); wxArrayString bpmChoices; @@ -97,7 +100,8 @@ CamCalImportDialog::CamCalImportDialog(wxWindow *parent) : if (bpmChoices.Count() > 1) { - m_bpmChoice = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, bpmChoices, 0, wxDefaultValidator, _("Bad-pix Map Profiles")); + m_bpmChoice = new wxChoice( + this, wxID_ANY, wxDefaultPosition, wxDefaultSize, bpmChoices, 0, wxDefaultValidator, _("Bad-pix Map Profiles")); m_bpmChoice->SetSelection(0); m_bpmChoice->Bind(wxEVT_COMMAND_CHOICE_SELECTED, &CamCalImportDialog::OnBPMProfileChoice, this); wxFlexGridSizer *bpmGrid = new wxFlexGridSizer(2, 2, 0, 0); @@ -112,29 +116,27 @@ CamCalImportDialog::CamCalImportDialog(wxWindow *parent) : vSizer->Add(bpmGroup, 0, wxALIGN_LEFT | wxALL, 10); // Add the buttons - wxBoxSizer* btnHSizer = new wxBoxSizer(wxHORIZONTAL); + wxBoxSizer *btnHSizer = new wxBoxSizer(wxHORIZONTAL); vSizer->Add(btnHSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 10); - wxButton* btnOk = new wxButton(this, wxID_ANY, _("OK"), wxDefaultPosition, wxDefaultSize, 0); + wxButton *btnOk = new wxButton(this, wxID_ANY, _("OK"), wxDefaultPosition, wxDefaultSize, 0); btnOk->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &CamCalImportDialog::OnOk, this); btnOk->SetDefault(); btnHSizer->Add(btnOk, 0, wxALIGN_CENTER_VERTICAL | wxALL, 10); - wxButton* btnCancel = new wxButton(this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0); + wxButton *btnCancel = new wxButton(this, wxID_CANCEL, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0); btnHSizer->Add(btnCancel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 10); - //PopulateLBs(darksLB, bpmLB); + // PopulateLBs(darksLB, bpmLB); SetSizerAndFit(vSizer); m_activeProfileName = pConfig->GetCurrentProfile(); m_sourceDarksProfileId = -1; m_sourceBpmProfileId = -1; } -CamCalImportDialog::~CamCalImportDialog(void) -{ -} +CamCalImportDialog::~CamCalImportDialog(void) { } -void CamCalImportDialog::FindCompatibleDarks(wxArrayString* pResults) +void CamCalImportDialog::FindCompatibleDarks(wxArrayString *pResults) { for (unsigned int i = 0; i < m_profileNames.GetCount(); i++) @@ -144,10 +146,9 @@ void CamCalImportDialog::FindCompatibleDarks(wxArrayString* pResults) if (pFrame->DarkLibExists(profileId, false)) pResults->Add(m_profileNames[i]); } - } -void CamCalImportDialog::FindCompatibleBPMs(wxArrayString* pResults) +void CamCalImportDialog::FindCompatibleBPMs(wxArrayString *pResults) { for (unsigned int i = 0; i < m_profileNames.GetCount(); i++) { @@ -174,7 +175,6 @@ void CamCalImportDialog::OnDarkProfileChoice(wxCommandEvent& evt) m_darkCameraChoice->SetLabelText(wxEmptyString); m_sourceDarksProfileId = -1; } - } void CamCalImportDialog::OnBPMProfileChoice(wxCommandEvent& evt) @@ -205,7 +205,8 @@ void CamCalImportDialog::OnOk(wxCommandEvent& evt) { if (DefectMap::ImportFromProfile(m_sourceBpmProfileId, m_thisProfileId)) { - Debug.Write(wxString::Format("Defect map files imported and loaded from profile %d to profile %d\n", m_sourceBpmProfileId, m_thisProfileId)); + Debug.Write(wxString::Format( + "Defect map files imported and loaded from profile %d to profile %d\n", m_sourceBpmProfileId, m_thisProfileId)); pFrame->LoadDefectMapHandler(true); bpmLoaded = true; } @@ -222,7 +223,8 @@ void CamCalImportDialog::OnOk(wxCommandEvent& evt) destName = MyFrame::DarkLibFileName(m_thisProfileId); if (wxCopyFile(sourceName, destName, true)) { - Debug.Write(wxString::Format("Dark library imported from profile %d to profile %d\n", m_sourceDarksProfileId, m_thisProfileId)); + Debug.Write(wxString::Format( + "Dark library imported from profile %d to profile %d\n", m_sourceDarksProfileId, m_thisProfileId)); if (!bpmLoaded) { pFrame->LoadDarkHandler(true); @@ -234,6 +236,6 @@ void CamCalImportDialog::OnOk(wxCommandEvent& evt) wxMessageBox(_("Dark library could not be imported because of errors in file/copy")); } } - pFrame->SetDarkMenuState(); // Get enabled states straightened out + pFrame->SetDarkMenuState(); // Get enabled states straightened out EndModal(wxID_OK); } diff --git a/src/camcal_import_dialog.h b/src/camcal_import_dialog.h index 740e09a3e..6ffef8aee 100644 --- a/src/camcal_import_dialog.h +++ b/src/camcal_import_dialog.h @@ -39,17 +39,16 @@ class CamCalImportDialog : public wxDialog { public: - CamCalImportDialog(wxWindow *parent); ~CamCalImportDialog(void); private: - wxChoice* m_darksChoice; - wxStaticText* m_darkCameraChoice; - wxChoice* m_bpmChoice; - wxStaticText* m_bpmCameraChoice; - void FindCompatibleDarks(wxArrayString* pResults); - void FindCompatibleBPMs(wxArrayString* pResults); + wxChoice *m_darksChoice; + wxStaticText *m_darkCameraChoice; + wxChoice *m_bpmChoice; + wxStaticText *m_bpmCameraChoice; + void FindCompatibleDarks(wxArrayString *pResults); + void FindCompatibleBPMs(wxArrayString *pResults); void OnDarkProfileChoice(wxCommandEvent& evt); void OnBPMProfileChoice(wxCommandEvent& evt); void OnOk(wxCommandEvent& evt); diff --git a/src/camera.cpp b/src/camera.cpp index 325e5e4db..549621433 100644 --- a/src/camera.cpp +++ b/src/camera.cpp @@ -50,135 +50,135 @@ const double GuideCamera::UnknownPixelSize = 0.0; wxSize UNDEFINED_FRAME_SIZE = wxSize(0, 0); -#if defined (ATIK16) +#if defined(ATIK16) # include "cam_atik16.h" #endif -#if defined (IOPTRON_CAMERA) +#if defined(IOPTRON_CAMERA) # include "cam_ioptron.h" #endif -#if defined (LE_SERIAL_CAMERA) +#if defined(LE_SERIAL_CAMERA) # include "cam_LESerialWebcam.h" #endif -#if defined (LE_PARALLEL_CAMERA) +#if defined(LE_PARALLEL_CAMERA) # include "cam_LEParallelwebcam.h" #endif -#if defined (LE_LXUSB_CAMERA) +#if defined(LE_LXUSB_CAMERA) # include "cam_LELXUSBwebcam.h" #endif -#if defined (QGUIDE) +#if defined(QGUIDE) # include "cam_qguide.h" #endif -#if defined (CAM_QHY5) +#if defined(CAM_QHY5) # include "cam_qhy5.h" #endif -#if defined (QHY_CAMERA) +#if defined(QHY_CAMERA) # include "cam_qhy.h" #endif -#if defined (SVB_CAMERA) +#if defined(SVB_CAMERA) # include "cam_svb.h" #endif -#if defined (ZWO_ASI) +#if defined(ZWO_ASI) # include "cam_zwo.h" #endif -#if defined (TOUPTEK_CAMERA) +#if defined(TOUPTEK_CAMERA) # include "cam_touptek.h" #endif -#if defined (SKYRAIDER_CAMERA) +#if defined(SKYRAIDER_CAMERA) # include "cam_skyraider.h" #endif -#if defined (ALTAIR) +#if defined(ALTAIR) # include "cam_altair.h" #endif -#if defined (ORION_DSCI) +#if defined(ORION_DSCI) # include "cam_StarShootDSCI.h" #endif -#if defined (OS_PL130) +#if defined(OS_PL130) # include "cam_OSPL130.h" #endif -#if defined (VFW_CAMERA) +#if defined(VFW_CAMERA) # include "cam_vfw.h" #endif -#if defined (OGMA_CAMERA) +#if defined(OGMA_CAMERA) # include "cam_ogma.h" #endif -#if defined (OPENCV_CAMERA) +#if defined(OPENCV_CAMERA) # include "cam_opencv.h" #endif -#if defined (WDM_CAMERA) +#if defined(WDM_CAMERA) # include "cam_wdm.h" #endif -#if defined (STARFISH_CAMERA) +#if defined(STARFISH_CAMERA) # include "cam_starfish.h" #endif -#if defined (SXV) +#if defined(SXV) # include "cam_sxv.h" #endif -#if defined (SBIG) +#if defined(SBIG) # include "cam_sbig.h" #endif -#if defined (NEB_SBIG) +#if defined(NEB_SBIG) # include "cam_NebSBIG.h" #endif -#if defined (FIREWIRE_CAMERA) +#if defined(FIREWIRE_CAMERA) # include "cam_firewire.h" #endif -#if defined (MEADE_DSI_CAMERA) +#if defined(MEADE_DSI_CAMERA) # include "cam_MeadeDSI.h" #endif -#if defined (MORAVIAN_CAMERA) +#if defined(MORAVIAN_CAMERA) # include "cam_moravian.h" #endif -#if defined (SSAG) +#if defined(SSAG) # include "cam_ssag.h" #endif -#if defined (OPENSSAG_CAMERA) +#if defined(OPENSSAG_CAMERA) # include "cam_openssag.h" #endif -#if defined (KWIQGUIDER_CAMERA) +#if defined(KWIQGUIDER_CAMERA) # include "cam_KWIQGuider.h" #endif -#if defined (SSPIAG) +#if defined(SSPIAG) # include "cam_sspiag.h" #endif -#if defined (INOVA_PLC) +#if defined(INOVA_PLC) # include "cam_INovaPLC.h" #endif -#if defined (ASCOM_CAMERA) +#if defined(ASCOM_CAMERA) # include "cam_ascom.h" #endif -#if defined (INDI_CAMERA) +#if defined(INDI_CAMERA) # include "cam_indi.h" #endif @@ -186,10 +186,11 @@ wxSize UNDEFINED_FRAME_SIZE = wxSize(0, 0); # include "cam_sbigrotator.h" #endif -#if defined (V4L_CAMERA) +#if defined(V4L_CAMERA) # include "cam_VIDEODEVICE.h" -extern "C" { -#include +extern "C" +{ +# include } #endif @@ -248,129 +249,130 @@ wxArrayString GuideCamera::GuideCameraList() wxArrayString CameraList; CameraList.Add(_("None")); -#if defined (ASCOM_CAMERA) +#if defined(ASCOM_CAMERA) wxArrayString ascomCameras = ASCOMCameraFactory::EnumAscomCameras(); for (unsigned int i = 0; i < ascomCameras.Count(); i++) CameraList.Add(ascomCameras[i]); #endif -#if defined (ATIK16) +#if defined(ATIK16) CameraList.Add(_T("Atik 16 series, mono")); CameraList.Add(_T("Atik 16 series, color")); #endif -#if defined (ATIK_GEN3) +#if defined(ATIK_GEN3) CameraList.Add(_T("Atik Gen3, mono")); CameraList.Add(_T("Atik Gen3, color")); #endif -#if defined (QGUIDE) +#if defined(QGUIDE) CameraList.Add(_T("CCD Labs Q-Guider")); #endif -#if defined (STARFISH_CAMERA) +#if defined(STARFISH_CAMERA) CameraList.Add(_T("Fishcamp Starfish")); #endif -#if defined (INOVA_PLC) +#if defined(INOVA_PLC) CameraList.Add(_T("i-Nova PLC-M")); #endif -#if defined (IOPTRON_CAMERA) +#if defined(IOPTRON_CAMERA) CameraList.Add(_T("iOptron iGuider")); #endif -#if defined (SSAG) +#if defined(SSAG) CameraList.Add(_T("StarShoot Autoguider")); #endif -#if defined (SSPIAG) +#if defined(SSPIAG) CameraList.Add(_T("StarShoot Planetary Imager & Autoguider")); #endif -#if defined (OS_PL130) +#if defined(OS_PL130) CameraList.Add(_T("Opticstar PL-130M")); CameraList.Add(_T("Opticstar PL-130C")); #endif -#if defined (ORION_DSCI) +#if defined(ORION_DSCI) CameraList.Add(_T("Orion StarShoot DSCI")); #endif -#if defined (OPENSSAG_CAMERA) +#if defined(OPENSSAG_CAMERA) CameraList.Add(_T("Orion StarShoot Autoguider")); #endif -#if defined (KWIQGUIDER_CAMERA) +#if defined(KWIQGUIDER_CAMERA) CameraList.Add(_T("KWIQGuider")); #endif -#if defined (QGUIDE) +#if defined(QGUIDE) CameraList.Add(_T("MagZero MZ-5")); #endif -#if defined (MEADE_DSI_CAMERA) +#if defined(MEADE_DSI_CAMERA) CameraList.Add(_T("Meade DSI I, II, or III")); #endif -#if defined (MORAVIAN_CAMERA) +#if defined(MORAVIAN_CAMERA) CameraList.Add(_T("Moravian Camera")); #endif -#if defined (CAM_QHY5) +#if defined(CAM_QHY5) CameraList.Add(_T("QHY 5")); #endif -#if defined (QHY_CAMERA) +#if defined(QHY_CAMERA) CameraList.Add(_T("QHY Camera")); #endif -#if defined (ALTAIR) - CameraList.Add(_T("Altair Camera")); +#if defined(ALTAIR) + CameraList.Add(_T("Altair Camera")); CameraList.Add(_T("Altair Camera (2015/2016)")); #endif -#if defined (ZWO_ASI) +#if defined(ZWO_ASI) CameraList.Add(_T("ZWO ASI Camera")); #endif -#if defined (TOUPTEK_CAMERA) +#if defined(TOUPTEK_CAMERA) CameraList.Add(_T("ToupTek Camera")); CameraList.Add(_T("Omegon Pro Camera")); #endif -#if defined (SKYRAIDER_CAMERA) +#if defined(SKYRAIDER_CAMERA) CameraList.Add(_T("MallinCam SkyRaider")); #endif -#if defined (SBIG) +#if defined(SBIG) CameraList.Add(_T("SBIG")); #endif -#if defined (SBIGROTATOR_CAMERA) +#if defined(SBIGROTATOR_CAMERA) CameraList.Add(_T("SBIG Rotator")); #endif -#if defined (SVB_CAMERA) +#if defined(SVB_CAMERA) CameraList.Add(_T("Svbony Camera")); #endif -#if defined (SXV) +#if defined(SXV) CameraList.Add(_T("Starlight Xpress SXV")); #endif -#if defined (FIREWIRE_CAMERA) +#if defined(FIREWIRE_CAMERA) CameraList.Add(_T("The Imaging Source (DCAM Firewire)")); #endif -#if defined (OGMA_CAMERA) +#if defined(OGMA_CAMERA) CameraList.Add(_T("OGMA Camera")); #endif -#if defined (OPENCV_CAMERA) +#if defined(OPENCV_CAMERA) CameraList.Add(_T("OpenCV webcam 1")); CameraList.Add(_T("OpenCV webcam 2")); #endif -#if defined (WDM_CAMERA) +#if defined(WDM_CAMERA) CameraList.Add(_T("Windows WDM-style webcam camera")); #endif -#if defined (VFW_CAMERA) +#if defined(VFW_CAMERA) CameraList.Add(_T("Windows VFW-style webcam camera (older & SAC8)")); #endif -#if defined (LE_LXUSB_CAMERA) +#if defined(LE_LXUSB_CAMERA) CameraList.Add(_T("Long exposure LXUSB webcam")); #endif -#if defined (LE_PARALLEL_CAMERA) +#if defined(LE_PARALLEL_CAMERA) CameraList.Add(_T("Long exposure Parallel webcam")); #endif -#if defined (LE_SERIAL_CAMERA) +#if defined(LE_SERIAL_CAMERA) CameraList.Add(_T("Long exposure Serial webcam")); #endif -#if defined (INDI_CAMERA) +#if defined(INDI_CAMERA) CameraList.Add(INDICamName()); #endif -#if defined (V4L_CAMERA) - if (true == Camera_VIDEODEVICE.ProbeDevices()) { +#if defined(V4L_CAMERA) + if (true == Camera_VIDEODEVICE.ProbeDevices()) + { CameraList.Add(_T("V4L(2) Camera")); } #endif -#if defined (SIMULATOR) +#if defined(SIMULATOR) CameraList.Add(_T("Simulator")); #endif -#if defined (NEB_SBIG) +#if defined(NEB_SBIG) CameraList.Add(_T("Guide chip on SBIG cam in Nebulosity")); #endif @@ -397,17 +399,19 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) } // Chack ASCOM and INDI first since those choices may match match other choices below (like Simulator) -#if defined (ASCOM_CAMERA) - else if (choice.Contains(_T("ASCOM"))) { +#if defined(ASCOM_CAMERA) + else if (choice.Contains(_T("ASCOM"))) + { pReturn = ASCOMCameraFactory::MakeASCOMCamera(choice); } #endif -#if defined (INDI_CAMERA) - else if (choice.Contains(_T("INDI"))) { +#if defined(INDI_CAMERA) + else if (choice.Contains(_T("INDI"))) + { pReturn = INDICameraFactory::MakeINDICamera(); } #endif -#if defined (IOPTRON_CAMERA) +#if defined(IOPTRON_CAMERA) else if (choice == _T("iOptron iGuider")) pReturn = IoptronCameraFactory::MakeIoptronCamera(); #endif @@ -415,7 +419,7 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) pReturn = nullptr; else if (choice == _T("Simulator")) pReturn = GearSimulator::MakeCamSimulator(); -#if defined (ATIK16) +#if defined(ATIK16) else if (choice.StartsWith("Atik 16 series")) { bool hsmodel = false; @@ -423,7 +427,7 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) pReturn = AtikCameraFactory::MakeAtikCamera(hsmodel, color); } #endif -#if defined (ATIK_GEN3) +#if defined(ATIK_GEN3) else if (choice.StartsWith(_T("Atik Gen3"))) { bool hsmodel = true; @@ -431,7 +435,7 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) pReturn = AtikCameraFactory::MakeAtikCamera(hsmodel, color); } #endif -#if defined (QGUIDE) +#if defined(QGUIDE) else if (choice.Contains(_T("CCD Labs Q-Guider"))) { pReturn = new CameraQGuider(); @@ -443,7 +447,7 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) pReturn->Name = _T("MagZero MZ-5"); } #endif -#if defined (QHY_CAMERA) +#if defined(QHY_CAMERA) else if (choice == _T("QHY Camera")) pReturn = QHYCameraFactory::MakeQHYCamera(); #endif @@ -458,8 +462,7 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) pReturn = ZWOCameraFactory::MakeZWOCamera(); #endif #if defined(TOUPTEK_CAMERA) - else if (choice == _T("ToupTek Camera") || - choice == _T("Omegon Pro Camera")) + else if (choice == _T("ToupTek Camera") || choice == _T("Omegon Pro Camera")) { pReturn = ToupTekCameraFactory::MakeToupTekCamera(); } @@ -468,27 +471,27 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) else if (choice == _T("MallinCam SkyRaider")) pReturn = SkyraiderCameraFactory::MakeSkyraiderCamera(); #endif -#if defined (CAM_QHY5) // must come afer other QHY 5's since this pattern would match them +#if defined(CAM_QHY5) // must come afer other QHY 5's since this pattern would match them else if (choice.Contains(_T("QHY 5"))) pReturn = new CameraQHY5(); #endif -#if defined (OPENSSAG_CAMERA) +#if defined(OPENSSAG_CAMERA) else if (choice.Contains(_T("Orion StarShoot Autoguider"))) pReturn = new CameraOpenSSAG(); #endif -#if defined (KWIQGUIDER_CAMERA) +#if defined(KWIQGUIDER_CAMERA) else if (choice.Contains(_T("KWIQGuider"))) pReturn = KWIQGuiderCameraFactory::MakeKWIQGuiderCamera(); #endif -#if defined (SSAG) +#if defined(SSAG) else if (choice.Contains(_T("StarShoot Autoguider"))) pReturn = SSAGCameraFactory::MakeSSAGCamera(); #endif -#if defined (SSPIAG) +#if defined(SSPIAG) else if (choice.Contains(_T("StarShoot Planetary Imager & Autoguider"))) pReturn = new CameraSSPIAG(); #endif -#if defined (ORION_DSCI) +#if defined(ORION_DSCI) else if (choice.Contains(_T("Orion StarShoot DSCI"))) pReturn = new CameraStarShootDSCI(); #endif @@ -500,7 +503,7 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) else if (choice == _T("OGMA Camera")) pReturn = OGMACameraFactory::MakeOGMACamera(); #endif -#if defined (OPENCV_CAMERA) +#if defined(OPENCV_CAMERA) else if (choice.Contains(_T("OpenCV webcam"))) { int dev = 0; @@ -511,27 +514,27 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) pReturn = new CameraOpenCV(dev); } #endif -#if defined (WDM_CAMERA) +#if defined(WDM_CAMERA) else if (choice.Contains(_T("Windows WDM"))) pReturn = WDMCameraFactory::MakeWDMCamera(); #endif -#if defined (VFW_CAMERA) +#if defined(VFW_CAMERA) else if (choice.Contains(_T("Windows VFW"))) pReturn = new CameraVFW(); #endif -#if defined (LE_SERIAL_CAMERA) +#if defined(LE_SERIAL_CAMERA) else if (choice.Contains(_T("Long exposure Serial webcam"))) pReturn = LESerialWebcamCameraFactory::MakeLESerialWebcamCamera(); #endif -#if defined (LE_PARALLEL_CAMERA) - else if (choice.Contains( _T("Long exposure Parallel webcam"))) +#if defined(LE_PARALLEL_CAMERA) + else if (choice.Contains(_T("Long exposure Parallel webcam"))) pReturn = LEParallelWebcamCameraFactory::MakeLEParallelWebcamCamera(); #endif -#if defined (LE_LXUSB_CAMERA) +#if defined(LE_LXUSB_CAMERA) else if (choice.Contains(_T("Long exposure LXUSB webcam"))) pReturn = LELxUsbWebcamCameraFactory::MakeLELxUsbWebcamCamera(); #endif -#if defined (MEADE_DSI_CAMERA) +#if defined(MEADE_DSI_CAMERA) else if (choice.Contains(_T("Meade DSI I, II, or III"))) pReturn = DSICameraFactory::MakeDSICamera(); #endif @@ -539,15 +542,15 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) else if (choice == _T("Moravian Camera")) pReturn = MoravianCameraFactory::MakeMoravianCamera(); #endif -#if defined (STARFISH_CAMERA) +#if defined(STARFISH_CAMERA) else if (choice.Contains(_T("Fishcamp Starfish"))) pReturn = StarfishCameraFactory::MakeStarfishCamera(); #endif -#if defined (SXV) +#if defined(SXV) else if (choice.Contains(_T("Starlight Xpress SXV"))) pReturn = SXVCameraFactory::MakeSXVCamera(); #endif -#if defined (OS_PL130) +#if defined(OS_PL130) else if (choice.Contains(_T("Opticstar PL-130M"))) { Camera_OSPL130.Color = false; @@ -561,28 +564,28 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) pReturn = new Camera_OSPL130Class(); } #endif -#if defined (NEB_SBIG) +#if defined(NEB_SBIG) else if (choice.Contains(_T("Nebulosity"))) pReturn = new CameraNebSBIG(); #endif -#if defined (SBIGROTATOR_CAMERA) +#if defined(SBIGROTATOR_CAMERA) // must go above SBIG else if (choice.Contains(_T("SBIG Rotator"))) pReturn = SBIGRotatorCameraFactory::MakeSBIGRotatorCamera(); #endif -#if defined (SBIG) +#if defined(SBIG) else if (choice.Contains(_T("SBIG"))) pReturn = SBIGCameraFactory::MakeSBIGCamera(); #endif -#if defined (FIREWIRE_CAMERA) +#if defined(FIREWIRE_CAMERA) else if (choice.Contains(_T("The Imaging Source (DCAM Firewire)"))) pReturn = new CameraFirewire(); #endif -#if defined (INOVA_PLC) +#if defined(INOVA_PLC) else if (choice.Contains(_T("i-Nova PLC-M"))) pReturn = new CameraINovaPLC(); #endif -#if defined (V4L_CAMERA) +#if defined(V4L_CAMERA) else if (choice.Contains(_T("V4L(2) Camera"))) { // There is at least ONE V4L(2) device ... let's find out exactly @@ -603,7 +606,8 @@ GuideCamera *GuideCamera::Factory(const wxString& choice) wxArrayString choices; int choice = 0; - if ((choice = wxGetSinglechoiceIndex(_("Select your camera"), _T("V4L(2) devices"), Camera_VIDEODEVICE.GetProductArray(choices))) != -1) + if ((choice = wxGetSinglechoiceIndex( + _("Select your camera"), _T("V4L(2) devices"), Camera_VIDEODEVICE.GetProductArray(choices))) != -1) { deviceInfo = Camera_VIDEODEVICE.GetDeviceAtIndex(choice); @@ -782,17 +786,17 @@ CameraConfigDialogPane *GuideCamera::GetConfigDialogPane(wxWindow *pParent) static wxSpinCtrl *NewSpinnerInt(wxWindow *parent, int width, int val, int minval, int maxval, int inc) { - wxSpinCtrl *pNewCtrl = pFrame->MakeSpinCtrl(parent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, minval, maxval, val); + wxSpinCtrl *pNewCtrl = pFrame->MakeSpinCtrl( + parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, minval, maxval, val); pNewCtrl->SetValue(val); return pNewCtrl; } -static wxSpinCtrlDouble *NewSpinnerDouble(wxWindow *parent, int width, double val, double minval, double maxval, double inc, - const wxString& tooltip) +static wxSpinCtrlDouble *NewSpinnerDouble( + wxWindow *parent, int width, double val, double minval, double maxval, double inc, const wxString& tooltip) { - wxSpinCtrlDouble *pNewCtrl = pFrame->MakeSpinCtrlDouble(parent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, minval, maxval, val, inc); + wxSpinCtrlDouble *pNewCtrl = pFrame->MakeSpinCtrlDouble( + parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, minval, maxval, val, inc); pNewCtrl->SetDigits(2); pNewCtrl->SetToolTip(tooltip); return pNewCtrl; @@ -829,9 +833,10 @@ void CameraConfigDialogPane::LayoutControls(GuideCamera *pCamera, BrainCtrlIdMap wxStaticBoxSizer *pSpecGroup = new wxStaticBoxSizer(wxVERTICAL, m_pParent, _("Camera-Specific Properties")); if (pCamera) { - wxFlexGridSizer *pDetailsSizer = new wxFlexGridSizer(6, 3, 15, 15); // Will auto-shrink to fit - // Create all possible property controls then disable individual controls later if camera doesn't support them. This is safer for "omnibus" style drivers that - // handle many cameras with different capabilities. Exceptions are 'port' and 'LE-delay' which will be created conditionally + wxFlexGridSizer *pDetailsSizer = new wxFlexGridSizer(6, 3, 15, 15); // Will auto-shrink to fit + // Create all possible property controls then disable individual controls later if camera doesn't support them. This is + // safer for "omnibus" style drivers that handle many cameras with different capabilities. Exceptions are 'port' and + // 'LE-delay' which will be created conditionally wxSizerFlags spec_flags = wxSizerFlags(0).Border(wxALL, 10).Align(wxVERTICAL).Expand(); pDetailsSizer->Add(GetSizerCtrl(CtrlMap, AD_szPixelSize)); pDetailsSizer->Add(GetSizerCtrl(CtrlMap, AD_szGain)); @@ -851,15 +856,14 @@ void CameraConfigDialogPane::LayoutControls(GuideCamera *pCamera, BrainCtrlIdMap wxStaticText *pNoCam = new wxStaticText(m_pParent, wxID_ANY, _("No camera specified")); pSpecGroup->Add(pNoCam, wxSizerFlags().Align(wxALIGN_CENTER_HORIZONTAL)); pSpecGroup->Layout(); - } if (pCamera) pGenGroup->Add(GetSizerCtrl(CtrlMap, AD_szSaturationOptions), wxSizerFlags(0).Border(wxALL, 2).Expand()); this->Add(pGenGroup, def_flags); if (pCamera && !pCamera->Connected) { - wxStaticText *pNotConnected = new wxStaticText(m_pParent, wxID_ANY, - _("Camera is not connected. Property controls may change if you connect to it first.")); + wxStaticText *pNotConnected = new wxStaticText( + m_pParent, wxID_ANY, _("Camera is not connected. Property controls may change if you connect to it first.")); MakeBold(pNotConnected); this->Add(pNotConnected, wxSizerFlags().Align(wxALIGN_CENTER_HORIZONTAL).Border(wxALL, 10)); } @@ -869,14 +873,16 @@ void CameraConfigDialogPane::LayoutControls(GuideCamera *pCamera, BrainCtrlIdMap Fit(m_pParent); } -CameraConfigDialogCtrlSet* GuideCamera::GetConfigDlgCtrlSet(wxWindow *pParent, GuideCamera *pCamera, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +CameraConfigDialogCtrlSet *GuideCamera::GetConfigDlgCtrlSet( + wxWindow *pParent, GuideCamera *pCamera, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) { return new CameraConfigDialogCtrlSet(pParent, pCamera, pAdvancedDialog, CtrlMap); } -CameraConfigDialogCtrlSet::CameraConfigDialogCtrlSet(wxWindow *pParent, GuideCamera *pCamera, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) - : ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap), - m_pUseSubframes(nullptr) +CameraConfigDialogCtrlSet::CameraConfigDialogCtrlSet( + wxWindow *pParent, GuideCamera *pCamera, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) + : ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) + , m_pUseSubframes(nullptr) { int textWidth = StringWidth(_T("0000")); assert(pCamera); @@ -884,11 +890,13 @@ CameraConfigDialogCtrlSet::CameraConfigDialogCtrlSet(wxWindow *pParent, GuideCam m_pCamera = pCamera; // Sub-frames m_pUseSubframes = new wxCheckBox(GetParentWindow(AD_cbUseSubFrames), wxID_ANY, _("Use Subframes")); - AddCtrl(CtrlMap, AD_cbUseSubFrames, m_pUseSubframes, _("Check to only download subframes (ROIs). Sub-frame size is equal to search region size.")); + AddCtrl(CtrlMap, AD_cbUseSubFrames, m_pUseSubframes, + _("Check to only download subframes (ROIs). Sub-frame size is equal to search region size.")); // Pixel size m_pPixelSize = NewSpinnerDouble(GetParentWindow(AD_szPixelSize), textWidth, m_pCamera->GetCameraPixelSize(), 0.0, 99.9, 0.1, - _("Guide camera un-binned pixel size in microns. Used with the guide telescope focal length to display guiding error in arc-seconds.")); + _("Guide camera un-binned pixel size in microns. Used with the guide telescope focal length to display guiding error " + "in arc-seconds.")); AddLabeledCtrl(CtrlMap, AD_szPixelSize, _("Pixel size"), m_pPixelSize, ""); // Gain control @@ -896,13 +904,13 @@ CameraConfigDialogCtrlSet::CameraConfigDialogCtrlSet(wxWindow *pParent, GuideCam wxStaticText *label = new wxStaticText(parent, wxID_ANY, _("Camera gain") + _(": ")); m_pCameraGain = NewSpinnerInt(parent, textWidth, 100, 0, 100, 1); m_pCameraGain->SetToolTip( - /* xgettext:no-c-format */ _("Camera gain, default = 95%, lower if you experience noise or wish to guide on a very bright star. Not available on all cameras.")); - m_resetGain = new wxButton(GetParentWindow(AD_szGain), wxID_ANY, _("Reset"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + /* xgettext:no-c-format */ _("Camera gain, default = 95%, lower if you experience noise or wish to guide on a very " + "bright star. Not available on all cameras.")); + m_resetGain = + new wxButton(GetParentWindow(AD_szGain), wxID_ANY, _("Reset"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); m_resetGain->SetToolTip(_("Reset gain to camera's default value (disabled when camera is not connected)")); - m_resetGain->Bind(wxEVT_COMMAND_BUTTON_CLICKED, [this](wxCommandEvent& evt) { - m_pCameraGain->SetValue(::pCamera->GetDefaultCameraGain()); - } - ); + m_resetGain->Bind(wxEVT_COMMAND_BUTTON_CLICKED, + [this](wxCommandEvent& evt) { m_pCameraGain->SetValue(::pCamera->GetDefaultCameraGain()); }); wxBoxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); sizer->Add(label, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); sizer->Add(m_pCameraGain, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); @@ -914,8 +922,7 @@ CameraConfigDialogCtrlSet::CameraConfigDialogCtrlSet(wxWindow *pParent, GuideCam wxArrayString opts; m_pCamera->GetBinningOpts(&opts); int width = StringArrayWidth(opts); - m_binning = new wxChoice(GetParentWindow(AD_szBinning), wxID_ANY, wxDefaultPosition, - wxSize(width + 35, -1), opts); + m_binning = new wxChoice(GetParentWindow(AD_szBinning), wxID_ANY, wxDefaultPosition, wxSize(width + 35, -1), opts); AddLabeledCtrl(CtrlMap, AD_szBinning, _("Binning"), m_binning, _("Camera pixel binning")); // Delay parameter @@ -929,14 +936,30 @@ CameraConfigDialogCtrlSet::CameraConfigDialogCtrlSet(wxWindow *pParent, GuideCam if (m_pCamera->HasPortNum) { wxString port_choices[] = { - _T("Port 378"), _T("Port 3BC"), _T("Port 278"), _T("COM1"), _T("COM2"), _T("COM3"), _T("COM4"), - _T("COM5"), _T("COM6"), _T("COM7"), _T("COM8"), _T("COM9"), _T("COM10"), _T("COM11"), _T("COM12"), - _T("COM13"), _T("COM14"), _T("COM15"), _T("COM16"), + _T("Port 378"), + _T("Port 3BC"), + _T("Port 278"), + _T("COM1"), + _T("COM2"), + _T("COM3"), + _T("COM4"), + _T("COM5"), + _T("COM6"), + _T("COM7"), + _T("COM8"), + _T("COM9"), + _T("COM10"), + _T("COM11"), + _T("COM12"), + _T("COM13"), + _T("COM14"), + _T("COM15"), + _T("COM16"), }; width = StringArrayWidth(port_choices, WXSIZEOF(port_choices)); - m_pPortNum = new wxChoice(GetParentWindow(AD_szPort), wxID_ANY, wxDefaultPosition, - wxSize(width + 35, -1), WXSIZEOF(port_choices), port_choices); + m_pPortNum = new wxChoice(GetParentWindow(AD_szPort), wxID_ANY, wxDefaultPosition, wxSize(width + 35, -1), + WXSIZEOF(port_choices), port_choices); AddLabeledCtrl(CtrlMap, AD_szPort, _("LE Port"), m_pPortNum, _("Port number for long-exposure control")); } @@ -954,19 +977,20 @@ CameraConfigDialogCtrlSet::CameraConfigDialogCtrlSet(wxWindow *pParent, GuideCam width = StringWidth(_T("65535")); parent = GetParentWindow(AD_szSaturationOptions); m_camSaturationADU = new wxTextCtrl(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(1.5 * width, -1)); - m_camSaturationADU->SetToolTip(_("ADU level to determine saturation - 65535 for most 16-bit cameras, or 255 for 8-bit cameras.")); + m_camSaturationADU->SetToolTip( + _("ADU level to determine saturation - 65535 for most 16-bit cameras, or 255 for 8-bit cameras.")); m_SaturationByADU = new wxRadioButton(parent, wxID_ANY, _("Saturation by Max-ADU value:")); m_SaturationByADU->SetToolTip(_("Identify star saturation based on camera maximum-ADU value (recommended)")); m_SaturationByADU->Bind(wxEVT_COMMAND_RADIOBUTTON_SELECTED, &CameraConfigDialogCtrlSet::OnSaturationChoiceChanged, this); - wxStaticBoxSizer* szADUGroup = new wxStaticBoxSizer(wxHORIZONTAL, parent, - wxEmptyString); + wxStaticBoxSizer *szADUGroup = new wxStaticBoxSizer(wxHORIZONTAL, parent, wxEmptyString); szADUGroup->Add(m_SaturationByADU, wxSizerFlags().Border(wxTOP, 2)); szADUGroup->Add(m_camSaturationADU, wxSizerFlags().Border(wxLEFT, 6)); m_SaturationByProfile = new wxRadioButton(parent, wxID_ANY, _("Saturation via star-profile")); m_SaturationByProfile->SetToolTip(_("Identify star saturation based on flat-topped profile, regardless of brightness")); - m_SaturationByProfile->Bind(wxEVT_COMMAND_RADIOBUTTON_SELECTED, &CameraConfigDialogCtrlSet::OnSaturationChoiceChanged, this); - wxFlexGridSizer* szSaturationGroup = new wxFlexGridSizer(1, 2, 5, 15); + m_SaturationByProfile->Bind( + wxEVT_COMMAND_RADIOBUTTON_SELECTED, &CameraConfigDialogCtrlSet::OnSaturationChoiceChanged, this); + wxFlexGridSizer *szSaturationGroup = new wxFlexGridSizer(1, 2, 5, 15); szSaturationGroup->Add(szADUGroup, wxSizerFlags().Border(wxALL, 3).Align(wxALIGN_CENTER_VERTICAL)); szSaturationGroup->Add(m_SaturationByProfile, wxSizerFlags(0).Border(wxLEFT, 70).Expand().Align(wxALIGN_CENTER_VERTICAL)); @@ -976,7 +1000,8 @@ CameraConfigDialogCtrlSet::CameraConfigDialogCtrlSet(wxWindow *pParent, GuideCam m_timeoutVal = NewSpinnerInt(GetParentWindow(AD_szCameraTimeout), textWidth, 5, 5, 9999, 1); AddLabeledCtrl(CtrlMap, AD_szCameraTimeout, _("Disconnect nonresponsive \ncamera after (seconds)"), m_timeoutVal, wxString::Format(_("The camera will be disconnected if it fails to respond for this long. " - "The default value, %d seconds, should be appropriate for most cameras."), DefaultGuideCameraTimeoutMs / 1000)); + "The default value, %d seconds, should be appropriate for most cameras."), + DefaultGuideCameraTimeoutMs / 1000)); } void CameraConfigDialogCtrlSet::OnSaturationChoiceChanged(wxCommandEvent& event) @@ -1070,52 +1095,52 @@ void CameraConfigDialogCtrlSet::LoadValues() case 0x278: m_pPortNum->SetSelection(2); break; - case 1: // COM1 + case 1: // COM1 m_pPortNum->SetSelection(3); break; - case 2: // COM2 + case 2: // COM2 m_pPortNum->SetSelection(4); break; - case 3: // COM3 + case 3: // COM3 m_pPortNum->SetSelection(5); break; - case 4: // COM4 + case 4: // COM4 m_pPortNum->SetSelection(6); break; - case 5: // COM5 + case 5: // COM5 m_pPortNum->SetSelection(7); break; - case 6: // COM6 + case 6: // COM6 m_pPortNum->SetSelection(8); break; - case 7: // COM7 + case 7: // COM7 m_pPortNum->SetSelection(9); break; - case 8: // COM8 + case 8: // COM8 m_pPortNum->SetSelection(10); break; - case 9: // COM9 + case 9: // COM9 m_pPortNum->SetSelection(11); break; - case 10: // COM10 + case 10: // COM10 m_pPortNum->SetSelection(12); break; - case 11: // COM11 + case 11: // COM11 m_pPortNum->SetSelection(13); break; - case 12: // COM12 + case 12: // COM12 m_pPortNum->SetSelection(14); break; - case 13: // COM13 + case 13: // COM13 m_pPortNum->SetSelection(15); break; - case 14: // COM14 + case 14: // COM14 m_pPortNum->SetSelection(16); break; - case 15: // COM15 + case 15: // COM15 m_pPortNum->SetSelection(17); break; - case 16: // COM16 + case 16: // COM16 m_pPortNum->SetSelection(18); break; default: @@ -1127,13 +1152,13 @@ void CameraConfigDialogCtrlSet::LoadValues() } double pxSize; - if (m_pCamera->GetDevicePixelSize(&pxSize)) // true=>error + if (m_pCamera->GetDevicePixelSize(&pxSize)) // true=>error { pxSize = m_pCamera->GetCameraPixelSize(); m_pPixelSize->Enable(!pFrame->CaptureActive); } else - m_pPixelSize->Enable(false); // Got a device-level pixel size, disable the control + m_pPixelSize->Enable(false); // Got a device-level pixel size, disable the control m_pPixelSize->SetValue(pxSize); @@ -1158,7 +1183,7 @@ void CameraConfigDialogCtrlSet::LoadValues() { setpt = pConfig->Profile.GetDouble("/camera/CoolerSetpt", 10.0); } - m_coolerSetpt->SetValue((int)floor(setpt)); + m_coolerSetpt->SetValue((int) floor(setpt)); } m_coolerOn->Enable(ok); @@ -1312,15 +1337,12 @@ wxString GuideCamera::GetSettingsSummary() else pixelSizeStr = wxString::Format(_("%0.1f um"), m_pixelSize); - return wxString::Format("Camera = %s%s%s%s, full size = %d x %d, %s, %s, pixel size = %s\n", - Name, - HasGainControl ? wxString::Format(", gain = %d", GuideCameraGain) : "", - HasDelayParam ? wxString::Format(", delay = %d", ReadDelay) : "", - HasPortNum ? wxString::Format(", port = 0x%hx", Port) : "", - FullSize.GetWidth(), FullSize.GetHeight(), - darkDur ? wxString::Format("have dark, dark dur = %d", darkDur) : "no dark", - CurrentDefectMap ? "defect map in use" : "no defect map", - pixelSizeStr); + return wxString::Format("Camera = %s%s%s%s, full size = %d x %d, %s, %s, pixel size = %s\n", Name, + HasGainControl ? wxString::Format(", gain = %d", GuideCameraGain) : "", + HasDelayParam ? wxString::Format(", delay = %d", ReadDelay) : "", + HasPortNum ? wxString::Format(", port = 0x%hx", Port) : "", FullSize.GetWidth(), FullSize.GetHeight(), + darkDur ? wxString::Format("have dark, dark dur = %d", darkDur) : "no dark", + CurrentDefectMap ? "defect map in use" : "no defect map", pixelSizeStr); } void GuideCamera::AddDark(usImage *dark) @@ -1455,21 +1477,21 @@ void GuideCamera::DisconnectWithAlert(CaptureFailType type) break; case CAPT_FAIL_TIMEOUT: - { - wxString msg; - // Dark library exposure times won't match the selected exposure time in the pull-down menu of the main window - if (!ShutterClosed) - msg = (wxString::Format(_("After %.1f sec the camera has not completed a %.1f sec exposure, so " - "it has been disconnected to prevent other problems. Refer to Trouble-shooting section of Help."), - (pFrame->RequestedExposureDuration() + m_timeoutMs) / 1000., - pFrame->RequestedExposureDuration() / 1000.)); - else - msg = _("The camera has not completed an exposure in at least 15 seconds, so " - "it has been disconnected to prevent other problems. Refer to Trouble-shooting section of Help."); + { + wxString msg; + // Dark library exposure times won't match the selected exposure time in the pull-down menu of the main window + if (!ShutterClosed) + msg = (wxString::Format( + _("After %.1f sec the camera has not completed a %.1f sec exposure, so " + "it has been disconnected to prevent other problems. Refer to Trouble-shooting section of Help."), + (pFrame->RequestedExposureDuration() + m_timeoutMs) / 1000., pFrame->RequestedExposureDuration() / 1000.)); + else + msg = _("The camera has not completed an exposure in at least 15 seconds, so " + "it has been disconnected to prevent other problems. Refer to Trouble-shooting section of Help."); - DisconnectWithAlert(msg, RECONNECT); - } - break; + DisconnectWithAlert(msg, RECONNECT); + } + break; } } @@ -1490,13 +1512,12 @@ void GuideCamera::DisconnectWithAlert(const wxString& msg, ReconnectType reconne } else { - pFrame->Alert(msg + "\n" + _("The camera has been disconnected. Please resolve the problem and re-connect the camera.")); + pFrame->Alert( + msg + "\n" + _("The camera has been disconnected. Please resolve the problem and re-connect the camera.")); } } -void GuideCamera::InitCapture() -{ -} +void GuideCamera::InitCapture() { } bool GuideCamera::Capture(GuideCamera *camera, int duration, usImage& img, int captureOptions, const wxRect& subframe) { diff --git a/src/camera.h b/src/camera.h index d980c5fe0..3aadf7173 100644 --- a/src/camera.h +++ b/src/camera.h @@ -41,7 +41,7 @@ class DefectMap; enum PropDlgType { PROPDLG_NONE = 0, - PROPDLG_WHEN_CONNECTED = (1 << 0), // property dialog available when connected + PROPDLG_WHEN_CONNECTED = (1 << 0), // property dialog available when connected PROPDLG_WHEN_DISCONNECTED = (1 << 1), // property dialog available when disconnected PROPDLG_ANY = (PROPDLG_WHEN_CONNECTED | PROPDLG_WHEN_DISCONNECTED), }; @@ -68,7 +68,7 @@ class CameraConfigDialogCtrlSet : public ConfigDialogCtrlSet wxSpinCtrl *m_pCameraGain; wxButton *m_resetGain; wxSpinCtrl *m_timeoutVal; - wxChoice *m_pPortNum; + wxChoice *m_pPortNum; wxSpinCtrl *m_pDelay; wxSpinCtrlDouble *m_pPixelSize; wxChoice *m_binning; @@ -81,7 +81,8 @@ class CameraConfigDialogCtrlSet : public ConfigDialogCtrlSet int m_prevBinning; public: - CameraConfigDialogCtrlSet(wxWindow *pParent, GuideCamera *pCamera, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + CameraConfigDialogCtrlSet( + wxWindow *pParent, GuideCamera *pCamera, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); virtual ~CameraConfigDialogCtrlSet() {}; virtual void LoadValues(); virtual void UnloadValues(); @@ -96,7 +97,7 @@ class CameraConfigDialogCtrlSet : public ConfigDialogCtrlSet enum CaptureOptionBits { CAPTURE_SUBTRACT_DARK = 1 << 0, - CAPTURE_RECON = 1 << 1, // debayer and/or deinterlace as required + CAPTURE_RECON = 1 << 1, // debayer and/or deinterlace as required CAPTURE_LIGHT = CAPTURE_SUBTRACT_DARK | CAPTURE_RECON, CAPTURE_DARK = 0, @@ -108,40 +109,39 @@ class GuideCamera : public wxMessageBoxProxy, public OnboardST4 friend class CameraConfigDialogPane; friend class CameraConfigDialogCtrlSet; - double m_pixelSize; + double m_pixelSize; protected: - bool m_hasGuideOutput; - int m_timeoutMs; - bool m_saturationByADU; - unsigned short m_saturationADU; + bool m_hasGuideOutput; + int m_timeoutMs; + bool m_saturationByADU; + unsigned short m_saturationADU; public: - static const double UnknownPixelSize; - int GuideCameraGain; - wxString Name; // User-friendly name - wxSize FullSize; // Size of current image - bool Connected; - PropDlgType PropertyDialogType; - bool HasPortNum; - bool HasDelayParam; - bool HasGainControl; - bool HasShutter; - bool HasSubframes; - wxByte MaxBinning; - wxByte Binning; - short Port; - int ReadDelay; - bool ShutterClosed; // false=light, true=dark - bool UseSubframes; - bool HasCooler; + int GuideCameraGain; + wxString Name; // User-friendly name + wxSize FullSize; // Size of current image + bool Connected; + PropDlgType PropertyDialogType; + bool HasPortNum; + bool HasDelayParam; + bool HasGainControl; + bool HasShutter; + bool HasSubframes; + wxByte MaxBinning; + wxByte Binning; + short Port; + int ReadDelay; + bool ShutterClosed; // false=light, true=dark + bool UseSubframes; + bool HasCooler; wxCriticalSection DarkFrameLock; // dark frames can be accessed in the main thread or the camera worker thread - usImage *CurrentDarkFrame; - ExposureImgMap Darks; // map exposure => dark frame - DefectMap *CurrentDefectMap; + usImage *CurrentDarkFrame; + ExposureImgMap Darks; // map exposure => dark frame + DefectMap *CurrentDefectMap; static wxArrayString GuideCameraList(); static GuideCamera *Factory(const wxString& choice); @@ -153,7 +153,10 @@ class GuideCamera : public wxMessageBoxProxy, public OnboardST4 virtual wxByte BitsPerPixel() = 0; static bool Capture(GuideCamera *camera, int duration, usImage& img, int captureOptions, const wxRect& subframe); - static bool Capture(GuideCamera *camera, int duration, usImage& img, int captureOptions) { return Capture(camera, duration, img, captureOptions, wxRect(0, 0, 0, 0)); } + static bool Capture(GuideCamera *camera, int duration, usImage& img, int captureOptions) + { + return Capture(camera, duration, img, captureOptions, wxRect(0, 0, 0, 0)); + } virtual bool CanSelectCamera() const { return false; } virtual bool HandleSelectCameraButtonClick(wxCommandEvent& evt); @@ -162,41 +165,42 @@ class GuideCamera : public wxMessageBoxProxy, public OnboardST4 // Opens up and connects to camera. cameraId identifies which camera to connect to if // there is more than one camera present - virtual bool Connect(const wxString& cameraId) = 0; - virtual bool Disconnect() = 0; // Disconnects, unloading any DLLs loaded by Connect - virtual void InitCapture(); // Gets run at the start of any loop (e.g., reset stream, set gain, etc). + virtual bool Connect(const wxString& cameraId) = 0; + virtual bool Disconnect() = 0; // Disconnects, unloading any DLLs loaded by Connect + virtual void InitCapture(); // Gets run at the start of any loop (e.g., reset stream, set gain, etc). - virtual bool ST4HasGuideOutput(); - virtual bool ST4HostConnected(); - virtual bool ST4HasNonGuiMove(); - virtual bool ST4PulseGuideScope(int direction, int duration); + virtual bool ST4HasGuideOutput(); + virtual bool ST4HostConnected(); + virtual bool ST4HasNonGuiMove(); + virtual bool ST4PulseGuideScope(int direction, int duration); CameraConfigDialogPane *GetConfigDialogPane(wxWindow *pParent); - CameraConfigDialogCtrlSet *GetConfigDlgCtrlSet(wxWindow *pParent, GuideCamera *pCamera, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + CameraConfigDialogCtrlSet *GetConfigDlgCtrlSet( + wxWindow *pParent, GuideCamera *pCamera, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); static void GetBinningOpts(int maxBin, wxArrayString *opts); void GetBinningOpts(wxArrayString *opts); bool SetBinning(int binning); - virtual void ShowPropertyDialog() { return; } - bool SetCameraPixelSize(double pixel_size); - double GetCameraPixelSize() const; - virtual bool GetDevicePixelSize(double *devPixelSize); // Value from device/driver or error return + virtual void ShowPropertyDialog() { return; } + bool SetCameraPixelSize(double pixel_size); + double GetCameraPixelSize() const; + virtual bool GetDevicePixelSize(double *devPixelSize); // Value from device/driver or error return - virtual bool SetCoolerOn(bool on); - virtual bool SetCoolerSetpoint(double temperature); - virtual bool GetCoolerStatus(bool *on, double *setpoint, double *power, double *temperature); - virtual bool GetSensorTemperature(double *temperature); + virtual bool SetCoolerOn(bool on); + virtual bool SetCoolerSetpoint(double temperature); + virtual bool GetCoolerStatus(bool *on, double *setpoint, double *power, double *temperature); + virtual bool GetSensorTemperature(double *temperature); virtual wxString GetSettingsSummary(); - void AddDark(usImage *dark); - void SelectDark(int exposureDuration); - void SetDefectMap(DefectMap *newMap); - void ClearDefectMap(); - void ClearDarks(); + void AddDark(usImage *dark); + void SelectDark(int exposureDuration); + void SetDefectMap(DefectMap *newMap); + void ClearDefectMap(); + void ClearDarks(); - void SubtractDark(usImage& img); - void GetDarklibProperties(int *pNumDarks, double *pMinExp, double *pMaxExp); + void SubtractDark(usImage& img); + void GetDarklibProperties(int *pNumDarks, double *pMinExp, double *pMaxExp); virtual const wxSize& DarkFrameSize() { return FullSize; } @@ -213,17 +217,18 @@ class GuideCamera : public wxMessageBoxProxy, public OnboardST4 virtual bool Capture(int duration, usImage& img, int captureOptions, const wxRect& subframe) = 0; protected: - int GetTimeoutMs() const; void SetTimeoutMs(int timeoutMs); static bool CamConnectFailed(const wxString& errorMessage); - enum CaptureFailType { + enum CaptureFailType + { CAPT_FAIL_MEMORY, CAPT_FAIL_TIMEOUT, }; - enum ReconnectType { + enum ReconnectType + { NO_RECONNECT, RECONNECT, }; @@ -248,7 +253,7 @@ inline double GuideCamera::GetCameraPixelSize() const inline bool GuideCamera::GetDevicePixelSize(double *devPixelSize) { - return true; // Return an error, the device/driver can't report pixel size + return true; // Return an error, the device/driver can't report pixel size } inline bool GuideCamera::IsSaturationByADU() const diff --git a/src/cameras.h b/src/cameras.h index 2bc48b16c..e3ee6ec4b 100644 --- a/src/cameras.h +++ b/src/cameras.h @@ -39,108 +39,108 @@ to detect or package this */ -#if defined(__WINDOWS__) +# if defined(__WINDOWS__) // Windows cameras -# define ALTAIR -# define ASCOM_CAMERA -# define ATIK16 -# define ATIK_GEN3 -# define INDI_CAMERA -# define INOVA_PLC -# define IOPTRON_CAMERA -# define LE_CAMERA -# define LE_LXUSB_CAMERA -# define LE_PARALLEL_CAMERA -# define LE_SERIAL_CAMERA -# define MORAVIAN_CAMERA -# define OGMA_CAMERA -# define OPENCV_CAMERA -# define ORION_DSCI -# define QGUIDE -# define QHY_CAMERA -# define SBIG -# define SBIGROTATOR_CAMERA -# define SIMULATOR -# define SSPIAG -# define SVB_CAMERA -# define SXV -# define TOUPTEK_CAMERA -# define WDM_CAMERA -# define ZWO_ASI - -//# define OS_PL130 // the Opticstar library is not yet included -//# define FIREWIRE_CAMERA // the The Imaging Source library is not yet included - -# ifdef HAVE_WXVIDCAP // These need wxVidCapLib, which needs to be built-up separately. The LE-webcams could go to WDM -# define VFW_CAMERA -# endif - -#elif defined(__APPLE__) -// Mac cameras -# ifdef HAVE_FIREWIRE_CAMERA -# define FIREWIRE_CAMERA -# endif -# define INDI_CAMERA -# ifdef HAVE_KWIQGUIDER_CAMERA -# define KWIQGUIDER_CAMERA -# endif -# ifdef HAVE_OGMA_CAMERA +# define ALTAIR +# define ASCOM_CAMERA +# define ATIK16 +# define ATIK_GEN3 +# define INDI_CAMERA +# define INOVA_PLC +# define IOPTRON_CAMERA +# define LE_CAMERA +# define LE_LXUSB_CAMERA +# define LE_PARALLEL_CAMERA +# define LE_SERIAL_CAMERA +# define MORAVIAN_CAMERA # define OGMA_CAMERA -# endif -# ifdef HAVE_OPENSSAG_CAMERA -# define OPENSSAG_CAMERA -# endif -# ifdef HAVE_QHY_CAMERA +# define OPENCV_CAMERA +# define ORION_DSCI +# define QGUIDE # define QHY_CAMERA -# endif -# ifdef HAVE_SBIG_CAMERA # define SBIG -# endif -# define SIMULATOR -# ifdef HAVE_SXV_CAMERA +# define SBIGROTATOR_CAMERA +# define SIMULATOR +# define SSPIAG +# define SVB_CAMERA # define SXV -# endif -# ifdef HAVE_TOUPTEK_CAMERA # define TOUPTEK_CAMERA -# endif -#ifdef HAVE_ZWO_CAMERA -# define ZWO_ASI -#endif -#ifdef HAVE_SVB_CAMERA -# define SVB_CAMERA -#endif +# define WDM_CAMERA +# define ZWO_ASI -#elif defined (__linux__) || defined (__FreeBSD__) +// # define OS_PL130 // the Opticstar library is not yet included +// # define FIREWIRE_CAMERA // the The Imaging Source library is not yet included -# define SIMULATOR -# define OPENCV_CAMERA -# define CAM_QHY5 -# ifdef HAVE_OGMA_CAMERA -# define OGMA_CAMERA -# endif -# ifdef HAVE_QHY_CAMERA -# define QHY_CAMERA -# endif -# define INDI_CAMERA -# ifdef HAVE_ZWO_CAMERA -# define ZWO_ASI -# endif -# ifdef HAVE_TOUPTEK_CAMERA -# define TOUPTEK_CAMERA -# endif -# ifdef HAVE_SXV_CAMERA -# define SXV -# endif -# ifdef HAVE_SBIG_CAMERA +# ifdef HAVE_WXVIDCAP // These need wxVidCapLib, which needs to be built-up separately. The LE-webcams could go to WDM +# define VFW_CAMERA +# endif + +# elif defined(__APPLE__) +// Mac cameras +# ifdef HAVE_FIREWIRE_CAMERA +# define FIREWIRE_CAMERA +# endif +# define INDI_CAMERA +# ifdef HAVE_KWIQGUIDER_CAMERA +# define KWIQGUIDER_CAMERA +# endif +# ifdef HAVE_OGMA_CAMERA +# define OGMA_CAMERA +# endif +# ifdef HAVE_OPENSSAG_CAMERA +# define OPENSSAG_CAMERA +# endif +# ifdef HAVE_QHY_CAMERA +# define QHY_CAMERA +# endif +# ifdef HAVE_SBIG_CAMERA # define SBIG -# endif -# ifdef HAVE_SVB_CAMERA +# endif +# define SIMULATOR +# ifdef HAVE_SXV_CAMERA +# define SXV +# endif +# ifdef HAVE_TOUPTEK_CAMERA +# define TOUPTEK_CAMERA +# endif +# ifdef HAVE_ZWO_CAMERA +# define ZWO_ASI +# endif +# ifdef HAVE_SVB_CAMERA # define SVB_CAMERA -# endif +# endif + +# elif defined(__linux__) || defined(__FreeBSD__) + +# define SIMULATOR +# define OPENCV_CAMERA +# define CAM_QHY5 +# ifdef HAVE_OGMA_CAMERA +# define OGMA_CAMERA +# endif +# ifdef HAVE_QHY_CAMERA +# define QHY_CAMERA +# endif +# define INDI_CAMERA +# ifdef HAVE_ZWO_CAMERA +# define ZWO_ASI +# endif +# ifdef HAVE_TOUPTEK_CAMERA +# define TOUPTEK_CAMERA +# endif +# ifdef HAVE_SXV_CAMERA +# define SXV +# endif +# ifdef HAVE_SBIG_CAMERA +# define SBIG +# endif +# ifdef HAVE_SVB_CAMERA +# define SVB_CAMERA +# endif // this should work ... needs testing -//# define OPENSSAG +// # define OPENSSAG -#endif +# endif // Currently unused // #define NEB_SBIG // This is for an on-hold project that would get the guide chip data from an SBIG connected in Neb diff --git a/src/circbuf.h b/src/circbuf.h index 167abb39b..440bb77dd 100644 --- a/src/circbuf.h +++ b/src/circbuf.h @@ -46,20 +46,43 @@ class circular_buffer unsigned int m_tail; unsigned int m_size; unsigned int m_capacity; + public: class iterator { friend class circular_buffer; circular_buffer& m_cb; unsigned int m_pos; - iterator(circular_buffer& cb, unsigned int pos) : m_cb(cb), m_pos(pos) { } + iterator(circular_buffer& cb, unsigned int pos) + : m_cb(cb) + , m_pos(pos) + { + } + public: - iterator& operator++() { ++m_pos; return *this; } - iterator operator++(int) { iterator it(*this); m_pos++; return it; } - bool operator==(const iterator& rhs) const { assert(&m_cb == &rhs.m_cb); return m_pos == rhs.m_pos; } - bool operator!=(const iterator& rhs) const { assert(&m_cb == &rhs.m_cb); return m_pos != rhs.m_pos; } + iterator& operator++() + { + ++m_pos; + return *this; + } + iterator operator++(int) + { + iterator it(*this); + m_pos++; + return it; + } + bool operator==(const iterator& rhs) const + { + assert(&m_cb == &rhs.m_cb); + return m_pos == rhs.m_pos; + } + bool operator!=(const iterator& rhs) const + { + assert(&m_cb == &rhs.m_cb); + return m_pos != rhs.m_pos; + } T& operator*() const { return m_cb.m_ary[m_pos % m_cb.m_capacity]; } - T* operator->() const { return &m_cb.m_ary[m_pos % m_cb.m_capacity]; } + T *operator->() const { return &m_cb.m_ary[m_pos % m_cb.m_capacity]; } }; friend class circular_buffer::iterator; circular_buffer(); @@ -78,21 +101,21 @@ class circular_buffer template circular_buffer::circular_buffer() - : m_ary(0), - m_head(0), - m_tail(0), - m_size(0), - m_capacity(0) + : m_ary(0) + , m_head(0) + , m_tail(0) + , m_size(0) + , m_capacity(0) { } template circular_buffer::circular_buffer(unsigned int capacity) - : m_ary(new T[capacity]), - m_head(0), - m_tail(0), - m_size(0), - m_capacity(capacity) + : m_ary(new T[capacity]) + , m_head(0) + , m_tail(0) + , m_size(0) + , m_capacity(capacity) { assert(capacity > 0); } @@ -100,7 +123,7 @@ circular_buffer::circular_buffer(unsigned int capacity) template circular_buffer::~circular_buffer() { - delete [] m_ary; + delete[] m_ary; } template diff --git a/src/comdispatch.cpp b/src/comdispatch.cpp index 773268b20..32cf54398 100644 --- a/src/comdispatch.cpp +++ b/src/comdispatch.cpp @@ -37,8 +37,8 @@ // windows only ASCOM helper code #if defined(__WINDOWS__) -#include "comdispatch.h" -#include +# include "comdispatch.h" +# include wxString ExcepMsg(const EXCEPINFO& excep) { @@ -124,20 +124,20 @@ bool DispatchClass::dispid_cached(DISPID *ret, IDispatch *idisp, OLECHAR *wname, } DispatchObj::DispatchObj() - : m_class(0), - m_idisp(0) + : m_class(0) + , m_idisp(0) { } DispatchObj::DispatchObj(DispatchClass *cls) - : m_class(cls), - m_idisp(0) + : m_class(cls) + , m_idisp(0) { } DispatchObj::DispatchObj(IDispatch *idisp, DispatchClass *cls) - : m_class(cls), - m_idisp(idisp) + : m_class(cls) + , m_idisp(idisp) { if (m_idisp) m_idisp->AddRef(); @@ -164,7 +164,7 @@ bool DispatchObj::Create(OLECHAR *progid) return false; IDispatch *idisp; HRESULT hr; - if (FAILED(hr = CoCreateInstance(clsid, NULL, CLSCTX_SERVER, IID_IDispatch, (LPVOID *)&idisp))) + if (FAILED(hr = CoCreateInstance(clsid, NULL, CLSCTX_SERVER, IID_IDispatch, (LPVOID *) &idisp))) { Debug.AddLine(wxString::Format("CoCreateInstance: [%x] %s", hr, _com_error(hr).ErrorMessage())); return false; @@ -365,7 +365,8 @@ bool DispatchObj::InvokeMethod(Variant *res, OLECHAR *name) } GITEntry::GITEntry() - : m_pIGlobalInterfaceTable(0), m_dwCookie(0) + : m_pIGlobalInterfaceTable(0) + , m_dwCookie(0) { } @@ -381,7 +382,7 @@ void GITEntry::Register(IDispatch *idisp) // first find the global table HRESULT hr; if (FAILED(hr = ::CoCreateInstance(CLSID_StdGlobalInterfaceTable, NULL, CLSCTX_INPROC_SERVER, IID_IGlobalInterfaceTable, - (void **)&m_pIGlobalInterfaceTable))) + (void **) &m_pIGlobalInterfaceTable))) { Debug.AddLine(wxString::Format("create global interface table: [%x] %s", hr, _com_error(hr).ErrorMessage())); throw ERROR_INFO("Cannot CoCreateInstance of Global Interface Table"); diff --git a/src/comdispatch.h b/src/comdispatch.h index 8bc8c23e7..d378fc598 100644 --- a/src/comdispatch.h +++ b/src/comdispatch.h @@ -49,6 +49,7 @@ struct Variant : public VARIANT class ExcepInfo : public EXCEPINFO { ExcepInfo& operator=(const ExcepInfo& rhs) = delete; + public: ExcepInfo(); ~ExcepInfo(); @@ -62,6 +63,7 @@ class DispatchClass { typedef std::map idmap_t; idmap_t m_idmap; + public: DispatchClass() { } ~DispatchClass() { } @@ -74,6 +76,7 @@ class DispatchObj DispatchClass *m_class; IDispatch *m_idisp; ExcepInfo m_excep; + public: DispatchObj(); DispatchObj(DispatchClass *cls); @@ -103,6 +106,7 @@ class GITEntry { IGlobalInterfaceTable *m_pIGlobalInterfaceTable; DWORD m_dwCookie; + public: GITEntry(); ~GITEntry(); @@ -114,17 +118,14 @@ class GITEntry { IDispatch *idisp = 0; if (m_dwCookie) - m_pIGlobalInterfaceTable->GetInterfaceFromGlobal(m_dwCookie, IID_IDispatch, (LPVOID *)&idisp); + m_pIGlobalInterfaceTable->GetInterfaceFromGlobal(m_dwCookie, IID_IDispatch, (LPVOID *) &idisp); return idisp; } }; struct GITObjRef : public DispatchObj { - GITObjRef(const GITEntry& gitentry) - { - Attach(gitentry.Get(), 0); - } + GITObjRef(const GITEntry& gitentry) { Attach(gitentry.Get(), 0); } }; #endif diff --git a/src/comet_tool.cpp b/src/comet_tool.cpp index f3c135335..231bb2d9a 100644 --- a/src/comet_tool.cpp +++ b/src/comet_tool.cpp @@ -81,34 +81,38 @@ static wxString TITLE_TRAINING = wxTRANSLATE("Comet Tracking - Training Active") static wxString TITLE_ACTIVE = wxTRANSLATE("Comet Tracking - Active"); CometToolWin::CometToolWin() - : wxDialog(pFrame, wxID_ANY, wxGetTranslation(TITLE), wxPoint(-1,-1), wxSize(300,300)), - m_training(false), - m_timer(this) + : wxDialog(pFrame, wxID_ANY, wxGetTranslation(TITLE), wxPoint(-1, -1), wxSize(300, 300)) + , m_training(false) + , m_timer(this) { - SetSizeHints( wxDefaultSize, wxDefaultSize ); + SetSizeHints(wxDefaultSize, wxDefaultSize); m_enable = new wxToggleButton(this, wxID_ANY, _("Enable"), wxDefaultPosition, wxDefaultSize, 0); m_enable->SetToolTip(_("Toggle comet tracking on or off.")); - m_xLabel = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(20,-1), wxALIGN_RIGHT); + m_xLabel = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(20, -1), wxALIGN_RIGHT); m_xLabel->Wrap(-1); m_yLabel = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(20, -1), wxALIGN_RIGHT); m_yLabel->Wrap(-1); - m_xRate = new wxSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, -5000., +5000., 0., 1.); + m_xRate = new wxSpinCtrlDouble( + this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, -5000., +5000., 0., 1.); m_xRate->SetToolTip(_("Comet tracking rate")); - m_yRate = new wxSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, -5000., +5000., 0., 1.); + m_yRate = new wxSpinCtrlDouble( + this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, -5000., +5000., 0., 1.); m_yRate->SetToolTip(_("Comet tracking rate")); wxString m_unitsChoices[] = { _("Pixels/hr"), _("Arcsec/hr") }; int m_unitsNChoices = sizeof(m_unitsChoices) / sizeof(wxString); - m_units = new wxRadioBox(this, wxID_ANY, _("Units"), wxDefaultPosition, wxDefaultSize, m_unitsNChoices, m_unitsChoices, 1, wxRA_SPECIFY_ROWS); + m_units = new wxRadioBox( + this, wxID_ANY, _("Units"), wxDefaultPosition, wxDefaultSize, m_unitsNChoices, m_unitsChoices, 1, wxRA_SPECIFY_ROWS); m_units->SetSelection(1); m_units->SetToolTip(_("Tracking rate units")); wxString m_axesChoices[] = { _("Camera (X/Y)"), _("Mount (RA/Dec)") }; int m_axesNChoices = sizeof(m_axesChoices) / sizeof(wxString); - m_axes = new wxRadioBox(this, wxID_ANY, _("Axes"), wxDefaultPosition, wxDefaultSize, m_axesNChoices, m_axesChoices, 1, wxRA_SPECIFY_ROWS); + m_axes = new wxRadioBox( + this, wxID_ANY, _("Axes"), wxDefaultPosition, wxDefaultSize, m_axesNChoices, m_axesChoices, 1, wxRA_SPECIFY_ROWS); m_axes->SetSelection(1); m_axes->SetToolTip(_("Tracking rate axes")); @@ -118,20 +122,21 @@ CometToolWin::CometToolWin() m_stop->SetToolTip(_("Stop training")); m_stop->Enable(false); - // Use a text ctrl for status, wxStaticText flickers. Adding the wxTE_NO_VSCROLL style also causes the control to flicker on Windows 7. + // Use a text ctrl for status, wxStaticText flickers. Adding the wxTE_NO_VSCROLL style also causes the control to flicker on + // Windows 7. long style = wxSTATIC_BORDER | wxTE_MULTILINE /*| wxTE_NO_VSCROLL*/; m_status = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(400, 60), style); m_status->Enable(false); wxBoxSizer *xSizer = new wxBoxSizer(wxHORIZONTAL); xSizer->Add(0, 0, 1, wxEXPAND, 5); - xSizer->Add(m_xLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); - xSizer->Add(m_xRate, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); + xSizer->Add(m_xLabel, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); + xSizer->Add(m_xRate, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); xSizer->Add(0, 0, 1, wxEXPAND, 5); wxBoxSizer *ySizer = new wxBoxSizer(wxHORIZONTAL); ySizer->Add(0, 0, 1, wxEXPAND, 5); - ySizer->Add(m_yLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); + ySizer->Add(m_yLabel, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); ySizer->Add(m_yRate, 0, wxALL, 5); ySizer->Add(0, 0, 1, wxEXPAND, 5); @@ -152,7 +157,7 @@ CometToolWin::CometToolWin() trainingSizer->Add(m_status, 0, wxALL, 5); wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL); - topSizer->Add(m_enable, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5); + topSizer->Add(m_enable, 0, wxALL | wxALIGN_CENTER_HORIZONTAL, 5); topSizer->Add(ratesSizer, 1, wxEXPAND, 5); topSizer->Add(trainingSizer, 0, wxEXPAND, 5); @@ -188,7 +193,7 @@ CometToolWin::~CometToolWin(void) pFrame->pCometTool = 0; } -static void SetEnabledState(CometToolWin* win, bool active) +static void SetEnabledState(CometToolWin *win, bool active) { if (active) { @@ -294,14 +299,14 @@ void CometToolWin::UpdateStatus() if (m_training) { m_status->SetValue(wxString::Format(_("Training, elapsed time %lus.\nUse the " - "\"Adjust Lock Position\" controls to center the comet\nin the imaging " - "camera and click Stop to complete training."), - (long)((::wxGetUTCTimeMillis().GetValue() - m_startTime) / 1000))); + "\"Adjust Lock Position\" controls to center the comet\nin the imaging " + "camera and click Stop to complete training."), + (long) ((::wxGetUTCTimeMillis().GetValue() - m_startTime) / 1000))); } else { m_status->SetValue(_("Center the comet in the imaging camera.\nSelect a guide " - "star and start Guiding.\nThen, click Start to begin training.")); + "star and start Guiding.\nThen, click Start to begin training.")); } } diff --git a/src/config_indi.cpp b/src/config_indi.cpp index 0d3a9e790..f14f0b7ad 100644 --- a/src/config_indi.cpp +++ b/src/config_indi.cpp @@ -40,16 +40,16 @@ #include "camera.h" #include "scope.h" -#if defined (INDI_CAMERA) || defined (GUIDE_INDI) +#if defined(INDI_CAMERA) || defined(GUIDE_INDI) -#include "config_indi.h" +# include "config_indi.h" -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include enum { @@ -60,18 +60,17 @@ enum FORCEVIDEO = 105, }; -#define POS(r, c) wxGBPosition(r,c) -#define SPAN(r, c) wxGBSpan(r,c) +# define POS(r, c) wxGBPosition(r, c) +# define SPAN(r, c) wxGBSpan(r, c) bool INDIConfig::s_verbose; INDIConfig::INDIConfig(wxWindow *parent, const wxString& title, IndiDevType devtype) - : - wxDialog(parent, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), - m_gui(nullptr), - dev_type(devtype) + : wxDialog(parent, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) + , m_gui(nullptr) + , dev_type(devtype) { - auto sizerLabelFlags = wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL; + auto sizerLabelFlags = wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL; auto sizerButtonFlags = wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL; auto sizerSectionFlags = wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL; auto sizerTextFlags = wxALIGN_LEFT | wxALL | wxEXPAND; @@ -82,18 +81,15 @@ INDIConfig::INDIConfig(wxWindow *parent, const wxString& title, IndiDevType devt wxBoxSizer *sizer; pos = 0; - gbs->Add(new wxStaticText(this, wxID_ANY, _("INDI Server")), - POS(pos, 0), SPAN(1, 1), sizerSectionFlags, border); + gbs->Add(new wxStaticText(this, wxID_ANY, _("INDI Server")), POS(pos, 0), SPAN(1, 1), sizerSectionFlags, border); ++pos; - gbs->Add(new wxStaticText(this, wxID_ANY, _("Hostname")), - POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); + gbs->Add(new wxStaticText(this, wxID_ANY, _("Hostname")), POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); host = new wxTextCtrl(this, wxID_ANY); gbs->Add(host, POS(pos, 1), SPAN(1, 1), sizerTextFlags, border); ++pos; - gbs->Add(new wxStaticText(this, wxID_ANY, _("Port")), - POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); + gbs->Add(new wxStaticText(this, wxID_ANY, _("Port")), POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); port = new wxTextCtrl(this, wxID_ANY); gbs->Add(port, POS(pos, 1), SPAN(1, 1), sizerTextFlags, border); @@ -104,8 +100,7 @@ INDIConfig::INDIConfig(wxWindow *parent, const wxString& title, IndiDevType devt gbs->Add(connect, POS(pos, 1), SPAN(1, 1), sizerButtonFlags, border); ++pos; - gbs->Add(new wxStaticText(this, wxID_ANY, _T("========")), - POS(pos, 0), SPAN(1, 1), wxALIGN_LEFT | wxALL, border); + gbs->Add(new wxStaticText(this, wxID_ANY, _T("========")), POS(pos, 0), SPAN(1, 1), wxALIGN_LEFT | wxALL, border); devlabel = new wxStaticText(this, wxID_ANY, _("Device")); if (dev_type == INDI_TYPE_CAMERA) @@ -122,8 +117,7 @@ INDIConfig::INDIConfig(wxWindow *parent, const wxString& title, IndiDevType devt gbs->Add(devlabel, POS(pos, 1), SPAN(1, 1), wxALIGN_LEFT | wxALL, border); ++pos; - gbs->Add(new wxStaticText(this, wxID_ANY, _("Driver")), - POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); + gbs->Add(new wxStaticText(this, wxID_ANY, _("Driver")), POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); dev = new wxComboBox(this, MDEV, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, nullptr, wxCB_READONLY); gbs->Add(dev, POS(pos, 1), SPAN(1, 1), sizerTextFlags, border); @@ -131,8 +125,7 @@ INDIConfig::INDIConfig(wxWindow *parent, const wxString& title, IndiDevType devt if (dev_type == INDI_TYPE_CAMERA) { ++pos; - gbs->Add(new wxStaticText(this, wxID_ANY, _("Dual CCD")), - POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); + gbs->Add(new wxStaticText(this, wxID_ANY, _("Dual CCD")), POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); ccd = new wxComboBox(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, nullptr, wxCB_READONLY); gbs->Add(ccd, POS(pos, 1), SPAN(1, 1), sizerTextFlags, border); } @@ -143,19 +136,18 @@ INDIConfig::INDIConfig(wxWindow *parent, const wxString& title, IndiDevType devt { ++pos; forcevideo = new wxCheckBox(this, FORCEVIDEO, _("Camera does not support exposure time")); - forcevideo->SetToolTip( - _("Force the use of streaming and frame stacking for cameras that do not support setting an absolute exposure time.")); - gbs->Add(forcevideo, POS(pos, 0), SPAN(1, 2), sizerTextFlags, border); + forcevideo->SetToolTip(_("Force the use of streaming and frame stacking for cameras that do not support setting an " + "absolute exposure time.")); + gbs->Add(forcevideo, POS(pos, 0), SPAN(1, 2), sizerTextFlags, border); ++pos; forceexposure = new wxCheckBox(this, wxID_ANY, _("Camera does not support streaming")); forceexposure->SetToolTip(_("Force the use of exposure time for cameras that do not support streaming.")); - gbs->Add(forceexposure, POS(pos, 0), SPAN(1, 2), sizerTextFlags, border); + gbs->Add(forceexposure, POS(pos, 0), SPAN(1, 2), sizerTextFlags, border); } ++pos; - gbs->Add(new wxStaticText(this, wxID_ANY, _("Other options")), - POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); + gbs->Add(new wxStaticText(this, wxID_ANY, _("Other options")), POS(pos, 0), SPAN(1, 1), sizerLabelFlags, border); guiBtn = new wxButton(this, MINDIGUI, _("INDI")); gbs->Add(guiBtn, POS(pos, 1), SPAN(1, 1), sizerButtonFlags, border); @@ -377,9 +369,9 @@ static wxString formatInterface(unsigned int ifs) wxString s; -#define F(t) \ - if (ifs & INDI::BaseDevice:: t ## _INTERFACE) \ - _append(s, #t) +# define F(t) \ + if (ifs & INDI::BaseDevice::t##_INTERFACE) \ + _append(s, #t) F(TELESCOPE); F(CCD); @@ -394,7 +386,7 @@ static wxString formatInterface(unsigned int ifs) F(LIGHTBOX); F(AUX); -#undef F +# undef F return s; } @@ -424,11 +416,11 @@ void INDIConfig::newProperty(INDI::Property property) if (!include) { Debug.Write(wxString::Format("exclude device %s not a valid %s\n", devname, - dev_type == INDI_TYPE_CAMERA ? "camera" : - dev_type == INDI_TYPE_MOUNT ? "mount" : - dev_type == INDI_TYPE_AUX_MOUNT ? "aux mount" : - dev_type == INDI_TYPE_AO ? "AO" : - "rotator")); + dev_type == INDI_TYPE_CAMERA ? "camera" + : dev_type == INDI_TYPE_MOUNT ? "mount" + : dev_type == INDI_TYPE_AUX_MOUNT ? "aux mount" + : dev_type == INDI_TYPE_AO ? "AO" + : "rotator")); int n = dev->FindString(devname, true); if (n != wxNOT_FOUND) diff --git a/src/config_indi.h b/src/config_indi.h index 99eff7309..0b2f96875 100644 --- a/src/config_indi.h +++ b/src/config_indi.h @@ -57,65 +57,62 @@ enum IndiDevType class INDIConfig : public wxDialog, public INDI::BaseClient { - static bool s_verbose; - - wxTextCtrl *host; - wxTextCtrl *port; - wxButton *connect; - wxStaticText *connect_status; - wxStaticText *devlabel; - wxComboBox *dev; - wxComboBox *ccd; - wxCheckBox *forcevideo; - wxCheckBox *forceexposure; - wxButton *guiBtn; - wxButton *okBtn; - - IndiGui *m_gui; - IndiDevType dev_type; - - public: - - INDIConfig(wxWindow *parent, const wxString& title, IndiDevType devtype); - ~INDIConfig(); - - long INDIport; - wxString INDIhost; - wxString INDIDevName; - long INDIDevCCD; - bool INDIForceVideo; - bool INDIForceExposure; - - void Connect(); - void Disconnect(); - void SetSettings(); - void SaveSettings(); - - static void LoadProfileSettings(); - static bool Verbose(); - static void SetVerbose(bool val); - - void OnUpdateFromThread(wxThreadEvent& event); - - protected: - - void newDevice(INDI::BaseDevice dp) override; - void removeDevice(INDI::BaseDevice dp) override {}; - void newProperty(INDI::Property property) override; - void removeProperty(INDI::Property property) override {} - void serverConnected() override; - void serverDisconnected(int exit_code) override; - - private: - - void OnConnectButton(wxCommandEvent& evt); - void OnIndiGui(wxCommandEvent& evt); - void OnDevSelected(wxCommandEvent& evt); - void OnVerboseChecked(wxCommandEvent& evt); - void OnForceVideoChecked(wxCommandEvent& evt); - void UpdateControlStates(); - - wxDECLARE_EVENT_TABLE(); + static bool s_verbose; + + wxTextCtrl *host; + wxTextCtrl *port; + wxButton *connect; + wxStaticText *connect_status; + wxStaticText *devlabel; + wxComboBox *dev; + wxComboBox *ccd; + wxCheckBox *forcevideo; + wxCheckBox *forceexposure; + wxButton *guiBtn; + wxButton *okBtn; + + IndiGui *m_gui; + IndiDevType dev_type; + +public: + INDIConfig(wxWindow *parent, const wxString& title, IndiDevType devtype); + ~INDIConfig(); + + long INDIport; + wxString INDIhost; + wxString INDIDevName; + long INDIDevCCD; + bool INDIForceVideo; + bool INDIForceExposure; + + void Connect(); + void Disconnect(); + void SetSettings(); + void SaveSettings(); + + static void LoadProfileSettings(); + static bool Verbose(); + static void SetVerbose(bool val); + + void OnUpdateFromThread(wxThreadEvent& event); + +protected: + void newDevice(INDI::BaseDevice dp) override; + void removeDevice(INDI::BaseDevice dp) override {}; + void newProperty(INDI::Property property) override; + void removeProperty(INDI::Property property) override { } + void serverConnected() override; + void serverDisconnected(int exit_code) override; + +private: + void OnConnectButton(wxCommandEvent& evt); + void OnIndiGui(wxCommandEvent& evt); + void OnDevSelected(wxCommandEvent& evt); + void OnVerboseChecked(wxCommandEvent& evt); + void OnForceVideoChecked(wxCommandEvent& evt); + void UpdateControlStates(); + + wxDECLARE_EVENT_TABLE(); }; inline bool INDIConfig::Verbose() diff --git a/src/configdialog.cpp b/src/configdialog.cpp index 54a68a363..d36e2926c 100644 --- a/src/configdialog.cpp +++ b/src/configdialog.cpp @@ -42,12 +42,12 @@ ConfigDialogPane::ConfigDialogPane(const wxString& heading, wxWindow *pParent) void ConfigDialogPane::DoAdd(wxSizer *pSizer) { - this->Add(pSizer, wxSizerFlags().Expand().Border(wxALL,3)); + this->Add(pSizer, wxSizerFlags().Expand().Border(wxALL, 3)); } void ConfigDialogPane::DoAdd(wxWindow *pWindow) { - this->Add(pWindow, wxSizerFlags().Expand().Border(wxALL,3)); + this->Add(pWindow, wxSizerFlags().Expand().Border(wxALL, 3)); } void ConfigDialogPane::DoAdd(wxWindow *pWindow, const wxString& toolTip) @@ -56,7 +56,8 @@ void ConfigDialogPane::DoAdd(wxWindow *pWindow, const wxString& toolTip) DoAdd(pWindow); } -wxSizer *ConfigDialogPane::MakeLabeledControl(const wxString& label, wxWindow *pControl, const wxString& toolTip, wxWindow *pControl2) +wxSizer *ConfigDialogPane::MakeLabeledControl( + const wxString& label, wxWindow *pControl, const wxString& toolTip, wxWindow *pControl2) { wxStaticText *pLabel = new wxStaticText(m_pParent, wxID_ANY, label + _(": ")); pControl->SetToolTip(toolTip); @@ -88,7 +89,7 @@ int ConfigDialogPane::StringArrayWidth(wxString string[], int nElements) { int width = 0; - for(int i=0;isecond.isPositioned = true; } - return ctrl; // May return null but client can use CondAddCtrl + return ctrl; // May return null but client can use CondAddCtrl } -// Handle the case where a control is not created because of state. wxWidgets handles a null window correctly in 'Add' but the behavior -// is technically undocumented. +// Handle the case where a control is not created because of state. wxWidgets handles a null window correctly in 'Add' but the +// behavior is technically undocumented. void ConfigDialogPane::CondAddCtrl(wxSizer *szr, BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, const wxSizerFlags& flags) { wxWindow *ctrl = GetSingleCtrl(CtrlMap, id); @@ -139,7 +139,7 @@ wxSizer *ConfigDialogPane::GetSizerCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS if (ctrl) it->second.isPositioned = true; } - return ctrl; // May return null, won't add entry in CtrlMap + return ctrl; // May return null, won't add entry in CtrlMap } void ConfigDialogPane::OnImageScaleChange() @@ -152,7 +152,7 @@ void ConfigDialogPane::EnableDecControls(bool enable) // Do nothing by default - subclasses will override if needed } -ConfigDialogCtrlSet::ConfigDialogCtrlSet(wxWindow *pParent, AdvancedDialog* pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +ConfigDialogCtrlSet::ConfigDialogCtrlSet(wxWindow *pParent, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) { m_pParent = pParent; m_pAdvDlg = pAdvancedDialog; @@ -231,7 +231,8 @@ void ConfigDialogCtrlSet::AddGroup(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, w AddMapElement(CtrlMap, id, pSizer); } -wxSizer *ConfigDialogCtrlSet::MakeLabeledControl(BRAIN_CTRL_IDS id, const wxString& label, wxWindow *pControl, const wxString& toolTip) +wxSizer *ConfigDialogCtrlSet::MakeLabeledControl( + BRAIN_CTRL_IDS id, const wxString& label, wxWindow *pControl, const wxString& toolTip) { wxStaticText *pLabel = new wxStaticText(GetParentWindow(id), wxID_ANY, label + _(": ")); pControl->SetToolTip(toolTip); @@ -243,7 +244,8 @@ wxSizer *ConfigDialogCtrlSet::MakeLabeledControl(BRAIN_CTRL_IDS id, const wxStri return pSizer; } -void ConfigDialogCtrlSet::AddLabeledCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, const wxString& Label, wxControl *pCtrl, const wxString& toolTip) +void ConfigDialogCtrlSet::AddLabeledCtrl( + BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, const wxString& Label, wxControl *pCtrl, const wxString& toolTip) { AddGroup(CtrlMap, id, MakeLabeledControl(id, Label, pCtrl, toolTip)); } diff --git a/src/configdialog.h b/src/configdialog.h index 59f9610b8..c1239530d 100644 --- a/src/configdialog.h +++ b/src/configdialog.h @@ -35,12 +35,14 @@ #ifndef CONFIG_DIALOG_H_INCLUDED #define CONFIG_DIALOG_H_INCLUDED -// Design Notes: The goal here is to separate the ownership of various controls from where they are displayed in the AD. A class that "owns" a control -// will create it and handle all its behavior - loading, unloading, all the semantics. This part is handled by the ConfigDlgControlSet. Where those controls -// are displayed is determined by the BrainIDControlMap, a dictionary that maps the control ids to the AD panel where they will be displayed. The owner of the -// AD panel - the "host" - is responsible for creating the panel UI and rendering all the controls that belong on that panel. This will be handled in the -// LayoutControls() method of the hosting class. Beyond that, the host class has no involvement with controls that are owned by a different class. -// Example: the focal length control (AD_szFocalLength) is owned by MyFrame but is displayed on the guiding tab +// Design Notes: The goal here is to separate the ownership of various controls from where they are displayed in the AD. A +// class that "owns" a control will create it and handle all its behavior - loading, unloading, all the semantics. This part is +// handled by the ConfigDlgControlSet. Where those controls are displayed is determined by the BrainIDControlMap, a dictionary +// that maps the control ids to the AD panel where they will be displayed. The owner of the AD panel - the "host" - is +// responsible for creating the panel UI and rendering all the controls that belong on that panel. This will be handled in the +// LayoutControls() method of the hosting class. Beyond that, the host class has no involvement with controls that are owned by +// a different class. Example: the focal length control (AD_szFocalLength) is owned by MyFrame but is displayed on the guiding +// tab // Segmented by the tab page location seen in the UI // "sz" => element is a sizer @@ -56,7 +58,7 @@ enum BRAIN_CTRL_IDS AD_cbEnableImageLogging, AD_szImageLoggingOptions, AD_szDither, - AD_GLOBAL_TAB_BOUNDARY, //-----end of global tab controls + AD_GLOBAL_TAB_BOUNDARY, //-----end of global tab controls AD_cbUseSubFrames, AD_szNoiseReduction, @@ -71,7 +73,7 @@ enum BRAIN_CTRL_IDS AD_szPort, AD_szBinning, AD_szCooler, - AD_CAMERA_TAB_BOUNDARY, // ------ end of camera tab controls + AD_CAMERA_TAB_BOUNDARY, // ------ end of camera tab controls AD_cbScaleImages, AD_szFocalLength, @@ -86,13 +88,13 @@ enum BRAIN_CTRL_IDS AD_cbSlewDetection, AD_cbUseDecComp, AD_cbBeepForLostStar, - AD_GUIDER_TAB_BOUNDARY, // --------------- end of guiding tab controls + AD_GUIDER_TAB_BOUNDARY, // --------------- end of guiding tab controls AD_szBLCompCtrls, AD_szMaxRAAmt, AD_szMaxDecAmt, AD_szDecGuideMode, - AD_MOUNT_TAB_BOUNDARY, // ----------- end of mount tab controls + AD_MOUNT_TAB_BOUNDARY, // ----------- end of mount tab controls AD_AOTravel, AD_szCalStepsPerIteration, @@ -104,25 +106,23 @@ enum BRAIN_CTRL_IDS AD_cbClearAOCalibration, AD_cbEnableAOGuiding, AD_cbRotatorReverse, - AD_DEVICES_TAB_BOUNDARY // ----------- end of devices tab controls + AD_DEVICES_TAB_BOUNDARY // ----------- end of devices tab controls }; struct BrainCtrlInfo { wxObject *panelCtrl; - bool isPositioned; // debug only + bool isPositioned; // debug only BrainCtrlInfo() - : - panelCtrl(0), - isPositioned(false) + : panelCtrl(0) + , isPositioned(false) { } BrainCtrlInfo(BRAIN_CTRL_IDS id, wxObject *ctrl) - : - panelCtrl(ctrl), - isPositioned(false) + : panelCtrl(ctrl) + , isPositioned(false) { } }; @@ -133,6 +133,7 @@ class ConfigDialogPane : public wxStaticBoxSizer { protected: wxWindow *m_pParent; + public: ConfigDialogPane(const wxString& heading, wxWindow *pParent); virtual ~ConfigDialogPane(void) {}; @@ -144,11 +145,13 @@ class ConfigDialogPane : public wxStaticBoxSizer wxWindow *GetSingleCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id); wxSizer *GetSizerCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id); void CondAddCtrl(wxSizer *szr, BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, const wxSizerFlags& flags = 0); - virtual void OnImageScaleChange(); // Only for adjustments made within the AD panels - virtual void EnableDecControls(bool enable); // Needed for guide algo ConfigDialogPanes which inherit directly from this class + virtual void OnImageScaleChange(); // Only for adjustments made within the AD panels + virtual void EnableDecControls( + bool enable); // Needed for guide algo ConfigDialogPanes which inherit directly from this class protected: - wxSizer *MakeLabeledControl(const wxString& label, wxWindow *pControl, const wxString& toolTip, wxWindow *pControl2 = nullptr); + wxSizer *MakeLabeledControl( + const wxString& label, wxWindow *pControl, const wxString& toolTip, wxWindow *pControl2 = nullptr); void DoAdd(wxSizer *pSizer); void DoAdd(wxWindow *pWindow); void DoAdd(wxWindow *pWindow, const wxString& toolTip); @@ -177,10 +180,11 @@ class ConfigDialogCtrlSet public: wxSizer *MakeLabeledControl(BRAIN_CTRL_IDS id, const wxString& label, wxWindow *pControl, const wxString& toolTip); void AddMapElement(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS, wxObject *pElem); - void AddGroup(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, wxSizer *pSizer); // Sizer - void AddCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, wxControl *pCtrl); // Bare control - void AddLabeledCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, const wxString& Label, wxControl *pCtrl, const wxString& toolTip); - void AddCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, wxControl *pCtrl, const wxString& toolTip); // Control with tooltip + void AddGroup(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, wxSizer *pSizer); // Sizer + void AddCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, wxControl *pCtrl); // Bare control + void AddLabeledCtrl( + BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, const wxString& Label, wxControl *pCtrl, const wxString& toolTip); + void AddCtrl(BrainCtrlIdMap& CtrlMap, BRAIN_CTRL_IDS id, wxControl *pCtrl, const wxString& toolTip); // Control with tooltip wxWindow *GetParentWindow(BRAIN_CTRL_IDS id); diff --git a/src/confirm_dialog.cpp b/src/confirm_dialog.cpp index 88237a7cd..8ba67d98f 100644 --- a/src/confirm_dialog.cpp +++ b/src/confirm_dialog.cpp @@ -34,7 +34,8 @@ #include "phd.h" -ConfirmDialog::ConfirmDialog(const wxString& prompt, const wxString& title, const wxString& affirmLabel, const wxString& negativeLabel) +ConfirmDialog::ConfirmDialog( + const wxString& prompt, const wxString& title, const wxString& affirmLabel, const wxString& negativeLabel) : wxDialog(pFrame, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) { dont_ask_again = new wxCheckBox(this, wxID_ANY, _("Don't ask again")); @@ -60,16 +61,15 @@ ConfirmDialog::ConfirmDialog(const wxString& prompt, const wxString& title, cons SetSizerAndFit(topLevelSizer); } -ConfirmDialog::~ConfirmDialog(void) -{ -} +ConfirmDialog::~ConfirmDialog(void) { } static wxString ConfigKey(const wxString& name) { return "/Confirm" + name; } -bool ConfirmDialog::Confirm(const wxString& prompt, const wxString& config_key, const wxString& affirmLabel, const wxString& negativeLabel, const wxString& title_arg) +bool ConfirmDialog::Confirm(const wxString& prompt, const wxString& config_key, const wxString& affirmLabel, + const wxString& negativeLabel, const wxString& title_arg) { wxString key(ConfigKey(config_key)); diff --git a/src/confirm_dialog.h b/src/confirm_dialog.h index e538e7335..9356477fa 100644 --- a/src/confirm_dialog.h +++ b/src/confirm_dialog.h @@ -35,15 +35,16 @@ #ifndef CONFIRM_DIALOG_H_INCLUDED #define CONFIRM_DIALOG_H_INCLUDED -class ConfirmDialog : - public wxDialog +class ConfirmDialog : public wxDialog { public: - ConfirmDialog(const wxString& prompt, const wxString& title, const wxString& affirmativeLabel, const wxString& negativeLabel); + ConfirmDialog( + const wxString& prompt, const wxString& title, const wxString& affirmativeLabel, const wxString& negativeLabel); ~ConfirmDialog(void); static bool Confirm(const wxString& prompt, const wxString& config_key, const wxString& title = ""); - static bool Confirm(const wxString& prompt, const wxString& config_key, const wxString& affirmativeLabel, const wxString& negativeLabel, const wxString& title = ""); + static bool Confirm(const wxString& prompt, const wxString& config_key, const wxString& affirmativeLabel, + const wxString& negativeLabel, const wxString& title = ""); static void ResetAllDontAskAgain(void); private: diff --git a/src/darks_dialog.cpp b/src/darks_dialog.cpp index 0e5859c8f..a6f95d8c0 100644 --- a/src/darks_dialog.cpp +++ b/src/darks_dialog.cpp @@ -44,7 +44,7 @@ static const int DefDarkCount = 5; static const int DefDMExpTime = 15; static const int DefDMCount = 25; -static const int MaxNoteLength = 65; // For now +static const int MaxNoteLength = 65; // For now // Utility function to add the pairs to a flexgrid static void AddTableEntryPair(wxWindow *parent, wxFlexGridSizer *pTable, const wxString& label, wxWindow *pControl) @@ -54,10 +54,11 @@ static void AddTableEntryPair(wxWindow *parent, wxFlexGridSizer *pTable, const w pTable->Add(pControl, 1, wxALL, 5); } -static wxSpinCtrl *NewSpinnerInt(wxWindow *parent, const wxSize& size, int val, int minval, int maxval, int inc, - const wxString& tooltip) +static wxSpinCtrl *NewSpinnerInt( + wxWindow *parent, const wxSize& size, int val, int minval, int maxval, int inc, const wxString& tooltip) { - wxSpinCtrl *pNewCtrl = pFrame->MakeSpinCtrl(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, size, wxSP_ARROW_KEYS, minval, maxval, val, _("Exposure time")); + wxSpinCtrl *pNewCtrl = pFrame->MakeSpinCtrl( + parent, wxID_ANY, wxEmptyString, wxDefaultPosition, size, wxSP_ARROW_KEYS, minval, maxval, val, _("Exposure time")); pNewCtrl->SetValue(val); pNewCtrl->SetToolTip(tooltip); return pNewCtrl; @@ -89,8 +90,8 @@ static wxString MaxExposureDefault() // Dialog operates in one of two modes: 1) To create a user-requested dark library or 2) To create a master dark frame // and associated data files needed to construct a new defect map -DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : - wxDialog(parent, wxID_ANY, _("Build Dark Library"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) +DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) + : wxDialog(parent, wxID_ANY, _("Build Dark Library"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) { buildDarkLib = darkLib; if (!buildDarkLib) @@ -105,22 +106,25 @@ DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : wxStaticBoxSizer *pDarkGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Dark Library")); wxFlexGridSizer *pDarkParams = new wxFlexGridSizer(2, 4, 5, 15); - m_pDarkMinExpTime = new wxComboBox(this, BUTTON_DURATION, wxEmptyString, wxDefaultPosition, wxDefaultSize, - m_expStrings, wxCB_READONLY); + m_pDarkMinExpTime = + new wxComboBox(this, BUTTON_DURATION, wxEmptyString, wxDefaultPosition, wxDefaultSize, m_expStrings, wxCB_READONLY); AddTableEntryPair(this, pDarkParams, _("Min Exposure Time"), m_pDarkMinExpTime); m_pDarkMinExpTime->SetValue(pConfig->Profile.GetString("/camera/darks_min_exptime", MinExposureDefault())); - m_pDarkMinExpTime->SetToolTip(_("Minimum exposure time for darks. Choose a value corresponding to the shortest camera exposure you will use for guiding.")); + m_pDarkMinExpTime->SetToolTip(_("Minimum exposure time for darks. Choose a value corresponding to the shortest camera " + "exposure you will use for guiding.")); - m_pDarkMaxExpTime = new wxComboBox(this, BUTTON_DURATION, wxEmptyString, wxDefaultPosition, wxDefaultSize, - m_expStrings, wxCB_READONLY); + m_pDarkMaxExpTime = + new wxComboBox(this, BUTTON_DURATION, wxEmptyString, wxDefaultPosition, wxDefaultSize, m_expStrings, wxCB_READONLY); AddTableEntryPair(this, pDarkParams, _("Max Exposure Time"), m_pDarkMaxExpTime); m_pDarkMaxExpTime->SetValue(pConfig->Profile.GetString("/camera/darks_max_exptime", MaxExposureDefault())); - m_pDarkMaxExpTime->SetToolTip(_("Maximum exposure time for darks. Choose a value corresponding to the longest camera exposure you will use for guiding.")); + m_pDarkMaxExpTime->SetToolTip(_("Maximum exposure time for darks. Choose a value corresponding to the longest camera " + "exposure you will use for guiding.")); - m_pDarkCount = NewSpinnerInt(this, pFrame->GetTextExtent("9999"), pConfig->Profile.GetInt("/camera/darks_num_frames", DefDarkCount), - 1, 20, 1, _("Number of dark frames for each exposure time")); + m_pDarkCount = NewSpinnerInt(this, pFrame->GetTextExtent("9999"), + pConfig->Profile.GetInt("/camera/darks_num_frames", DefDarkCount), 1, 20, 1, + _("Number of dark frames for each exposure time")); AddTableEntryPair(this, pDarkParams, _("Frames to take for each \n exposure time"), m_pDarkCount); pDarkGroup->Add(pDarkParams, wxSizerFlags().Border(wxALL, 10)); pvSizer->Add(pDarkGroup, wxSizerFlags().Border(wxALL, 10).Expand()); @@ -129,11 +133,14 @@ DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : wxBoxSizer *hSizer = new wxBoxSizer(wxHORIZONTAL); wxStaticText *pInfo = new wxStaticText(this, wxID_ANY, wxEmptyString, wxPoint(-1, -1), wxSize(-1, -1)); m_rbModifyDarkLib = new wxRadioButton(this, wxID_ANY, _("Modify/extend existing dark library")); - m_rbModifyDarkLib->SetToolTip(_("Darks created now will replace older darks having matching exposure times. If different exposure times are used, " + m_rbModifyDarkLib->SetToolTip(_( + "Darks created now will replace older darks having matching exposure times. If different exposure times are used, " "those darks will be added to the library.")); m_rbNewDarkLib = new wxRadioButton(this, wxID_ANY, _("Create entirely new dark library")); - m_rbNewDarkLib->SetToolTip(_("Darks created now will be used to build a completely new dark library - old dark frames will be discarded. You " - " MUST use this option if you've seen alert messages about incompatible frame sizes or mismatches with the current camera.")); + m_rbNewDarkLib->SetToolTip( + _("Darks created now will be used to build a completely new dark library - old dark frames will be discarded. You " + " MUST use this option if you've seen alert messages about incompatible frame sizes or mismatches with the " + "current camera.")); if (pFrame->DarkLibExists(pConfig->GetCurrentProfileId(), false)) { if (pFrame->LoadDarkHandler(true)) @@ -141,8 +148,9 @@ DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : double min_v, max_v; int num; pCamera->GetDarklibProperties(&num, &min_v, &max_v); - pInfo->SetLabel(wxString::Format(_("Existing dark library covers %d exposure times in the range of %g s to %g s"), - num, min_v / 1000., max_v / 1000.)); + pInfo->SetLabel( + wxString::Format(_("Existing dark library covers %d exposure times in the range of %g s to %g s"), num, + min_v / 1000., max_v / 1000.)); m_rbModifyDarkLib->SetValue(true); } else @@ -170,11 +178,13 @@ DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : // Defect map controls wxStaticBoxSizer *pDMapGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Dark Frame Settings")); wxFlexGridSizer *pDMapParams = new wxFlexGridSizer(2, 4, 5, 15); - m_pDefectExpTime = NewSpinnerInt(this, pFrame->GetTextExtent("9999"), pConfig->Profile.GetInt("/camera/dmap_exptime", DefDMExpTime), - 5, 15, 1, _("Exposure time for building defect map")); + m_pDefectExpTime = + NewSpinnerInt(this, pFrame->GetTextExtent("9999"), pConfig->Profile.GetInt("/camera/dmap_exptime", DefDMExpTime), 5, + 15, 1, _("Exposure time for building defect map")); AddTableEntryPair(this, pDMapParams, _("Exposure Time"), m_pDefectExpTime); - m_pNumDefExposures = NewSpinnerInt(this, pFrame->GetTextExtent("9999"), pConfig->Profile.GetInt("/camera/dmap_num_frames", DefDMCount), - 5, 25, 1, _("Number of exposures for building defect map")); + m_pNumDefExposures = + NewSpinnerInt(this, pFrame->GetTextExtent("9999"), pConfig->Profile.GetInt("/camera/dmap_num_frames", DefDMCount), + 5, 25, 1, _("Number of exposures for building defect map")); AddTableEntryPair(this, pDMapParams, _("Number of Exposures"), m_pNumDefExposures); pDMapGroup->Add(pDMapParams, wxSizerFlags().Border(wxALL, 10)); pvSizer->Add(pDMapGroup, wxSizerFlags().Border(wxALL, 10)); @@ -182,7 +192,7 @@ DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : // Controls for notes and status wxBoxSizer *phSizer = new wxBoxSizer(wxHORIZONTAL); - wxStaticText *pNoteLabel = new wxStaticText(this, wxID_ANY, _("Notes: "), wxPoint(-1, -1), wxSize(-1, -1)); + wxStaticText *pNoteLabel = new wxStaticText(this, wxID_ANY, _("Notes: "), wxPoint(-1, -1), wxSize(-1, -1)); wxSize sz(38 * StringWidth(this, "M"), -1); m_pNotes = new wxTextCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, sz); m_pNotes->SetToolTip(_("Free-form note, included in FITs header for each dark frame; max length=65")); @@ -198,7 +208,7 @@ DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : pvSizer->Add(m_pProgress, wxSizerFlags().Border(wxLEFT, 60)); // Buttons - wxBoxSizer *pButtonSizer = new wxBoxSizer( wxHORIZONTAL ); + wxBoxSizer *pButtonSizer = new wxBoxSizer(wxHORIZONTAL); m_pResetBtn = new wxButton(this, wxID_ANY, _("Reset")); m_pResetBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &DarksDialog::OnReset, this); m_pResetBtn->SetToolTip(_("Reset all parameters to application defaults")); @@ -211,15 +221,9 @@ DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : m_pStopBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &DarksDialog::OnStop, this); m_pStopBtn->SetToolTip(""); - pButtonSizer->Add( - m_pResetBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); - pButtonSizer->Add( - m_pStartBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); - pButtonSizer->Add( - m_pStopBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pButtonSizer->Add(m_pResetBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pButtonSizer->Add(m_pStartBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pButtonSizer->Add(m_pStopBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); pvSizer->Add(pButtonSizer, wxSizerFlags().Center().Border(wxALL, 10)); // status bar @@ -229,7 +233,7 @@ DarksDialog::DarksDialog(wxWindow *parent, bool darkLib) : pvSizer->Add(m_pStatusBar, 0, wxGROW); SetAutoLayout(true); - SetSizerAndFit (pvSizer); + SetSizerAndFit(pvSizer); m_cancelling = false; m_started = false; @@ -270,16 +274,16 @@ void DarksDialog::OnStart(wxCommandEvent& evt) tot_dur += exposureDurations[i] * darkFrameCount; m_pProgress->SetRange(tot_dur); - if (m_rbNewDarkLib->GetValue()) // User rebuilding from scratch + if (m_rbNewDarkLib->GetValue()) // User rebuilding from scratch pCamera->ClearDarks(); for (int inx = minExpInx; inx <= maxExpInx; inx++) { int darkExpTime = exposureDurations[inx]; if (darkExpTime >= 1000) - ShowStatus (wxString::Format(_("Building master dark at %.1f sec:"), (double)darkExpTime / 1000.0), false); + ShowStatus(wxString::Format(_("Building master dark at %.1f sec:"), (double) darkExpTime / 1000.0), false); else - ShowStatus (wxString::Format(_("Building master dark at %d mSec:"), darkExpTime), false); + ShowStatus(wxString::Format(_("Building master dark at %d mSec:"), darkExpTime), false); usImage *newDark = new usImage(); err = CreateMasterDarkFrame(*newDark, exposureDurations[inx], darkFrameCount); wxYield(); @@ -296,7 +300,9 @@ void DarksDialog::OnStart(wxCommandEvent& evt) if (m_cancelling || err) { - ShowStatus(m_cancelling ? _("Operation cancelled - no changes have been made") : _("Operation failed - no changes have been made"), false); + ShowStatus(m_cancelling ? _("Operation cancelled - no changes have been made") + : _("Operation failed - no changes have been made"), + false); if (pFrame->DarkLibExists(pConfig->GetCurrentProfileId(), false)) { if (pFrame->LoadDarkHandler(true)) @@ -308,7 +314,7 @@ void DarksDialog::OnStart(wxCommandEvent& evt) else { pFrame->SaveDarkLibrary(m_pNotes->GetValue()); - pFrame->LoadDarkHandler(true); // Put it to use, including selection of matching dark frame + pFrame->LoadDarkHandler(true); // Put it to use, including selection of matching dark frame wrapupMsg = _("dark library built"); if (m_rbNewDarkLib) Debug.AddLine("Dark library - new dark lib created from scratch."); @@ -320,7 +326,7 @@ void DarksDialog::OnStart(wxCommandEvent& evt) else { // Start by computing master dark frame with longish exposure times - ShowStatus(_("Taking darks to compute defect map: "), false); + ShowStatus(_("Taking darks to compute defect map: "), false); int defectFrameCount = m_pNumDefExposures->GetValue(); int defectExpTime = m_pDefectExpTime->GetValue() * 1000; @@ -356,7 +362,7 @@ void DarksDialog::OnStart(wxCommandEvent& evt) m_pStartBtn->Enable(true); m_pResetBtn->Enable(true); - pFrame->SetDarkMenuState(); // Hard to know where we are at this point + pFrame->SetDarkMenuState(); // Hard to know where we are at this point if (m_cancelling || err) { @@ -370,7 +376,7 @@ void DarksDialog::OnStart(wxCommandEvent& evt) // Put up a message showing results and maybe notice to uncover the scope; then close the dialog pCamera->ShutterClosed = false; // Lights if (!pCamera->HasShutter) - wrapupMsg = _("Uncover guide scope") + wxT("\n\n") + wrapupMsg; // Results will appear in smaller font + wrapupMsg = _("Uncover guide scope") + wxT("\n\n") + wrapupMsg; // Results will appear in smaller font wxMessageBox(wxString::Format(_("Operation complete: %s"), wrapupMsg)); EndDialog(wxOK); } @@ -449,7 +455,7 @@ struct Histogram mean += v; v >>= (img.BitsPerPixel - 8); if (v > 255) - v = 255; // should never happen if BitsPerPixel is valid + v = 255; // should never happen if BitsPerPixel is valid ++val[v]; } mean /= img.NPixels; @@ -502,7 +508,7 @@ bool DarksDialog::CreateMasterDarkFrame(usImage& darkFrame, int expTime, int fra err = GuideCamera::Capture(pCamera, expTime, darkFrame, CAPTURE_DARK); if (err) { - ShowStatus(wxString::Format(_("%.1f s dark FAILED"), (double)expTime / 1000.0), true); + ShowStatus(wxString::Format(_("%.1f s dark FAILED"), (double) expTime / 1000.0), true); pCamera->ShutterClosed = false; break; } @@ -512,9 +518,9 @@ bool DarksDialog::CreateMasterDarkFrame(usImage& darkFrame, int expTime, int fra darkFrame.CalcStats(); - Debug.Write(wxString::Format("dark frame stats: bpp %u min %u max %u med %u filtmin %u filtmax %u\n", - darkFrame.BitsPerPixel, darkFrame.MinADU, darkFrame.MaxADU, - darkFrame.MedianADU, darkFrame.FiltMin, darkFrame.FiltMax)); + Debug.Write( + wxString::Format("dark frame stats: bpp %u min %u max %u med %u filtmin %u filtmax %u\n", darkFrame.BitsPerPixel, + darkFrame.MinADU, darkFrame.MaxADU, darkFrame.MedianADU, darkFrame.FiltMin, darkFrame.FiltMax)); Histogram h(darkFrame); h.Dump(); @@ -538,7 +544,7 @@ bool DarksDialog::CreateMasterDarkFrame(usImage& darkFrame, int expTime, int fra const unsigned int *iptr = avgimg; unsigned short *usptr = darkFrame.ImageData; for (unsigned int i = 0; i < darkFrame.NPixels; i++) - *usptr++ = (unsigned short)(*iptr++ / frameCount); + *usptr++ = (unsigned short) (*iptr++ / frameCount); } m_pProgress->SetValue(m_pProgress->GetValue() + expTime); @@ -549,6 +555,4 @@ bool DarksDialog::CreateMasterDarkFrame(usImage& darkFrame, int expTime, int fra return err; } -DarksDialog::~DarksDialog(void) -{ -} +DarksDialog::~DarksDialog(void) { } diff --git a/src/darks_dialog.h b/src/darks_dialog.h index eae9adb93..e1503e0f9 100644 --- a/src/darks_dialog.h +++ b/src/darks_dialog.h @@ -69,7 +69,6 @@ class DarksDialog : public wxDialog private: bool buildDarkLib; - }; #endif diff --git a/src/debuglog.cpp b/src/debuglog.cpp index ac00b6b48..5d3532b3f 100644 --- a/src/debuglog.cpp +++ b/src/debuglog.cpp @@ -41,9 +41,8 @@ const int RetentionPeriod = 30; DebugLog::DebugLog() - : - m_enabled(false), - m_lastWriteTime(wxDateTime::UNow()) + : m_enabled(false) + , m_lastWriteTime(wxDateTime::UNow()) { } @@ -57,8 +56,7 @@ static bool ParseLogTimestamp(wxDateTime *p, const wxString& s) { wxDateTime dt; wxString::const_iterator iter; - if (dt.ParseFormat(s, "%Y-%m-%d_%H%M%S", wxDateTime(), &iter) && - iter == s.end()) + if (dt.ParseFormat(s, "%Y-%m-%d_%H%M%S", wxDateTime(), &iter) && iter == s.end()) { *p = dt; return true; @@ -77,9 +75,8 @@ wxDateTime DebugLog::GetLogFileTime() while (cont) { wxDateTime dt; - if (filename.length() == 35 && - ParseLogTimestamp(&dt, filename.substr(14, 17)) - && (!latest.IsValid() || dt.IsLaterThan(latest))) + if (filename.length() == 35 && ParseLogTimestamp(&dt, filename.substr(14, 17)) && + (!latest.IsValid() || dt.IsLaterThan(latest))) { latest = dt; } @@ -161,7 +158,7 @@ wxString DebugLog::AddBytes(const wxString& str, const unsigned char *pBytes, un { wxString Line = str + " - "; - for (unsigned int i=0; i < count; i++) + for (unsigned int i = 0; i < count; i++) { unsigned char ch = pBytes[i]; Line += wxString::Format("%2.2X (%c) ", ch, isprint(ch) ? ch : '?'); @@ -193,10 +190,8 @@ wxString DebugLog::Write(const wxString& str) wxDateTime now = wxDateTime::UNow(); wxTimeSpan deltaTime = now - m_lastWriteTime; m_lastWriteTime = now; - wxString outputLine = wxString::Format("%s %s %lu %s", now.Format("%H:%M:%S.%l"), - deltaTime.Format("%S.%l"), - (unsigned long) wxThread::GetCurrentId(), - str); + wxString outputLine = wxString::Format("%s %s %lu %s", now.Format("%H:%M:%S.%l"), deltaTime.Format("%S.%l"), + (unsigned long) wxThread::GetCurrentId(), str); wxFFile::Write(outputLine); #if defined(ALWAYS_FLUSH_DEBUGLOG) @@ -210,25 +205,25 @@ wxString DebugLog::Write(const wxString& str) return str; } -DebugLog& operator<< (DebugLog& out, const wxString &str) +DebugLog& operator<<(DebugLog& out, const wxString& str) { out.Write(str); return out; } -DebugLog& operator<< (DebugLog& out, const char *str) +DebugLog& operator<<(DebugLog& out, const char *str) { out.Write(str); return out; } -DebugLog& operator<< (DebugLog& out, const int i) +DebugLog& operator<<(DebugLog& out, const int i) { out.Write(wxString::Format(_T("%d"), i)); return out; } -DebugLog& operator<< (DebugLog& out, const double d) +DebugLog& operator<<(DebugLog& out, const double d) { out.Write(wxString::Format(_T("%f"), d)); return out; diff --git a/src/debuglog.h b/src/debuglog.h index 21fc34377..547f85989 100644 --- a/src/debuglog.h +++ b/src/debuglog.h @@ -63,10 +63,10 @@ class DebugLog : public wxFFile, public Logger void RemoveOldFiles(); }; -extern DebugLog& operator<< (DebugLog& out, const wxString& str); -extern DebugLog& operator<< (DebugLog& out, const char *str); -extern DebugLog& operator<< (DebugLog& out, const int i); -extern DebugLog& operator<< (DebugLog& out, const double d); +extern DebugLog& operator<<(DebugLog& out, const wxString& str); +extern DebugLog& operator<<(DebugLog& out, const char *str); +extern DebugLog& operator<<(DebugLog& out, const int i); +extern DebugLog& operator<<(DebugLog& out, const double d); inline bool DebugLog::IsEnabled() const { diff --git a/src/drift_tool.cpp b/src/drift_tool.cpp index 729a29516..ba790d59b 100644 --- a/src/drift_tool.cpp +++ b/src/drift_tool.cpp @@ -116,7 +116,7 @@ struct DriftToolWin : public wxFrame void UpdateScopeCoordinates(void); - void SetStatusText(const wxString &text, int number = 0) override; + void SetStatusText(const wxString& text, int number = 0) override; wxDECLARE_EVENT_TABLE(); }; @@ -136,9 +136,10 @@ wxEND_EVENT_TABLE(); DriftToolWin::DriftToolWin() : wxFrame(pFrame, wxID_ANY, _("Drift Align"), wxDefaultPosition, wxDefaultSize, - wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxTAB_TRAVERSAL|wxFRAME_FLOAT_ON_PARENT|wxFRAME_NO_TASKBAR), - m_need_end_dec_drift(false), - m_slewing(false) + wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxFRAME_FLOAT_ON_PARENT | + wxFRAME_NO_TASKBAR) + , m_need_end_dec_drift(false) + , m_slewing(false) { SetSizeHints(wxDefaultSize, wxDefaultSize); @@ -148,20 +149,21 @@ DriftToolWin::DriftToolWin() // a horizontal box sizer for the bitmap and the instructions wxBoxSizer *instrSizer = new wxBoxSizer(wxHORIZONTAL); -# include "icons/AzArrow.xpm" +#include "icons/AzArrow.xpm" m_azArrowBmp = new wxBitmap(AzArrow); -# include "icons/AltArrow.xpm" +#include "icons/AltArrow.xpm" m_altArrowBmp = new wxBitmap(AltArrow); m_bmp = new wxStaticBitmap(this, wxID_ANY, *m_azArrowBmp, wxDefaultPosition, wxSize(80, 100)); - instrSizer->Add(m_bmp, 0, wxALIGN_CENTER_VERTICAL|wxFIXED_MINSIZE, 5); + instrSizer->Add(m_bmp, 0, wxALIGN_CENTER_VERTICAL | wxFIXED_MINSIZE, 5); - m_instructions = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(400,120), wxALIGN_LEFT|wxST_NO_AUTORESIZE); + m_instructions = + new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(400, 120), wxALIGN_LEFT | wxST_NO_AUTORESIZE); #ifdef __WXOSX__ m_instructions->SetFont(*wxSMALL_FONT); #endif m_instructions->Wrap(-1); - instrSizer->Add(m_instructions, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); + instrSizer->Add(m_instructions, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); topSizer->Add(instrSizer); @@ -219,14 +221,14 @@ DriftToolWin::DriftToolWin() sbSizer->Add(gbSizer, 1, wxALIGN_CENTER, 5); // add static sizer to top-level sizer - topSizer->Add(sbSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); + topSizer->Add(sbSizer, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); // add some padding below the static sizer topSizer->Add(0, 3, 0, wxEXPAND, 3); m_notesLabel = new wxStaticText(this, wxID_ANY, _("Altitude adjustment notes")); m_notesLabel->Wrap(-1); - topSizer->Add(m_notesLabel, 0, wxEXPAND|wxTOP|wxLEFT, 8); + topSizer->Add(m_notesLabel, 0, wxEXPAND | wxTOP | wxLEFT, 8); m_notes = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(-1, 54), wxTE_MULTILINE); pFrame->RegisterTextCtrl(m_notes); @@ -240,22 +242,22 @@ DriftToolWin::DriftToolWin() hSizer->Add(0, 0, 2, wxEXPAND, 5); m_drift = new wxButton(this, ID_DRIFT, _("Drift")); - hSizer->Add(m_drift, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); + hSizer->Add(m_drift, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); // proportional pad on right of Drift button hSizer->Add(0, 0, 1, wxEXPAND, 5); m_adjust = new wxButton(this, ID_ADJUST, _("Adjust")); - hSizer->Add(m_adjust, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); + hSizer->Add(m_adjust, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); // proportional pad on right of Align button hSizer->Add(0, 0, 2, wxEXPAND, 5); m_phaseBtn = new wxButton(this, ID_PHASE, wxT("???")); - hSizer->Add(m_phaseBtn, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5); + hSizer->Add(m_phaseBtn, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); // add button sizer to top level sizer - topSizer->Add(hSizer, 1, wxEXPAND|wxALL, 5); + topSizer->Add(hSizer, 1, wxEXPAND | wxALL, 5); SetSizer(topSizer); @@ -282,7 +284,10 @@ DriftToolWin::DriftToolWin() m_timer = NULL; if (m_can_slew || (pPointingSource && pPointingSource->CanReportPosition())) { - enum { SCOPE_POS_POLL_MS = 1500 }; + enum + { + SCOPE_POS_POLL_MS = 1500 + }; m_timer = new wxTimer(this, ID_TIMER); m_timer->Start(SCOPE_POS_POLL_MS, false /* continuous */); } @@ -374,12 +379,11 @@ void DriftToolWin::UpdatePhaseState() { SetTitle(_("Drift Align - Azimuth Adjustment")); m_bmp->SetBitmap(*m_azArrowBmp); - m_instructions->SetLabel( - _("Slew to near the Meridian and the Equator.\n" - "Press Drift to measure drift, watch the Dec trend line.\n" - "Press Adjust and adjust your mount's azimuth.\n" - "Repeat Drift/Adjust until alignment is complete.\n" - "Then, click Altitude to begin Altitude adjustment.")); + m_instructions->SetLabel(_("Slew to near the Meridian and the Equator.\n" + "Press Drift to measure drift, watch the Dec trend line.\n" + "Press Adjust and adjust your mount's azimuth.\n" + "Repeat Drift/Adjust until alignment is complete.\n" + "Then, click Altitude to begin Altitude adjustment.")); m_notesLabel->SetLabel(_("Azimuth adjustment notes")); m_notes->SetValue(pConfig->Profile.GetString("/DriftTool/Az/Notes", wxEmptyString)); m_phaseBtn->SetLabel(_("> Altitude")); @@ -388,12 +392,11 @@ void DriftToolWin::UpdatePhaseState() { SetTitle(_("Drift Align - Altitude Adjustment")); m_bmp->SetBitmap(*m_altArrowBmp); - m_instructions->SetLabel( - _("Slew to a location near the Equator and the Eastern or Western horizon.\n" - "Press Drift to measure drift, watch the Dec trend line.\n" - "Press Adjust and adjust your mount's altitude.\n" - "Repeat Drift/Adjust until alignment is complete.\n" - "Click Azimuth to repeat Azimuth adjustment.")); + m_instructions->SetLabel(_("Slew to a location near the Equator and the Eastern or Western horizon.\n" + "Press Drift to measure drift, watch the Dec trend line.\n" + "Press Adjust and adjust your mount's altitude.\n" + "Repeat Drift/Adjust until alignment is complete.\n" + "Click Azimuth to repeat Azimuth adjustment.")); m_notesLabel->SetLabel(_("Altitude adjustment notes")); m_notes->SetValue(pConfig->Profile.GetString("/DriftTool/Alt/Notes", wxEmptyString)); m_phaseBtn->SetLabel(_("< Azimuth")); @@ -420,8 +423,7 @@ void DriftToolWin::UpdateModeState() if (!m_drifting) { - if (!pCamera->Connected || - !pMount || !pMount->IsConnected()) + if (!pCamera->Connected || !pMount || !pMount->IsConnected()) { idleStatus = _("Please connect a camera and a mount"); m_mode = MODE_IDLE; @@ -465,7 +467,8 @@ void DriftToolWin::UpdateModeState() SetStatusText(_("Start guiding...")); pFrame->GuideButtonClick(false, _T("DriftTool:drift")); return; - case STATE_GUIDING: { + case STATE_GUIDING: + { // turn of dec guiding if (!m_need_end_dec_drift) { @@ -491,8 +494,8 @@ void DriftToolWin::UpdateModeState() m_adjust->Enable(false); m_drifting = false; EnableSlew(m_can_slew); - SetStatusText(m_phase == PHASE_ADJUST_AZ ? _("Adjust azimuth, click Drift when done") : - _("Adjust altitude, click Drift when done")); + SetStatusText(m_phase == PHASE_ADJUST_AZ ? _("Adjust azimuth, click Drift when done") + : _("Adjust altitude, click Drift when done")); // use full frames for adjust phase pCamera->UseSubframes = false; @@ -504,9 +507,10 @@ void DriftToolWin::UpdateModeState() // Set the lock position to the where the star has drifted to. This will be the center of the polar align circle. pFrame->pGuider->SetLockPosition(pFrame->pGuider->CurrentPosition()); - // Make sure guider does not react to star lost (like by invalidating the lock position) while adjustment is in progress + // Make sure guider does not react to star lost (like by invalidating the lock position) while adjustment is in + // progress pFrame->pGuider->SetIgnoreLostStarLooping(true); - pFrame->pGraphLog->Refresh(); // polar align circle is updated in graph window's OnPaint handler + pFrame->pGraphLog->Refresh(); // polar align circle is updated in graph window's OnPaint handler } } else // MODE_IDLE @@ -545,8 +549,8 @@ void DriftToolWin::OnSlew(wxCommandEvent& evt) double slew_ra = norm_ra(cur_st + (raSlew * 24.0 / 360.0)); - Debug.Write(wxString::Format("Drift tool: slew from ra %.2f, dec %.1f to ra %.2f, dec %.1f\n", - cur_ra, cur_dec, slew_ra, decSlew)); + Debug.Write( + wxString::Format("Drift tool: slew from ra %.2f, dec %.1f to ra %.2f, dec %.1f\n", cur_ra, cur_dec, slew_ra, decSlew)); if (pPointingSource->CanSlewAsync()) { @@ -554,7 +558,9 @@ void DriftToolWin::OnSlew(wxCommandEvent& evt) { double ra, dec; SlewInBg(wxWindow *parent, double ra_, double dec_) - : RunInBg(parent, _("Slew"), _("Slewing...")), ra(ra_), dec(dec_) + : RunInBg(parent, _("Slew"), _("Slewing...")) + , ra(ra_) + , dec(dec_) { SetPopupDelay(100); } @@ -808,7 +814,7 @@ void DriftToolWin::OnTimer(wxTimerEvent& evt) } } -void DriftToolWin::SetStatusText(const wxString &text, int number) +void DriftToolWin::SetStatusText(const wxString& text, int number) { Debug.Write(wxString::Format("Drift tool: status: %s\n", text)); wxFrame::SetStatusText(text, number); @@ -826,15 +832,14 @@ wxWindow *DriftTool::CreateDriftToolWindow() if (pFrame->GetCameraPixelScale() == 1.0) { - bool confirmed = ConfirmDialog::Confirm(_( - "The Drift Align tool is most effective when PHD2 knows your guide\n" - "scope focal length and camera pixel size.\n" - "\n" - "Enter your guide scope focal length on the Global tab in the Brain.\n" - "Enter your camera pixel size on the Camera tab in the Brain.\n" - "\n" - "Would you like to run the drift tool anyway?"), - "/drift_tool_without_pixscale"); + bool confirmed = ConfirmDialog::Confirm(_("The Drift Align tool is most effective when PHD2 knows your guide\n" + "scope focal length and camera pixel size.\n" + "\n" + "Enter your guide scope focal length on the Global tab in the Brain.\n" + "Enter your camera pixel size on the Camera tab in the Brain.\n" + "\n" + "Would you like to run the drift tool anyway?"), + "/drift_tool_without_pixscale"); if (!confirmed) { diff --git a/src/eegg.cpp b/src/eegg.cpp index 2a379fea3..6b055be38 100644 --- a/src/eegg.cpp +++ b/src/eegg.cpp @@ -45,7 +45,8 @@ static wxString FlipCalEnabledKey() { - // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting to be per-profile + // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting + // to be per-profile return wxString::Format("/Confirm/%d/FlipCalWarningEnabled", pConfig->GetCurrentProfileId()); } @@ -77,7 +78,7 @@ void MyFrame::OnEEGG(wxCommandEvent& evt) } else { - if (pCalReviewDlg) // Review dialog is non-modal + if (pCalReviewDlg) // Review dialog is non-modal pCalReviewDlg->Destroy(); pCalReviewDlg = new CalReviewDialog(this); pCalReviewDlg->Show(); @@ -88,8 +89,8 @@ void MyFrame::OnEEGG(wxCommandEvent& evt) if (pMount) { Calibration cal; - cal.xRate = pMount->xRate(); - cal.yRate = pMount->yRate(); + cal.xRate = pMount->xRate(); + cal.yRate = pMount->yRate(); cal.xAngle = pMount->xAngle(); cal.yAngle = pMount->yAngle(); cal.declination = pPointingSource->GetDeclinationRadians(); @@ -101,15 +102,15 @@ void MyFrame::OnEEGG(wxCommandEvent& evt) if (!pMount->IsCalibrated()) { - cal.xRate = 1.0; - cal.yRate = 1.0; - cal.xAngle = 0.0; - cal.yAngle = M_PI / 2.; + cal.xRate = 1.0; + cal.yRate = 1.0; + cal.xAngle = 0.0; + cal.yAngle = M_PI / 2.; cal.declination = UNKNOWN_DECLINATION; } ManualCalDialog manualcal(cal); - if (manualcal.ShowModal () == wxID_OK) + if (manualcal.ShowModal() == wxID_OK) { manualcal.GetValues(&cal); pMount->SetCalibration(cal); @@ -134,8 +135,10 @@ void MyFrame::OnEEGG(wxCommandEvent& evt) } if (devicestr.Length() > 0) { - if (wxMessageBox(wxString::Format(_("%s calibration will be cleared - calibration will be re-done when guiding is started."), devicestr), - _("Clear Calibration"), wxOK | wxCANCEL) == wxOK) + if (wxMessageBox(wxString::Format( + _("%s calibration will be cleared - calibration will be re-done when guiding is started."), + devicestr), + _("Clear Calibration"), wxOK | wxCANCEL) == wxOK) { if (pMount) pMount->ClearCalibration(); @@ -168,22 +171,24 @@ void MyFrame::OnEEGG(wxCommandEvent& evt) lastCal.pierSide != PIER_SIDE_UNKNOWN) { pFrame->SuppressableAlert(FlipCalEnabledKey(), - _("This is unnecessary because PHD2 has pointing info from the mount. If you are seeing run-away Dec guiding " - "after a meridian flip, use Help and look in the index for 'Reverse Dec output'."), + _("This is unnecessary because PHD2 has pointing info from the mount. If you are seeing run-away Dec " + "guiding " + "after a meridian flip, use Help and look in the index for 'Reverse Dec output'."), SuppressFlipCalAlert, 0, true); } else { if (FlipCalibrationData()) { - wxMessageBox(_("Failed to flip calibration - please upload debug log file to PHD2 forum for assistance.")); + wxMessageBox( + _("Failed to flip calibration - please upload debug log file to PHD2 forum for assistance.")); } else { double xnew = degrees(scope->xAngle()); double ynew = degrees(scope->yAngle()); - wxMessageBox(wxString::Format(_("Calibration angles flipped: (%.2f, %.2f) to (%.2f, %.2f)"), - xorig, yorig, xnew, ynew)); + wxMessageBox(wxString::Format( + _("Calibration angles flipped: (%.2f, %.2f) to (%.2f, %.2f)"), xorig, yorig, xnew, ynew)); } } } @@ -287,12 +292,10 @@ void MyFrame::OnGuidingAssistant(wxCommandEvent& WXUNUSED(evt)) if (pFrame->pGuider->IsGuiding()) { - ok = ConfirmDialog::Confirm(_( - "The Guiding Assitant will disable guide output and\n" - "allow the guide star to drift.\n" - "\n" - "Ok to disable guide output?" - ), + ok = ConfirmDialog::Confirm(_("The Guiding Assitant will disable guide output and\n" + "allow the guide star to drift.\n" + "\n" + "Ok to disable guide output?"), "/guiding_assistant_while_guiding", _("Confirm Disable Guiding")); } diff --git a/src/event_server.cpp b/src/event_server.cpp index 889ce966d..bb3a05b6b 100644 --- a/src/event_server.cpp +++ b/src/event_server.cpp @@ -61,14 +61,22 @@ static wxString state_name(EXPOSED_STATE st) { switch (st) { - case EXPOSED_STATE_NONE: return "Stopped"; - case EXPOSED_STATE_SELECTED: return "Selected"; - case EXPOSED_STATE_CALIBRATING: return "Calibrating"; - case EXPOSED_STATE_GUIDING_LOCKED: return "Guiding"; - case EXPOSED_STATE_GUIDING_LOST: return "LostLock"; - case EXPOSED_STATE_PAUSED: return "Paused"; - case EXPOSED_STATE_LOOPING: return "Looping"; - default: return "Unknown"; + case EXPOSED_STATE_NONE: + return "Stopped"; + case EXPOSED_STATE_SELECTED: + return "Selected"; + case EXPOSED_STATE_CALIBRATING: + return "Calibrating"; + case EXPOSED_STATE_GUIDING_LOCKED: + return "Guiding"; + case EXPOSED_STATE_GUIDING_LOST: + return "LostLock"; + case EXPOSED_STATE_PAUSED: + return "Paused"; + case EXPOSED_STATE_LOOPING: + return "Looping"; + default: + return "Unknown"; } } @@ -96,9 +104,23 @@ struct JSeq wxString m_s; bool m_first; bool m_closed; - JSeq() : m_first(true), m_closed(false) { m_s << LDELIM; } - void close() { m_s << RDELIM; m_closed = true; } - wxString str() { if (!m_closed) close(); return m_s; } + JSeq() + : m_first(true) + , m_closed(false) + { + m_s << LDELIM; + } + void close() + { + m_s << RDELIM; + m_closed = true; + } + wxString str() + { + if (!m_closed) + close(); + return m_s; + } }; typedef JSeq<'[', ']'> JAry; @@ -129,13 +151,16 @@ static wxString json_format(const json_value *j) if (!j) return literal_null; - switch (j->type) { + switch (j->type) + { default: - case JSON_NULL: return literal_null; - case JSON_OBJECT: { + case JSON_NULL: + return literal_null; + case JSON_OBJECT: + { wxString ret("{"); bool first = true; - json_for_each (jj, j) + json_for_each(jj, j) { if (first) first = false; @@ -146,10 +171,11 @@ static wxString json_format(const json_value *j) ret << "}"; return ret; } - case JSON_ARRAY: { + case JSON_ARRAY: + { wxString ret("["); bool first = true; - json_for_each (jj, j) + json_for_each(jj, j) { if (first) first = false; @@ -160,37 +186,109 @@ static wxString json_format(const json_value *j) ret << "]"; return ret; } - case JSON_STRING: return '"' + json_escape(j->string_value) + '"'; - case JSON_INT: return wxString::Format("%d", j->int_value); - case JSON_FLOAT: return wxString::Format("%g", (double) j->float_value); - case JSON_BOOL: return j->int_value ? literal_true : literal_false; + case JSON_STRING: + return '"' + json_escape(j->string_value) + '"'; + case JSON_INT: + return wxString::Format("%d", j->int_value); + case JSON_FLOAT: + return wxString::Format("%g", (double) j->float_value); + case JSON_BOOL: + return j->int_value ? literal_true : literal_false; } } -struct NULL_TYPE { } NULL_VALUE; +struct NULL_TYPE +{ +} NULL_VALUE; // name-value pair struct NV { wxString n; wxString v; - NV(const wxString& n_, const wxString& v_) : n(n_), v('"' + json_escape(v_) + '"') { } - NV(const wxString& n_, const char *v_) : n(n_), v('"' + json_escape(v_) + '"') { } - NV(const wxString& n_, const wchar_t *v_) : n(n_), v('"' + json_escape(v_) + '"') { } - NV(const wxString& n_, int v_) : n(n_), v(wxString::Format("%d", v_)) { } - NV(const wxString& n_, unsigned int v_) : n(n_), v(wxString::Format("%u", v_)) { } - NV(const wxString& n_, double v_) : n(n_), v(wxString::Format("%g", v_)) { } - NV(const wxString& n_, double v_, int prec) : n(n_), v(wxString::Format("%.*f", prec, v_)) { } - NV(const wxString& n_, bool v_) : n(n_), v(v_ ? literal_true : literal_false) { } + NV(const wxString& n_, const wxString& v_) + : n(n_) + , v('"' + json_escape(v_) + '"') + { + } + NV(const wxString& n_, const char *v_) + : n(n_) + , v('"' + json_escape(v_) + '"') + { + } + NV(const wxString& n_, const wchar_t *v_) + : n(n_) + , v('"' + json_escape(v_) + '"') + { + } + NV(const wxString& n_, int v_) + : n(n_) + , v(wxString::Format("%d", v_)) + { + } + NV(const wxString& n_, unsigned int v_) + : n(n_) + , v(wxString::Format("%u", v_)) + { + } + NV(const wxString& n_, double v_) + : n(n_) + , v(wxString::Format("%g", v_)) + { + } + NV(const wxString& n_, double v_, int prec) + : n(n_) + , v(wxString::Format("%.*f", prec, v_)) + { + } + NV(const wxString& n_, bool v_) + : n(n_) + , v(v_ ? literal_true : literal_false) + { + } template NV(const wxString& n_, const std::vector& vec); - NV(const wxString& n_, JAry& ary) : n(n_), v(ary.str()) { } - NV(const wxString& n_, JObj& obj) : n(n_), v(obj.str()) { } - NV(const wxString& n_, const json_value *v_) : n(n_), v(json_format(v_)) { } - NV(const wxString& n_, const PHD_Point& p) : n(n_) { JAry ary; ary << p.X << p.Y; v = ary.str(); } - NV(const wxString& n_, const wxPoint& p) : n(n_) { JAry ary; ary << p.x << p.y; v = ary.str(); } - NV(const wxString& n_, const wxSize& s) : n(n_) { JAry ary; ary << s.x << s.y; v = ary.str(); } - NV(const wxString& n_, const NULL_TYPE& nul) : n(n_), v(literal_null) { } + NV(const wxString& n_, JAry& ary) + : n(n_) + , v(ary.str()) + { + } + NV(const wxString& n_, JObj& obj) + : n(n_) + , v(obj.str()) + { + } + NV(const wxString& n_, const json_value *v_) + : n(n_) + , v(json_format(v_)) + { + } + NV(const wxString& n_, const PHD_Point& p) + : n(n_) + { + JAry ary; + ary << p.X << p.Y; + v = ary.str(); + } + NV(const wxString& n_, const wxPoint& p) + : n(n_) + { + JAry ary; + ary << p.x << p.y; + v = ary.str(); + } + NV(const wxString& n_, const wxSize& s) + : n(n_) + { + JAry ary; + ary << s.x << s.y; + v = ary.str(); + } + NV(const wxString& n_, const NULL_TYPE& nul) + : n(n_) + , v(literal_null) + { + } }; template @@ -239,20 +337,16 @@ struct Ev : public JObj Ev(const wxString& event) { double const now = ::wxGetUTCTimeMillis().ToDouble() / 1000.0; - *this << NV("Event", event) - << NV("Timestamp", now, 3) - << NV("Host", wxGetHostName()) - << NV("Inst", wxGetApp().GetInstanceNumber()); + *this << NV("Event", event) << NV("Timestamp", now, 3) << NV("Host", wxGetHostName()) + << NV("Inst", wxGetApp().GetInstanceNumber()); } }; static Ev ev_message_version() { Ev ev("Version"); - ev << NV("PHDVersion", PHDVERSION) - << NV("PHDSubver", PHDSUBVER) - << NV("OverlapSupport", true) - << NV("MsgVersion", MSG_PROTOCOL_VERSION); + ev << NV("PHDVersion", PHDVERSION) << NV("PHDSubver", PHDSUBVER) << NV("OverlapSupport", true) + << NV("MsgVersion", MSG_PROTOCOL_VERSION); return ev; } @@ -311,10 +405,7 @@ static Ev ev_settling(double distance, double time, double settleTime, bool star { Ev ev("Settling"); - ev << NV("Distance", distance, 2) - << NV("Time", time, 1) - << NV("SettleTime", settleTime, 1) - << NV("StarLocked", starLocked); + ev << NV("Distance", distance, 2) << NV("Time", time, 1) << NV("SettleTime", settleTime, 1) << NV("StarLocked", starLocked); return ev; } @@ -332,15 +423,17 @@ static Ev ev_settle_done(const wxString& errorMsg, int settleFrames, int dropped ev << NV("Error", errorMsg); } - ev << NV("TotalFrames", settleFrames) - << NV("DroppedFrames", droppedFrames); + ev << NV("TotalFrames", settleFrames) << NV("DroppedFrames", droppedFrames); return ev; } struct ClientReadBuf { - enum { SIZE = 1024 }; + enum + { + SIZE = 1024 + }; char m_buf[SIZE]; char *dest; @@ -358,7 +451,11 @@ struct ClientData ClientReadBuf rdbuf; wxMutex wrlock; - ClientData(wxSocketClient *cli_) : cli(cli_), refcnt(1) { } + ClientData(wxSocketClient *cli_) + : cli(cli_) + , refcnt(1) + { + } void AddRef() { ++refcnt; } void RemoveRef() { @@ -373,7 +470,11 @@ struct ClientData struct ClientDataGuard { ClientData *cd; - ClientDataGuard(wxSocketClient *cli) : cd((ClientData *) cli->GetClientData()) { cd->AddRef(); } + ClientDataGuard(wxSocketClient *cli) + : cd((ClientData *) cli->GetClientData()) + { + cd->AddRef(); + } ~ClientDataGuard() { cd->RemoveRef(); } ClientData *operator->() const { return cd; } }; @@ -385,18 +486,30 @@ inline static wxMutex *client_wrlock(wxSocketClient *cli) static wxString SockErrStr(wxSocketError e) { - switch (e) { - case wxSOCKET_NOERROR: return ""; - case wxSOCKET_INVOP: return "Invalid operation"; - case wxSOCKET_IOERR: return "Input / Output error"; - case wxSOCKET_INVADDR: return "Invalid address"; - case wxSOCKET_INVSOCK: return "Invalid socket(uninitialized)"; - case wxSOCKET_NOHOST: return "No corresponding host"; - case wxSOCKET_INVPORT: return "Invalid port"; - case wxSOCKET_WOULDBLOCK: return "operation would block"; - case wxSOCKET_TIMEDOUT: return "timeout expired"; - case wxSOCKET_MEMERR: return "Memory exhausted"; - default: return wxString::Format("unknown socket error %d", e); + switch (e) + { + case wxSOCKET_NOERROR: + return ""; + case wxSOCKET_INVOP: + return "Invalid operation"; + case wxSOCKET_IOERR: + return "Input / Output error"; + case wxSOCKET_INVADDR: + return "Invalid address"; + case wxSOCKET_INVSOCK: + return "Invalid socket(uninitialized)"; + case wxSOCKET_NOHOST: + return "No corresponding host"; + case wxSOCKET_INVPORT: + return "Invalid port"; + case wxSOCKET_WOULDBLOCK: + return "operation would block"; + case wxSOCKET_TIMEDOUT: + return "timeout expired"; + case wxSOCKET_MEMERR: + return "Memory exhausted"; + default: + return wxString::Format("unknown socket error %d", e); } } @@ -406,9 +519,8 @@ static void send_buf(wxSocketClient *client, const wxCharBuffer& buf) client->Write(buf.data(), buf.length()); if (client->LastWriteCount() != buf.length()) { - Debug.Write(wxString::Format("evsrv: cli %p short write %u/%u %s\n", - client, client->LastWriteCount(), (unsigned int) buf.length(), - SockErrStr(client->Error() ? client->LastError() : wxSOCKET_NOERROR))); + Debug.Write(wxString::Format("evsrv: cli %p short write %u/%u %s\n", client, client->LastWriteCount(), + (unsigned int) buf.length(), SockErrStr(client->Error() ? client->LastError() : wxSOCKET_NOERROR))); } } @@ -426,8 +538,7 @@ static void do_notify(const EventServer::CliSockSet& cli, const JObj& jj) { wxCharBuffer buf = (JObj(jj).str() + "\r\n").ToUTF8(); - for (EventServer::CliSockSet::const_iterator it = cli.begin(); - it != cli.end(); ++it) + for (EventServer::CliSockSet::const_iterator it = cli.begin(); it != cli.end(); ++it) { send_buf(*it, buf); } @@ -480,7 +591,8 @@ static void send_catchup_events(wxSocketClient *cli) mount = pSecondaryMount; do_notify1(cli, ev_start_calibration(mount)); } - else if (st == EXPOSED_STATE_PAUSED) { + else if (st == EXPOSED_STATE_PAUSED) + { do_notify1(cli, ev_paused()); } @@ -503,7 +615,8 @@ static void drain_input(wxSocketInputStream& sis) } } -enum { +enum +{ JSONRPC_PARSE_ERROR = -32700, JSONRPC_INVALID_REQUEST = -32600, JSONRPC_METHOD_NOT_FOUND = -32601, @@ -542,19 +655,17 @@ struct JRpcResponse : public JObj static wxString parser_error(const JsonParser& parser) { - return wxString::Format("invalid JSON request: %s on line %d at \"%.12s...\"", - parser.ErrorDesc(), parser.ErrorLine(), parser.ErrorPos()); + return wxString::Format( + "invalid JSON request: %s on line %d at \"%.12s...\"", parser.ErrorDesc(), parser.ErrorLine(), parser.ErrorPos()); } -static void -parse_request(const json_value *req, const json_value **pmethod, const json_value **pparams, - const json_value **pid) +static void parse_request(const json_value *req, const json_value **pmethod, const json_value **pparams, const json_value **pid) { *pmethod = *pparams = *pid = 0; if (req) { - json_for_each (t, req) + json_for_each(t, req) { if (t->name) { @@ -570,13 +681,15 @@ parse_request(const json_value *req, const json_value **pmethod, const json_valu } // paranoia -#define VERIFY_GUIDER(response) do { \ - if (!pFrame || !pFrame->pGuider) \ - { \ - response << jrpc_error(1, "internal error"); \ - return; \ - } \ -} while (0) +#define VERIFY_GUIDER(response) \ + do \ + { \ + if (!pFrame || !pFrame->pGuider) \ + { \ + response << jrpc_error(1, "internal error"); \ + return; \ + } \ + } while (0) static void deselect_star(JObj& response, const json_value *params) { @@ -710,7 +823,7 @@ static void get_current_equipment(JObj& response, const json_value *params) JObj t; if (pCamera) - devstat(t, "camera", pCamera->Name, pCamera->Connected); + devstat(t, "camera", pCamera->Name, pCamera->Connected); Mount *mount = TheScope(); if (mount) @@ -733,8 +846,7 @@ static void get_current_equipment(JObj& response, const json_value *params) static bool all_equipment_connected() { - return pCamera && pCamera->Connected && - (!pMount || pMount->IsConnected()) && + return pCamera && pCamera->Connected && (!pMount || pMount->IsConnected()) && (!pSecondaryMount || pSecondaryMount->IsConnected()); } @@ -781,8 +893,7 @@ static void set_connected(JObj& response, const json_value *params) VERIFY_GUIDER(response); wxString errMsg; - bool error = val->int_value ? pFrame->pGearDialog->ConnectAll(&errMsg) : - pFrame->pGearDialog->DisconnectAll(&errMsg); + bool error = val->int_value ? pFrame->pGearDialog->ConnectAll(&errMsg) : pFrame->pGearDialog->DisconnectAll(&errMsg); if (error) { @@ -1028,7 +1139,10 @@ inline static const char *string_val(const json_value *j) enum WHICH_MOUNT { - MOUNT, AO, WHICH_MOUNT_BOTH, WHICH_MOUNT_ERR + MOUNT, + AO, + WHICH_MOUNT_BOTH, + WHICH_MOUNT_ERR }; static WHICH_MOUNT which_mount(const json_value *p) @@ -1068,9 +1182,15 @@ static void clear_calibration(JObj& response, const json_value *params) WHICH_MOUNT which = which_mount(p.param("which")); switch (which) { - case MOUNT: clear_mount = true; break; - case AO: clear_ao = true; break; - case WHICH_MOUNT_BOTH: clear_mount = clear_ao = true; break; + case MOUNT: + clear_mount = true; + break; + case AO: + clear_ao = true; + break; + case WHICH_MOUNT_BOTH: + clear_mount = clear_ao = true; + break; case WHICH_MOUNT_ERR: response << jrpc_error(JSONRPC_INVALID_PARAMS, "expected param \"mount\", \"ao\", or \"both\""); return; @@ -1131,8 +1251,7 @@ static bool is_camera_shift_req(const json_value *params) if (j) { const char *axes = string_val(j); - if (wxStricmp(axes, "x/y") == 0 || - wxStricmp(axes, "camera") == 0) + if (wxStricmp(axes, "x/y") == 0 || wxStricmp(axes, "camera") == 0) { return true; } @@ -1145,8 +1264,7 @@ static JObj& operator<<(JObj& j, const LockPosShiftParams& l) j << NV("enabled", l.shiftEnabled); if (l.shiftRate.IsValid()) { - j << NV("rate", l.shiftRate) - << NV("units", l.shiftUnits == UNIT_ARCSEC ? "arcsec/hr" : "pixels/hr") + j << NV("rate", l.shiftRate) << NV("units", l.shiftUnits == UNIT_ARCSEC ? "arcsec/hr" : "pixels/hr") << NV("axes", l.shiftIsMountCoords ? "RA/Dec" : "X/Y"); } return j; @@ -1233,8 +1351,7 @@ static bool parse_lock_shift_params(LockPosShiftParams *shift, const json_value j = p.param("units"); const char *units = j ? string_val(j) : ""; - if (wxStricmp(units, "arcsec/hr") == 0 || - wxStricmp(units, "arc-sec/hr") == 0) + if (wxStricmp(units, "arcsec/hr") == 0 || wxStricmp(units, "arc-sec/hr") == 0) { shift->shiftUnits = UNIT_ARCSEC; } @@ -1372,7 +1489,8 @@ struct B64Encode size_t nread; B64Encode() - : t(0), nread(0) + : t(0) + , nread(0) { } void append1(unsigned char ch) @@ -1381,10 +1499,7 @@ struct B64Encode t |= ch; if (++nread % 3 == 0) { - os << E[t >> 18] - << E[(t >> 12) & 0x3F] - << E[(t >> 6) & 0x3F] - << E[t & 0x3F]; + os << E[t >> 18] << E[(t >> 12) & 0x3F] << E[(t >> 6) & 0x3F] << E[t & 0x3F]; t = 0; } } @@ -1397,17 +1512,13 @@ struct B64Encode } std::string finish() { - switch (nread % 3) { + switch (nread % 3) + { case 1: - os << E[t >> 2] - << E[(t & 0x3) << 4] - << "=="; + os << E[t >> 2] << E[(t & 0x3) << 4] << "=="; break; case 2: - os << E[t >> 10] - << E[(t >> 4) & 0x3F] - << E[(t & 0xf) << 2] - << '='; + os << E[t >> 10] << E[(t >> 4) & 0x3F] << E[(t & 0xf) << 2] << '='; break; } return os.str(); @@ -1463,11 +1574,8 @@ static void get_star_image(JObj& response, const json_value *params) pos.Y -= rect.GetTop(); JObj rslt; - rslt << NV("frame", img->FrameNum) - << NV("width", rect.GetWidth()) - << NV("height", rect.GetHeight()) - << NV("star_pos", pos) - << NV("pixels", enc.finish()); + rslt << NV("frame", img->FrameNum) << NV("width", rect.GetWidth()) << NV("height", rect.GetHeight()) << NV("star_pos", pos) + << NV("pixels", enc.finish()); response << jrpc_result(rslt); } @@ -1476,7 +1584,7 @@ static bool parse_settle(SettleParams *settle, const json_value *j, wxString *er { bool found_pixels = false, found_time = false, found_timeout = false; - json_for_each (t, j) + json_for_each(t, j) { if (float_param("pixels", t, &settle->tolerancePx)) { @@ -1593,7 +1701,8 @@ static void dither(JObj& response, const json_value *params) // // {"method": "dither", "params": [10, false, {"pixels": 1.5, "time": 8, "timeout": 30}], "id": 42} // or - // {"method": "dither", "params": {"amount": 10, "raOnly": false, "settle": {"pixels": 1.5, "time": 8, "timeout": 30}}, "id": 42} + // {"method": "dither", "params": {"amount": 10, "raOnly": false, "settle": {"pixels": 1.5, "time": 8, "timeout": 30}}, + // "id": 42} Params p("amount", "raOnly", "settle", params); const json_value *jv; @@ -1863,24 +1972,23 @@ static void get_settling(JObj& response, const json_value *params) response << jrpc_result(settling); } -static void get_variable_delay_settings(JObj& response, const json_value* params) +static void get_variable_delay_settings(JObj& response, const json_value *params) { JObj rslt; VarDelayCfg delayParams = pFrame->GetVariableDelayConfig(); - rslt << NV("Enabled", delayParams.enabled) - << NV("ShortDelaySeconds", delayParams.shortDelay / 1000) - << NV("LongDelaySeconds", delayParams.longDelay / 1000); + rslt << NV("Enabled", delayParams.enabled) << NV("ShortDelaySeconds", delayParams.shortDelay / 1000) + << NV("LongDelaySeconds", delayParams.longDelay / 1000); response << jrpc_result(rslt); } // set_variable_delay values are in units of seconds to match the UI convention in the Advanced Settings dialog -static void set_variable_delay_settings(JObj& response, const json_value* params) +static void set_variable_delay_settings(JObj& response, const json_value *params) { Params p("Enabled", "ShortDelaySeconds", "LongDelaySeconds", params); - const json_value* p0 = p.param("Enabled"); - const json_value* p1 = p.param("ShortDelaySeconds"); - const json_value* p2 = p.param("LongDelaySeconds"); + const json_value *p0 = p.param("Enabled"); + const json_value *p1 = p.param("ShortDelaySeconds"); + const json_value *p2 = p.param("LongDelaySeconds"); bool enabled; double shortDelaySec; double longDelaySec; @@ -1890,7 +1998,7 @@ static void set_variable_delay_settings(JObj& response, const json_value* params return; } VarDelayCfg currParams; - pFrame->SetVariableDelayConfig(enabled, (int)shortDelaySec * 1000, (int)longDelaySec * 1000); + pFrame->SetVariableDelayConfig(enabled, (int) shortDelaySec * 1000, (int) longDelaySec * 1000); response << jrpc_result(0); } @@ -1899,8 +2007,10 @@ static GUIDE_DIRECTION dir_param(const json_value *p) if (!p || p->type != JSON_STRING) return GUIDE_DIRECTION::NONE; - struct { - const char *s; GUIDE_DIRECTION d; + struct + { + const char *s; + GUIDE_DIRECTION d; } dirs[] = { { "n", GUIDE_DIRECTION::NORTH }, { "s", GUIDE_DIRECTION::SOUTH }, @@ -1925,12 +2035,18 @@ static GUIDE_DIRECTION dir_param(const json_value *p) static GUIDE_DIRECTION opposite(GUIDE_DIRECTION d) { - switch (d) { - case UP: return DOWN; - case DOWN: return UP; - case LEFT: return RIGHT; - case RIGHT: return LEFT; - default: return d; + switch (d) + { + case UP: + return DOWN; + case DOWN: + return UP; + case LEFT: + return RIGHT; + case RIGHT: + return LEFT; + default: + return d; } } @@ -1956,8 +2072,12 @@ static void guide_pulse(JObj& response, const json_value *params) Mount *m = nullptr; switch (which) { - case MOUNT: m = TheScope(); break; - case AO: m = TheAO(); break; + case MOUNT: + m = TheScope(); + break; + case AO: + m = TheAO(); + break; case WHICH_MOUNT_BOTH: case WHICH_MOUNT_ERR: response << jrpc_error(1, "invalid 'which' param"); @@ -1990,10 +2110,14 @@ static void guide_pulse(JObj& response, const json_value *params) static const char *parity_str(GuideParity p) { - switch (p) { - case GUIDE_PARITY_EVEN: return "+"; - case GUIDE_PARITY_ODD: return "-"; - default: return "?"; + switch (p) + { + case GUIDE_PARITY_EVEN: + return "+"; + case GUIDE_PARITY_ODD: + return "-"; + default: + return "?"; } } @@ -2005,14 +2129,18 @@ static void get_calibration_data(JObj& response, const json_value *params) Mount *m = nullptr; switch (which) { - case MOUNT: m = TheScope(); break; - case AO: m = TheAO(); break; + case MOUNT: + m = TheScope(); + break; + case AO: + m = TheAO(); + break; case WHICH_MOUNT_BOTH: case WHICH_MOUNT_ERR: - { - response << jrpc_error(1, "invalid 'which' param"); - return; - } + { + response << jrpc_error(1, "invalid 'which' param"); + return; + } } if (!m || !m->IsConnected()) @@ -2026,13 +2154,10 @@ static void get_calibration_data(JObj& response, const json_value *params) if (m->IsCalibrated()) { - rslt << NV("xAngle", degrees(m->xAngle()), 1) - << NV("xRate", m->xRate() * 1000.0, 3) - << NV("xParity", parity_str(m->RAParity())) - << NV("yAngle", degrees(m->yAngle()), 1) - << NV("yRate", m->yRate() * 1000.0, 3) - << NV("yParity", parity_str(m->DecParity())) - << NV("declination", degrees(m->GetCalibrationDeclination())); + rslt << NV("xAngle", degrees(m->xAngle()), 1) << NV("xRate", m->xRate() * 1000.0, 3) + << NV("xParity", parity_str(m->RAParity())) << NV("yAngle", degrees(m->yAngle()), 1) + << NV("yRate", m->yRate() * 1000.0, 3) << NV("yParity", parity_str(m->DecParity())) + << NV("declination", degrees(m->GetCalibrationDeclination())); } response << jrpc_result(rslt); @@ -2058,13 +2183,11 @@ static void get_cooler_status(JObj& response, const json_value *params) JObj rslt; - rslt << NV("coolerOn", on) - << NV("temperature", temperature, 1); + rslt << NV("coolerOn", on) << NV("temperature", temperature, 1); if (on) { - rslt << NV("setpoint", setpoint, 1) - << NV("power", power, 1); + rslt << NV("setpoint", setpoint, 1) << NV("power", power, 1); } response << jrpc_result(rslt); @@ -2116,7 +2239,12 @@ struct JRpcCall const json_value *method; JRpcResponse response; - JRpcCall(wxSocketClient *cli_, const json_value *req_) : cli(cli_), req(req_), method(nullptr) { } + JRpcCall(wxSocketClient *cli_, const json_value *req_) + : cli(cli_) + , req(req_) + , method(nullptr) + { + } }; static void dump_request(const JRpcCall& call) @@ -2164,62 +2292,208 @@ static bool handle_request(JRpcCall& call) return true; } - static struct { + static struct + { const char *name; void (*fn)(JObj& response, const json_value *params); - } methods[] = { - { "clear_calibration", &clear_calibration, }, - { "deselect_star", &deselect_star, }, - { "get_exposure", &get_exposure, }, - { "set_exposure", &set_exposure, }, - { "get_exposure_durations", &get_exposure_durations, }, - { "get_profiles", &get_profiles, }, - { "get_profile", &get_profile, }, - { "set_profile", &set_profile, }, - { "get_connected", &get_connected, }, - { "set_connected", &set_connected, }, - { "get_calibrated", &get_calibrated, }, - { "get_paused", &get_paused, }, - { "set_paused", &set_paused, }, - { "get_lock_position", &get_lock_position, }, - { "set_lock_position", &set_lock_position, }, - { "loop", &loop, }, - { "stop_capture", &stop_capture, }, - { "guide", &guide, }, - { "dither", &dither, }, - { "find_star", &find_star, }, - { "get_pixel_scale", &get_pixel_scale, }, - { "get_app_state", &get_app_state, }, - { "flip_calibration", &flip_calibration, }, - { "get_lock_shift_enabled", &get_lock_shift_enabled, }, - { "set_lock_shift_enabled", &set_lock_shift_enabled, }, - { "get_lock_shift_params", &get_lock_shift_params, }, - { "set_lock_shift_params", &set_lock_shift_params, }, - { "save_image", &save_image, }, - { "get_star_image", &get_star_image, }, - { "get_use_subframes", &get_use_subframes, }, - { "get_search_region", &get_search_region, }, - { "shutdown", &shutdown, }, - { "get_camera_binning", &get_camera_binning, }, - { "get_camera_frame_size", &get_camera_frame_size, }, - { "get_current_equipment", &get_current_equipment, }, - { "get_guide_output_enabled", &get_guide_output_enabled, }, - { "set_guide_output_enabled", &set_guide_output_enabled, }, - { "get_algo_param_names", &get_algo_param_names, }, - { "get_algo_param", &get_algo_param, }, - { "set_algo_param", &set_algo_param, }, - { "get_dec_guide_mode", &get_dec_guide_mode, }, - { "set_dec_guide_mode", &set_dec_guide_mode, }, - { "get_settling", &get_settling, }, - { "guide_pulse", &guide_pulse, }, - { "get_calibration_data", &get_calibration_data, }, - { "capture_single_frame", &capture_single_frame, }, - { "get_cooler_status", &get_cooler_status, }, - { "get_ccd_temperature", &get_sensor_temperature, }, - { "export_config_settings", &export_config_settings, }, - { "get_variable_delay_settings", &get_variable_delay_settings}, - { "set_variable_delay_settings", &set_variable_delay_settings} - }; + } methods[] = { { + "clear_calibration", + &clear_calibration, + }, + { + "deselect_star", + &deselect_star, + }, + { + "get_exposure", + &get_exposure, + }, + { + "set_exposure", + &set_exposure, + }, + { + "get_exposure_durations", + &get_exposure_durations, + }, + { + "get_profiles", + &get_profiles, + }, + { + "get_profile", + &get_profile, + }, + { + "set_profile", + &set_profile, + }, + { + "get_connected", + &get_connected, + }, + { + "set_connected", + &set_connected, + }, + { + "get_calibrated", + &get_calibrated, + }, + { + "get_paused", + &get_paused, + }, + { + "set_paused", + &set_paused, + }, + { + "get_lock_position", + &get_lock_position, + }, + { + "set_lock_position", + &set_lock_position, + }, + { + "loop", + &loop, + }, + { + "stop_capture", + &stop_capture, + }, + { + "guide", + &guide, + }, + { + "dither", + &dither, + }, + { + "find_star", + &find_star, + }, + { + "get_pixel_scale", + &get_pixel_scale, + }, + { + "get_app_state", + &get_app_state, + }, + { + "flip_calibration", + &flip_calibration, + }, + { + "get_lock_shift_enabled", + &get_lock_shift_enabled, + }, + { + "set_lock_shift_enabled", + &set_lock_shift_enabled, + }, + { + "get_lock_shift_params", + &get_lock_shift_params, + }, + { + "set_lock_shift_params", + &set_lock_shift_params, + }, + { + "save_image", + &save_image, + }, + { + "get_star_image", + &get_star_image, + }, + { + "get_use_subframes", + &get_use_subframes, + }, + { + "get_search_region", + &get_search_region, + }, + { + "shutdown", + &shutdown, + }, + { + "get_camera_binning", + &get_camera_binning, + }, + { + "get_camera_frame_size", + &get_camera_frame_size, + }, + { + "get_current_equipment", + &get_current_equipment, + }, + { + "get_guide_output_enabled", + &get_guide_output_enabled, + }, + { + "set_guide_output_enabled", + &set_guide_output_enabled, + }, + { + "get_algo_param_names", + &get_algo_param_names, + }, + { + "get_algo_param", + &get_algo_param, + }, + { + "set_algo_param", + &set_algo_param, + }, + { + "get_dec_guide_mode", + &get_dec_guide_mode, + }, + { + "set_dec_guide_mode", + &set_dec_guide_mode, + }, + { + "get_settling", + &get_settling, + }, + { + "guide_pulse", + &guide_pulse, + }, + { + "get_calibration_data", + &get_calibration_data, + }, + { + "capture_single_frame", + &capture_single_frame, + }, + { + "get_cooler_status", + &get_cooler_status, + }, + { + "get_ccd_temperature", + &get_sensor_temperature, + }, + { + "export_config_settings", + &export_config_settings, + }, + { "get_variable_delay_settings", &get_variable_delay_settings }, + { "set_variable_delay_settings", &set_variable_delay_settings } }; for (unsigned int i = 0; i < WXSIZEOF(methods); i++) { @@ -2269,7 +2543,7 @@ static void handle_cli_input_complete(wxSocketClient *cli, char *input, JsonPars JAry ary; bool found = false; - json_for_each (req, root) + json_for_each(req, root) { JRpcCall call(cli, req); if (handle_request(call)) @@ -2354,9 +2628,7 @@ EventServer::EventServer() { } -EventServer::~EventServer() -{ -} +EventServer::~EventServer() { } bool EventServer::EventServerStart(unsigned int instanceId) { @@ -2395,8 +2667,7 @@ void EventServer::EventServerStop() if (!m_serverSocket) return; - for (CliSockSet::const_iterator it = m_eventServerClients.begin(); - it != m_eventServerClients.end(); ++it) + for (CliSockSet::const_iterator it = m_eventServerClients.begin(); it != m_eventServerClients.end(); ++it) { destroy_client(*it); } @@ -2472,13 +2743,8 @@ void EventServer::NotifyCalibrationStep(const CalibrationStepInfo& info) Ev ev("Calibrating"); - ev << NVMount(info.mount) - << NV("dir", info.direction) - << NV("dist", info.dist) - << NV("dx", info.dx) - << NV("dy", info.dy) - << NV("pos", info.pos) - << NV("step", info.stepNumber); + ev << NVMount(info.mount) << NV("dir", info.direction) << NV("dist", info.dist) << NV("dx", info.dx) << NV("dy", info.dy) + << NV("pos", info.pos) << NV("step", info.stepNumber); if (!info.msg.empty()) ev << NV("State", info.msg); @@ -2549,9 +2815,7 @@ void EventServer::NotifyLooping(unsigned int exposure, const Star *star, const F if (mass) { - ev << NV("StarMass", mass, 0) - << NV("SNR", snr, 2) - << NV("HFD", hfd, 2); + ev << NV("StarMass", mass, 0) << NV("SNR", snr, 2) << NV("HFD", hfd, 2); } if (err) @@ -2580,12 +2844,8 @@ void EventServer::NotifyStarLost(const FrameDroppedInfo& info) Ev ev("StarLost"); - ev << NV("Frame", info.frameNumber) - << NV("Time", info.time, 3) - << NV("StarMass", info.starMass, 0) - << NV("SNR", info.starSNR, 2) - << NV("HFD", info.starHFD, 2) - << NV("AvgDist", info.avgDist, 2); + ev << NV("Frame", info.frameNumber) << NV("Time", info.time, 3) << NV("StarMass", info.starMass, 0) + << NV("SNR", info.starSNR, 2) << NV("HFD", info.starHFD, 2) << NV("AvgDist", info.avgDist, 2); if (info.starError) ev << NV("ErrorCode", info.starError); @@ -2623,26 +2883,21 @@ void EventServer::NotifyGuideStep(const GuideStepInfo& step) Ev ev("GuideStep"); - ev << NV("Frame", step.frameNumber) - << NV("Time", step.time, 3) - << NVMount(step.mount) - << NV("dx", step.cameraOffset.X, 3) - << NV("dy", step.cameraOffset.Y, 3) - << NV("RADistanceRaw", step.mountOffset.X, 3) - << NV("DECDistanceRaw", step.mountOffset.Y, 3) - << NV("RADistanceGuide", step.guideDistanceRA, 3) + ev << NV("Frame", step.frameNumber) << NV("Time", step.time, 3) << NVMount(step.mount) << NV("dx", step.cameraOffset.X, 3) + << NV("dy", step.cameraOffset.Y, 3) << NV("RADistanceRaw", step.mountOffset.X, 3) + << NV("DECDistanceRaw", step.mountOffset.Y, 3) << NV("RADistanceGuide", step.guideDistanceRA, 3) << NV("DECDistanceGuide", step.guideDistanceDec, 3); if (step.durationRA > 0) { - ev << NV("RADuration", step.durationRA) - << NV("RADirection", step.mount->DirectionStr((GUIDE_DIRECTION)step.directionRA)); + ev << NV("RADuration", step.durationRA) + << NV("RADirection", step.mount->DirectionStr((GUIDE_DIRECTION) step.directionRA)); } if (step.durationDec > 0) { ev << NV("DECDuration", step.durationDec) - << NV("DECDirection", step.mount->DirectionStr((GUIDE_DIRECTION)step.directionDec)); + << NV("DECDirection", step.mount->DirectionStr((GUIDE_DIRECTION) step.directionDec)); } if (step.mount->IsStepGuider()) @@ -2650,13 +2905,11 @@ void EventServer::NotifyGuideStep(const GuideStepInfo& step) ev << NV("Pos", step.aoPos); } - ev << NV("StarMass", step.starMass, 0) - << NV("SNR", step.starSNR, 2) - << NV("HFD", step.starHFD, 2) + ev << NV("StarMass", step.starMass, 0) << NV("SNR", step.starSNR, 2) << NV("HFD", step.starHFD, 2) << NV("AvgDist", step.avgDist, 2); if (step.starError) - ev << NV("ErrorCode", step.starError); + ev << NV("ErrorCode", step.starError); if (step.raLimited) ev << NV("RALimited", true); diff --git a/src/fitsiowrap.cpp b/src/fitsiowrap.cpp index 1ad2aba61..5ff5168d4 100644 --- a/src/fitsiowrap.cpp +++ b/src/fitsiowrap.cpp @@ -1,37 +1,37 @@ /* -* fitsiowrap.cpp -* PHD Guiding -* -* Created by Andy Galasso -* Copyright (c) 2014 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs, -* Bret McKee, Dad Dog Development, Ltd, nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * fitsiowrap.cpp + * PHD Guiding + * + * Created by Andy Galasso + * Copyright (c) 2014 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs, + * Bret McKee, Dad Dog Development, Ltd, nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" @@ -46,7 +46,8 @@ class FitsFname public: FitsFname(const wxString& str, bool create, bool clobber); - ~FitsFname() { + ~FitsFname() + { #ifdef __WINDOWS__ delete[] m_str; #endif diff --git a/src/fitsiowrap.h b/src/fitsiowrap.h index b4794bc65..415775a3f 100644 --- a/src/fitsiowrap.h +++ b/src/fitsiowrap.h @@ -1,37 +1,37 @@ /* -* fitsiowrap.h -* PHD Guiding -* -* Created by Andy Galasso -* Copyright (c) 2014 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs, -* Bret McKee, Dad Dog Development, Ltd, nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * fitsiowrap.h + * PHD Guiding + * + * Created by Andy Galasso + * Copyright (c) 2014 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs, + * Bret McKee, Dad Dog Development, Ltd, nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef FITSIOWRAP_INCLUDED #define FITSIOWRAP_INCLUDED @@ -48,26 +48,34 @@ class FITSHdrWriter int *status; public: + FITSHdrWriter(fitsfile *fptr_, int *status_) + : fptr(fptr_) + , status(status_) + { + } - FITSHdrWriter(fitsfile *fptr_, int *status_) : fptr(fptr_), status(status_) { } - - void write(const char *key, float val, const char *comment) { + void write(const char *key, float val, const char *comment) + { fits_write_key(fptr, TFLOAT, const_cast(key), &val, const_cast(comment), status); } - void write(const char *key, unsigned int val, const char *comment) { + void write(const char *key, unsigned int val, const char *comment) + { fits_write_key(fptr, TUINT, const_cast(key), &val, const_cast(comment), status); } - void write(const char *key, int val, const char *comment) { + void write(const char *key, int val, const char *comment) + { fits_write_key(fptr, TINT, const_cast(key), &val, const_cast(comment), status); } - void write(const char *key, const char *val, const char *comment) { + void write(const char *key, const char *val, const char *comment) + { fits_write_key(fptr, TSTRING, const_cast(key), const_cast(val), const_cast(comment), status); } - void write(const char *key, const wxDateTime& t, const wxDateTime::TimeZone& z, const char *comment) { + void write(const char *key, const wxDateTime& t, const wxDateTime::TimeZone& z, const char *comment) + { wxString s = t.Format("%Y-%m-%dT%H:%M:%S", z) + wxString::Format(".%03d", t.GetMillisecond(z)); write(key, (const char *) s.c_str(), comment); } diff --git a/src/gear_dialog.cpp b/src/gear_dialog.cpp index 77691ad3b..fb7df84ff 100644 --- a/src/gear_dialog.cpp +++ b/src/gear_dialog.cpp @@ -118,33 +118,33 @@ wxEND_EVENT_TABLE(); * | +-------------------+ +-------------------+ | * +--------------------------------------------------------------------------+ */ -GearDialog::GearDialog(wxWindow *pParent) : - wxDialog(pParent, wxID_ANY, _("Connect Equipment"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX), - m_cameraUpdated(false), - m_mountUpdated(false), - m_stepGuiderUpdated(false), - m_rotatorUpdated(false), - m_showDarksDialog(false), - m_camWarningIssued(false), - m_camChanged(false), - m_imageScaleRatio(1.0), - m_flushConfig(false) -{ - m_pCamera = nullptr; - m_pScope = nullptr; +GearDialog::GearDialog(wxWindow *pParent) + : wxDialog(pParent, wxID_ANY, _("Connect Equipment"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) + , m_cameraUpdated(false) + , m_mountUpdated(false) + , m_stepGuiderUpdated(false) + , m_rotatorUpdated(false) + , m_showDarksDialog(false) + , m_camWarningIssued(false) + , m_camChanged(false) + , m_imageScaleRatio(1.0) + , m_flushConfig(false) +{ + m_pCamera = nullptr; + m_pScope = nullptr; m_pAuxScope = nullptr; m_pStepGuider = nullptr; m_pRotator = nullptr; - m_pCameras = nullptr; - m_pScopes = nullptr; - m_pAuxScopes = nullptr; - m_pStepGuiders = nullptr; + m_pCameras = nullptr; + m_pScopes = nullptr; + m_pAuxScopes = nullptr; + m_pStepGuiders = nullptr; m_pRotators = nullptr; - m_pConnectCameraButton = nullptr; - m_pConnectScopeButton = nullptr; - m_pConnectAuxScopeButton = nullptr; + m_pConnectCameraButton = nullptr; + m_pConnectScopeButton = nullptr; + m_pConnectAuxScopeButton = nullptr; m_pConnectStepGuiderButton = nullptr; m_pConnectRotatorButton = nullptr; @@ -171,8 +171,8 @@ GearDialog::~GearDialog() delete m_pRotator; // prevent double frees - pCamera = nullptr; - pMount = nullptr; + pCamera = nullptr; + pMount = nullptr; pSecondaryMount = nullptr; pPointingSource = nullptr; pRotator = nullptr; @@ -182,9 +182,9 @@ GearDialog::~GearDialog() static wxToggleButton *MakeConnectBtn(wxWindow *parent, wxWindowID id) { -# include "icons/connected.png.h" +#include "icons/connected.png.h" wxBitmap connected_bmp(wxBITMAP_PNG_FROM_DATA(connected)); -# include "icons/disconnected.png.h" +#include "icons/disconnected.png.h" wxBitmap disconnected_bmp(wxBITMAP_PNG_FROM_DATA(disconnected)); wxToggleButton *btn = new wxToggleButton(parent, id, _("Disconnect"), wxDefaultPosition, wxDefaultSize, wxBORDER_NONE); @@ -206,9 +206,9 @@ static wxToggleButton *MakeConnectBtn(wxWindow *parent, wxWindowID id) void GearDialog::Initialize() { - wxSizerFlags sizerFlags = wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL,2).Expand(); - wxSizerFlags sizerTextFlags = wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL,2).Expand(); - wxSizerFlags sizerLabelFlags = wxSizerFlags().Align(wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL).Border(wxALL, 2); + wxSizerFlags sizerFlags = wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 2).Expand(); + wxSizerFlags sizerTextFlags = wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 2).Expand(); + wxSizerFlags sizerLabelFlags = wxSizerFlags().Align(wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL).Border(wxALL, 2); wxSizerFlags sizerButtonFlags = wxSizerFlags().Align(wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL).Border(wxALL, 2).Expand(); wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL); @@ -216,13 +216,15 @@ void GearDialog::Initialize() wxBoxSizer *profilesSizer = new wxBoxSizer(wxHORIZONTAL); profilesSizer->Add(new wxStaticText(this, wxID_ANY, _("Equipment profile")), sizerLabelFlags); m_profiles = new wxChoice(this, GEAR_PROFILES, wxDefaultPosition, wxDefaultSize, pConfig->ProfileNames()); - m_profiles->SetToolTip(_("Select the Equipment Profile you would like to use. PHD stores all of your settings and equipment selections in an Equipment Profile. " + m_profiles->SetToolTip(_("Select the Equipment Profile you would like to use. PHD stores all of your settings and " + "equipment selections in an Equipment Profile. " "You can create multiple profiles and switch back and forth between them.")); m_profiles->SetStringSelection(pConfig->GetCurrentProfile()); profilesSizer->Add(m_profiles, sizerButtonFlags); m_menuProfileManage = new wxMenu(); - m_menuProfileManage->Append(GEAR_PROFILE_WIZARD, _("New using Wizard..."), _("Run the first-light wizard to create a new profile")); + m_menuProfileManage->Append( + GEAR_PROFILE_WIZARD, _("New using Wizard..."), _("Run the first-light wizard to create a new profile")); m_menuProfileManage->Append(GEAR_PROFILE_NEW, _("New"), _("Create a new profile, optionally copying from another profile")); m_menuProfileManage->Append(GEAR_PROFILE_DELETE, _("Delete"), _("Delete the selected profile")); m_menuProfileManage->Append(GEAR_PROFILE_RENAME, _("Rename"), _("Rename the selected profile")); @@ -234,17 +236,20 @@ void GearDialog::Initialize() m_btnProfileManage->SetToolTip(_("Create a new Equipment Profile, or delete or rename the selected Equipment Profile")); profilesSizer->Add(m_btnProfileManage, sizerButtonFlags); - pTopLevelSizer->Add(profilesSizer, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL,2)); + pTopLevelSizer->Add(profilesSizer, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 2)); pTopLevelSizer->AddSpacer(10); // text at the top. I tried (really really hard) to get it to resize/Wrap() // with the rest of the sizer, but it just didn't want to work, and I needed // to get the rest of the dialog working. - wxStaticText *pText = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER | wxALIGN_CENTER_VERTICAL); + wxStaticText *pText = new wxStaticText( + this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER | wxALIGN_CENTER_VERTICAL); int width, height; - pText->SetLabel(_("Select your equipment below and click Connect All to connect, or click Disconnect All to disconnect. You can also connect or disconnect individual equipment items by clicking the button next to the item.")); + pText->SetLabel( + _("Select your equipment below and click Connect All to connect, or click Disconnect All to disconnect. You can also " + "connect or disconnect individual equipment items by clicking the button next to the item.")); pText->GetTextExtent(_T("MMMMMMMMMM"), &width, &height); - pText->Wrap(4*width); + pText->Wrap(4 * width); pTopLevelSizer->Add(pText, sizerTextFlags.Align(wxALIGN_CENTER)); // The Gear grid in the middle of the screen @@ -252,14 +257,15 @@ void GearDialog::Initialize() pTopLevelSizer->Add(m_gearSizer, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 2)); // Camera - m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("Camera"), wxDefaultPosition, wxDefaultSize), wxGBPosition(0, 0), wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); - m_pCameras = new wxChoice(this, GEAR_CHOICE_CAMERA, wxDefaultPosition, wxDefaultSize, - 0, nullptr, 0, wxDefaultValidator, _("Camera")); + m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("Camera"), wxDefaultPosition, wxDefaultSize), wxGBPosition(0, 0), + wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); + m_pCameras = new wxChoice( + this, GEAR_CHOICE_CAMERA, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0, wxDefaultValidator, _("Camera")); m_gearSizer->Add(m_pCameras, wxGBPosition(0, 1), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); -# include "icons/select.png.h" +#include "icons/select.png.h" wxBitmap select_bmp(wxBITMAP_PNG_FROM_DATA(select)); -# include "icons/setup.png.h" +#include "icons/setup.png.h" wxBitmap setup_bmp(wxBITMAP_PNG_FROM_DATA(setup)); m_selectCameraButton = new wxBitmapButton(this, GEAR_BUTTON_SELECT_CAMERA, select_bmp); @@ -270,35 +276,44 @@ void GearDialog::Initialize() m_pSetupCameraButton->SetToolTip(_("Camera Setup")); m_gearSizer->Add(m_pSetupCameraButton, wxGBPosition(0, 3), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_pConnectCameraButton = MakeConnectBtn(this, GEAR_BUTTON_CONNECT_CAMERA); - m_gearSizer->Add(m_pConnectCameraButton, wxGBPosition(0, 4), wxGBSpan(1, 1), wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); + m_gearSizer->Add(m_pConnectCameraButton, wxGBPosition(0, 4), wxGBSpan(1, 1), + wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); // mount - m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("Mount"), wxDefaultPosition, wxDefaultSize), wxGBPosition(1, 0), wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); - m_pScopes = new wxChoice(this, GEAR_CHOICE_SCOPE, wxDefaultPosition, wxDefaultSize, - 0, nullptr, 0, wxDefaultValidator, _("Mount")); - m_pScopes->SetToolTip(_("Specify how guide commands will be sent to the mount - via an ASCOM or INDI driver, directly from the camera or AO, " - "or via one of the GPxxx devices. An ASCOM connection is recommended.")); + m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("Mount"), wxDefaultPosition, wxDefaultSize), wxGBPosition(1, 0), + wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); + m_pScopes = + new wxChoice(this, GEAR_CHOICE_SCOPE, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0, wxDefaultValidator, _("Mount")); + m_pScopes->SetToolTip( + _("Specify how guide commands will be sent to the mount - via an ASCOM or INDI driver, directly from the camera or AO, " + "or via one of the GPxxx devices. An ASCOM connection is recommended.")); m_gearSizer->Add(m_pScopes, wxGBPosition(1, 1), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_pSetupScopeButton = new wxBitmapButton(this, GEAR_BUTTON_SETUP_SCOPE, setup_bmp); m_pSetupScopeButton->SetToolTip(_("Mount Setup")); m_gearSizer->Add(m_pSetupScopeButton, wxGBPosition(1, 3), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_pConnectScopeButton = MakeConnectBtn(this, GEAR_BUTTON_CONNECT_SCOPE); - m_gearSizer->Add(m_pConnectScopeButton, wxGBPosition(1, 4), wxGBSpan(1, 1), wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); + m_gearSizer->Add(m_pConnectScopeButton, wxGBPosition(1, 4), wxGBSpan(1, 1), + wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); // aux mount - used for position/state information when not guiding through ASCOM interface - m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("Aux Mount"), wxDefaultPosition, wxDefaultSize), wxGBPosition(2, 0), wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); - m_pAuxScopes = new wxChoice(this, GEAR_CHOICE_AUXSCOPE, wxDefaultPosition, wxDefaultSize, - 0, nullptr, 0, wxDefaultValidator, _("Aux Mount")); + m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("Aux Mount"), wxDefaultPosition, wxDefaultSize), wxGBPosition(2, 0), + wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); + m_pAuxScopes = new wxChoice( + this, GEAR_CHOICE_AUXSCOPE, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0, wxDefaultValidator, _("Aux Mount")); #if defined(GUIDE_ASCOM) || defined(GUIDE_INDI) -#ifdef GUIDE_ASCOM +# ifdef GUIDE_ASCOM wxString driverName = _T("ASCOM"); # else wxString driverName = _T("INDI"); -#endif - m_pAuxScopes->SetToolTip(wxString::Format(_("If you are using a guide port (On-camera or GPXXX) interface for guiding, you can also use an 'aux' connection to your %s-compatible mount. This will " - "be used to make automatic calibration adjustments based on declination and side-of-pier. If you have already selected an %s driver for your 'mount', the 'aux' mount " - "parameter will not be used."), driverName, driverName)); +# endif + m_pAuxScopes->SetToolTip( + wxString::Format(_("If you are using a guide port (On-camera or GPXXX) interface for guiding, you can also use an " + "'aux' connection to your %s-compatible mount. This will " + "be used to make automatic calibration adjustments based on declination and side-of-pier. If you " + "have already selected an %s driver for your 'mount', the 'aux' mount " + "parameter will not be used."), + driverName, driverName)); #endif // ASCOM or INDI m_gearSizer->Add(m_pAuxScopes, wxGBPosition(2, 1), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); @@ -306,47 +321,54 @@ void GearDialog::Initialize() m_pSetupAuxScopeButton->SetToolTip(_("Aux Mount Setup")); m_gearSizer->Add(m_pSetupAuxScopeButton, wxGBPosition(2, 3), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_pConnectAuxScopeButton = MakeConnectBtn(this, GEAR_BUTTON_CONNECT_AUXSCOPE); - m_gearSizer->Add(m_pConnectAuxScopeButton, wxGBPosition(2, 4), wxGBSpan(1, 1), wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); + m_gearSizer->Add(m_pConnectAuxScopeButton, wxGBPosition(2, 4), wxGBSpan(1, 1), + wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_moreButton = new wxButton(this, GEAR_BUTTON_MORE, wxEmptyString); m_gearSizer->Add(m_moreButton, wxGBPosition(3, 0), wxGBSpan(1, 4), wxALL | /*wxALIGN_CENTER*/ wxALIGN_LEFT, 5); // ao - m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("AO"), wxDefaultPosition, wxDefaultSize), wxGBPosition(4, 0), wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); - m_pStepGuiders = new wxChoice(this, GEAR_CHOICE_STEPGUIDER, wxDefaultPosition, wxDefaultSize, - 0, nullptr, 0, wxDefaultValidator, _("AO")); + m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("AO"), wxDefaultPosition, wxDefaultSize), wxGBPosition(4, 0), + wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); + m_pStepGuiders = new wxChoice( + this, GEAR_CHOICE_STEPGUIDER, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0, wxDefaultValidator, _("AO")); m_gearSizer->Add(m_pStepGuiders, wxGBPosition(4, 1), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_pSetupStepGuiderButton = new wxBitmapButton(this, GEAR_BUTTON_SETUP_STEPGUIDER, setup_bmp); m_pSetupStepGuiderButton->SetToolTip(_("AO Setup")); - m_gearSizer->Add(m_pSetupStepGuiderButton, wxGBPosition(4, 3), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); + m_gearSizer->Add( + m_pSetupStepGuiderButton, wxGBPosition(4, 3), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_pConnectStepGuiderButton = MakeConnectBtn(this, GEAR_BUTTON_CONNECT_STEPGUIDER); - m_gearSizer->Add(m_pConnectStepGuiderButton, wxGBPosition(4, 4), wxGBSpan(1, 1), wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); + m_gearSizer->Add(m_pConnectStepGuiderButton, wxGBPosition(4, 4), wxGBSpan(1, 1), + wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); // rotator - m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("Rotator"), wxDefaultPosition, wxDefaultSize), wxGBPosition(5, 0), wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); - m_pRotators = new wxChoice(this, GEAR_CHOICE_ROTATOR, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0, wxDefaultValidator, _("Rotator")); + m_gearSizer->Add(new wxStaticText(this, wxID_ANY, _("Rotator"), wxDefaultPosition, wxDefaultSize), wxGBPosition(5, 0), + wxGBSpan(1, 1), wxALL | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL, 5); + m_pRotators = new wxChoice( + this, GEAR_CHOICE_ROTATOR, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0, wxDefaultValidator, _("Rotator")); m_gearSizer->Add(m_pRotators, wxGBPosition(5, 1), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_pSetupRotatorButton = new wxBitmapButton(this, GEAR_BUTTON_SETUP_ROTATOR, setup_bmp); m_pSetupRotatorButton->SetToolTip(_("Rotator Setup")); m_gearSizer->Add(m_pSetupRotatorButton, wxGBPosition(5, 3), wxGBSpan(1, 1), wxALL | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); m_pConnectRotatorButton = MakeConnectBtn(this, GEAR_BUTTON_CONNECT_ROTATOR); - m_gearSizer->Add(m_pConnectRotatorButton, wxGBPosition(5, 4), wxGBSpan(1, 1), wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); + m_gearSizer->Add(m_pConnectRotatorButton, wxGBPosition(5, 4), wxGBSpan(1, 1), + wxBOTTOM | wxTOP | wxRIGHT | wxEXPAND | wxALIGN_CENTER_VERTICAL, 5); // Setup the bottom row of buttons wxBoxSizer *pButtonSizer = new wxBoxSizer(wxHORIZONTAL); - m_pConnectAllButton = new wxButton( this, GEAR_BUTTON_CONNECT_ALL, _("Connect All")); + m_pConnectAllButton = new wxButton(this, GEAR_BUTTON_CONNECT_ALL, _("Connect All")); m_pConnectAllButton->SetToolTip(_("Connect all equipment and close the equipment selection window")); pButtonSizer->Add(m_pConnectAllButton, sizerFlags); - m_pDisconnectAllButton = new wxButton( this, GEAR_BUTTON_DISCONNECT_ALL, _("Disconnect All")); + m_pDisconnectAllButton = new wxButton(this, GEAR_BUTTON_DISCONNECT_ALL, _("Disconnect All")); m_pDisconnectAllButton->SetToolTip(_("Disconnect all equipment")); pButtonSizer->Add(m_pDisconnectAllButton, sizerFlags); - wxButton* closeBtn = new wxButton(this, wxID_CANCEL, _("Close")); + wxButton *closeBtn = new wxButton(this, wxID_CANCEL, _("Close")); pButtonSizer->Add(closeBtn, sizerFlags); - pTopLevelSizer->Add(pButtonSizer, wxSizerFlags().Align(wxALIGN_TOP|wxALIGN_CENTER_HORIZONTAL).Border(wxALL,2)); + pTopLevelSizer->Add(pButtonSizer, wxSizerFlags().Align(wxALIGN_TOP | wxALIGN_CENTER_HORIZONTAL).Border(wxALL, 2)); // preselect the choices LoadGearChoices(); @@ -424,8 +446,10 @@ static wxString NewAoName(const wxString& oldname) // we renamed the AOs when we added the INDI SBIG AO // temporary code to convert the old names to the new // this should be removed after a release or two - if (oldname == _T("sxAO")) return _T("SX AO"); - if (oldname == _T("INDI sxAO")) return _T("SX AO (INDI)"); + if (oldname == _T("sxAO")) + return _T("SX AO"); + if (oldname == _T("INDI sxAO")) + return _T("SX AO (INDI)"); return oldname; } #endif @@ -488,10 +512,8 @@ int GearDialog::ShowGearDialog(bool autoConnect) wxCommandEvent dummyEvent; OnButtonConnectAll(dummyEvent); - if (m_pCamera && m_pCamera->Connected && - (!m_pScope || m_pScope->IsConnected()) && - (!m_pAuxScope || m_pAuxScope->IsConnected()) && - (!m_pStepGuider || m_pStepGuider->IsConnected()) && + if (m_pCamera && m_pCamera->Connected && (!m_pScope || m_pScope->IsConnected()) && + (!m_pAuxScope || m_pAuxScope->IsConnected()) && (!m_pStepGuider || m_pStepGuider->IsConnected()) && (!m_pRotator || m_pRotator->IsConnected())) { callSuper = false; @@ -544,10 +566,9 @@ void GearDialog::EndModal(int retCode) pFrame->pGraphLog->UpdateControls(); pFrame->pTarget->UpdateControls(); - if (pFrame->GetAutoLoadCalibration() && !m_camChanged) // ok to reload calibration + if (pFrame->GetAutoLoadCalibration() && !m_camChanged) // ok to reload calibration { - if (pMount && pMount->IsConnected() && - (!pSecondaryMount || pSecondaryMount->IsConnected())) + if (pMount && pMount->IsConnected() && (!pSecondaryMount || pSecondaryMount->IsConnected())) { Debug.Write("Auto-loading calibration data\n"); pFrame->LoadCalibration(); @@ -677,7 +698,8 @@ void GearDialog::UpdateScopeButtonState() { m_pConnectScopeButton->Enable(false); } - else if (m_pScope->RequiresStepGuider() && (!m_pStepGuider || !m_pStepGuider->ST4HasGuideOutput() || !m_pStepGuider->IsConnected())) + else if (m_pScope->RequiresStepGuider() && + (!m_pStepGuider || !m_pStepGuider->ST4HasGuideOutput() || !m_pStepGuider->IsConnected())) { m_pConnectScopeButton->Enable(false); } @@ -694,7 +716,7 @@ void GearDialog::UpdateAuxScopeButtonState() // Now set up the buttons to match our current state if (m_pScope && m_pScope->CanReportPosition()) { - int noneInx = m_pAuxScopes->FindString(_("None")); // Should always be first in list + int noneInx = m_pAuxScopes->FindString(_("None")); // Should always be first in list m_pAuxScopes->SetSelection(noneInx); m_pAuxScopes->Enable(false); m_pSetupAuxScopeButton->Enable(false); @@ -820,11 +842,9 @@ void GearDialog::UpdateRotatorButtonState() void GearDialog::UpdateConnectAllButtonState() { - if ((m_pCamera && !m_pCamera->Connected) || - (m_pScope && !m_pScope->IsConnected()) || - (m_pAuxScope && !m_pAuxScope->IsConnected()) || - (m_pStepGuider && !m_pStepGuider->IsConnected()) || - (m_pRotator && !m_pRotator->IsConnected())) + if ((m_pCamera && !m_pCamera->Connected) || (m_pScope && !m_pScope->IsConnected()) || + (m_pAuxScope && !m_pAuxScope->IsConnected()) || (m_pStepGuider && !m_pStepGuider->IsConnected()) || + (m_pRotator && !m_pRotator->IsConnected())) { m_pConnectAllButton->Enable(true); } @@ -836,11 +856,9 @@ void GearDialog::UpdateConnectAllButtonState() void GearDialog::UpdateDisconnectAllButtonState() { - if ((m_pCamera && m_pCamera->Connected) || - (m_pScope && m_pScope->IsConnected()) || - (m_pAuxScope && m_pAuxScope->IsConnected()) || - (m_pStepGuider && m_pStepGuider->IsConnected()) || - (m_pRotator && m_pRotator->IsConnected())) + if ((m_pCamera && m_pCamera->Connected) || (m_pScope && m_pScope->IsConnected()) || + (m_pAuxScope && m_pAuxScope->IsConnected()) || (m_pStepGuider && m_pStepGuider->IsConnected()) || + (m_pRotator && m_pRotator->IsConnected())) { m_pDisconnectAllButton->Enable(true); m_profiles->Enable(false); @@ -1109,9 +1127,9 @@ bool GearDialog::DoConnectCamera(bool autoReconnecting) Debug.Write(wxString::Format("DoConnectCamera: reconnecting=%d warningIssued=%d lastCam=[%s] scaleRatio=%.3f\n", autoReconnecting, m_camWarningIssued, m_lastCamera, m_imageScaleRatio)); - // No very reliable way to know if cam selection has changed - id's and name strings may be the same for different cams from same mfr - // so do what we can here including consideration of image scale change - // Purpose is to warn user of potential loss of dark/bpm files and later, to adjust guide params as best we can + // No very reliable way to know if cam selection has changed - id's and name strings may be the same for different cams + // from same mfr so do what we can here including consideration of image scale change Purpose is to warn user of + // potential loss of dark/bpm files and later, to adjust guide params as best we can if (!m_camWarningIssued && !autoReconnecting) { if ((m_lastCamera != _("None") && newCam != _("None") && !DeviceSelectionMatches(m_lastCamera, newCam)) || @@ -1128,12 +1146,13 @@ bool GearDialog::DoConnectCamera(bool autoReconnecting) { Debug.Write("DoConnectCamera: displaying camera-change warning\n"); - wxString msg = _("By changing cameras in this profile, you won't be able to use the existing dark library or bad-pixel maps. You should consider" - " creating a new profile for this set-up. Do you want to connect to this camera anyway?"); + wxString msg = _("By changing cameras in this profile, you won't be able to use the existing dark library " + "or bad-pixel maps. You should consider" + " creating a new profile for this set-up. Do you want to connect to this camera anyway?"); if (wxMessageBox(msg, _("Camera Change Warning"), wxYES_NO, this) == wxYES) { m_camWarningIssued = true; - m_lastCamera = newCam; // make consistent with what's in the UI + m_lastCamera = newCam; // make consistent with what's in the UI } else { @@ -1159,8 +1178,8 @@ bool GearDialog::DoConnectCamera(bool autoReconnecting) m_pCamera->SetCameraGain(defaultGain); } - // See if the profile was created with a binning level that isn't supported by the camera (user mistake) - if so, reset binning to 1 - // Must be done here because orig binning level is not saved + // See if the profile was created with a binning level that isn't supported by the camera (user mistake) - if so, reset + // binning to 1 Must be done here because orig binning level is not saved if (profileBinning > m_pCamera->MaxBinning) { int rslt; @@ -1193,7 +1212,7 @@ bool GearDialog::DoConnectCamera(bool autoReconnecting) Debug.Write(wxString::Format("HasSubFrames=%d\n", m_pCamera->HasSubframes)); Debug.Write(wxString::Format("ST4HasGuideOutput=%d\n", m_pCamera->ST4HasGuideOutput())); - if (!autoReconnecting) // On a reconnect, this stuff is already established + if (!autoReconnecting) // On a reconnect, this stuff is already established { AutoLoadDefectMap(); if (!pCamera->CurrentDefectMap) @@ -1286,8 +1305,7 @@ void GearDialog::UpdateGearPointers() pSecondaryMount = nullptr; } - pPointingSource = m_pScope && (!m_pAuxScope || m_pScope->CanReportPosition()) ? - m_pScope : m_pAuxScope; + pPointingSource = m_pScope && (!m_pAuxScope || m_pScope->CanReportPosition()) ? m_pScope : m_pAuxScope; pRotator = m_pRotator; } @@ -1816,7 +1834,7 @@ void GearDialog::OnButtonDisconnectRotator(wxCommandEvent& event) void GearDialog::OnButtonProfileManage(wxCommandEvent& event) { PopupMenu(m_menuProfileManage, m_btnProfileManage->GetPosition().x, - m_btnProfileManage->GetPosition().y + m_btnProfileManage->GetSize().GetHeight()); + m_btnProfileManage->GetPosition().y + m_btnProfileManage->GetSize().GetHeight()); } void GearDialog::OnButtonWizard(wxCommandEvent& event) @@ -1826,7 +1844,8 @@ void GearDialog::OnButtonWizard(wxCommandEvent& event) bool firstLight = IsEmptyProfile(); wxString current = m_profiles->GetStringSelection(); - bool showGreeting = event.GetId() == 0; // Event id of 0 comes from "first light" launch; show first light UI panel only then + bool showGreeting = + event.GetId() == 0; // Event id of 0 comes from "first light" launch; show first light UI panel only then bool darks_requested; if (EquipmentProfileWizard::ShowModal(this, showGreeting, &darks_requested)) { @@ -1834,7 +1853,7 @@ void GearDialog::OnButtonWizard(wxCommandEvent& event) // if this was a first-light run, we may have left an empty "My Equipment" profile behind - if so, delete it if (firstLight) { - pConfig->DeleteProfile(current); // Can't be any dark/bpm files associated with it + pConfig->DeleteProfile(current); // Can't be any dark/bpm files associated with it } wxArrayString profiles = pConfig->ProfileNames(); @@ -1872,9 +1891,9 @@ void GearDialog::ShowProfileWizard() void GearDialog::ShowProfileWizard(wxCommandEvent& evt) { OnButtonWizard(evt); - if (!IsEmptyProfile()) // User didn't just cancel out + if (!IsEmptyProfile()) // User didn't just cancel out { - ShowGearDialog(m_showDarksDialog); // Maybe auto-connect, close, launch darks; or just display dialog + ShowGearDialog(m_showDarksDialog); // Maybe auto-connect, close, launch darks; or just display dialog } } @@ -1911,10 +1930,8 @@ bool GearDialog::SetProfile(int profileId, wxString *error) return true; } - if ((m_pCamera && m_pCamera->Connected) || - (m_pScope && m_pScope->IsConnected()) || - (m_pAuxScope && m_pAuxScope->IsConnected()) || - (m_pStepGuider && m_pStepGuider->IsConnected()) || + if ((m_pCamera && m_pCamera->Connected) || (m_pScope && m_pScope->IsConnected()) || + (m_pAuxScope && m_pAuxScope->IsConnected()) || (m_pStepGuider && m_pStepGuider->IsConnected()) || (m_pRotator && m_pRotator->IsConnected())) { *error = "cannot set profile when equipment is connected"; @@ -1947,10 +1964,8 @@ bool GearDialog::SetProfile(int profileId, wxString *error) bool GearDialog::ConnectAll(wxString *error) { - if (m_pCamera && m_pCamera->Connected && - (!m_pScope || m_pScope->IsConnected()) && - (!m_pAuxScope || m_pAuxScope->IsConnected()) && - (!m_pStepGuider || m_pStepGuider->IsConnected()) && + if (m_pCamera && m_pCamera->Connected && (!m_pScope || m_pScope->IsConnected()) && + (!m_pAuxScope || m_pAuxScope->IsConnected()) && (!m_pStepGuider || m_pStepGuider->IsConnected()) && (!m_pRotator || m_pRotator->IsConnected())) { // everything already connected @@ -2003,10 +2018,8 @@ bool GearDialog::ConnectAll(wxString *error) bool GearDialog::DisconnectAll(wxString *error) { - if ((!m_pCamera || !m_pCamera->Connected) && - (!m_pScope || !m_pScope->IsConnected()) && - (!m_pAuxScope || !m_pAuxScope->IsConnected()) && - (!m_pStepGuider || !m_pStepGuider->IsConnected()) && + if ((!m_pCamera || !m_pCamera->Connected) && (!m_pScope || !m_pScope->IsConnected()) && + (!m_pAuxScope || !m_pAuxScope->IsConnected()) && (!m_pStepGuider || !m_pStepGuider->IsConnected()) && (!m_pRotator || !m_pRotator->IsConnected())) { // nothing connected @@ -2084,12 +2097,14 @@ struct NewProfileDialog : public wxDialog NewProfileDialog::NewProfileDialog(wxWindow *parent) : wxDialog(parent, wxID_ANY, _("New Equipment Profile")) { - wxSizerFlags sizerLabelFlags = wxSizerFlags().Align(wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL).Border(wxALL,2).Expand(); - wxSizerFlags sizerTextFlags = wxSizerFlags().Align(wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL).Border(wxALL,2).Expand(); - wxSizerFlags sizerButtonFlags = wxSizerFlags().Align(wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL).Border(wxALL,2).Expand(); + wxSizerFlags sizerLabelFlags = wxSizerFlags().Align(wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL).Border(wxALL, 2).Expand(); + wxSizerFlags sizerTextFlags = wxSizerFlags().Align(wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL).Border(wxALL, 2).Expand(); + wxSizerFlags sizerButtonFlags = wxSizerFlags().Align(wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL).Border(wxALL, 2).Expand(); wxSizer *sizer1 = new wxBoxSizer(wxHORIZONTAL); - sizer1->Add(new wxStaticText(this, wxID_ANY, _("Name"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL), sizerLabelFlags); + sizer1->Add( + new wxStaticText(this, wxID_ANY, _("Name"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL), + sizerLabelFlags); wxSize size = GetTextExtent("MMMMMMMMMMMMMMMMMMMMMMMMMMMM"); size.SetHeight(-1); m_name = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, size); @@ -2100,10 +2115,13 @@ NewProfileDialog::NewProfileDialog(wxWindow *parent) choices.Insert(_("PHD Defaults"), 0); wxSizer *sizer2 = new wxBoxSizer(wxHORIZONTAL); - sizer2->Add(new wxStaticText(this, wxID_ANY, _("Profile initial settings"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL), sizerLabelFlags); + sizer2->Add(new wxStaticText(this, wxID_ANY, _("Profile initial settings"), wxDefaultPosition, wxDefaultSize, + wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL), + sizerLabelFlags); m_copyFrom = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, choices); m_copyFrom->SetSelection(0); - m_copyFrom->SetToolTip(_("Select PHD Defaults to create a profile with default PHD settings, or select an existing Equipment Profile to copy its settings into your new profile.")); + m_copyFrom->SetToolTip(_("Select PHD Defaults to create a profile with default PHD settings, or select an existing " + "Equipment Profile to copy its settings into your new profile.")); sizer2->Add(m_copyFrom, sizerTextFlags); wxSizer *sizer3 = new wxBoxSizer(wxVERTICAL); @@ -2127,7 +2145,8 @@ void GearDialog::OnProfileNew(wxCommandEvent& event) if (pConfig->GetProfileId(newname) > 0) { - wxMessageBox(wxString::Format(_("Cannot create profile %s, there is already a profile with that name"), newname), _("Error")); + wxMessageBox( + wxString::Format(_("Cannot create profile %s, there is already a profile with that name"), newname), _("Error")); return; } @@ -2159,7 +2178,8 @@ void GearDialog::OnProfileNew(wxCommandEvent& event) void GearDialog::OnProfileDelete(wxCommandEvent& event) { wxString current = m_profiles->GetStringSelection(); - int result = wxMessageBox(wxString::Format(_("Delete profile %s?"), current), _("Delete Equipment Profile"), wxOK | wxCANCEL | wxCENTRE); + int result = wxMessageBox( + wxString::Format(_("Delete profile %s?"), current), _("Delete Equipment Profile"), wxOK | wxCANCEL | wxCENTRE); if (result != wxOK) return; int id = pConfig->GetProfileId(current); @@ -2188,7 +2208,8 @@ void GearDialog::OnProfileRename(wxCommandEvent& event) if (pConfig->GetProfileId(newname) > 0) { - wxMessageBox(_(wxString::Format("Cannot not rename profile to %s, there is already a profile with that name", newname)), _("Error")); + wxMessageBox(_(wxString::Format("Cannot not rename profile to %s, there is already a profile with that name", newname)), + _("Error")); return; } @@ -2209,7 +2230,7 @@ void GearDialog::OnProfileLoad(wxCommandEvent& event) wxString default_path = pConfig->Global.GetString("/profileFilePath", wxEmptyString); wxFileDialog dlg(this, _("Import PHD Equipment Profiles"), default_path, wxEmptyString, - wxT("PHD profile files (*.phd)|*.phd"), wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE); + wxT("PHD profile files (*.phd)|*.phd"), wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE); if (dlg.ShowModal() == wxID_CANCEL) { @@ -2241,9 +2262,8 @@ void GearDialog::OnProfileLoad(wxCommandEvent& event) void GearDialog::OnProfileSave(wxCommandEvent& event) { wxString default_path = pConfig->Global.GetString("/profileFilePath", wxEmptyString); - wxString fname = wxFileSelector(_("Export PHD Equipment Profile"), default_path, - pConfig->GetCurrentProfile() + wxT(".phd"), wxT("phd"), - wxT("PHD profile files (*.phd)|*.phd"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT, this); + wxString fname = wxFileSelector(_("Export PHD Equipment Profile"), default_path, pConfig->GetCurrentProfile() + wxT(".phd"), + wxT("phd"), wxT("PHD profile files (*.phd)|*.phd"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT, this); if (fname.IsEmpty()) { diff --git a/src/gear_dialog.h b/src/gear_dialog.h index 3d727ed00..c6daa9128 100644 --- a/src/gear_dialog.h +++ b/src/gear_dialog.h @@ -40,10 +40,10 @@ class wxGridBagSizer; class GearDialog : public wxDialog { GuideCamera *m_pCamera; - Scope *m_pScope; - Scope *m_pAuxScope; - StepGuider *m_pStepGuider; - Rotator *m_pRotator; + Scope *m_pScope; + Scope *m_pAuxScope; + StepGuider *m_pStepGuider; + Rotator *m_pRotator; bool m_cameraUpdated; bool m_mountUpdated; diff --git a/src/gear_simulator.cpp b/src/gear_simulator.cpp index 1c5d588ae..4f6effd76 100644 --- a/src/gear_simulator.cpp +++ b/src/gear_simulator.cpp @@ -38,20 +38,20 @@ #ifdef SIMULATOR -#include "camera.h" -#include "gear_simulator.h" -#include "image_math.h" +# include "camera.h" +# include "gear_simulator.h" +# include "image_math.h" -#include -#include -#include -#include +# include +# include +# include +# include -#include -#include -#include +# include +# include +# include -#define SIMMODE 3 // 1=FITS, 2=BMP, 3=Generate +# define SIMMODE 3 // 1=FITS, 2=BMP, 3=Generate // #define SIMDEBUG /* simulation parameters for SIMMODE = 3*/ @@ -74,7 +74,7 @@ struct SimCamParams static PierSide pier_side; static bool reverse_dec_pulse_on_west_side; static unsigned int clouds_inten; - static double clouds_opacity; // UI has percentage, internally 0-1.0 + static double clouds_opacity; // UI has percentage, internally 0-1.0 static double image_scale; // arc-sec per pixel static bool use_pe; static bool use_stiction; @@ -88,23 +88,24 @@ struct SimCamParams static unsigned int frame_download_ms; }; -unsigned int SimCamParams::width = 752; // simulated camera image width -unsigned int SimCamParams::height = 580; // simulated camera image height -unsigned int SimCamParams::border = 12; // do not place any stars within this size border -unsigned int SimCamParams::nr_stars; // number of stars to generate -unsigned int SimCamParams::nr_hot_pixels; // number of hot pixels to generate -double SimCamParams::noise_multiplier; // noise factor, increase to increase noise -double SimCamParams::dec_backlash; // dec backlash amount (pixels) -double SimCamParams::pe_scale; // scale factor controlling magnitude of simulated periodic error -double SimCamParams::dec_drift_rate; // dec drift rate (pixels per second) -double SimCamParams::seeing_scale; // simulated seeing scale factor -double SimCamParams::cam_angle; // simulated camera angle (degrees) -double SimCamParams::guide_rate; // guide rate, pixels per second -PierSide SimCamParams::pier_side; // side of pier -bool SimCamParams::reverse_dec_pulse_on_west_side; // reverse dec pulse on west side of pier, like ASCOM pulse guided equatorial mounts -unsigned int SimCamParams::clouds_inten = 50; // seed brightness for cloud contribution +unsigned int SimCamParams::width = 752; // simulated camera image width +unsigned int SimCamParams::height = 580; // simulated camera image height +unsigned int SimCamParams::border = 12; // do not place any stars within this size border +unsigned int SimCamParams::nr_stars; // number of stars to generate +unsigned int SimCamParams::nr_hot_pixels; // number of hot pixels to generate +double SimCamParams::noise_multiplier; // noise factor, increase to increase noise +double SimCamParams::dec_backlash; // dec backlash amount (pixels) +double SimCamParams::pe_scale; // scale factor controlling magnitude of simulated periodic error +double SimCamParams::dec_drift_rate; // dec drift rate (pixels per second) +double SimCamParams::seeing_scale; // simulated seeing scale factor +double SimCamParams::cam_angle; // simulated camera angle (degrees) +double SimCamParams::guide_rate; // guide rate, pixels per second +PierSide SimCamParams::pier_side; // side of pier +bool SimCamParams::reverse_dec_pulse_on_west_side; // reverse dec pulse on west side of pier, like ASCOM pulse guided equatorial + // mounts +unsigned int SimCamParams::clouds_inten = 50; // seed brightness for cloud contribution double SimCamParams::clouds_opacity; -double SimCamParams::image_scale; // arc-sec per pixel +double SimCamParams::image_scale; // arc-sec per pixel bool SimCamParams::use_pe; bool SimCamParams::use_stiction; bool SimCamParams::use_default_pe_params; @@ -114,37 +115,37 @@ bool SimCamParams::show_comet; double SimCamParams::comet_rate_x; double SimCamParams::comet_rate_y; bool SimCamParams::allow_async_st4 = true; -unsigned int SimCamParams::frame_download_ms; // frame download time, ms +unsigned int SimCamParams::frame_download_ms; // frame download time, ms // Note: these are all in units appropriate for the UI -#define NR_STARS_DEFAULT 20 -#define NR_HOT_PIXELS_DEFAULT 8 -#define NOISE_DEFAULT 2.0 -#define NOISE_MAX 5.0 -#define DEC_BACKLASH_DEFAULT 5.0 // arc-sec -#define DEC_BACKLASH_MAX 100.0 -#define DEC_DRIFT_DEFAULT 5.0 // arc-sec per minute -#define DEC_DRIFT_MAX 30.0 -#define SEEING_DEFAULT 2.0 // arc-sec FWHM -#define SEEING_MAX 5.0 -#define CAM_ANGLE_DEFAULT 15.0 -#define CAM_ANGLE_MAX 360.0 -#define GUIDE_RATE_DEFAULT (1.0 * 15.0) // multiples of sidereal rate, a-s/sec -#define GUIDE_RATE_MAX (1.0 * 15.0) -#define PIER_SIDE_DEFAULT PIER_SIDE_EAST -#define REVERSE_DEC_PULSE_ON_WEST_SIDE_DEFAULT true -#define CLOUDS_OPACITY_DEFAULT 0 -#define USE_PE_DEFAULT true -#define USE_STICTION_DEFAULT false -#define PE_SCALE_DEFAULT 5.0 // amplitude arc-sec -#define PE_SCALE_MAX 30.0 -#define USE_PE_DEFAULT_PARAMS true -#define PE_CUSTOM_AMP_DEFAULT 2.0 // Give them a trivial 2 a-s 4 min smooth curve -#define PE_CUSTOM_PERIOD_DEFAULT 240.0 -#define SHOW_COMET_DEFAULT false -#define COMET_RATE_X_DEFAULT 555.0 // pixels per hour -#define COMET_RATE_Y_DEFAULT -123.4 // pixels per hour -#define SIM_FILE_DISPLACEMENTS_DEFAULT "star_displacements.csv" +# define NR_STARS_DEFAULT 20 +# define NR_HOT_PIXELS_DEFAULT 8 +# define NOISE_DEFAULT 2.0 +# define NOISE_MAX 5.0 +# define DEC_BACKLASH_DEFAULT 5.0 // arc-sec +# define DEC_BACKLASH_MAX 100.0 +# define DEC_DRIFT_DEFAULT 5.0 // arc-sec per minute +# define DEC_DRIFT_MAX 30.0 +# define SEEING_DEFAULT 2.0 // arc-sec FWHM +# define SEEING_MAX 5.0 +# define CAM_ANGLE_DEFAULT 15.0 +# define CAM_ANGLE_MAX 360.0 +# define GUIDE_RATE_DEFAULT (1.0 * 15.0) // multiples of sidereal rate, a-s/sec +# define GUIDE_RATE_MAX (1.0 * 15.0) +# define PIER_SIDE_DEFAULT PIER_SIDE_EAST +# define REVERSE_DEC_PULSE_ON_WEST_SIDE_DEFAULT true +# define CLOUDS_OPACITY_DEFAULT 0 +# define USE_PE_DEFAULT true +# define USE_STICTION_DEFAULT false +# define PE_SCALE_DEFAULT 5.0 // amplitude arc-sec +# define PE_SCALE_MAX 30.0 +# define USE_PE_DEFAULT_PARAMS true +# define PE_CUSTOM_AMP_DEFAULT 2.0 // Give them a trivial 2 a-s 4 min smooth curve +# define PE_CUSTOM_PERIOD_DEFAULT 240.0 +# define SHOW_COMET_DEFAULT false +# define COMET_RATE_X_DEFAULT 555.0 // pixels per hour +# define COMET_RATE_Y_DEFAULT -123.4 // pixels per hour +# define SIM_FILE_DISPLACEMENTS_DEFAULT "star_displacements.csv" // Needed to handle legacy registry values that may no longer be in correct units or range static double range_check(double thisval, double minval, double maxval) @@ -166,18 +167,22 @@ static void load_sim_params() SimCamParams::custom_pe_period = pConfig->Profile.GetDouble("/SimCam/pe_cust_period", PE_CUSTOM_PERIOD_DEFAULT); double dval = pConfig->Profile.GetDouble("/SimCam/dec_drift", DEC_DRIFT_DEFAULT); - SimCamParams::dec_drift_rate = range_check(dval, -DEC_DRIFT_MAX, DEC_DRIFT_MAX) / (SimCamParams::image_scale * 60.0); //a-s per min is saved + SimCamParams::dec_drift_rate = + range_check(dval, -DEC_DRIFT_MAX, DEC_DRIFT_MAX) / (SimCamParams::image_scale * 60.0); // a-s per min is saved // backlash is in arc-secs in UI - map to px for internal use dval = pConfig->Profile.GetDouble("/SimCam/dec_backlash", DEC_BACKLASH_DEFAULT); SimCamParams::dec_backlash = range_check(dval, 0, DEC_BACKLASH_MAX) / SimCamParams::image_scale; SimCamParams::pe_scale = range_check(pConfig->Profile.GetDouble("/SimCam/pe_scale", PE_SCALE_DEFAULT), 0, PE_SCALE_MAX); - SimCamParams::seeing_scale = range_check(pConfig->Profile.GetDouble("/SimCam/seeing_scale", SEEING_DEFAULT), 0, SEEING_MAX); // FWHM a-s + SimCamParams::seeing_scale = + range_check(pConfig->Profile.GetDouble("/SimCam/seeing_scale", SEEING_DEFAULT), 0, SEEING_MAX); // FWHM a-s SimCamParams::cam_angle = pConfig->Profile.GetDouble("/SimCam/cam_angle", CAM_ANGLE_DEFAULT); SimCamParams::clouds_opacity = pConfig->Profile.GetDouble("/SimCam/clouds_opacity", CLOUDS_OPACITY_DEFAULT); - SimCamParams::guide_rate = range_check(pConfig->Profile.GetDouble("/SimCam/guide_rate", GUIDE_RATE_DEFAULT), 0, GUIDE_RATE_MAX); + SimCamParams::guide_rate = + range_check(pConfig->Profile.GetDouble("/SimCam/guide_rate", GUIDE_RATE_DEFAULT), 0, GUIDE_RATE_MAX); SimCamParams::pier_side = (PierSide) pConfig->Profile.GetInt("/SimCam/pier_side", PIER_SIDE_DEFAULT); - SimCamParams::reverse_dec_pulse_on_west_side = pConfig->Profile.GetBoolean("/SimCam/reverse_dec_pulse_on_west_side", REVERSE_DEC_PULSE_ON_WEST_SIDE_DEFAULT); + SimCamParams::reverse_dec_pulse_on_west_side = + pConfig->Profile.GetBoolean("/SimCam/reverse_dec_pulse_on_west_side", REVERSE_DEC_PULSE_ON_WEST_SIDE_DEFAULT); SimCamParams::show_comet = pConfig->Profile.GetBoolean("/SimCam/show_comet", SHOW_COMET_DEFAULT); SimCamParams::comet_rate_x = pConfig->Profile.GetDouble("/SimCam/comet_rate_x", COMET_RATE_X_DEFAULT); @@ -211,13 +216,13 @@ static void save_sim_params() pConfig->Profile.SetInt("/SimCam/frame_download_ms", SimCamParams::frame_download_ms); } -#ifdef STEPGUIDER_SIMULATOR +# ifdef STEPGUIDER_SIMULATOR struct SimAoParams { static unsigned int max_position; // max position in steps - static double scale; // arcsec per step - static double angle; // angle relative to camera (degrees) + static double scale; // arcsec per step + static double angle; // angle relative to camera (degrees) }; unsigned int SimAoParams::max_position = 45; @@ -249,9 +254,7 @@ StepGuiderSimulator::StepGuiderSimulator() SimAoParams::max_position = pConfig->Profile.GetInt("/SimAo/max_steps", 45); } -StepGuiderSimulator::~StepGuiderSimulator() -{ -} +StepGuiderSimulator::~StepGuiderSimulator() { } bool StepGuiderSimulator::Connect() { @@ -266,7 +269,8 @@ bool StepGuiderSimulator::Connect() if (!pCamera || pCamera->Name != _T("Simulator")) { - pFrame->Alert(_("The AO Simulator only works with the Camera Simulator. You should either disconnect the AO Simulator or connect the Camera Simulator.")); + pFrame->Alert(_("The AO Simulator only works with the Camera Simulator. You should either disconnect the AO Simulator " + "or connect the Camera Simulator.")); } return false; @@ -277,7 +281,8 @@ bool StepGuiderSimulator::Disconnect() if (StepGuider::Disconnect()) return true; - if (s_sim_ao == this) { + if (s_sim_ao == this) + { Debug.AddLine("AO Simulator Disconnected"); s_sim_ao = 0; } @@ -293,17 +298,20 @@ bool StepGuiderSimulator::Center() StepGuider::STEP_RESULT StepGuiderSimulator::Step(GUIDE_DIRECTION direction, int steps) { -#if 0 // enable to test step failure +# if 0 // enable to test step failure wxPoint pos = GetAoPos(); if (direction == LEFT && pos.x - steps < -35) { Debug.Write("simulate step failure\n"); return STEP_LIMIT_REACHED; } -#endif +# endif // parent class maintains x/y offsets, so nothing to do here. Just simulate a delay. - enum { LATENCY_MS_PER_STEP = 5 }; + enum + { + LATENCY_MS_PER_STEP = 5 + }; wxMilliSleep(steps * LATENCY_MS_PER_STEP); return STEP_OK; } @@ -325,9 +333,9 @@ bool StepGuiderSimulator::HasNonGuiMove() return true; } -#endif // STEPGUIDER_SIMULATOR +# endif // STEPGUIDER_SIMULATOR -#ifdef ROTATOR_SIMULATOR +# ifdef ROTATOR_SIMULATOR class RotatorSimulator : public Rotator { @@ -345,19 +353,16 @@ class RotatorSimulator : public Rotator float Position() const override; }; -RotatorSimulator::RotatorSimulator() -{ -} +RotatorSimulator::RotatorSimulator() { } -RotatorSimulator::~RotatorSimulator() -{ -} +RotatorSimulator::~RotatorSimulator() { } bool RotatorSimulator::Connect() { if (!pCamera || pCamera->Name != _T("Simulator")) { - pFrame->Alert(_("The Rotator Simulator only works with the Camera Simulator. You must either disconnect the Rotator Simulator or connect the Camera Simulator.")); + pFrame->Alert(_("The Rotator Simulator only works with the Camera Simulator. You must either disconnect the Rotator " + "Simulator or connect the Camera Simulator.")); return true; } @@ -382,7 +387,7 @@ float RotatorSimulator::Position() const return SimCamParams::cam_angle; } -#endif // ROTATOR_SIMULATOR +# endif // ROTATOR_SIMULATOR // value with backlash // There is an index value, and a lower and upper limit separated by the @@ -391,24 +396,31 @@ float RotatorSimulator::Position() const // the value of the upper limit. struct BacklashVal { - double cur; // current index value - double upper; // upper limit + double cur; // current index value + double upper; // upper limit double amount; // backlash amount (lower limit is upper - amount) BacklashVal() { } BacklashVal(double backlash_amount) - : cur(0), upper(backlash_amount), amount(backlash_amount) { } + : cur(0) + , upper(backlash_amount) + , amount(backlash_amount) + { + } double val() const { return upper; } - void incr(double d) { + void incr(double d) + { cur += d; - if (d > 0.) { + if (d > 0.) + { if (cur > upper) upper = cur; } - else if (d < 0.) { + else if (d < 0.) + { if (cur < upper - amount) upper = cur + amount; } @@ -478,7 +490,16 @@ struct Cooler double rate; // degrees per second double direction; // -1 = cooling, +1 = warming - Cooler() : on(false), startTemp(AMBIENT_TEMP), endTemp(AMBIENT_TEMP), setTemp(AMBIENT_TEMP), endTime(0), rate(1. / 8.), direction(0.) { } + Cooler() + : on(false) + , startTemp(AMBIENT_TEMP) + , endTemp(AMBIENT_TEMP) + , setTemp(AMBIENT_TEMP) + , endTime(0) + , rate(1. / 8.) + , direction(0.) + { + } double CurrentTemp() const { @@ -487,7 +508,7 @@ struct Cooler if (now >= endTime) return endTemp; - return endTemp - rate * direction * (double)(endTime - now); + return endTemp - rate * direction * (double) (endTime - now); } void TurnOn() @@ -531,32 +552,32 @@ struct SimCamState unsigned int height; wxVector stars; // star positions and intensities (ra, dec) wxVector hotpx; // hot pixels - double ra_ofs; // assume no backlash in RA - BacklashVal dec_ofs; // simulate backlash in DEC - double cum_dec_drift; // cumulative dec drift - wxStopWatch timer; // platform-independent timer + double ra_ofs; // assume no backlash in RA + BacklashVal dec_ofs; // simulate backlash in DEC + double cum_dec_drift; // cumulative dec drift + wxStopWatch timer; // platform-independent timer long last_exposure_time; // last exposure time, milliseconds - Cooler cooler; // simulated cooler + Cooler cooler; // simulated cooler StictionSim stictionSim; -#ifdef SIMDEBUG +# ifdef SIMDEBUG wxFFile DebugFile; double last_ra_move; double last_dec_move; -#endif +# endif -#ifdef SIM_FILE_DISPLACEMENTS - wxFileInputStream* pIStream; - wxTextInputStream* pText; +# ifdef SIM_FILE_DISPLACEMENTS + wxFileInputStream *pIStream; + wxTextInputStream *pText; double scaleConversion; void ReadDisplacements(double& cumX, double& cumY); -#endif +# endif -#if SIMMODE == 1 +# if SIMMODE == 1 wxDir dir; bool dirStarted; bool ReadNextImage(usImage& img, const wxRect& subframe); -#endif +# endif void Initialize(); void FillImage(usImage& img, const wxRect& subframe, int exptime, int gain, int offset); @@ -575,11 +596,11 @@ void SimCamState::Initialize() for (unsigned int i = 0; i < nr_stars; i++) { // generate stars in ra/dec coordinates - stars[i].pos.x = (double)(rand() % (width - 2 * border)) - 0.5 * width; - stars[i].pos.y = (double)(rand() % (height - 2 * border)) - 0.5 * height; + stars[i].pos.x = (double) (rand() % (width - 2 * border)) - 0.5 * width; + stars[i].pos.y = (double) (rand() % (height - 2 * border)) - 0.5 * height; double r = (double) (rand() % 90) / 3.0; // 0..30 if (i == 10) - stars[i].inten = 30.1; // Always have one saturated star + stars[i].inten = 30.1; // Always have one saturated star else stars[i].inten = 0.1 + (double) (r * r * r) / 9000.0; @@ -595,7 +616,8 @@ void SimCamState::Initialize() // generate hot pixels unsigned int const nr_hot = SimCamParams::nr_hot_pixels; hotpx.resize(nr_hot); - for (unsigned int i = 0; i < nr_hot; i++) { + for (unsigned int i = 0; i < nr_hot; i++) + { hotpx[i].x = rand() % width; hotpx[i].y = rand() % height; } @@ -605,11 +627,11 @@ void SimCamState::Initialize() cum_dec_drift = 0.; last_exposure_time = 0; -#if SIMMODE == 1 +# if SIMMODE == 1 dirStarted = false; -#endif +# endif -#ifdef SIM_FILE_DISPLACEMENTS +# ifdef SIM_FILE_DISPLACEMENTS pIStream = nullptr; wxString csvName = Debug.GetLogDir() + PATHSEPSTR + SIM_FILE_DISPLACEMENTS_DEFAULT; if (wxFile::Exists(csvName)) @@ -633,21 +655,21 @@ void SimCamState::Initialize() if (pIStream && pIStream->IsOk()) pText = new wxTextInputStream(*pIStream); else - pText = nullptr; // User cancelled open dialog or file is useless - scaleConversion = 1.0; // safe default -#endif - -#ifdef SIMDEBUG - DebugFile.Open ("Sim_Debug.txt", "w"); -#ifdef SIM_FILE_DISPLACEMENTS - DebugFile.Write ("Total_X, Total_Y, RA_Ofs, Dec_Ofs \n"); -#else - DebugFile.Write ("PE, Drift, RA_Seeing, Dec_Seeing, Total_X, Total_Y, RA_Ofs, Dec_Ofs, \n"); -#endif -#endif + pText = nullptr; // User cancelled open dialog or file is useless + scaleConversion = 1.0; // safe default +# endif + +# ifdef SIMDEBUG + DebugFile.Open("Sim_Debug.txt", "w"); +# ifdef SIM_FILE_DISPLACEMENTS + DebugFile.Write("Total_X, Total_Y, RA_Ofs, Dec_Ofs \n"); +# else + DebugFile.Write("PE, Drift, RA_Seeing, Dec_Seeing, Total_X, Total_Y, RA_Ofs, Dec_Ofs, \n"); +# endif +# endif } -#if SIMMODE == 1 +# if SIMMODE == 1 bool SimCamState::ReadNextImage(usImage& img, const wxRect& subframe) { wxString filename; @@ -675,8 +697,8 @@ bool SimCamState::ReadNextImage(usImage& img, const wxRect& subframe) } Debug.Write("Sim file opened: " + filename + "\n"); - fitsfile *fptr; // FITS file pointer - int status = 0; // CFITSIO status value MUST be initialized to zero! + fitsfile *fptr; // FITS file pointer + int status = 0; // CFITSIO status value MUST be initialized to zero! if (PHD_fits_open_diskfile(&fptr, wxFileName(dir.GetName(), filename).GetFullPath(), READONLY, &status)) return true; @@ -694,7 +716,8 @@ bool SimCamState::ReadNextImage(usImage& img, const wxRect& subframe) int nhdus; fits_get_num_hdus(fptr, &nhdus, &status); - if ((nhdus != 1) || (naxis != 2)) { + if ((nhdus != 1) || (naxis != 2)) + { pFrame->Alert(_("Unsupported type or read error loading FITS file")); PHD_fits_close_file(fptr); return true; @@ -706,7 +729,8 @@ bool SimCamState::ReadNextImage(usImage& img, const wxRect& subframe) int xsize = (int) fits_size[0]; int ysize = (int) fits_size[1]; - if (img.Init(xsize, ysize)) { + if (img.Init(xsize, ysize)) + { pFrame->Alert(_("Memory allocation error")); PHD_fits_close_file(fptr); return true; @@ -757,7 +781,7 @@ bool SimCamState::ReadNextImage(usImage& img, const wxRect& subframe) return false; } -#endif // SIMMODE == 1 +# endif // SIMMODE == 1 // get a pair of normally-distributed independent random values - Box-Muller algorithm, sigma=1 static void rand_normal(double r[2]) @@ -789,25 +813,60 @@ inline static void set_pixel(usImage& img, int x, int y, unsigned short val) inline static void incr_pixel(usImage& img, int x, int y, unsigned int val) { unsigned short *const addr = pixel_addr(img, x, y); - if (addr) { + if (addr) + { unsigned int t = *addr; t += val; - if (t > (unsigned int)(unsigned short)-1) - *addr = (unsigned short)-1; + if (t > (unsigned int) (unsigned short) -1) + *addr = (unsigned short) -1; else - *addr = (unsigned short)t; + *addr = (unsigned short) t; } } static void render_comet(usImage& img, int binning, const wxRect& subframe, const wxRealPoint& p, double inten) { - enum { WIDTH = 5 }; - double STAR[][WIDTH] = { { 0.0, 0.8, 2.2, 0.8, 0.0, }, - { 0.8, 16.6, 46.1, 16.6, 0.8, }, - { 2.2, 46.1, 128.0, 46.1, 2.2, }, - { 0.8, 16.6, 46.1, 16.6, 0.8, }, - { 0.0, 0.8, 2.2, 0.8, 0.0, }, - }; + enum + { + WIDTH = 5 + }; + double STAR[][WIDTH] = { + { + 0.0, + 0.8, + 2.2, + 0.8, + 0.0, + }, + { + 0.8, + 16.6, + 46.1, + 16.6, + 0.8, + }, + { + 2.2, + 46.1, + 128.0, + 46.1, + 2.2, + }, + { + 0.8, + 16.6, + 46.1, + 16.6, + 0.8, + }, + { + 0.0, + 0.8, + 2.2, + 0.8, + 0.0, + }, + }; wxRealPoint intpart; double fx = modf(p.x / (double) binning, &intpart.x); @@ -819,21 +878,20 @@ static void render_comet(usImage& img, int binning, const wxRect& subframe, cons double d[WIDTH + 1][WIDTH + 1] = { { 0.0 } }; for (unsigned int i = 0; i < WIDTH; i++) - for (unsigned int j = 0; j < WIDTH; j++) - { - double s = STAR[i][j]; - if (s > 0.0) + for (unsigned int j = 0; j < WIDTH; j++) { - s *= inten / 256.0; - d[i][j] += f00 * s; - d[i + 1][j] += f10 * s; - d[i][j + 1] += f01 * s; - d[i + 1][j + 1] += f11 * s; + double s = STAR[i][j]; + if (s > 0.0) + { + s *= inten / 256.0; + d[i][j] += f00 * s; + d[i + 1][j] += f10 * s; + d[i][j + 1] += f01 * s; + d[i + 1][j + 1] += f11 * s; + } } - } - wxPoint c((int)intpart.x - (WIDTH - 1) / 2, - (int)intpart.y - (WIDTH - 1) / 2); + wxPoint c((int) intpart.x - (WIDTH - 1) / 2, (int) intpart.y - (WIDTH - 1) / 2); for (unsigned int x_inc = 0; x_inc < 10; x_inc++) { @@ -842,22 +900,54 @@ static void render_comet(usImage& img, int binning, const wxRect& subframe, cons int const cx = c.x + x_inc; int const cy = c.y + y * x_inc; if (cx < subframe.GetRight() && cy < subframe.GetBottom() && cy > subframe.GetTop()) - incr_pixel(img, cx, cy, (int)d[2][2]); + incr_pixel(img, cx, cy, (int) d[2][2]); } - } - } static void render_star(usImage& img, int binning, const wxRect& subframe, const wxRealPoint& p, double inten) { - enum { WIDTH = 5 }; - double STAR[][WIDTH] = {{ 0.0, 0.8, 2.2, 0.8, 0.0, }, - { 0.8, 16.6, 46.1, 16.6, 0.8, }, - { 2.2, 46.1, 128.0, 46.1, 2.2, }, - { 0.8, 16.6, 46.1, 16.6, 0.8, }, - { 0.0, 0.8, 2.2, 0.8, 0.0, }, - }; + enum + { + WIDTH = 5 + }; + double STAR[][WIDTH] = { + { + 0.0, + 0.8, + 2.2, + 0.8, + 0.0, + }, + { + 0.8, + 16.6, + 46.1, + 16.6, + 0.8, + }, + { + 2.2, + 46.1, + 128.0, + 46.1, + 2.2, + }, + { + 0.8, + 16.6, + 46.1, + 16.6, + 0.8, + }, + { + 0.0, + 0.8, + 2.2, + 0.8, + 0.0, + }, + }; wxRealPoint intpart; double fx = modf(p.x / (double) binning, &intpart.x); @@ -876,14 +966,13 @@ static void render_star(usImage& img, int binning, const wxRect& subframe, const { s *= inten / 256.0; d[i][j] += f00 * s; - d[i+1][j] += f10 * s; - d[i][j+1] += f01 * s; - d[i+1][j+1] += f11 * s; + d[i + 1][j] += f10 * s; + d[i][j + 1] += f01 * s; + d[i + 1][j + 1] += f11 * s; } } - wxPoint c((int) intpart.x - (WIDTH - 1) / 2, - (int) intpart.y - (WIDTH - 1) / 2); + wxPoint c((int) intpart.x - (WIDTH - 1) / 2, (int) intpart.y - (WIDTH - 1) / 2); for (unsigned int i = 0; i < WIDTH + 1; i++) { @@ -896,8 +985,8 @@ static void render_star(usImage& img, int binning, const wxRect& subframe, const if (cy < subframe.GetTop() || cy > subframe.GetBottom()) continue; int incr = (int) d[i][j]; - if (incr > (unsigned short)-1) - incr = (unsigned short)-1; + if (incr > (unsigned short) -1) + incr = (unsigned short) -1; incr_pixel(img, cx, cy, incr); } } @@ -913,13 +1002,14 @@ static void render_clouds(usImage& img, const wxRect& subframe, int exptime, int for (unsigned short *p = p0; p < end; p++) { // Compute a randomized brightness contribution from clouds, then overlay that on the guide frame - cloud_amt = (unsigned short)(SimCamParams::clouds_inten * ((double)gain / 10.0 * offset * exptime / 100.0 + ((rand() % (gain * 100)) / 30.0))); - *p = (unsigned short) (SimCamParams::clouds_opacity * cloud_amt + (1 - SimCamParams::clouds_opacity) * *p); + cloud_amt = (unsigned short) (SimCamParams::clouds_inten * + ((double) gain / 10.0 * offset * exptime / 100.0 + ((rand() % (gain * 100)) / 30.0))); + *p = (unsigned short) (SimCamParams::clouds_opacity * cloud_amt + (1 - SimCamParams::clouds_opacity) * *p); } } } -#ifdef SIM_FILE_DISPLACEMENTS +# ifdef SIM_FILE_DISPLACEMENTS // Get raw star displacements from a file generated by using the CAPTURE_DEFLECTIONS // compile-time option in guider.cpp to record them void SimCamState::ReadDisplacements(double& incX, double& incY) @@ -943,7 +1033,7 @@ void SimCamState::ReadDisplacements(double& incX, double& incY) wxString tk = tok.GetNextToken(); while (tk != "Scale") tk = tok.GetNextToken(); - tk = tok.GetNextToken(); // numeric image scale a-s/p + tk = tok.GetNextToken(); // numeric image scale a-s/p double realImageScale; if (tk.ToDouble(&realImageScale)) { @@ -969,21 +1059,22 @@ void SimCamState::ReadDisplacements(double& incX, double& incY) } } } -#endif +# endif void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, int gain, int offset) { unsigned int const nr_stars = stars.size(); -#ifdef SIMDEBUG - static int CountUp (0); +# ifdef SIMDEBUG + static int CountUp(0); if (CountUp == 0) { // Changes in the setup dialog are hard to track - just make sure we are using the params we think we are - Debug.AddLine (wxString::Format("SimDebug: img_scale: %.3f, seeing_scale: %.3f", SimCamParams::image_scale, SimCamParams::seeing_scale)); + Debug.AddLine(wxString::Format( + "SimDebug: img_scale: %.3f, seeing_scale: %.3f", SimCamParams::image_scale, SimCamParams::seeing_scale)); } CountUp++; -#endif +# endif // start with original star positions wxVector pos(nr_stars); @@ -993,7 +1084,7 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i double total_shift_x = 0; double total_shift_y = 0; -#ifdef SIM_FILE_DISPLACEMENTS +# ifdef SIM_FILE_DISPLACEMENTS double inc_x; double inc_y; @@ -1011,7 +1102,7 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i } } -#else // SIM_FILE_DISPLACEMENTS +# else // SIM_FILE_DISPLACEMENTS long const cur_time = timer.Time(); long const delta_time_ms = last_exposure_time - cur_time; @@ -1037,32 +1128,46 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i double const now = cur_time / 1000. - s_ra_offset; // Compute PE - canned PE terms create some "steep" sections of the curve - static double const max_amp = 4.85; // max amplitude of canned PE + static double const max_amp = 4.85; // max amplitude of canned PE double pe = 0.; if (SimCamParams::use_pe) { if (SimCamParams::use_default_pe_params) { - static double const period[] = { 230.5, 122.0, 49.4, 9.56, 76.84, }; - static double const amp[] = {2.02, 0.69, 0.22, 0.137, 0.14}; // in a-s - static double const phase[] = { 0.0, 1.4, 98.8, 35.9, 150.4, }; + static double const period[] = { + 230.5, + 122.0, + 49.4, + 9.56, + 76.84, + }; + static double const amp[] = { 2.02, 0.69, 0.22, 0.137, 0.14 }; // in a-s + static double const phase[] = { + 0.0, + 1.4, + 98.8, + 35.9, + 150.4, + }; for (unsigned int i = 0; i < WXSIZEOF(period); i++) pe += amp[i] * cos((now - phase[i]) / period[i] * 2. * M_PI); - pe *= (SimCamParams::pe_scale / (max_amp * SimCamParams::image_scale)); // modulated PE in px + pe *= (SimCamParams::pe_scale / (max_amp * SimCamParams::image_scale)); // modulated PE in px } else { - pe = SimCamParams::custom_pe_amp * cos(now / SimCamParams::custom_pe_period * 2.0 * M_PI) / SimCamParams::image_scale; + pe = SimCamParams::custom_pe_amp * cos(now / SimCamParams::custom_pe_period * 2.0 * M_PI) / + SimCamParams::image_scale; } } // simulate drift in DEC cum_dec_drift += (double) delta_time_ms * SimCamParams::dec_drift_rate / 1000.; - // Compute total movements from all sources - ra_ofs and dec_ofs are cumulative sums of all guider movements relative to zero-point + // Compute total movements from all sources - ra_ofs and dec_ofs are cumulative sums of all guider movements relative to + // zero-point total_shift_x = pe + ra_ofs; total_shift_y = cum_dec_drift + dec_ofs.val(); @@ -1072,7 +1177,7 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i if (SimCamParams::seeing_scale > 0.0) { rand_normal(seeing); - static const double seeing_adjustment = (2.345 * 1.4 * 2.4); //FWHM, geometry, empirical + static const double seeing_adjustment = (2.345 * 1.4 * 2.4); // FWHM, geometry, empirical double sigma = SimCamParams::seeing_scale / (seeing_adjustment * SimCamParams::image_scale); seeing[0] *= sigma; seeing[1] *= sigma; @@ -1080,7 +1185,7 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i total_shift_y += seeing[1]; } -#endif // SIM_FILE_DISPLACEMENTS +# endif // SIM_FILE_DISPLACEMENTS for (unsigned int i = 0; i < nr_stars; i++) { @@ -1088,16 +1193,14 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i pos[i].y += total_shift_y; } -#ifdef SIMDEBUG -#ifdef SIM_FILE_DISPLACEMENTS - DebugFile.Write(wxString::Format("%.3f, %.3f, %.3f, %.3f\n", total_shift_x, total_shift_y, - ra_ofs, dec_ofs.val())); -#else - DebugFile.Write(wxString::Format( "%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f\n", - pe, drift, seeing[0], seeing[1], total_shift_x, total_shift_y, - ra_ofs, dec_ofs.val())); -#endif -#endif +# ifdef SIMDEBUG +# ifdef SIM_FILE_DISPLACEMENTS + DebugFile.Write(wxString::Format("%.3f, %.3f, %.3f, %.3f\n", total_shift_x, total_shift_y, ra_ofs, dec_ofs.val())); +# else + DebugFile.Write(wxString::Format("%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f\n", pe, drift, seeing[0], seeing[1], + total_shift_x, total_shift_y, ra_ofs, dec_ofs.val())); +# endif +# endif // check for pier-flip if (pPointingSource) @@ -1105,7 +1208,8 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i PierSide new_side = pPointingSource->SideOfPier(); if (new_side != SimCamParams::pier_side) { - Debug.Write(wxString::Format("Cam simulator: pointing source pier side changed from %d to %d\n", SimCamParams::pier_side, new_side)); + Debug.Write(wxString::Format( + "Cam simulator: pointing source pier side changed from %d to %d\n", SimCamParams::pier_side, new_side)); SimCamParams::pier_side = new_side; } } @@ -1118,14 +1222,16 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i angle += M_PI; double const cos_t = cos(angle); double const sin_t = sin(angle); - for (unsigned int i = 0; i < nr_stars; i++) { + for (unsigned int i = 0; i < nr_stars; i++) + { cc[i].x = pos[i].x * cos_t - pos[i].y * sin_t + width / 2.0; cc[i].y = pos[i].x * sin_t + pos[i].y * cos_t + height / 2.0; } -#ifdef STEPGUIDER_SIMULATOR +# ifdef STEPGUIDER_SIMULATOR // add-in AO offset - if (s_sim_ao) { + if (s_sim_ao) + { double const ao_angle = radians(SimAoParams::angle); double const cos_a = cos(ao_angle); double const sin_a = sin(ao_angle); @@ -1133,12 +1239,13 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i double const ao_y = (double) s_sim_ao->CurrentPosition(UP) * SimAoParams::scale; double const dx = ao_x * cos_a - ao_y * sin_a; double const dy = ao_x * sin_a + ao_y * cos_a; - for (unsigned int i = 0; i < nr_stars; i++) { + for (unsigned int i = 0; i < nr_stars; i++) + { cc[i].x += dx; cc[i].y += dy; } } -#endif // STEPGUIDER_SIMULATOR +# endif // STEPGUIDER_SIMULATOR // render each star if (!pCamera->ShutterClosed) @@ -1147,13 +1254,13 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i { double star = stars[i].inten * exptime * gain; double dark = (double) gain / 10.0 * offset * exptime / 100.0; - double noise = (double)(rand() % (gain * 100)); + double noise = (double) (rand() % (gain * 100)); double inten = star + dark + noise; render_star(img, pCamera->Binning, subframe, cc[i], inten); } -#ifndef SIM_FILE_DISPLACEMENTS +# ifndef SIM_FILE_DISPLACEMENTS if (SimCamParams::show_comet) { double x = total_shift_x + now * SimCamParams::comet_rate_x / 3600.; @@ -1164,12 +1271,12 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i double inten = 3.0; double star = inten * exptime * gain; double dark = (double) gain / 10.0 * offset * exptime / 100.0; - double noise = (double)(rand() % (gain * 100)); + double noise = (double) (rand() % (gain * 100)); inten = star + dark + noise; render_comet(img, pCamera->Binning, subframe, wxRealPoint(cx, cy), inten); } -#endif +# endif } if (SimCamParams::clouds_opacity > 0) @@ -1182,31 +1289,32 @@ void SimCamState::FillImage(usImage& img, const wxRect& subframe, int exptime, i p.x /= pCamera->Binning; p.y /= pCamera->Binning; if (subframe.Contains(p)) - set_pixel(img, p.x, p.y, (unsigned short)-1); + set_pixel(img, p.x, p.y, (unsigned short) -1); } } class CameraSimulator : public GuideCamera { SimCamState sim; + public: CameraSimulator(); ~CameraSimulator(); - bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; - bool Connect(const wxString& camId) override; - bool Disconnect() override; - void ShowPropertyDialog() override; - bool HasNonGuiCapture() override { return true; } - wxByte BitsPerPixel() override; - bool SetCoolerOn(bool on) override; - bool SetCoolerSetpoint(double temperature) override; - bool GetCoolerStatus(bool *on, double *setpoint, double *power, double *temperature) override; - bool GetSensorTemperature(double *temperature) override; - bool ST4HasNonGuiMove() override { return true; } - bool ST4SynchronousOnly() override; - bool ST4PulseGuideScope(int direction, int duration) override; + bool Capture(int duration, usImage& img, int options, const wxRect& subframe) override; + bool Connect(const wxString& camId) override; + bool Disconnect() override; + void ShowPropertyDialog() override; + bool HasNonGuiCapture() override { return true; } + wxByte BitsPerPixel() override; + bool SetCoolerOn(bool on) override; + bool SetCoolerSetpoint(double temperature) override; + bool GetCoolerStatus(bool *on, double *setpoint, double *power, double *temperature) override; + bool GetSensorTemperature(double *temperature) override; + bool ST4HasNonGuiMove() override { return true; } + bool ST4SynchronousOnly() override; + bool ST4PulseGuideScope(int direction, int duration) override; PierSide SideOfPier() const; - void FlipPierSide(); + void FlipPierSide(); }; CameraSimulator::CameraSimulator() @@ -1224,11 +1332,11 @@ CameraSimulator::CameraSimulator() wxByte CameraSimulator::BitsPerPixel() { -#if 1 +# if 1 return 16; -#else +# else return 8; -#endif +# endif } bool CameraSimulator::Connect(const wxString& camId) @@ -1239,18 +1347,21 @@ bool CameraSimulator::Connect(const wxString& camId) struct ConnectInBg : public ConnectCameraInBg { CameraSimulator *cam; - ConnectInBg(CameraSimulator *cam_) : cam(cam_) { } + ConnectInBg(CameraSimulator *cam_) + : cam(cam_) + { + } bool Entry() { -//#define TEST_SLOW_CONNECT -#ifdef TEST_SLOW_CONNECT +// #define TEST_SLOW_CONNECT +# ifdef TEST_SLOW_CONNECT for (int i = 0; i < 100; i++) { wxMilliSleep(100); if (IsCanceled()) return true; } -#endif +# endif return false; } }; @@ -1270,18 +1381,18 @@ bool CameraSimulator::Disconnect() CameraSimulator::~CameraSimulator() { -#ifdef SIMDEBUG +# ifdef SIMDEBUG sim.DebugFile.Close(); -#endif -#ifdef SIM_FILE_DISPLACEMENTS +# endif +# ifdef SIM_FILE_DISPLACEMENTS if (sim.pText) delete sim.pText; if (sim.pIStream) delete sim.pIStream; -#endif +# endif } -#if SIMMODE==2 +# if SIMMODE == 2 bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxRect& subframe) { int xsize, ysize; @@ -1290,30 +1401,33 @@ bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxR unsigned char *imgptr; bool retval = disk_image.LoadFile("/Users/stark/dev/PHD/simimage.bmp"); - if (!retval) { + if (!retval) + { pFrame->Alert(_("Cannot load simulated image")); return true; } xsize = disk_image.GetWidth(); ysize = disk_image.GetHeight(); - if (img.Init(xsize,ysize)) { + if (img.Init(xsize, ysize)) + { pFrame->Alert(_("Memory allocation error")); return true; } dataptr = img.ImageData; imgptr = disk_image.GetData(); - for (unsigned int i = 0; i < img.NPixels; i++, dataptr++, imgptr++) { + for (unsigned int i = 0; i < img.NPixels; i++, dataptr++, imgptr++) + { *dataptr = (unsigned short) *imgptr; - imgptr++; imgptr++; + imgptr++; + imgptr++; } QuickLRecon(img); return false; - } -#endif +# endif -#if SIMMODE == 3 +# if SIMMODE == 3 static void fill_noise(usImage& img, const wxRect& subframe, int exptime, int gain, int offset) { unsigned short *p0 = &img.Pixel(subframe.GetLeft(), subframe.GetTop()); @@ -1321,17 +1435,19 @@ static void fill_noise(usImage& img, const wxRect& subframe, int exptime, int ga { unsigned short *const end = p0 + subframe.GetWidth(); for (unsigned short *p = p0; p < end; p++) - *p = (unsigned short) (SimCamParams::noise_multiplier * ((double) gain / 10.0 * offset * exptime / 100.0 + (rand() % (gain * 100)))); + *p = (unsigned short) (SimCamParams::noise_multiplier * + ((double) gain / 10.0 * offset * exptime / 100.0 + (rand() % (gain * 100)))); } } -#endif // SIMMODE == 3 +# endif // SIMMODE == 3 bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxRect& subframeArg) { wxRect subframe(subframeArg); CameraWatchdog watchdog(duration, GetTimeoutMs()); - // sleep before rendering the image so that any changes made in the middle of a long exposure (e.g. manual guide pulse) shows up in the image + // sleep before rendering the image so that any changes made in the middle of a long exposure (e.g. manual guide pulse) + // shows up in the image if (duration > 5) { @@ -1344,7 +1460,7 @@ bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxR } } -#if SIMMODE == 1 +# if SIMMODE == 1 if (!UseSubframes) subframe = wxRect(); @@ -1354,7 +1470,7 @@ bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxR FullSize = img.Size; -#else +# else int width = sim.width / Binning; int height = sim.height / Binning; @@ -1386,9 +1502,10 @@ bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxR if (usingSubframe) img.Subframe = subframe; - if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); + if (options & CAPTURE_SUBTRACT_DARK) + SubtractDark(img); -#endif // SIMMODE == 1 +# endif // SIMMODE == 1 unsigned int tot_dur = duration + SimCamParams::frame_download_ms; long elapsed = watchdog.Time(); @@ -1428,18 +1545,33 @@ bool CameraSimulator::ST4PulseGuideScope(int direction, int duration) if (SimCamParams::pier_side == PIER_SIDE_WEST && SimCamParams::reverse_dec_pulse_on_west_side) { // after pier flip, North/South have opposite affect on declination - switch (direction) { - case NORTH: direction = SOUTH; break; - case SOUTH: direction = NORTH; break; + switch (direction) + { + case NORTH: + direction = SOUTH; + break; + case SOUTH: + direction = NORTH; + break; } } - switch (direction) { - case WEST: sim.ra_ofs += d; break; - case EAST: sim.ra_ofs -= d; break; - case NORTH: sim.dec_ofs.incr(d); break; - case SOUTH: sim.dec_ofs.incr(-d); break; - default: return true; + switch (direction) + { + case WEST: + sim.ra_ofs += d; + break; + case EAST: + sim.ra_ofs -= d; + break; + case NORTH: + sim.dec_ofs.incr(d); + break; + case SOUTH: + sim.dec_ofs.incr(-d); + break; + default: + return true; } WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY); return false; @@ -1474,7 +1606,9 @@ bool CameraSimulator::GetCoolerStatus(bool *onp, double *setpoint, double *power if (on) { *setpoint = sim.cooler.setTemp; - *power = cur < MIN_COOLER_TEMP ? 100. : cur >= AMBIENT_TEMP ? 0. : (AMBIENT_TEMP - cur) * 100. / (AMBIENT_TEMP - MIN_COOLER_TEMP); + *power = cur < MIN_COOLER_TEMP ? 100. + : cur >= AMBIENT_TEMP ? 0. + : (AMBIENT_TEMP - cur) * 100. / (AMBIENT_TEMP - MIN_COOLER_TEMP); *temperature = cur; } else @@ -1510,21 +1644,22 @@ static PierSide OtherSide(PierSide side) void CameraSimulator::FlipPierSide() { SimCamParams::pier_side = OtherSide(SimCamParams::pier_side); - Debug.Write(wxString::Format("CamSimulator FlipPierSide: side = %d cam_angle = %.1f\n", SimCamParams::pier_side, SimCamParams::cam_angle)); + Debug.Write(wxString::Format( + "CamSimulator FlipPierSide: side = %d cam_angle = %.1f\n", SimCamParams::pier_side, SimCamParams::cam_angle)); } -#if SIMMODE == 4 +# if SIMMODE == 4 bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxRect& subframe) { int xsize, ysize; // unsigned short *dataptr; // int i; - fitsfile *fptr; // FITS file pointer - int status = 0; // CFITSIO status value MUST be initialized to zero! + fitsfile *fptr; // FITS file pointer + int status = 0; // CFITSIO status value MUST be initialized to zero! int hdutype, naxis; - int nhdus=0; + int nhdus = 0; long fits_size[2]; - long fpixel[3] = {1,1,1}; + long fpixel[3] = { 1, 1, 1 }; // char keyname[15]; // char keystrval[80]; static int frame = 0; @@ -1533,7 +1668,8 @@ bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxR snprintf(fname, sizeof(fname), "/Users/stark/dev/PHD/simimg/DriftSim_%d.fit", frame); if (!PHD_fits_open_diskfile(&fptr, fname, READONLY, &status)) { - if (fits_get_hdu_type(fptr, &hdutype, &status) || hdutype != IMAGE_HDU) { + if (fits_get_hdu_type(fptr, &hdutype, &status) || hdutype != IMAGE_HDU) + { pFrame->Alert(_("FITS file is not of an image")); PHD_fits_close_file(fptr); return true; @@ -1544,38 +1680,41 @@ bool CameraSimulator::Capture(int duration, usImage& img, int options, const wxR fits_get_img_size(fptr, 2, fits_size, &status); xsize = (int) fits_size[0]; ysize = (int) fits_size[1]; - fits_get_num_hdus(fptr,&nhdus,&status); - if ((nhdus != 1) || (naxis != 2)) { - pFrame->Alert(wxString::Format(_("Unsupported type or read error loading FITS file %d %d"),nhdus,naxis)); + fits_get_num_hdus(fptr, &nhdus, &status); + if ((nhdus != 1) || (naxis != 2)) + { + pFrame->Alert(wxString::Format(_("Unsupported type or read error loading FITS file %d %d"), nhdus, naxis)); PHD_fits_close_file(fptr); return true; } - if (img.Init(xsize,ysize)) { + if (img.Init(xsize, ysize)) + { pFrame->Alert(_("Memory allocation error")); PHD_fits_close_file(fptr); return true; } - if (fits_read_pix(fptr, TUSHORT, fpixel, xsize*ysize, nullptr, img.ImageData, nullptr, &status) ) { // Read image + if (fits_read_pix(fptr, TUSHORT, fpixel, xsize * ysize, nullptr, img.ImageData, nullptr, &status)) + { // Read image pFrame->Alert(_("Error reading data")); PHD_fits_close_file(fptr); return true; } PHD_fits_close_file(fptr); frame = frame + step; - if (frame > 440) { + if (frame > 440) + { step = -1; frame = 439; } - else if (frame < 0) { + else if (frame < 0) + { step = 1; frame = 1; } - } return false; - } -#endif // SIMMODE == 4 +# endif // SIMMODE == 4 struct SimCamDialog : public wxDialog { @@ -1588,7 +1727,7 @@ struct SimCamDialog : public wxDialog wxSpinCtrlDouble *pGuideRateSpin; wxSpinCtrlDouble *pCameraAngleSpin; wxSpinCtrlDouble *pSeeingSpin; - wxCheckBox* showComet; + wxCheckBox *showComet; wxCheckBox *pUsePECbx; wxCheckBox *pUseStiction; wxCheckBox *pReverseDecPulseCbx; @@ -1624,17 +1763,18 @@ wxEND_EVENT_TABLE(); // Utility functions for adding controls with specified properties static wxSlider *NewSlider(wxWindow *parent, int val, int minval, int maxval, const wxString& tooltip) { - wxSlider *pNewCtrl = new wxSlider(parent, wxID_ANY, val, minval, maxval, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL | wxSL_VALUE_LABEL); + wxSlider *pNewCtrl = new wxSlider( + parent, wxID_ANY, val, minval, maxval, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL | wxSL_VALUE_LABEL); pNewCtrl->SetToolTip(tooltip); return pNewCtrl; } -static wxSpinCtrlDouble *NewSpinner(wxWindow *parent, double val, double minval, double maxval, double inc, - const wxString& tooltip) +static wxSpinCtrlDouble *NewSpinner( + wxWindow *parent, double val, double minval, double maxval, double inc, const wxString& tooltip) { wxSize sz = pFrame->GetTextExtent(wxString::Format("%.2f", maxval * 10.)); - wxSpinCtrlDouble *pNewCtrl = pFrame->MakeSpinCtrlDouble(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, - sz, wxSP_ARROW_KEYS, minval, maxval, val, inc); + wxSpinCtrlDouble *pNewCtrl = pFrame->MakeSpinCtrlDouble( + parent, wxID_ANY, wxEmptyString, wxDefaultPosition, sz, wxSP_ARROW_KEYS, minval, maxval, val, inc); pNewCtrl->SetDigits(2); pNewCtrl->SetToolTip(tooltip); return pNewCtrl; @@ -1651,18 +1791,19 @@ static wxCheckBox *NewCheckBox(wxWindow *parent, bool val, const wxString& label // Utility function to add the pairs to a grid including tool-tips static void AddTableEntryPair(wxWindow *parent, wxFlexGridSizer *pTable, const wxString& label, wxWindow *pControl) { - wxStaticText *pLabel = new wxStaticText(parent, wxID_ANY, label + _(": "), wxPoint(-1,-1), wxSize(-1,-1)); + wxStaticText *pLabel = new wxStaticText(parent, wxID_ANY, label + _(": "), wxPoint(-1, -1), wxSize(-1, -1)); pTable->Add(pLabel, 1, wxALL, 5); pTable->Add(pControl, 1, wxALL, 5); } -static wxTextCtrl *AddCustomPEField(wxWindow *parent, wxFlexGridSizer *pTable, const wxString& label, const wxString& tip, double val) +static wxTextCtrl *AddCustomPEField( + wxWindow *parent, wxFlexGridSizer *pTable, const wxString& label, const wxString& tip, double val) { int width; int height; parent->GetTextExtent(_T("999.9"), &width, &height); - wxTextCtrl *pCtrl = new wxTextCtrl(parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width+30, -1)); + wxTextCtrl *pCtrl = new wxTextCtrl(parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width + 30, -1)); pCtrl->SetValue(wxString::Format("%.1f", val)); pCtrl->SetToolTip(tip); AddTableEntryPair(parent, pTable, label, pCtrl); @@ -1689,7 +1830,7 @@ static void SetControlStates(SimCamDialog *dlg, bool captureActive) dlg->pPECustomPeriod->Enable(enable); dlg->pPECustomRb->Enable(enable); dlg->pUsePECbx->Enable(enable); - dlg->pUseStiction->Show(false); // no good for end-users + dlg->pUseStiction->Show(false); // no good for end-users dlg->pPierFlip->Enable(enable); dlg->pReverseDecPulseCbx->Enable(enable); dlg->pResetBtn->Enable(enable); @@ -1751,7 +1892,7 @@ SimCamDialog::SimCamDialog(wxWindow *parent) AddTableEntryPair(this, pCamTable, _("Stars"), pStarsSlider); pHotpxSlider = NewSlider(this, SimCamParams::nr_hot_pixels, 0, 50, _("Number of hot pixels")); AddTableEntryPair(this, pCamTable, _("Hot pixels"), pHotpxSlider); - pNoiseSlider = NewSlider(this, (int)floor(SimCamParams::noise_multiplier * 100 / NOISE_MAX), 0, 100, + pNoiseSlider = NewSlider(this, (int) floor(SimCamParams::noise_multiplier * 100 / NOISE_MAX), 0, 100, /* xgettext:no-c-format */ _("% Simulated noise")); AddTableEntryPair(this, pCamTable, _("Noise"), pNoiseSlider); pCamGroup->Add(pCamTable); @@ -1759,14 +1900,16 @@ SimCamDialog::SimCamDialog(wxWindow *parent) // Mount group controls wxStaticBoxSizer *pMountGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Mount")); wxFlexGridSizer *pMountTable = new wxFlexGridSizer(2, 6, 5, 15); - pBacklashSpin = NewSpinner(this, SimCamParams::dec_backlash * imageScale, 0, DEC_BACKLASH_MAX, 0.1, _("Dec backlash, arc-secs")); + pBacklashSpin = + NewSpinner(this, SimCamParams::dec_backlash * imageScale, 0, DEC_BACKLASH_MAX, 0.1, _("Dec backlash, arc-secs")); AddTableEntryPair(this, pMountTable, _("Dec backlash"), pBacklashSpin); - pDriftSpin = NewSpinner(this, SimCamParams::dec_drift_rate * 60.0 * imageScale, -DEC_DRIFT_MAX, DEC_DRIFT_MAX, 0.5, _("Dec drift, arc-sec/min")); + pDriftSpin = NewSpinner(this, SimCamParams::dec_drift_rate * 60.0 * imageScale, -DEC_DRIFT_MAX, DEC_DRIFT_MAX, 0.5, + _("Dec drift, arc-sec/min")); AddTableEntryPair(this, pMountTable, _("Dec drift"), pDriftSpin); pGuideRateSpin = NewSpinner(this, SimCamParams::guide_rate / 15.0, 0.25, GUIDE_RATE_MAX, 0.25, _("Guide rate, x sidereal")); AddTableEntryPair(this, pMountTable, _("Guide rate"), pGuideRateSpin); pUseStiction = NewCheckBox(this, SimCamParams::use_stiction, _("Apply stiction"), _("Simulate dec axis stiction")); - pUseStiction->Enable(false); // too crude to put in hands of users + pUseStiction->Enable(false); // too crude to put in hands of users pMountTable->Add(pUseStiction, 1, wxBOTTOM, 15); pMountGroup->Add(pMountTable); @@ -1779,8 +1922,8 @@ SimCamDialog::SimCamDialog(wxWindow *parent) pPEDefaultRb = new wxRadioButton(this, wxID_ANY, _("Default curve"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP); pPEDefaultRb->SetValue(SimCamParams::use_default_pe_params); pPEDefaultRb->SetToolTip(_("Use a built-in PE curve that has some steep and smooth sections.")); - pPEDefaultRb->Bind(wxEVT_COMMAND_RADIOBUTTON_SELECTED, &SimCamDialog::OnRbDefaultPE, this); // Event handler binding - wxStaticText *pSliderLabel = new wxStaticText(this, wxID_ANY, _("Amplitude: "),wxPoint(-1,-1),wxSize(-1,-1)); + pPEDefaultRb->Bind(wxEVT_COMMAND_RADIOBUTTON_SELECTED, &SimCamDialog::OnRbDefaultPE, this); // Event handler binding + wxStaticText *pSliderLabel = new wxStaticText(this, wxID_ANY, _("Amplitude: "), wxPoint(-1, -1), wxSize(-1, -1)); pPEDefScale = NewSpinner(this, SimCamParams::pe_scale, 0, PE_SCALE_MAX, 0.5, _("PE Amplitude, arc-secs")); int hor_spacing = StringWidth(this, "9"); @@ -1792,7 +1935,7 @@ SimCamDialog::SimCamDialog(wxWindow *parent) pPECustomRb = new wxRadioButton(this, wxID_ANY, _("Custom curve"), wxDefaultPosition, wxDefaultSize); pPECustomRb->SetValue(!SimCamParams::use_default_pe_params); pPECustomRb->SetToolTip(_("Use a simple sinusoidal curve. You can specify the amplitude and period.")); - pPECustomRb->Bind(wxEVT_COMMAND_RADIOBUTTON_SELECTED, &SimCamDialog::OnRbCustomPE, this); // Event handler binding + pPECustomRb->Bind(wxEVT_COMMAND_RADIOBUTTON_SELECTED, &SimCamDialog::OnRbCustomPE, this); // Event handler binding pPECustom->Add(pPECustomRb, wxSizerFlags().Border(wxTOP, 4)); pPECustomAmp = AddCustomPEField(this, pPECustom, _("Amplitude"), _("Amplitude, arc-secs"), SimCamParams::custom_pe_amp); pPECustomPeriod = AddCustomPEField(this, pPECustom, _("Period"), _("Period, seconds"), SimCamParams::custom_pe_period); @@ -1807,14 +1950,15 @@ SimCamDialog::SimCamDialog(wxWindow *parent) // Now add some miscellaneous mount-related stuff (still within mount group) wxBoxSizer *pMiscSizer = new wxBoxSizer(wxHORIZONTAL); - pReverseDecPulseCbx = NewCheckBox(this, SimCamParams::reverse_dec_pulse_on_west_side, _("Reverse Dec pulse on West side of pier"), - _("Simulate a mount that reverses guide pulse direction after a meridian flip, like an ASCOM pulse-guided mount.")); + pReverseDecPulseCbx = + NewCheckBox(this, SimCamParams::reverse_dec_pulse_on_west_side, _("Reverse Dec pulse on West side of pier"), + _("Simulate a mount that reverses guide pulse direction after a meridian flip, like an ASCOM pulse-guided mount.")); pPierSide = SimCamParams::pier_side; pPiersideLabel = new wxStaticText(this, wxID_ANY, _("Side of Pier: MMMMM")); pMiscSizer->Add(pReverseDecPulseCbx, wxSizerFlags().Border(10).Expand()); pPierFlip = new wxButton(this, wxID_CONVERT, _("Pier Flip")); pMiscSizer->Add(pPierFlip, wxSizerFlags().Border(wxLEFT, 30).Expand()); - pMiscSizer->Add(pPiersideLabel , wxSizerFlags().Border(wxLEFT, 30).Expand()); + pMiscSizer->Add(pPiersideLabel, wxSizerFlags().Border(wxLEFT, 30).Expand()); pMountGroup->Add(pPEGroup, wxSizerFlags().Center().Border(10).Expand()); pMountGroup->Add(pMiscSizer, wxSizerFlags().Border(wxTOP, 10).Expand()); @@ -1825,7 +1969,7 @@ SimCamDialog::SimCamDialog(wxWindow *parent) AddTableEntryPair(this, pSessionTable, _("Camera angle"), pCameraAngleSpin); pSeeingSpin = NewSpinner(this, SimCamParams::seeing_scale, 0, SEEING_MAX, 0.5, _("Seeing, FWHM arc-sec")); AddTableEntryPair(this, pSessionTable, _("Seeing"), pSeeingSpin); - pCloudSlider = NewSlider(this, (int)(100 * SimCamParams::clouds_opacity), 0, 100, _("% cloud opacity")); + pCloudSlider = NewSlider(this, (int) (100 * SimCamParams::clouds_opacity), 0, 100, _("% cloud opacity")); AddTableEntryPair(this, pSessionTable, _("Cloud %"), pCloudSlider); showComet = new wxCheckBox(this, wxID_ANY, _("Comet")); showComet->SetValue(SimCamParams::show_comet); @@ -1837,31 +1981,23 @@ SimCamDialog::SimCamDialog(wxWindow *parent) pVSizer->Add(pSessionGroup, wxSizerFlags().Border(wxRIGHT | wxLEFT, 10).Expand()); // Now deal with the buttons - wxBoxSizer *pButtonSizer = new wxBoxSizer( wxHORIZONTAL ); + wxBoxSizer *pButtonSizer = new wxBoxSizer(wxHORIZONTAL); pResetBtn = new wxButton(this, wxID_RESET, _("Reset")); pResetBtn->SetToolTip(_("Reset all values to application defaults")); - pButtonSizer->Add( - pResetBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pButtonSizer->Add(pResetBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); // Need to handle the OK event ourselves to validate text input fields wxButton *pBtn = new wxButton(this, wxID_OK, _("OK")); pBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &SimCamDialog::OnOkClick, this); - pButtonSizer->Add( - pBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); - pButtonSizer->Add( - new wxButton( this, wxID_CANCEL, _("Cancel") ), - wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pButtonSizer->Add(pBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); + pButtonSizer->Add(new wxButton(this, wxID_CANCEL, _("Cancel")), wxSizerFlags(0).Align(0).Border(wxALL, 10)); // position the buttons centered with no border - pVSizer->Add( - pButtonSizer, - wxSizerFlags(0).Center() ); + pVSizer->Add(pButtonSizer, wxSizerFlags(0).Center()); SetSizerAndFit(pVSizer); SetControlStates(this, pFrame->CaptureActive); if (!pFrame->CaptureActive) - SetRBState(this, pPEDefaultRb->GetValue()); // Enable matching PE-related controls + SetRBState(this, pPEDefaultRb->GetValue()); // Enable matching PE-related controls UpdatePierSideLabel(); } @@ -1869,7 +2005,7 @@ void SimCamDialog::OnReset(wxCommandEvent& event) { pStarsSlider->SetValue(NR_STARS_DEFAULT); pHotpxSlider->SetValue(NR_HOT_PIXELS_DEFAULT); - pNoiseSlider->SetValue((int)floor(NOISE_DEFAULT * 100.0 / NOISE_MAX)); + pNoiseSlider->SetValue((int) floor(NOISE_DEFAULT * 100.0 / NOISE_MAX)); pBacklashSpin->SetValue(DEC_BACKLASH_DEFAULT); pCloudSlider->SetValue(0); @@ -1883,10 +2019,10 @@ void SimCamDialog::OnReset(wxCommandEvent& event) pPEDefaultRb->SetValue(USE_PE_DEFAULT_PARAMS); pPECustomRb->SetValue(!USE_PE_DEFAULT_PARAMS); pPEDefScale->SetValue(PE_SCALE_DEFAULT); - pPECustomAmp->SetValue(wxString::Format("%0.1f",PE_CUSTOM_AMP_DEFAULT)); + pPECustomAmp->SetValue(wxString::Format("%0.1f", PE_CUSTOM_AMP_DEFAULT)); pPECustomPeriod->SetValue(wxString::Format("%0.1f", PE_CUSTOM_PERIOD_DEFAULT)); pPierSide = PIER_SIDE_DEFAULT; - SetRBState( this, USE_PE_DEFAULT_PARAMS); + SetRBState(this, USE_PE_DEFAULT_PARAMS); UpdatePierSideLabel(); showComet->SetValue(SHOW_COMET_DEFAULT); } @@ -1898,7 +2034,7 @@ void SimCamDialog::OnPierFlip(wxCommandEvent& event) if (angle >= 360) angle -= 360; pCameraAngleSpin->SetValue(angle); - pPierSide= OtherSide(pPierSide); + pPierSide = OtherSide(pPierSide); UpdatePierSideLabel(); } @@ -1910,9 +2046,13 @@ void SimCamDialog::UpdatePierSideLabel() struct UpdateChecker { bool updated; - UpdateChecker() : updated(false) { } + UpdateChecker() + : updated(false) + { + } template - void Update(T& val, const U& newval) { + void Update(T& val, const U& newval) + { if (val != newval) { val = newval; @@ -1925,15 +2065,15 @@ struct UpdateChecker void CameraSimulator::ShowPropertyDialog() { SimCamDialog dlg(pFrame); - double imageScale = pFrame->GetCameraPixelScale(); // arc-sec/pixel, defaults to 1.0 if no user specs - SimCamParams::image_scale = imageScale; // keep current - might have gotten changed in brain dialog + double imageScale = pFrame->GetCameraPixelScale(); // arc-sec/pixel, defaults to 1.0 if no user specs + SimCamParams::image_scale = imageScale; // keep current - might have gotten changed in brain dialog if (dlg.ShowModal() == wxID_OK) { UpdateChecker upd; // keep track of whether any values changed upd.Update(SimCamParams::nr_stars, dlg.pStarsSlider->GetValue()); upd.Update(SimCamParams::nr_hot_pixels, dlg.pHotpxSlider->GetValue()); SimCamParams::noise_multiplier = (double) dlg.pNoiseSlider->GetValue() * NOISE_MAX / 100.0; - upd.Update(SimCamParams::dec_backlash, dlg.pBacklashSpin->GetValue() / imageScale); // a-s -> px + upd.Update(SimCamParams::dec_backlash, dlg.pBacklashSpin->GetValue() / imageScale); // a-s -> px bool use_pe = dlg.pUsePECbx->GetValue(); SimCamParams::use_pe = use_pe; @@ -1949,10 +2089,10 @@ void CameraSimulator::ShowPropertyDialog() dlg.pPECustomAmp->GetValue().ToDouble(&SimCamParams::custom_pe_amp); dlg.pPECustomPeriod->GetValue().ToDouble(&SimCamParams::custom_pe_period); } - SimCamParams::dec_drift_rate = dlg.pDriftSpin->GetValue() / (imageScale * 60.0); // a-s per min to px per second - SimCamParams::seeing_scale = dlg.pSeeingSpin->GetValue(); // already in a-s + SimCamParams::dec_drift_rate = dlg.pDriftSpin->GetValue() / (imageScale * 60.0); // a-s per min to px per second + SimCamParams::seeing_scale = dlg.pSeeingSpin->GetValue(); // already in a-s upd.Update(SimCamParams::cam_angle, dlg.pCameraAngleSpin->GetValue()); - SimCamParams::guide_rate = dlg.pGuideRateSpin->GetValue() * 15.0; + SimCamParams::guide_rate = dlg.pGuideRateSpin->GetValue() * 15.0; SimCamParams::pier_side = dlg.pPierSide; SimCamParams::reverse_dec_pulse_on_west_side = dlg.pReverseDecPulseCbx->GetValue(); SimCamParams::show_comet = dlg.showComet->GetValue(); diff --git a/src/graph-stepguider.cpp b/src/graph-stepguider.cpp index 735e4e3b1..3b62684c4 100644 --- a/src/graph-stepguider.cpp +++ b/src/graph-stepguider.cpp @@ -41,7 +41,6 @@ class GraphStepguiderClient : public wxWindow { public: - static const unsigned int m_maxHistorySize = 64; struct @@ -53,11 +52,11 @@ class GraphStepguiderClient : public wxWindow PHD_Point m_avgPos; PHD_Point m_curBump; - wxPen *m_pPens[m_maxHistorySize]; + wxPen *m_pPens[m_maxHistorySize]; wxBrush *m_pBrushes[m_maxHistorySize]; - unsigned int m_nItems; // # of items in the history - unsigned int m_length; // # of items to display + unsigned int m_nItems; // # of items in the history + unsigned int m_length; // # of items to display int m_xMax; int m_yMax; @@ -84,8 +83,8 @@ wxBEGIN_EVENT_TABLE(GraphStepguiderWindow, wxWindow) wxEND_EVENT_TABLE(); // clang-format on -GraphStepguiderWindow::GraphStepguiderWindow(wxWindow *parent) : - wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, _("AO Position")) +GraphStepguiderWindow::GraphStepguiderWindow(wxWindow *parent) + : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, _("AO Position")) { SetBackgroundColour(*wxBLACK); @@ -98,23 +97,25 @@ GraphStepguiderWindow::GraphStepguiderWindow(wxWindow *parent) : pMainSizer->Add(pLeftSizer, wxSizerFlags().Expand()); m_pClient->m_length = pConfig->Global.GetInt("/graph_stepguider/length", 1); - wxString label = wxString::Format(_T("%3d"),m_pClient->m_length); - LengthButton = new OptionsButton(this,BUTTON_GRAPH_LENGTH,label,wxPoint(10,10),wxSize(80,-1),wxALIGN_CENTER_HORIZONTAL); + wxString label = wxString::Format(_T("%3d"), m_pClient->m_length); + LengthButton = + new OptionsButton(this, BUTTON_GRAPH_LENGTH, label, wxPoint(10, 10), wxSize(80, -1), wxALIGN_CENTER_HORIZONTAL); LengthButton->SetToolTip(_("Select the number of frames of history to display")); pLeftSizer->Add(LengthButton, wxSizerFlags().Border(wxALL, 3).Expand()); - ClearButton = new wxButton(this,BUTTON_GRAPH_CLEAR,_("Clear"),wxPoint(10,100),wxSize(80,-1)); + ClearButton = new wxButton(this, BUTTON_GRAPH_CLEAR, _("Clear"), wxPoint(10, 100), wxSize(80, -1)); ClearButton->SetToolTip(_("Clear graph data")); pLeftSizer->Add(ClearButton, wxSizerFlags().Center().Border(wxALL, 3)); pLeftSizer->AddStretchSpacer(); - m_hzText = new wxStaticText(this, wxID_ANY, wxEmptyString/*wxString::Format(_("%.1f Hz"), 999.9)*/, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER | wxST_NO_AUTORESIZE); + m_hzText = new wxStaticText(this, wxID_ANY, wxEmptyString /*wxString::Format(_("%.1f Hz"), 999.9)*/, wxDefaultPosition, + wxDefaultSize, wxALIGN_CENTER | wxST_NO_AUTORESIZE); m_hzText->SetForegroundColour(*wxLIGHT_GREY); m_hzText->SetBackgroundColour(*wxBLACK); pLeftSizer->Add(m_hzText, wxSizerFlags().Border(wxALL, 3).Expand()); - pMainSizer->Add(m_pClient, wxSizerFlags().Border(wxALL,3).Expand().Proportion(1)); + pMainSizer->Add(m_pClient, wxSizerFlags().Border(wxALL, 3).Expand().Proportion(1)); SetSizer(pMainSizer); pMainSizer->SetSizeHints(this); @@ -142,8 +143,7 @@ void GraphStepguiderWindow::OnButtonLength(wxCommandEvent& WXUNUSED(evt)) break; } - PopupMenu(menu, LengthButton->GetPosition().x, - LengthButton->GetPosition().y + LengthButton->GetSize().GetHeight()); + PopupMenu(menu, LengthButton->GetPosition().x, LengthButton->GetPosition().y + LengthButton->GetSize().GetHeight()); delete menu; } @@ -175,8 +175,7 @@ bool GraphStepguiderWindow::SetState(bool is_active) return m_visible; } -void GraphStepguiderWindow::SetLimits(unsigned int xMax, unsigned int yMax, - unsigned int xBump, unsigned int yBump) +void GraphStepguiderWindow::SetLimits(unsigned int xMax, unsigned int yMax, unsigned int xBump, unsigned int yBump) { assert(wxThread::IsMain()); @@ -240,8 +239,8 @@ wxBEGIN_EVENT_TABLE(GraphStepguiderClient, wxWindow) wxEND_EVENT_TABLE(); // clang-format on -GraphStepguiderClient::GraphStepguiderClient(wxWindow *parent) : - wxWindow(parent, wxID_ANY, wxDefaultPosition, wxSize(201,201), wxFULL_REPAINT_ON_RESIZE) +GraphStepguiderClient::GraphStepguiderClient(wxWindow *parent) + : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxSize(201, 201), wxFULL_REPAINT_ON_RESIZE) { SetBackgroundStyle(wxBG_STYLE_PAINT); @@ -250,9 +249,9 @@ GraphStepguiderClient::GraphStepguiderClient(wxWindow *parent) : for (unsigned int i = 0; i < m_maxHistorySize; i++) { - int color = (int)(i * 255 / m_maxHistorySize); - m_pPens[i] = new wxPen(wxColor(color,color,color)); - m_pBrushes[i] = new wxBrush(wxColor(color,color,color), wxBRUSHSTYLE_SOLID); + int color = (int) (i * 255 / m_maxHistorySize); + m_pPens[i] = new wxPen(wxColor(color, color, color)); + m_pBrushes[i] = new wxBrush(wxColor(color, color, color), wxBRUSHSTYLE_SOLID); } SetLimits(0, 0, 0, 0); @@ -267,8 +266,7 @@ GraphStepguiderClient::~GraphStepguiderClient(void) } } -void GraphStepguiderClient::SetLimits(unsigned int xMax, unsigned int yMax, - unsigned int xBump, unsigned int yBump) +void GraphStepguiderClient::SetLimits(unsigned int xMax, unsigned int yMax, unsigned int xBump, unsigned int yBump) { m_xMax = xMax; m_yMax = yMax; @@ -297,7 +295,7 @@ void GraphStepguiderClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) wxAutoBufferedPaintDC dc(this); dc.SetBackground(*wxBLACK_BRUSH); - //dc.SetBackground(wxColour(10,0,0)); + // dc.SetBackground(wxColour(10,0,0)); dc.Clear(); wxSize size = GetClientSize(); @@ -311,8 +309,8 @@ void GraphStepguiderClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) return; } - wxPen GreySolidPen = wxPen(wxColour(200,200,200),2, wxPENSTYLE_SOLID); - wxPen GreyDashPen = wxPen(wxColour(200,200,200),1, wxPENSTYLE_DOT); + wxPen GreySolidPen = wxPen(wxColour(200, 200, 200), 2, wxPENSTYLE_SOLID); + wxPen GreyDashPen = wxPen(wxColour(200, 200, 200), 1, wxPENSTYLE_DOT); const int stepsPerDivision = 10; @@ -326,16 +324,16 @@ void GraphStepguiderClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) int yDivisions = ySteps / stepsPerDivision; int yPixelsPerStep = (size.y - 1) / (2 * ySteps); - int leftEdge = center.x - xDivisions * stepsPerDivision * xPixelsPerStep; - int rightEdge = center.x + xDivisions * stepsPerDivision * xPixelsPerStep; + int leftEdge = center.x - xDivisions * stepsPerDivision * xPixelsPerStep; + int rightEdge = center.x + xDivisions * stepsPerDivision * xPixelsPerStep; - int topEdge = center.y - yDivisions * stepsPerDivision * yPixelsPerStep; - int bottomEdge = center.y + yDivisions * stepsPerDivision * yPixelsPerStep; + int topEdge = center.y - yDivisions * stepsPerDivision * yPixelsPerStep; + int bottomEdge = center.y + yDivisions * stepsPerDivision * yPixelsPerStep; // Draw axes dc.SetPen(GreySolidPen); - dc.DrawLine(leftEdge, center.y , rightEdge, center.y); + dc.DrawLine(leftEdge, center.y, rightEdge, center.y); dc.DrawLine(center.x, topEdge, center.x, bottomEdge); // Draw divisions @@ -418,7 +416,7 @@ void GraphStepguiderClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) for (unsigned int i = startPoint; i < m_maxHistorySize; i++) { - if (i == m_maxHistorySize-1) + if (i == m_maxHistorySize - 1) { dotSize *= 2; } @@ -435,16 +433,14 @@ void GraphStepguiderClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) dc.SetPen(*wxGREEN_PEN); dc.SetBrush(*wxTRANSPARENT_BRUSH); - dc.DrawCircle(center.x + (int)(m_avgPos.X * xPixelsPerStep), - center.y + (int)(m_avgPos.Y * yPixelsPerStep), dotSize); + dc.DrawCircle(center.x + (int) (m_avgPos.X * xPixelsPerStep), center.y + (int) (m_avgPos.Y * yPixelsPerStep), dotSize); if (m_curBump.IsValid()) { dc.SetPen(*wxGREEN_PEN); - dc.DrawLine(center.x + (int)(m_avgPos.X * xPixelsPerStep), - center.y + (int)(m_avgPos.Y * yPixelsPerStep), - center.x + (int)((m_avgPos.X + m_curBump.X * 2.0) * xPixelsPerStep), - center.y + (int)((m_avgPos.Y + m_curBump.Y * 2.0) * yPixelsPerStep)); + dc.DrawLine(center.x + (int) (m_avgPos.X * xPixelsPerStep), center.y + (int) (m_avgPos.Y * yPixelsPerStep), + center.x + (int) ((m_avgPos.X + m_curBump.X * 2.0) * xPixelsPerStep), + center.y + (int) ((m_avgPos.Y + m_curBump.Y * 2.0) * yPixelsPerStep)); } } } diff --git a/src/graph.cpp b/src/graph.cpp index 82a556e01..255d52084 100644 --- a/src/graph.cpp +++ b/src/graph.cpp @@ -64,17 +64,21 @@ wxEND_EVENT_TABLE(); // clang-format on #ifdef __WXOSX__ -# define OSX_SMALL_FONT(lbl) do { (lbl)->SetFont(*wxSMALL_FONT); } while (0) +# define OSX_SMALL_FONT(lbl) \ + do \ + { \ + (lbl)->SetFont(*wxSMALL_FONT); \ + } while (0) #else # define OSX_SMALL_FONT(lbl) #endif -GraphLogWindow::GraphLogWindow(wxWindow *parent) : - wxWindow(parent,wxID_ANY,wxDefaultPosition,wxDefaultSize, wxFULL_REPAINT_ON_RESIZE,_T("Graph")) +GraphLogWindow::GraphLogWindow(wxWindow *parent) + : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE, _T("Graph")) { SetBackgroundStyle(wxBG_STYLE_PAINT); - wxBoxSizer *pMainSizer = new wxBoxSizer(wxHORIZONTAL); + wxBoxSizer *pMainSizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer *pButtonSizer = new wxBoxSizer(wxVERTICAL); wxBoxSizer *pClientSizer = new wxBoxSizer(wxVERTICAL); @@ -87,13 +91,13 @@ GraphLogWindow::GraphLogWindow(wxWindow *parent) : { m_pXControlPane = pMount->GetXGuideAlgorithmControlPane(this); m_pYControlPane = pMount->GetYGuideAlgorithmControlPane(this); - m_pScopePane = pMount->GetGraphControlPane(this, _("Scope:")); + m_pScopePane = pMount->GetGraphControlPane(this, _("Scope:")); } else { m_pXControlPane = nullptr; m_pYControlPane = nullptr; - m_pScopePane = nullptr; + m_pScopePane = nullptr; } if (m_pXControlPane) @@ -115,26 +119,30 @@ GraphLogWindow::GraphLogWindow(wxWindow *parent) : SetBackgroundColour(*wxBLACK); - m_pLengthButton = new OptionsButton(this,BUTTON_GRAPH_LENGTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_HORIZONTAL); + m_pLengthButton = new OptionsButton( + this, BUTTON_GRAPH_LENGTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_HORIZONTAL); m_pLengthButton->SetToolTip(_("Select the number of frames of history to display on the X-axis")); m_pLengthButton->SetLabel(wxString::Format(_T("x: %3d"), m_pClient->m_length)); pButtonSizer->Add(m_pLengthButton, wxSizerFlags().Border(wxTOP, 5).Expand()); - m_pHeightButton = new OptionsButton(this,BUTTON_GRAPH_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_HORIZONTAL); + m_pHeightButton = new OptionsButton( + this, BUTTON_GRAPH_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_HORIZONTAL); m_heightButtonLabelVal = 0; UpdateHeightButtonLabel(); pButtonSizer->Add(m_pHeightButton, wxSizerFlags().Expand()); - m_pSettingsButton = new OptionsButton(this, BUTTON_GRAPH_SETTINGS, _("Settings"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_HORIZONTAL); + m_pSettingsButton = new OptionsButton( + this, BUTTON_GRAPH_SETTINGS, _("Settings"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_HORIZONTAL); m_pSettingsButton->SetToolTip(_("Graph settings")); pButtonSizer->Add(m_pSettingsButton, wxSizerFlags().Expand()); wxButton *clearButton = new wxButton(this, BUTTON_GRAPH_CLEAR, _("Clear")); - clearButton->SetToolTip(_("Clear graph data. You can also partially clear the graph by holding down the Ctrl key and clicking on the graph where you want the data to start.")); + clearButton->SetToolTip(_("Clear graph data. You can also partially clear the graph by holding down the Ctrl key and " + "clicking on the graph where you want the data to start.")); clearButton->SetBackgroundStyle(wxBG_STYLE_TRANSPARENT); pButtonSizer->Add(clearButton, wxSizerFlags().Expand()); - m_pCheckboxTrendlines = new wxCheckBox(this,CHECKBOX_GRAPH_TRENDLINES,_("Trendlines")); + m_pCheckboxTrendlines = new wxCheckBox(this, CHECKBOX_GRAPH_TRENDLINES, _("Trendlines")); #if defined(__WXOSX__) // workaround inability to set checkbox foreground color m_pCheckboxTrendlines->SetBackgroundColour(wxColor(200, 200, 200)); @@ -144,7 +152,7 @@ GraphLogWindow::GraphLogWindow(wxWindow *parent) : m_pCheckboxTrendlines->SetToolTip(_("Plot trend lines")); pButtonSizer->Add(m_pCheckboxTrendlines, wxSizerFlags().Expand().Border(wxTOP, 1)); - m_pCheckboxCorrections = new wxCheckBox(this,CHECKBOX_GRAPH_CORRECTIONS,_("Corrections")); + m_pCheckboxCorrections = new wxCheckBox(this, CHECKBOX_GRAPH_CORRECTIONS, _("Corrections")); #if defined(__WXOSX__) // workaround inability to set checkbox foreground color m_pCheckboxCorrections->SetBackgroundColour(wxColor(200, 200, 200)); @@ -188,7 +196,7 @@ GraphLogWindow::GraphLogWindow(wxWindow *parent) : OSX_SMALL_FONT(lbl); lbl->SetForegroundColour(*wxLIGHT_GREY); lbl->SetBackgroundColour(*wxBLACK); - m_pClient->m_pRaRMS = new wxStaticText(this, wxID_ANY, _T("0.00"), wxDefaultPosition, wxSize(80,-1)); + m_pClient->m_pRaRMS = new wxStaticText(this, wxID_ANY, _T("0.00"), wxDefaultPosition, wxSize(80, -1)); OSX_SMALL_FONT(m_pClient->m_pRaRMS); m_pClient->m_pRaRMS->SetForegroundColour(*wxLIGHT_GREY); m_pClient->m_pRaRMS->SetBackgroundColour(*wxBLACK); @@ -201,7 +209,7 @@ GraphLogWindow::GraphLogWindow(wxWindow *parent) : OSX_SMALL_FONT(lbl); lbl->SetForegroundColour(*wxLIGHT_GREY); lbl->SetBackgroundColour(*wxBLACK); - m_pClient->m_pDecRMS = new wxStaticText(this, wxID_ANY, _T("0.00"), wxDefaultPosition, wxSize(80,-1)); + m_pClient->m_pDecRMS = new wxStaticText(this, wxID_ANY, _T("0.00"), wxDefaultPosition, wxSize(80, -1)); OSX_SMALL_FONT(m_pClient->m_pDecRMS); m_pClient->m_pDecRMS->SetForegroundColour(*wxLIGHT_GREY); m_pClient->m_pDecRMS->SetBackgroundColour(*wxBLACK); @@ -214,7 +222,7 @@ GraphLogWindow::GraphLogWindow(wxWindow *parent) : OSX_SMALL_FONT(lbl); lbl->SetForegroundColour(*wxLIGHT_GREY); lbl->SetBackgroundColour(*wxBLACK); - m_pClient->m_pTotRMS = new wxStaticText(this, wxID_ANY, _T("0.00"), wxDefaultPosition, wxSize(80,-1)); + m_pClient->m_pTotRMS = new wxStaticText(this, wxID_ANY, _T("0.00"), wxDefaultPosition, wxSize(80, -1)); OSX_SMALL_FONT(m_pClient->m_pTotRMS); m_pClient->m_pTotRMS->SetForegroundColour(*wxLIGHT_GREY); m_pClient->m_pTotRMS->SetBackgroundColour(*wxBLACK); @@ -325,14 +333,14 @@ void GraphLogWindow::UpdateRADecDxDyLabels() { switch (m_pClient->m_mode) { - case GraphLogClientWindow::MODE_RADEC: - m_pLabel1->SetLabel(_("RA")); - m_pLabel2->SetLabel(_("Dec")); - break; - case GraphLogClientWindow::MODE_DXDY: - m_pLabel1->SetLabel(_("dx")); - m_pLabel2->SetLabel(_("dy")); - break; + case GraphLogClientWindow::MODE_RADEC: + m_pLabel1->SetLabel(_("RA")); + m_pLabel2->SetLabel(_("Dec")); + break; + case GraphLogClientWindow::MODE_DXDY: + m_pLabel1->SetLabel(_("dx")); + m_pLabel2->SetLabel(_("dy")); + break; } } @@ -373,7 +381,7 @@ void GraphLogWindow::OnArcsecsPixels(wxCommandEvent& evt) m_pClient->m_heightUnits = UNIT_PIXELS; break; } - pConfig->Global.SetInt("/graph/HeightUnits", (int)m_pClient->m_heightUnits); + pConfig->Global.SetInt("/graph/HeightUnits", (int) m_pClient->m_heightUnits); Refresh(); } @@ -450,8 +458,8 @@ void GraphLogWindow::OnButtonLength(wxCommandEvent& WXUNUSED(evt)) { wxMenu *menu = GetLengthMenu(); - PopupMenu(menu, m_pLengthButton->GetPosition().x, - m_pLengthButton->GetPosition().y + m_pLengthButton->GetSize().GetHeight()); + PopupMenu( + menu, m_pLengthButton->GetPosition().x, m_pLengthButton->GetPosition().y + m_pLengthButton->GetSize().GetHeight()); delete menu; } @@ -506,8 +514,8 @@ void GraphLogWindow::OnButtonHeight(wxCommandEvent& WXUNUSED(evt)) break; } - PopupMenu(menu, m_pHeightButton->GetPosition().x, - m_pHeightButton->GetPosition().y + m_pHeightButton->GetSize().GetHeight()); + PopupMenu( + menu, m_pHeightButton->GetPosition().x, m_pHeightButton->GetPosition().y + m_pHeightButton->GetSize().GetHeight()); delete menu; } @@ -604,13 +612,13 @@ void GraphLogWindow::UpdateControls() { m_pXControlPane = pMount->GetXGuideAlgorithmControlPane(this); m_pYControlPane = pMount->GetYGuideAlgorithmControlPane(this); - m_pScopePane = pMount->GetGraphControlPane(this, _("Scope:")); + m_pScopePane = pMount->GetGraphControlPane(this, _("Scope:")); } else { m_pXControlPane = nullptr; m_pYControlPane = nullptr; - m_pScopePane = nullptr; + m_pScopePane = nullptr; } if (m_pXControlPane) @@ -676,7 +684,7 @@ void GraphLogWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) wxAutoBufferedPaintDC dc(this); dc.SetBackground(*wxBLACK_BRUSH); - //dc.SetBackground(wxColour(10,0,0)); + // dc.SetBackground(wxColour(10,0,0)); dc.Clear(); UpdateHeightButtonLabel(); @@ -756,10 +764,10 @@ wxBEGIN_EVENT_TABLE(GraphLogClientWindow, wxWindow) wxEND_EVENT_TABLE(); // clang-format on -GraphLogClientWindow::GraphLogClientWindow(wxWindow *parent) : - wxWindow(parent, wxID_ANY, wxDefaultPosition, wxSize(401,200), wxFULL_REPAINT_ON_RESIZE), - m_line1(0), - m_line2(0) +GraphLogClientWindow::GraphLogClientWindow(wxWindow *parent) + : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxSize(401, 200), wxFULL_REPAINT_ON_RESIZE) + , m_line1(0) + , m_line2(0) { SetBackgroundStyle(wxBG_STYLE_PAINT); @@ -768,12 +776,12 @@ GraphLogClientWindow::GraphLogClientWindow(wxWindow *parent) : if (!m_raOrDxColor.Set(pConfig->Global.GetString("/graph/RAColor", wxEmptyString))) { - m_raOrDxColor = wxColour(100,100,255); + m_raOrDxColor = wxColour(100, 100, 255); pConfig->Global.SetString("/graph/RAColor", m_raOrDxColor.GetAsString(wxC2S_HTML_SYNTAX)); } if (!m_decOrDyColor.Set(pConfig->Global.GetString("/graph/DecColor", wxEmptyString))) { - m_decOrDyColor = wxColour(255,0,0); + m_decOrDyColor = wxColour(255, 0, 0); pConfig->Global.SetString("/graph/DecColor", m_decOrDyColor.GetAsString(wxC2S_HTML_SYNTAX)); } @@ -792,9 +800,10 @@ GraphLogClientWindow::GraphLogClientWindow(wxWindow *parent) : m_length = pConfig->Global.GetInt("/graph/length", m_minLength * 2); m_noDitherDec.ChangeWindowSize(m_length); m_noDitherRA.ChangeWindowSize(m_length); - Debug.Write(wxString::Format("GraphStats window size = %d\n", (int)m_length)); + Debug.Write(wxString::Format("GraphStats window size = %d\n", (int) m_length)); m_height = pConfig->Global.GetInt("/graph/height", m_minHeight * 2 * 2); // match PHD1 4-pixel scale for new users - m_heightUnits = (GRAPH_UNITS) pConfig->Global.GetInt("graph/HeightUnits", (int) UNIT_ARCSEC); // preferred units, will still display pixels if camera pixel scale not available + m_heightUnits = (GRAPH_UNITS) pConfig->Global.GetInt("graph/HeightUnits", + (int) UNIT_ARCSEC); // preferred units, will still display pixels if camera pixel scale not available m_showTrendlines = false; m_showCorrections = pConfig->Global.GetBoolean("/graph/showCorrections", true); @@ -805,8 +814,8 @@ GraphLogClientWindow::GraphLogClientWindow(wxWindow *parent) : GraphLogClientWindow::~GraphLogClientWindow() { - delete [] m_line1; - delete [] m_line2; + delete[] m_line1; + delete[] m_line2; } static void reset_trend_accums(TrendLineAccum accums[4]) @@ -879,10 +888,10 @@ bool GraphLogClientWindow::SetMaxLength(unsigned int maxLength) m_history.resize(maxLength); - delete [] m_line1; + delete[] m_line1; m_line1 = new wxPoint[maxLength]; - delete [] m_line2; + delete[] m_line2; m_line2 = new wxPoint[maxLength]; pConfig->Global.SetInt("/graph/maxLength", m_history.capacity()); @@ -966,7 +975,7 @@ static double rms(unsigned int nr, const TrendLineAccum *accum) { if (nr == 0) return 0.0; - double const n = (double)nr; + double const n = (double) nr; double const s1 = accum->sum_y; double const s2 = accum->sum_y2; return sqrt(n * s2 - s1 * s1) / n; @@ -983,7 +992,7 @@ void GraphLogClientWindow::UpdateStats(unsigned int nr, const S_HISTORY *cur) if (nr >= 2) { - m_stats.osc_index = 1.0 - (double) m_raSameSides / (double)(nr - 1); + m_stats.osc_index = 1.0 - (double) m_raSameSides / (double) (nr - 1); m_stats.osc_alert = m_stats.osc_index > 0.6 || m_stats.osc_index < 0.15; } else @@ -1001,12 +1010,13 @@ void GraphLogClientWindow::UpdateStats(unsigned int nr, const S_HISTORY *cur) } } -static double peak_ra(const circular_buffer &history, unsigned int nr) +static double peak_ra(const circular_buffer& history, unsigned int nr) { double peak = 0.0; const int end = history.size(); const int begin = end - nr; - for (int i = begin; i < end; i++) { + for (int i = begin; i < end; i++) + { double val = fabs(history[i].ra); if (val > peak) peak = val; @@ -1014,12 +1024,13 @@ static double peak_ra(const circular_buffer &history, unsigned int nr return peak; } -static double peak_dec(const circular_buffer &history, unsigned int nr) +static double peak_dec(const circular_buffer& history, unsigned int nr) { double peak = 0.0; const int end = history.size(); const int begin = end - nr; - for (int i = begin; i < end; i++) { + for (int i = begin; i < end; i++) + { double val = fabs(history[i].dec); if (val > peak) peak = val; @@ -1101,7 +1112,8 @@ void GraphLogClientWindow::RecalculateTrendLines() reset_trend_accums(m_trendLineAccum); unsigned int trend_items = GetItemCount(); const int begin = m_history.size() - trend_items; - for (unsigned int x = 0, i = begin; x < trend_items; i++, x++) { + for (unsigned int x = 0, i = begin; x < trend_items; i++, x++) + { const S_HISTORY& h = m_history[i]; update_trend(x, trend_items, h.dx, 0.0, &m_trendLineAccum[0]); update_trend(x, trend_items, h.dy, 0.0, &m_trendLineAccum[1]); @@ -1175,10 +1187,14 @@ struct ScaleAndTranslate { int m_xorig, m_yorig; double m_xmag, m_ymag; - ScaleAndTranslate(int xorig, int yorig, double xmag, double ymag) : m_xorig(xorig), m_yorig(yorig), m_xmag(xmag), m_ymag(ymag) { } - wxPoint pt(double x, double y) const { - return wxPoint(m_xorig + (int)(x * m_xmag), m_yorig + (int)(y * m_ymag)); + ScaleAndTranslate(int xorig, int yorig, double xmag, double ymag) + : m_xorig(xorig) + , m_yorig(yorig) + , m_xmag(xmag) + , m_ymag(ymag) + { } + wxPoint pt(double x, double y) const { return wxPoint(m_xorig + (int) (x * m_xmag), m_yorig + (int) (y * m_ymag)); } }; static wxString rms_label(double rms, double sampling) @@ -1229,7 +1245,10 @@ static double GetMaxStarSNR(const circular_buffer& history, int start return maxSNR; } -enum { GRAPH_BORDER = 5 }; +enum +{ + GRAPH_BORDER = 5 +}; void GraphLogClientWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) { @@ -1262,12 +1281,12 @@ void GraphLogClientWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) dc.SetBackground(*wxBLACK_BRUSH); dc.Clear(); - wxPen GreyDashPen(wxColour(200,200,200),1, wxPENSTYLE_DOT); + wxPen GreyDashPen(wxColour(200, 200, 200), 1, wxPENSTYLE_DOT); // Draw axes dc.SetPen(*wxGREY_PEN); - dc.DrawLine(center.x,topEdge,center.x,bottomEdge); - dc.DrawLine(leftEdge,center.y,rightEdge,center.y); + dc.DrawLine(center.x, topEdge, center.x, bottomEdge); + dc.DrawLine(leftEdge, center.y, rightEdge, center.y); // draw a box around the client area dc.DrawLine(leftEdge, topEdge, rightEdge, topEdge); @@ -1289,12 +1308,15 @@ void GraphLogClientWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) for (int i = 1; i <= m_yDivisions; i++) { double div_y = center.y - i * yPixelsPerDivision; - dc.DrawLine(leftEdge,div_y, rightEdge, div_y); - dc.DrawText(wxString::Format("%g%s", i * (double)m_height / (m_yDivisions + 1), units == UNIT_ARCSEC ? "''" : (i == 3 ? " px" : "")), leftEdge + 3, div_y - 13); + dc.DrawLine(leftEdge, div_y, rightEdge, div_y); + dc.DrawText(wxString::Format("%g%s", i * (double) m_height / (m_yDivisions + 1), + units == UNIT_ARCSEC ? "''" : (i == 3 ? " px" : "")), + leftEdge + 3, div_y - 13); div_y = center.y + i * yPixelsPerDivision; dc.DrawLine(leftEdge, div_y, rightEdge, div_y); - dc.DrawText(wxString::Format("%g%s", -i * (double)m_height / (m_yDivisions + 1), units == UNIT_ARCSEC ? "''" : ""), leftEdge + 3, div_y - 13); + dc.DrawText(wxString::Format("%g%s", -i * (double) m_height / (m_yDivisions + 1), units == UNIT_ARCSEC ? "''" : ""), + leftEdge + 3, div_y - 13); } for (int i = 1; i <= xDivisions; i++) @@ -1304,7 +1326,8 @@ void GraphLogClientWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) } const double xmag = size.x / (double) m_length; - const double ymag = yPixelsPerDivision * (double)(m_yDivisions + 1) / (double)m_height * (units == UNIT_ARCSEC ? sampling : 1.0); + const double ymag = + yPixelsPerDivision * (double) (m_yDivisions + 1) / (double) m_height * (units == UNIT_ARCSEC ? sampling : 1.0); ScaleAndTranslate sctr(xorig, yorig, xmag, ymag); @@ -1387,7 +1410,7 @@ void GraphLogClientWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) wxPoint pt(sctr.pt(j, decDur)); pt.x += 5; if (decDur < 0) - dc.DrawRectangle(pt,wxSize(4, yorig - pt.y)); + dc.DrawRectangle(pt, wxSize(4, yorig - pt.y)); else dc.DrawRectangle(wxPoint(pt.x, yorig), wxSize(4, pt.y - yorig)); } @@ -1515,9 +1538,9 @@ void GraphLogClientWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) { const S_HISTORY& h0 = m_history[start_item]; const S_HISTORY& h1 = m_history[m_history.size() - 1]; - double dt = (double)(h1.timestamp - h0.timestamp) / (1000.0 * 60.0); // time span in minutes - double ddec = (double) (plot_length - 1) * trendDecOrDy.first; // dec drift (pixels) - ddec *= sampling; // convert pixels to arc-seconds + double dt = (double) (h1.timestamp - h0.timestamp) / (1000.0 * 60.0); // time span in minutes + double ddec = (double) (plot_length - 1) * trendDecOrDy.first; // dec drift (pixels) + ddec *= sampling; // convert pixels to arc-seconds // From Frank Barrett, "Determining Polar Axis Alignment Accuracy" // http://celestialwonders.com/articles/polaralignment/PolarAlignmentAccuracy.pdf double err_arcmin = (3.82 * ddec) / (dt * cos(declination)); @@ -1525,15 +1548,15 @@ void GraphLogClientWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) double correction = pFrame->pGuider->GetPolarAlignCircleCorrection(); double err_px = polarAlignCircleRadius * correction; dc.DrawText(wxString::Format("Polar alignment error: %.2f' (%s%.f px)", err_arcmin, - correction < 1.0 ? "" : "< ", err_px), + correction < 1.0 ? "" : "< ", err_px), leftEdge + 30, bottomEdge - 18); } } } // when drifting, center the polar align circle on the star; when adjusting, center the polar // align circle at the lock position - const PHD_Point& center = pFrame->pGuider->IsCalibratingOrGuiding() ? - pFrame->pGuider->CurrentPosition() : pFrame->pGuider->LockPosition(); + const PHD_Point& center = + pFrame->pGuider->IsCalibratingOrGuiding() ? pFrame->pGuider->CurrentPosition() : pFrame->pGuider->LockPosition(); pFrame->pGuider->SetPolarAlignCircle(center, polarAlignCircleRadius); m_pRaRMS->SetLabel(rms_label(m_stats.rms_ra, sampling)); @@ -1542,7 +1565,7 @@ void GraphLogClientWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) if (m_stats.osc_alert) { - m_pOscIndex->SetForegroundColour(wxColour(185,20,0)); + m_pOscIndex->SetForegroundColour(wxColour(185, 20, 0)); } else { @@ -1571,7 +1594,7 @@ void GraphLogClientWindow::OnLeftBtnDown(wxMouseEvent& evt) unsigned int plot_length = GetItemCount(); unsigned int start_item = m_history.size() - plot_length; - unsigned int i = start_item + (unsigned int) floor((double)(evt.GetX() - xorig) / xmag + 0.5); + unsigned int i = start_item + (unsigned int) floor((double) (evt.GetX() - xorig) / xmag + 0.5); if (i < m_history.size()) { wxLongLong_t deltaT = m_history[m_history.size() - 1].timestamp - m_history[i].timestamp; @@ -1580,7 +1603,8 @@ void GraphLogClientWindow::OnLeftBtnDown(wxMouseEvent& evt) // Some items removed from m_history may not be resident in the "noDither" collections int numDeletes = wxMin(m_noDitherDec.GetCount(), i); - long newStart = m_noDitherDec.GetLastEntry().DeltaTime - deltaT; // mSec for new starting point in noDither collections + long newStart = + m_noDitherDec.GetLastEntry().DeltaTime - deltaT; // mSec for new starting point in noDither collections while (numDeletes > 0) { @@ -1623,8 +1647,8 @@ GraphControlPane::GraphControlPane(wxWindow *pParent, const wxString& label) SetBackgroundColour(*wxBLACK); - int width = StringWidth(label); - wxStaticText *pLabel = new wxStaticText(this,wxID_ANY,label, wxDefaultPosition, wxSize(width + 5, -1)); + int width = StringWidth(label); + wxStaticText *pLabel = new wxStaticText(this, wxID_ANY, label, wxDefaultPosition, wxSize(width + 5, -1)); wxFont f = pLabel->GetFont(); f.SetWeight(wxFONTWEIGHT_BOLD); pLabel->SetFont(f); @@ -1635,18 +1659,11 @@ GraphControlPane::GraphControlPane(wxWindow *pParent, const wxString& label) SetSizer(m_pControlSizer); } -GraphControlPane::~GraphControlPane() -{ -} +GraphControlPane::~GraphControlPane() { } -void GraphControlPane::UpdateControls() -{ -} - -void GraphControlPane::EnableDecControls(bool enable) -{ +void GraphControlPane::UpdateControls() { } -} +void GraphControlPane::EnableDecControls(bool enable) { } int GraphControlPane::StringWidth(const wxString& string) { diff --git a/src/graph.h b/src/graph.h index 7f4368010..c1b2b1eee 100644 --- a/src/graph.h +++ b/src/graph.h @@ -71,12 +71,21 @@ struct S_HISTORY bool decLimited; S_HISTORY() { } S_HISTORY(const GuideStepInfo& step) - : timestamp(::wxGetUTCTimeMillis().GetValue()), - dx(step.cameraOffset.X), dy(step.cameraOffset.Y), ra(step.mountOffset.X), dec(step.mountOffset.Y), - starSNR(step.starSNR), starMass(step.starMass), - raDur(step.durationRA), decDur(step.durationDec), - raDir(step.directionRA), decDir(step.directionDec), - raLimited(step.raLimited), decLimited(step.decLimited) { } + : timestamp(::wxGetUTCTimeMillis().GetValue()) + , dx(step.cameraOffset.X) + , dy(step.cameraOffset.Y) + , ra(step.mountOffset.X) + , dec(step.mountOffset.Y) + , starSNR(step.starSNR) + , starMass(step.starMass) + , raDur(step.durationRA) + , decDur(step.durationDec) + , raDir(step.directionRA) + , decDir(step.directionDec) + , raLimited(step.raLimited) + , decLimited(step.decLimited) + { + } }; struct DitherInfo @@ -209,8 +218,8 @@ class GraphLogWindow : public wxWindow void UpdateRADecDxDyLabels(); public: - - enum { + enum + { DefaultMinLength = 50, DefaultMaxLength = 400, DefaultMinHeight = 1, @@ -234,7 +243,7 @@ class GraphLogWindow : public wxWindow void SetHeight(int height); wxMenu *GetLengthMenu(); unsigned int GetHistoryItemCount() const; - void EnableDecControls(bool enable); // For changes to Dec mode made outside of graph pane (e.g. AD) + void EnableDecControls(bool enable); // For changes to Dec mode made outside of graph pane (e.g. AD) void OnPaint(wxPaintEvent& evt); void OnButtonSettings(wxCommandEvent& evt); @@ -273,6 +282,7 @@ class GraphControlPane : public wxWindow ~GraphControlPane(); virtual void UpdateControls(); virtual void EnableDecControls(bool enable); + protected: wxBoxSizer *m_pControlSizer; diff --git a/src/guide_algorithm.cpp b/src/guide_algorithm.cpp index 59a2e84eb..d6133d031 100644 --- a/src/guide_algorithm.cpp +++ b/src/guide_algorithm.cpp @@ -41,8 +41,8 @@ wxString GuideAlgorithm::GetConfigPath() const { - return "/" + m_pMount->GetMountClassName() + "/GuideAlgorithm/" + - (m_guideAxis == GUIDE_X ? "X/" : "Y/") + GetGuideAlgorithmClassName(); + return "/" + m_pMount->GetMountClassName() + "/GuideAlgorithm/" + (m_guideAxis == GUIDE_X ? "X/" : "Y/") + + GetGuideAlgorithmClassName(); } wxString GuideAlgorithm::GetAxis() const @@ -50,9 +50,9 @@ wxString GuideAlgorithm::GetAxis() const return m_guideAxis == GUIDE_RA ? _("RA") : _("DEC"); } -// Default technique to force a reset on algo parameters is simply to remove the keys from the Registry - a subsequent creation of the algo -// class will then use default values for everything. If this is too brute-force for a particular algo, the function can be overridden. -// For algos that use a min-move parameter, a smart value will be applied based on image scale +// Default technique to force a reset on algo parameters is simply to remove the keys from the Registry - a subsequent creation +// of the algo class will then use default values for everything. If this is too brute-force for a particular algo, the +// function can be overridden. For algos that use a min-move parameter, a smart value will be applied based on image scale void GuideAlgorithm::ResetParams() { wxString configPath = GetConfigPath(); @@ -87,25 +87,22 @@ double GuideAlgorithm::SmartDefaultMinMove() } } -void GuideAlgorithm::AdjustMinMoveSpinCtrl(wxSpinCtrlDouble* minMoveCtrl) +void GuideAlgorithm::AdjustMinMoveSpinCtrl(wxSpinCtrlDouble *minMoveCtrl) { // Always use current AD values for all params affecting image scale - double smartMove = GuideAlgorithm::SmartDefaultMinMove(pFrame->pAdvancedDialog->GetFocalLength(), pFrame->pAdvancedDialog->GetPixelSize(), pFrame->pAdvancedDialog->GetBinning()); + double smartMove = GuideAlgorithm::SmartDefaultMinMove(pFrame->pAdvancedDialog->GetFocalLength(), + pFrame->pAdvancedDialog->GetPixelSize(), pFrame->pAdvancedDialog->GetBinning()); minMoveCtrl->SetValue(smartMove); } -void GuideAlgorithm::GuidingStarted() -{ -} +void GuideAlgorithm::GuidingStarted() { } void GuideAlgorithm::GuidingStopped() { reset(); } -void GuideAlgorithm::GuidingPaused() -{ -} +void GuideAlgorithm::GuidingPaused() { } void GuideAlgorithm::GuidingResumed() { @@ -117,17 +114,14 @@ void GuideAlgorithm::GuidingDithered(double amt) reset(); } -void GuideAlgorithm::GuidingDitherSettleDone(bool success) -{ -} +void GuideAlgorithm::GuidingDitherSettleDone(bool success) { } -void GuideAlgorithm::DirectMoveApplied(double amt) -{ -} +void GuideAlgorithm::DirectMoveApplied(double amt) { } void GuideAlgorithm::GuidingDisabled() { - // By default, guide star deflections will be accumulated even with guiding disabled - algo can override if this is a problem + // By default, guide star deflections will be accumulated even with guiding disabled - algo can override if this is a + // problem } void GuideAlgorithm::GuidingEnabled() @@ -136,9 +130,7 @@ void GuideAlgorithm::GuidingEnabled() reset(); } -void GuideAlgorithm::GetParamNames(wxArrayString& names) const -{ -} +void GuideAlgorithm::GetParamNames(wxArrayString& names) const { } bool GuideAlgorithm::GetParam(const wxString& name, double *val) const { diff --git a/src/guide_algorithm.h b/src/guide_algorithm.h index 2426d7d36..880bf2e01 100644 --- a/src/guide_algorithm.h +++ b/src/guide_algorithm.h @@ -76,7 +76,9 @@ class GuideAlgorithm GuideAxis m_guideAxis; public: - GuideAlgorithm(Mount *pMount, GuideAxis axis) : m_pMount(pMount), m_guideAxis(axis) {}; + GuideAlgorithm(Mount *pMount, GuideAxis axis) + : m_pMount(pMount) + , m_guideAxis(axis) {}; virtual ~GuideAlgorithm() {}; virtual GUIDE_ALGORITHM Algorithm() const = 0; @@ -102,11 +104,11 @@ class GuideAlgorithm virtual bool GetParam(const wxString& name, double *val) const; virtual bool SetParam(const wxString& name, double val); virtual double GetMinMove() const { return -1.0; }; - virtual bool SetMinMove(double minMove) { return true; }; // true indicates error + virtual bool SetMinMove(double minMove) { return true; }; // true indicates error wxString GetConfigPath() const; wxString GetAxis() const; - virtual void ResetParams(); // Override if fine-tuned logic is needed by a particular algo - static void AdjustMinMoveSpinCtrl(wxSpinCtrlDouble* minMoveCtrl); + virtual void ResetParams(); // Override if fine-tuned logic is needed by a particular algo + static void AdjustMinMoveSpinCtrl(wxSpinCtrlDouble *minMoveCtrl); static double SmartDefaultMinMove(); static double SmartDefaultMinMove(int focalLength, double pixelSize, int binning); }; diff --git a/src/guide_algorithm_gaussian_process.cpp b/src/guide_algorithm_gaussian_process.cpp index a50251be6..ae08ad6e7 100644 --- a/src/guide_algorithm_gaussian_process.cpp +++ b/src/guide_algorithm_gaussian_process.cpp @@ -13,31 +13,31 @@ */ /* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, nor the names of its -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -*/ + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, nor the names of its + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ #include "phd.h" @@ -52,25 +52,26 @@ /** Default values for the parameters of this algorithm */ -static const double DefaultControlGain = 0.6; // control gain -static const double DefaultPeriodLengthsForInference = 2.0; // minimal number of period lengths for full prediction -static const double DefaultMinMove = 0.2; +static const double DefaultControlGain = 0.6; // control gain +static const double DefaultPeriodLengthsForInference = 2.0; // minimal number of period lengths for full prediction +static const double DefaultMinMove = 0.2; -static const double DefaultLengthScaleSE0Ker = 700.0; // length-scale of the long-range SE-kernel -static const double DefaultSignalVarianceSE0Ker = 20.0; // signal variance of the long-range SE-kernel -static const double DefaultLengthScalePerKer = 10.0; // length-scale of the periodic kernel -static const double DefaultPeriodLengthPerKer = 200.0; // P_p, period-length of the periodic kernel -static const double DefaultSignalVariancePerKer = 20.0; // signal variance of the periodic kernel -static const double DefaultLengthScaleSE1Ker = 25.0; // length-scale of the short-range SE-kernel -static const double DefaultSignalVarianceSE1Ker = 10.0; // signal variance of the short range SE-kernel +static const double DefaultLengthScaleSE0Ker = 700.0; // length-scale of the long-range SE-kernel +static const double DefaultSignalVarianceSE0Ker = 20.0; // signal variance of the long-range SE-kernel +static const double DefaultLengthScalePerKer = 10.0; // length-scale of the periodic kernel +static const double DefaultPeriodLengthPerKer = 200.0; // P_p, period-length of the periodic kernel +static const double DefaultSignalVariancePerKer = 20.0; // signal variance of the periodic kernel +static const double DefaultLengthScaleSE1Ker = 25.0; // length-scale of the short-range SE-kernel +static const double DefaultSignalVarianceSE1Ker = 10.0; // signal variance of the short range SE-kernel static const double DefaultPeriodLengthsForPeriodEstimation = 2.0; // minimal number of period lengts for PL estimation -static const int DefaultNumPointsForApproximation = 100; // number of points used in the GP approximation -static const double DefaultPredictionGain = 0.5; // amount of GP prediction to blend in +static const int DefaultNumPointsForApproximation = 100; // number of points used in the GP approximation +static const double DefaultPredictionGain = 0.5; // amount of GP prediction to blend in -static const double DefaultNoresetMaxPctPeriod = 40.; // max percent of worm period elapsed to skip resetting the model when guiding is stopped and resumed +static const double DefaultNoresetMaxPctPeriod = + 40.; // max percent of worm period elapsed to skip resetting the model when guiding is stopped and resumed -static const bool DefaultComputePeriod = true; +static const bool DefaultComputePeriod = true; static void MakeBold(wxControl *ctrl) { @@ -79,15 +80,22 @@ static void MakeBold(wxControl *ctrl) ctrl->SetFont(font); } -GuideAlgorithmGaussianProcess:: -GPExpertDialog::GPExpertDialog(wxWindow *Parent) : - wxDialog(Parent, wxID_ANY, _("Expert Settings"), wxDefaultPosition, wxDefaultSize), - m_pPeriodLengthsInference(0), m_pPeriodLengthsPeriodEstimation(0), m_pNumPointsApproximation(0), m_pSE0KLengthScale(0), m_pSE0KSignalVariance(0), m_pPKLengthScale(0), - m_pPKSignalVariance(0), m_pSE1KLengthScale(0), m_pSE1KSignalVariance(0) +GuideAlgorithmGaussianProcess::GPExpertDialog::GPExpertDialog(wxWindow *Parent) + : wxDialog(Parent, wxID_ANY, _("Expert Settings"), wxDefaultPosition, wxDefaultSize) + , m_pPeriodLengthsInference(0) + , m_pPeriodLengthsPeriodEstimation(0) + , m_pNumPointsApproximation(0) + , m_pSE0KLengthScale(0) + , m_pSE0KSignalVariance(0) + , m_pPKLengthScale(0) + , m_pPKSignalVariance(0) + , m_pSE1KLengthScale(0) + , m_pSE1KSignalVariance(0) { // create the expert options UI wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); - wxStaticText *warning = new wxStaticText(this, wxID_ANY, _("Warning! Intended for use by experts"), wxPoint(-1, -1), wxSize(-1, -1)); + wxStaticText *warning = + new wxStaticText(this, wxID_ANY, _("Warning! Intended for use by experts"), wxPoint(-1, -1), wxSize(-1, -1)); MakeBold(warning); vSizer->Add(warning, wxSizerFlags().Center().Border(wxBOTTOM, 10)); @@ -95,85 +103,93 @@ GPExpertDialog::GPExpertDialog(wxWindow *Parent) : int width; width = StringWidth(this, _T("0000")); - m_pNumPointsApproximation = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0, 2000, DefaultNumPointsForApproximation); + m_pNumPointsApproximation = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0, 2000, DefaultNumPointsForApproximation); AddTableEntry(flexGrid, _("Approximation Data Points"), m_pNumPointsApproximation, wxString::Format(_("Number of data points used in the approximation. Both prediction accuracy " - "as well as runtime rise with the number of datapoints. Default = %d"), DefaultNumPointsForApproximation)); + "as well as runtime rise with the number of datapoints. Default = %d"), + DefaultNumPointsForApproximation)); width = StringWidth(this, _T("0.00")); - m_pPeriodLengthsInference = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 10.0, DefaultPeriodLengthsForInference, 0.1); + m_pPeriodLengthsInference = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 10.0, DefaultPeriodLengthsForInference, 0.1); m_pPeriodLengthsInference->SetDigits(2); AddTableEntry(flexGrid, _("Minimum Worm Cycles (Prediction)"), m_pPeriodLengthsInference, wxString::Format(_("Minimal number of worm cycles needed to use the prediction. " - "If there are too little data points, the prediction might be poor. " - "Default = %.2f"), DefaultPeriodLengthsForInference)); + "If there are too little data points, the prediction might be poor. " + "Default = %.2f"), + DefaultPeriodLengthsForInference)); width = StringWidth(this, _T("0000")); - m_pPeriodLengthsPeriodEstimation = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 10.0, DefaultPeriodLengthsForPeriodEstimation, 0.1); + m_pPeriodLengthsPeriodEstimation = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 10.0, DefaultPeriodLengthsForPeriodEstimation, 0.1); m_pPeriodLengthsPeriodEstimation->SetDigits(2); AddTableEntry(flexGrid, _("Minimum Worm Cycles (Period Estimation)"), m_pPeriodLengthsPeriodEstimation, wxString::Format(_("Minimal number of worm cycles for estimating the period length. " - "If there are too little data points, the estimation might not work. Default = %d"), - (int)DefaultPeriodLengthsForPeriodEstimation)); + "If there are too little data points, the estimation might not work. Default = %d"), + (int) DefaultPeriodLengthsForPeriodEstimation)); width = StringWidth(this, _T("0000.0")); - m_pSE0KLengthScale = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 100.0, 5000.0, DefaultLengthScaleSE0Ker, 10.0); + m_pSE0KLengthScale = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 100.0, 5000.0, DefaultLengthScaleSE0Ker, 10.0); m_pSE0KLengthScale->SetDigits(2); AddTableEntry(flexGrid, _("Length Scale (Long Range)"), m_pSE0KLengthScale, wxString::Format(_("The length scale (in seconds) of the large non-periodic structure. " - "This is essentially a high-pass filter for the periodic error and the length scale " - "defines the corner frequency. Default = %.2f"), - DefaultLengthScaleSE0Ker)); + "This is essentially a high-pass filter for the periodic error and the length scale " + "defines the corner frequency. Default = %.2f"), + DefaultLengthScaleSE0Ker)); width = StringWidth(this, _T("000.0")); - m_pSE0KSignalVariance = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 100.0, DefaultSignalVarianceSE0Ker, 1.0); + m_pSE0KSignalVariance = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 100.0, DefaultSignalVarianceSE0Ker, 1.0); m_pSE0KSignalVariance->SetDigits(2); AddTableEntry(flexGrid, _("Signal Variance (Long Range)"), m_pSE0KSignalVariance, - wxString::Format(_("Signal variance (in pixels) of the long-term variations. Default = %.2f"), DefaultSignalVarianceSE0Ker)); + wxString::Format( + _("Signal variance (in pixels) of the long-term variations. Default = %.2f"), DefaultSignalVarianceSE0Ker)); width = StringWidth(this, _T("000.0")); - m_pPKLengthScale = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 50.0, DefaultLengthScalePerKer, 5.0); + m_pPKLengthScale = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 1.0, 50.0, DefaultLengthScalePerKer, 5.0); m_pPKLengthScale->SetDigits(2); AddTableEntry(flexGrid, _("Length Scale (Periodic)"), m_pPKLengthScale, wxString::Format(_("The length scale (in seconds) defines the \"wigglyness\" of the periodic structure. " - "The smaller the length scale, the more structure can be learned. If chosen too " - "small, some non-periodic structure might be picked up as well. Default = %.2f"), DefaultLengthScalePerKer)); + "The smaller the length scale, the more structure can be learned. If chosen too " + "small, some non-periodic structure might be picked up as well. Default = %.2f"), + DefaultLengthScalePerKer)); width = StringWidth(this, _T("000.0")); - m_pPKSignalVariance = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 100.0, DefaultSignalVariancePerKer, 0.1); + m_pPKSignalVariance = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 100.0, DefaultSignalVariancePerKer, 0.1); m_pPKSignalVariance->SetDigits(2); AddTableEntry(flexGrid, _("Signal Variance (Periodic)"), m_pPKSignalVariance, wxString::Format(_("The signal variance (in pixels) of the periodic error. " - "Default = %.2f"), DefaultSignalVariancePerKer)); + "Default = %.2f"), + DefaultSignalVariancePerKer)); width = StringWidth(this, _T("000.0")); - m_pSE1KLengthScale = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 100.0, DefaultLengthScaleSE1Ker, 1.0); + m_pSE1KLengthScale = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 1.0, 100.0, DefaultLengthScaleSE1Ker, 1.0); m_pSE1KLengthScale->SetDigits(2); AddTableEntry(flexGrid, _("Length Scale (Short Range)"), m_pSE1KLengthScale, wxString::Format(_("Length scale (in seconds) of the short range non-periodic parts " - "of the gear error. This is essentially a low-pass filter for the periodic error and the length " - "scale defines the corner frequency. Default = %.2f"), DefaultLengthScaleSE1Ker)); + "of the gear error. This is essentially a low-pass filter for the periodic error and the length " + "scale defines the corner frequency. Default = %.2f"), + DefaultLengthScaleSE1Ker)); width = StringWidth(this, _T("000.0")); - m_pSE1KSignalVariance = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 100.0, DefaultSignalVarianceSE1Ker, 0.1); + m_pSE1KSignalVariance = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 100.0, DefaultSignalVarianceSE1Ker, 0.1); m_pSE1KSignalVariance->SetDigits(2); AddTableEntry(flexGrid, _("Signal Variance (Short Range)"), m_pSE1KSignalVariance, - wxString::Format(_("Signal variance (in pixels) of the short-term variations. Default = %.2f"), DefaultSignalVarianceSE1Ker)); + wxString::Format( + _("Signal variance (in pixels) of the short-term variations. Default = %.2f"), DefaultSignalVarianceSE1Ker)); vSizer->Add(flexGrid); SetSizerAndFit(vSizer); } -void GuideAlgorithmGaussianProcess::GPExpertDialog::AddTableEntry(wxFlexGridSizer *Grid, const wxString& Label, wxWindow *Ctrl, const wxString& ToolTip) +void GuideAlgorithmGaussianProcess::GPExpertDialog::AddTableEntry( + wxFlexGridSizer *Grid, const wxString& Label, wxWindow *Ctrl, const wxString& ToolTip) { wxStaticText *pLabel = new wxStaticText(this, wxID_ANY, Label + _(": "), wxPoint(-1, -1), wxSize(-1, -1)); Grid->Add(pLabel, 1, wxALL, 5); @@ -181,7 +197,8 @@ void GuideAlgorithmGaussianProcess::GPExpertDialog::AddTableEntry(wxFlexGridSize Ctrl->SetToolTip(ToolTip); } -void GuideAlgorithmGaussianProcess::GPExpertDialog::LoadExpertValues(GuideAlgorithmGaussianProcess *m_pGuideAlgorithm, const std::vector& hyperParams) +void GuideAlgorithmGaussianProcess::GPExpertDialog::LoadExpertValues( + GuideAlgorithmGaussianProcess *m_pGuideAlgorithm, const std::vector& hyperParams) { m_pPeriodLengthsInference->SetValue(m_pGuideAlgorithm->GetPeriodLengthsInference()); m_pPeriodLengthsPeriodEstimation->SetValue(m_pGuideAlgorithm->GetPeriodLengthsPeriodEstimation()); @@ -195,7 +212,8 @@ void GuideAlgorithmGaussianProcess::GPExpertDialog::LoadExpertValues(GuideAlgori m_pSE1KSignalVariance->SetValue(hyperParams[SE1KSignalVariance]); } -void GuideAlgorithmGaussianProcess::GPExpertDialog::UnloadExpertValues(GuideAlgorithmGaussianProcess *m_pGuideAlgorithm, std::vector& hyperParams) +void GuideAlgorithmGaussianProcess::GPExpertDialog::UnloadExpertValues( + GuideAlgorithmGaussianProcess *m_pGuideAlgorithm, std::vector& hyperParams) { m_pGuideAlgorithm->SetPeriodLengthsInference(m_pPeriodLengthsInference->GetValue()); m_pGuideAlgorithm->SetPeriodLengthsPeriodEstimation(m_pPeriodLengthsPeriodEstimation->GetValue()); @@ -209,8 +227,8 @@ void GuideAlgorithmGaussianProcess::GPExpertDialog::UnloadExpertValues(GuideAlgo hyperParams[SE1KSignalVariance] = m_pSE1KSignalVariance->GetValue(); } -GuideAlgorithmGaussianProcess:: -GuideAlgorithmGPGraphControlPane::GuideAlgorithmGPGraphControlPane(wxWindow *pParent, GuideAlgorithmGaussianProcess *pAlgorithm, const wxString& label) +GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::GuideAlgorithmGPGraphControlPane( + wxWindow *pParent, GuideAlgorithmGaussianProcess *pAlgorithm, const wxString& label) : GraphControlPane(pParent, label) { int width; @@ -219,31 +237,38 @@ GuideAlgorithmGPGraphControlPane::GuideAlgorithmGPGraphControlPane(wxWindow *pPa // Prediction Weight width = StringWidth(_T("000")); - m_pWeight = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0, 100, 0, _T("Prediction Weight")); + m_pWeight = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0, 100, 0, _T("Prediction Weight")); m_pWeight->SetToolTip(wxString::Format(_("What percent of the predictive guide correction should be applied? " - "Default = %.f%%, increase to rely more on the predictions"), 100 * DefaultPredictionGain)); - m_pWeight->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::OnWeightSpinCtrl, this); + "Default = %.f%%, increase to rely more on the predictions"), + 100 * DefaultPredictionGain)); + m_pWeight->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, + &GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::OnWeightSpinCtrl, this); DoAdd(m_pWeight, _("PredWt")); // Reactive Weight width = StringWidth(_T("000")); - m_pAggressiveness = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0, 100, 0, _T("Reactive Weight")); + m_pAggressiveness = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0, 100, 0, _T("Reactive Weight")); m_pAggressiveness->SetToolTip(wxString::Format(_("What percent of the reactive guide correction should be applied? " - "Default = %.f%%, adjust if responding too much or too slowly"), 100 * DefaultControlGain)); - m_pAggressiveness->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::OnAggressivenessSpinCtrl, this); + "Default = %.f%%, adjust if responding too much or too slowly"), + 100 * DefaultControlGain)); + m_pAggressiveness->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, + &GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::OnAggressivenessSpinCtrl, this); DoAdd(m_pAggressiveness, _("ReactWt")); // Min move width = StringWidth(_T("00.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(""), wxPoint(-1, -1), - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + this, wxID_ANY, _T(""), wxPoint(-1, -1), wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); - m_pMinMove->SetToolTip(wxString::Format(_("How many (fractional) pixels must the star move to trigger a reactive guide correction? " - "If camera is binned, this is a fraction of the binned pixel size. Note this has no effect " - "on the predictive guide correction. Default = %.2f"), DefaultMinMove)); - m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::OnMinMoveSpinCtrlDouble, this); + m_pMinMove->SetToolTip( + wxString::Format(_("How many (fractional) pixels must the star move to trigger a reactive guide correction? " + "If camera is binned, this is a fraction of the binned pixel size. Note this has no effect " + "on the predictive guide correction. Default = %.2f"), + DefaultMinMove)); + m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, + &GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::OnMinMoveSpinCtrlDouble, this); DoAdd(m_pMinMove, _("MnMo")); m_pWeight->SetValue(100.0 * m_pGuideAlgorithm->GetPredictionGain()); @@ -251,11 +276,7 @@ GuideAlgorithmGPGraphControlPane::GuideAlgorithmGPGraphControlPane(wxWindow *pPa m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); } -GuideAlgorithmGaussianProcess:: -GuideAlgorithmGPGraphControlPane::~GuideAlgorithmGPGraphControlPane() -{ - -} +GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::~GuideAlgorithmGPGraphControlPane() { } void GuideAlgorithmGaussianProcess::GuideAlgorithmGPGraphControlPane::OnWeightSpinCtrl(wxSpinEvent& WXUNUSED(evt)) { @@ -292,60 +313,65 @@ class GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcessDialogPane : p wxSpinCtrlDouble *m_pMinMove; wxSpinCtrlDouble *m_pPKPeriodLength; wxSpinCtrl *m_pPredictionGain; - wxCheckBox *m_checkboxComputePeriod; + wxCheckBox *m_checkboxComputePeriod; wxSpinCtrlDouble *m_retainModelPct; - wxButton *m_btnExpertOptions; + wxButton *m_btnExpertOptions; public: GuideAlgorithmGaussianProcessDialogPane(wxWindow *pParent, GuideAlgorithmGaussianProcess *pGuideAlgorithm) - : - ConfigDialogPane(_("Predictive PEC Guide Algorithm"),pParent), m_pGuideAlgorithm(pGuideAlgorithm) + : ConfigDialogPane(_("Predictive PEC Guide Algorithm"), pParent) + , m_pGuideAlgorithm(pGuideAlgorithm) { int width; width = StringWidth(_T("0.00")); - m_pPredictionGain = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0, 100, 100 * DefaultPredictionGain); + m_pPredictionGain = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0, 100, 100 * DefaultPredictionGain); DoAdd(_("Predictive Weight"), m_pPredictionGain, wxString::Format(_("What percent of the predictive guide correction should be applied? " - "Default = %.f%%, increase to rely more on the predictions"), 100 * DefaultPredictionGain)); + "Default = %.f%%, increase to rely more on the predictions"), + 100 * DefaultPredictionGain)); width = StringWidth(_T("0.00")); - m_pControlGain = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0, 100, 100 * DefaultControlGain); + m_pControlGain = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, + 0, 100, 100 * DefaultControlGain); DoAdd(_("Reactive Weight"), m_pControlGain, wxString::Format(_("What percent of the reactive guide correction should be applied? " - "Default = %.f%%, adjust if responding too much or too slowly"), 100 * DefaultControlGain)); + "Default = %.f%%, adjust if responding too much or too slowly"), + 100 * DefaultControlGain)); width = StringWidth(_T("0.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 5.0, DefaultMinMove, 0.01); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 5.0, DefaultMinMove, 0.01); m_pMinMove->SetDigits(2); DoAdd(_("Minimum Move (pixels)"), m_pMinMove, wxString::Format(_("How many (fractional) pixels must the star move to trigger a reactive guide correction? " - "If camera is binned, this is a fraction of the binned pixel size. Note this has no effect " - "on the predictive guide correction. Default = %.2f"), DefaultMinMove)); + "If camera is binned, this is a fraction of the binned pixel size. Note this has no effect " + "on the predictive guide correction. Default = %.2f"), + DefaultMinMove)); width = StringWidth(_T("0000.0")); - m_pPKPeriodLength = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 10.0, 2000.0, DefaultPeriodLengthPerKer, 1); + m_pPKPeriodLength = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 10.0, 2000.0, DefaultPeriodLengthPerKer, 1); m_pPKPeriodLength->SetDigits(2); m_checkboxComputePeriod = new wxCheckBox(pParent, wxID_ANY, _("Auto-adjust period")); - m_checkboxComputePeriod->SetToolTip(wxString::Format(_("Auto-adjust the period length based on identified repetitive errors. Default = %s"), - DefaultComputePeriod ? _("On") : _("Off"))); + m_checkboxComputePeriod->SetToolTip( + wxString::Format(_("Auto-adjust the period length based on identified repetitive errors. Default = %s"), + DefaultComputePeriod ? _("On") : _("Off"))); DoAdd(_("Period Length"), m_pPKPeriodLength, wxString::Format(_("The period length (in seconds) of the strongest periodic error component. Default = %.2f"), - DefaultPeriodLengthPerKer)); + DefaultPeriodLengthPerKer)); DoAdd(m_checkboxComputePeriod); width = StringWidth(_T("888")); - m_retainModelPct = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 80.0, DefaultNoresetMaxPctPeriod, 1.0); + m_retainModelPct = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 80.0, DefaultNoresetMaxPctPeriod, 1.0); m_retainModelPct->SetDigits(0); DoAdd(wxString::Format(_("Retain model (%% period)")), m_retainModelPct, wxString::Format(_("Enter a percentage greater than 0 to retain the PPEC model after guiding stops. " - "Default = %.f%% of the period length."), DefaultNoresetMaxPctPeriod)); + "Default = %.f%% of the period length."), + DefaultNoresetMaxPctPeriod)); m_btnExpertOptions = new wxButton(pParent, wxID_ANY, _("Expert...")); m_btnExpertOptions->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &GuideAlgorithmGaussianProcessDialogPane::OnExpertButton, this); @@ -353,12 +379,13 @@ class GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcessDialogPane : p this->Add(m_btnExpertOptions, wxSizerFlags().Center().Border(wxALL, 3)); if (!m_pGuideAlgorithm->m_expertDialog) - m_pGuideAlgorithm->m_expertDialog = new GPExpertDialog(m_pParent); // Do this here so the parent window has been built + m_pGuideAlgorithm->m_expertDialog = + new GPExpertDialog(m_pParent); // Do this here so the parent window has been built } virtual ~GuideAlgorithmGaussianProcessDialogPane() { - // no need to destroy the widgets, this is done by the parent... + // no need to destroy the widgets, this is done by the parent... } /* Fill the GUI with the parameters that are currently configured in the @@ -397,29 +424,28 @@ class GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcessDialogPane : p m_pGuideAlgorithm->SetGPHyperparameters(hyperparameters); if (pFrame->pGuider->IsGuiding() && m_pGuideAlgorithm->GetBoolComputePeriod() != m_checkboxComputePeriod->GetValue()) - pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " PPEC Adjust Period Length", m_checkboxComputePeriod->GetValue()); + pFrame->NotifyGuidingParam( + m_pGuideAlgorithm->GetAxis() + " PPEC Adjust Period Length", m_checkboxComputePeriod->GetValue()); m_pGuideAlgorithm->SetBoolComputePeriod(m_checkboxComputePeriod->GetValue()); SetRetainModelPct(m_pGuideAlgorithm, m_retainModelPct->GetValue()); } - virtual void OnImageScaleChange() - { - GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove); - } + virtual void OnImageScaleChange() { GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove); } - virtual void OnExpertButton(wxCommandEvent& evt) - { - m_pGuideAlgorithm->m_expertDialog->ShowModal(); - } + virtual void OnExpertButton(wxCommandEvent& evt) { m_pGuideAlgorithm->m_expertDialog->ShowModal(); } // make the class non-copyable (if we ever need this, we must implement a deep copy) - GuideAlgorithmGaussianProcessDialogPane(const GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcessDialogPane&) = delete; - GuideAlgorithmGaussianProcessDialogPane& operator=(const GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcessDialogPane&) = delete; + GuideAlgorithmGaussianProcessDialogPane( + const GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcessDialogPane&) = delete; + GuideAlgorithmGaussianProcessDialogPane& operator=( + const GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcessDialogPane&) = delete; }; GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcess(Mount *pMount, GuideAxis axis) - : GuideAlgorithm(pMount, axis), GPG(0), dark_tracking_mode_(false) + : GuideAlgorithm(pMount, axis) + , GPG(0) + , dark_tracking_mode_(false) { // create guide parameters, load default values at first GaussianProcessGuider::guide_parameters parameters; @@ -449,26 +475,36 @@ GuideAlgorithmGaussianProcess::GuideAlgorithmGaussianProcess(Mount *pMount, Guid double min_move = pConfig->Profile.GetDouble(configPath + "/gp_min_move", DefaultMinMove); SetMinMove(min_move); - double period_lengths_for_inference = pConfig->Profile.GetDouble(configPath + "/gp_period_lengths_inference", DefaultPeriodLengthsForInference); + double period_lengths_for_inference = + pConfig->Profile.GetDouble(configPath + "/gp_period_lengths_inference", DefaultPeriodLengthsForInference); SetPeriodLengthsInference(period_lengths_for_inference); - double period_lengths_for_period_estimation = pConfig->Profile.GetDouble(configPath + "/gp_period_lengths_period_estimation", DefaultPeriodLengthsForPeriodEstimation); + double period_lengths_for_period_estimation = pConfig->Profile.GetDouble( + configPath + "/gp_period_lengths_period_estimation", DefaultPeriodLengthsForPeriodEstimation); SetPeriodLengthsPeriodEstimation(period_lengths_for_period_estimation); - int num_points_approximation = pConfig->Profile.GetInt(configPath + "/gp_points_for_approximation", DefaultNumPointsForApproximation); + int num_points_approximation = + pConfig->Profile.GetInt(configPath + "/gp_points_for_approximation", DefaultNumPointsForApproximation); SetNumPointsForApproximation(num_points_approximation); double prediction_gain = pConfig->Profile.GetDouble(configPath + "/gp_prediction_gain", DefaultPredictionGain); SetPredictionGain(prediction_gain); std::vector v_hyperparameters(NumParameters); - v_hyperparameters[SE0KLengthScale] = pConfig->Profile.GetDouble(configPath + "/gp_length_scale_se0_kern", DefaultLengthScaleSE0Ker); - v_hyperparameters[SE0KSignalVariance] = pConfig->Profile.GetDouble(configPath + "/gp_sigvar_se0_kern", DefaultSignalVarianceSE0Ker); - v_hyperparameters[PKLengthScale] = pConfig->Profile.GetDouble(configPath + "/gp_length_scale_per_kern", DefaultLengthScalePerKer); - v_hyperparameters[PKSignalVariance] = pConfig->Profile.GetDouble(configPath + "/gp_sigvar_per_kern", DefaultSignalVariancePerKer); - v_hyperparameters[SE1KLengthScale] = pConfig->Profile.GetDouble(configPath + "/gp_length_scale_se1_kern", DefaultLengthScaleSE1Ker); - v_hyperparameters[SE1KSignalVariance] = pConfig->Profile.GetDouble(configPath + "/gp_sigvar_se1_kern", DefaultSignalVarianceSE1Ker); - v_hyperparameters[PKPeriodLength] = pConfig->Profile.GetDouble(configPath + "/gp_period_per_kern", DefaultPeriodLengthPerKer); + v_hyperparameters[SE0KLengthScale] = + pConfig->Profile.GetDouble(configPath + "/gp_length_scale_se0_kern", DefaultLengthScaleSE0Ker); + v_hyperparameters[SE0KSignalVariance] = + pConfig->Profile.GetDouble(configPath + "/gp_sigvar_se0_kern", DefaultSignalVarianceSE0Ker); + v_hyperparameters[PKLengthScale] = + pConfig->Profile.GetDouble(configPath + "/gp_length_scale_per_kern", DefaultLengthScalePerKer); + v_hyperparameters[PKSignalVariance] = + pConfig->Profile.GetDouble(configPath + "/gp_sigvar_per_kern", DefaultSignalVariancePerKer); + v_hyperparameters[SE1KLengthScale] = + pConfig->Profile.GetDouble(configPath + "/gp_length_scale_se1_kern", DefaultLengthScaleSE1Ker); + v_hyperparameters[SE1KSignalVariance] = + pConfig->Profile.GetDouble(configPath + "/gp_sigvar_se1_kern", DefaultSignalVarianceSE1Ker); + v_hyperparameters[PKPeriodLength] = + pConfig->Profile.GetDouble(configPath + "/gp_period_per_kern", DefaultPeriodLengthPerKer); SetGPHyperparameters(v_hyperparameters); @@ -519,8 +555,7 @@ bool GuideAlgorithmGaussianProcess::GetParam(const wxString& name, double *val) *val = GetPredictionGain(); else if (name == "reactiveWeight") *val = GetControlGain(); - else - if (name == "periodLength") + else if (name == "periodLength") { std::vector hyperparameters = GetGPHyperparameters(); assert(hyperparameters.size() == NumParameters); @@ -542,8 +577,7 @@ bool GuideAlgorithmGaussianProcess::SetParam(const wxString& name, double val) err = SetPredictionGain(val); else if (name == "reactiveWeight") err = SetControlGain(val); - else - if (name == "periodLength") + else if (name == "periodLength") { std::vector hyperparameters(NumParameters); hyperparameters[PKPeriodLength] = val; @@ -899,38 +933,26 @@ bool GuideAlgorithmGaussianProcess::SetDarkTracking(bool value) wxString GuideAlgorithmGaussianProcess::GetSettingsSummary() const { - static const char* format = - "Control gain = %.3f\n" - "Prediction gain = %.3f\n" - "Minimum move = %.3f\n" - "Hyperparameters\n" - "\tLength scale long range SE kernel = %.3f\n" - "\tSignal variance long range SE kernel = %.3f\n" - "\tLength scale periodic kernel = %.3f\n" - "\tSignal variance periodic kernel = %.3f\n" - "\tLength scale short range SE kernel = %.3f\n" - "\tSignal variance short range SE kernel = %.3f\n" - "\tPeriod length periodic kernel = %.3f\n" - "\tFFT called after = %.3f worm cycles\n" - "\tAuto-adjust period length = %s\n" - ; + static const char *format = "Control gain = %.3f\n" + "Prediction gain = %.3f\n" + "Minimum move = %.3f\n" + "Hyperparameters\n" + "\tLength scale long range SE kernel = %.3f\n" + "\tSignal variance long range SE kernel = %.3f\n" + "\tLength scale periodic kernel = %.3f\n" + "\tSignal variance periodic kernel = %.3f\n" + "\tLength scale short range SE kernel = %.3f\n" + "\tSignal variance short range SE kernel = %.3f\n" + "\tPeriod length periodic kernel = %.3f\n" + "\tFFT called after = %.3f worm cycles\n" + "\tAuto-adjust period length = %s\n"; std::vector hyperparameters = GetGPHyperparameters(); - return wxString::Format( - format, - GetControlGain(), - GetPredictionGain(), - GetMinMove(), - hyperparameters[SE0KLengthScale], - hyperparameters[SE0KSignalVariance], - hyperparameters[PKLengthScale], - hyperparameters[PKSignalVariance], - hyperparameters[SE1KLengthScale], - hyperparameters[SE1KSignalVariance], - hyperparameters[PKPeriodLength], - GetPeriodLengthsPeriodEstimation(), - GetBoolComputePeriod() ? "On" : "Off"); + return wxString::Format(format, GetControlGain(), GetPredictionGain(), GetMinMove(), hyperparameters[SE0KLengthScale], + hyperparameters[SE0KSignalVariance], hyperparameters[PKLengthScale], hyperparameters[PKSignalVariance], + hyperparameters[SE1KLengthScale], hyperparameters[SE1KSignalVariance], hyperparameters[PKPeriodLength], + GetPeriodLengthsPeriodEstimation(), GetBoolComputePeriod() ? "On" : "Off"); } GUIDE_ALGORITHM GuideAlgorithmGaussianProcess::Algorithm() const @@ -941,7 +963,7 @@ GUIDE_ALGORITHM GuideAlgorithmGaussianProcess::Algorithm() const double GuideAlgorithmGaussianProcess::result(double input) { if (block_updates_) - return(0); + return (0); if (dark_tracking_mode_ == true) { @@ -952,8 +974,8 @@ double GuideAlgorithmGaussianProcess::result(double input) const Star& star = pFrame->pGuider->PrimaryStar(); double control_signal = GPG->result(input, star.SNR, (double) pFrame->RequestedExposureDuration() / 1000.0); - Debug.Write(wxString::Format("PPEC: input: %.2f, control: %.2f, exposure: %d\n", - input, control_signal, pFrame->RequestedExposureDuration())); + Debug.Write(wxString::Format( + "PPEC: input: %.2f, control: %.2f, exposure: %d\n", input, control_signal, pFrame->RequestedExposureDuration())); return control_signal; } @@ -962,8 +984,8 @@ double GuideAlgorithmGaussianProcess::deduceResult() { double control_signal = GPG->deduceResult((double) pFrame->RequestedExposureDuration() / 1000.0); - Debug.Write(wxString::Format("PPEC (deduced): control: %.2f, exposure: %d\n", control_signal, - pFrame->RequestedExposureDuration())); + Debug.Write( + wxString::Format("PPEC (deduced): control: %.2f, exposure: %d\n", control_signal, pFrame->RequestedExposureDuration())); return control_signal; } @@ -1002,7 +1024,7 @@ inline static wxString FormatRA(double ra) void GuideAlgorithmGaussianProcess::GuidingStarted() { bool need_reset = true; - double ra_offset; // RA delta in SI seconds + double ra_offset; // RA delta in SI seconds auto now = std::chrono::system_clock::now(); @@ -1012,16 +1034,15 @@ void GuideAlgorithmGaussianProcess::GuidingStarted() PierSide prev_side = guiding_pier_side_; guiding_pier_side_ = CurrentPierSide(); - Debug.Write(wxString::Format("PPEC: guiding starts RA = %s, pier %s, prev RA = %s, pier %s\n", - FormatRA(guiding_ra_), Mount::PierSideStr(guiding_pier_side_), - FormatRA(prev_ra), Mount::PierSideStr(prev_side))); + Debug.Write(wxString::Format("PPEC: guiding starts RA = %s, pier %s, prev RA = %s, pier %s\n", FormatRA(guiding_ra_), + Mount::PierSideStr(guiding_pier_side_), FormatRA(prev_ra), Mount::PierSideStr(prev_side))); // retain the model (do not reset) if: // - guiding on the same side of pier, and // - worm rotation is less than 40% of the worm period - if (!math_tools::isNaN(guiding_ra_) && !math_tools::isNaN(prev_ra) && - prev_side != PIER_SIDE_UNKNOWN && prev_side == guiding_pier_side_) + if (!math_tools::isNaN(guiding_ra_) && !math_tools::isNaN(prev_ra) && prev_side != PIER_SIDE_UNKNOWN && + prev_side == guiding_pier_side_) { const double SECONDS_PER_HOUR = 60. * 60.; const double SIDEREAL_SECONDS_PER_SEC = 0.9973; @@ -1039,11 +1060,11 @@ void GuideAlgorithmGaussianProcess::GuidingStarted() double period_length = GPG->GetGPHyperparameters()[PKPeriodLength]; double max_pct_period = GetRetainModelPct(this); - Debug.Write(wxString::Format("PPEC: guiding was stopped for %.1f seconds, deltaRA %+.1fs, worm delta %+.1fs, %.1f%% of period " - "(%.1fs), limit %.1f%% (%.1fs)\n", - elapsed_time, -ra_offset, worm_offset, - fabs(worm_offset) / period_length * 100., period_length, - max_pct_period, max_pct_period / 100. * period_length)); + Debug.Write( + wxString::Format("PPEC: guiding was stopped for %.1f seconds, deltaRA %+.1fs, worm delta %+.1fs, %.1f%% of period " + "(%.1fs), limit %.1f%% (%.1fs)\n", + elapsed_time, -ra_offset, worm_offset, fabs(worm_offset) / period_length * 100., period_length, max_pct_period, + max_pct_period / 100. * period_length)); if (fabs(worm_offset) < max_pct_period / 100. * period_length) { @@ -1081,20 +1102,16 @@ void GuideAlgorithmGaussianProcess::GuidingStopped() guiding_stopped_time_ = std::chrono::system_clock::now(); } -void GuideAlgorithmGaussianProcess::GuidingPaused() -{ -} +void GuideAlgorithmGaussianProcess::GuidingPaused() { } -void GuideAlgorithmGaussianProcess::GuidingResumed() -{ -} +void GuideAlgorithmGaussianProcess::GuidingResumed() { } void GuideAlgorithmGaussianProcess::GuidingDisabled() { // Don't submit guide star movements to the GP while guiding is disabled Debug.Write("PPEC model updates disabled\n"); block_updates_ = true; - GuidingStopped(); // Keep our last state and reset + GuidingStopped(); // Keep our last state and reset } void GuideAlgorithmGaussianProcess::GuidingEnabled() diff --git a/src/guide_algorithm_gaussian_process.h b/src/guide_algorithm_gaussian_process.h index 7d3439841..5b102b56b 100644 --- a/src/guide_algorithm_gaussian_process.h +++ b/src/guide_algorithm_gaussian_process.h @@ -64,7 +64,7 @@ class GuideAlgorithmGaussianProcess : public GuideAlgorithm { wxSpinCtrlDouble *m_pPeriodLengthsInference; wxSpinCtrlDouble *m_pPeriodLengthsPeriodEstimation; - wxSpinCtrl *m_pNumPointsApproximation; + wxSpinCtrl *m_pNumPointsApproximation; wxSpinCtrlDouble *m_pSE0KLengthScale; wxSpinCtrlDouble *m_pSE0KSignalVariance; wxSpinCtrlDouble *m_pPKLengthScale; @@ -97,10 +97,9 @@ class GuideAlgorithmGaussianProcess : public GuideAlgorithm void OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& evt); }; - GPExpertDialog *m_expertDialog; // Exactly one per GP instance independent from ConfigDialogPane lifetimes + GPExpertDialog *m_expertDialog; // Exactly one per GP instance independent from ConfigDialogPane lifetimes private: - /** * Holds all data that is needed for the GP guiding. */ @@ -120,8 +119,8 @@ class GuideAlgorithmGaussianProcess : public GuideAlgorithm * Dark tracking mode is for debugging: only deduceResult is called if enabled. */ bool dark_tracking_mode_; - bool block_updates_; // Don't update GP if guiding is disabled - double guiding_ra_; // allow resuming guiding after guiding stopped if there is no change in RA + bool block_updates_; // Don't update GP if guiding is disabled + double guiding_ra_; // allow resuming guiding after guiding stopped if there is no change in RA PierSide guiding_pier_side_; std::chrono::system_clock::time_point guiding_stopped_time_; // time guiding stopped @@ -235,7 +234,6 @@ class GuideAlgorithmGaussianProcess : public GuideAlgorithm void GetParamNames(wxArrayString& names) const override; bool GetParam(const wxString& name, double *val) const override; bool SetParam(const wxString& name, double val) override; - }; -#endif // GUIDE_GAUSSIAN_PROCESS +#endif // GUIDE_GAUSSIAN_PROCESS diff --git a/src/guide_algorithm_hysteresis.cpp b/src/guide_algorithm_hysteresis.cpp index a7e4ca96f..99e5396bd 100644 --- a/src/guide_algorithm_hysteresis.cpp +++ b/src/guide_algorithm_hysteresis.cpp @@ -39,7 +39,7 @@ #include "phd.h" -static const double DefaultMinMove = 0.2; +static const double DefaultMinMove = 0.2; static const double DefaultHysteresis = 0.1; static const double DefaultAggression = 0.7; static const double MaxAggression = 2.0; @@ -50,7 +50,7 @@ GuideAlgorithmHysteresis::GuideAlgorithmHysteresis(Mount *pMount, GuideAxis axis { wxString configPath = GetConfigPath(); - double minMove = pConfig->Profile.GetDouble(configPath + "/minMove", DefaultMinMove); + double minMove = pConfig->Profile.GetDouble(configPath + "/minMove", DefaultMinMove); SetMinMove(minMove); double hysteresis = pConfig->Profile.GetDouble(configPath + "/hysteresis", DefaultHysteresis); @@ -62,9 +62,7 @@ GuideAlgorithmHysteresis::GuideAlgorithmHysteresis(Mount *pMount, GuideAxis axis reset(); } -GuideAlgorithmHysteresis::~GuideAlgorithmHysteresis(void) -{ -} +GuideAlgorithmHysteresis::~GuideAlgorithmHysteresis(void) { } GUIDE_ALGORITHM GuideAlgorithmHysteresis::Algorithm() const { @@ -105,7 +103,6 @@ bool GuideAlgorithmHysteresis::SetMinMove(double minMove) } m_minMove = minMove; - } catch (const wxString& Msg) { @@ -131,7 +128,6 @@ bool GuideAlgorithmHysteresis::SetHysteresis(double hysteresis) } m_hysteresis = hysteresis; - } catch (const wxString& Msg) { @@ -174,11 +170,8 @@ bool GuideAlgorithmHysteresis::SetAggression(double aggression) wxString GuideAlgorithmHysteresis::GetSettingsSummary() const { // return a loggable summary of current mount settings - return wxString::Format("Hysteresis = %.3f, Aggression = %.3f, Minimum move = %.3f\n", - GetHysteresis(), - GetAggression(), - GetMinMove() - ); + return wxString::Format( + "Hysteresis = %.3f, Aggression = %.3f, Minimum move = %.3f\n", GetHysteresis(), GetAggression(), GetMinMove()); } void GuideAlgorithmHysteresis::GetParamNames(wxArrayString& names) const @@ -225,9 +218,8 @@ ConfigDialogPane *GuideAlgorithmHysteresis::GetConfigDialogPane(wxWindow *pParen return new GuideAlgorithmHysteresisConfigDialogPane(pParent, this); } -GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisConfigDialogPane:: -GuideAlgorithmHysteresisConfigDialogPane(wxWindow *pParent, GuideAlgorithmHysteresis *pGuideAlgorithm) +GuideAlgorithmHysteresis::GuideAlgorithmHysteresisConfigDialogPane::GuideAlgorithmHysteresisConfigDialogPane( + wxWindow *pParent, GuideAlgorithmHysteresis *pGuideAlgorithm) : ConfigDialogPane(_("Hysteresis Guide Algorithm"), pParent) { int width; @@ -235,61 +227,56 @@ GuideAlgorithmHysteresisConfigDialogPane(wxWindow *pParent, GuideAlgorithmHyster m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("000")); - m_pHysteresis = pFrame->MakeSpinCtrl(pParent, wxID_ANY,_T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, MaxHysteresis * 100.0, 0.0, _T("Hysteresis")); + m_pHysteresis = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, + MaxHysteresis * 100.0, 0.0, _T("Hysteresis")); DoAdd(_("Hysteresis"), m_pHysteresis, - wxString::Format(_("How much history of previous guide pulses should be applied\nDefault = %.f%%, increase to smooth out guiding commands"), DefaultHysteresis * 100.0)); + wxString::Format(_("How much history of previous guide pulses should be applied\nDefault = %.f%%, increase to smooth " + "out guiding commands"), + DefaultHysteresis * 100.0)); width = StringWidth(_T("000")); - m_pAggression = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, MaxAggression * 100.0, 0.0, _T("Aggressiveness")); + m_pAggression = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, + MaxAggression * 100.0, 0.0, _T("Aggressiveness")); DoAdd(_("Aggressiveness"), m_pAggression, - wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%, adjust if responding too much or too slowly"), DefaultAggression * 100.0)); + wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%, adjust if " + "responding too much or too slowly"), + DefaultAggression * 100.0)); width = StringWidth(_T("00.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); DoAdd(_("Minimum Move (pixels)"), m_pMinMove, - wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); + wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); } -GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisConfigDialogPane:: -~GuideAlgorithmHysteresisConfigDialogPane(void) -{ -} +GuideAlgorithmHysteresis::GuideAlgorithmHysteresisConfigDialogPane::~GuideAlgorithmHysteresisConfigDialogPane(void) { } -void GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisConfigDialogPane:: -LoadValues(void) +void GuideAlgorithmHysteresis::GuideAlgorithmHysteresisConfigDialogPane::LoadValues(void) { m_pHysteresis->SetValue(100.0 * m_pGuideAlgorithm->GetHysteresis()); m_pAggression->SetValue(100.0 * m_pGuideAlgorithm->GetAggression()); m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); } -void GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisConfigDialogPane:: -UnloadValues(void) +void GuideAlgorithmHysteresis::GuideAlgorithmHysteresisConfigDialogPane::UnloadValues(void) { m_pGuideAlgorithm->SetHysteresis(m_pHysteresis->GetValue() / 100.0); m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0); m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); } -void GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisConfigDialogPane::OnImageScaleChange() +void GuideAlgorithmHysteresis::GuideAlgorithmHysteresisConfigDialogPane::OnImageScaleChange() { GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove); } -void GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisConfigDialogPane::EnableDecControls(bool enable) +void GuideAlgorithmHysteresis::GuideAlgorithmHysteresisConfigDialogPane::EnableDecControls(bool enable) { m_pAggression->Enable(enable); m_pMinMove->Enable(enable); @@ -301,9 +288,8 @@ GraphControlPane *GuideAlgorithmHysteresis::GetGraphControlPane(wxWindow *pParen return new GuideAlgorithmHysteresisGraphControlPane(pParent, this, label); } -GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisGraphControlPane:: -GuideAlgorithmHysteresisGraphControlPane(wxWindow *pParent, GuideAlgorithmHysteresis *pGuideAlgorithm, const wxString& label) +GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::GuideAlgorithmHysteresisGraphControlPane( + wxWindow *pParent, GuideAlgorithmHysteresis *pGuideAlgorithm, const wxString& label) : GraphControlPane(pParent, label) { int width; @@ -312,29 +298,38 @@ GuideAlgorithmHysteresisGraphControlPane(wxWindow *pParent, GuideAlgorithmHyster // Aggression width = StringWidth(_T("000")); - m_pAggression = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0.0, MaxAggression * 100.0, 0.0, _T("Aggressiveness")); - m_pAggression->SetToolTip(wxString::Format(_("What percentage of the computed correction should be applied?? Default = %.f%%, adjust if responding too much or too slowly"), DefaultAggression * 100.0)); - m_pAggression->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnAggressionSpinCtrl, this); + m_pAggression = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0.0, MaxAggression * 100.0, 0.0, _T("Aggressiveness")); + m_pAggression->SetToolTip(wxString::Format(_("What percentage of the computed correction should be applied?? Default = " + "%.f%%, adjust if responding too much or too slowly"), + DefaultAggression * 100.0)); + m_pAggression->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, + &GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnAggressionSpinCtrl, this); DoAdd(m_pAggression, _("Agr")); // Hysteresis width = StringWidth(_T("000")); - m_pHysteresis = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0.0, MaxHysteresis * 100.0, 0.0, _T("Hysteresis")); - m_pHysteresis->SetToolTip(wxString::Format(_("How much history of previous guide pulses should be applied\nDefault = %.f%%, increase to smooth out guiding commands"), DefaultHysteresis * 100.0)); - m_pHysteresis->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnHysteresisSpinCtrl, this); - DoAdd(m_pHysteresis,_("Hys")); + m_pHysteresis = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0.0, MaxHysteresis * 100.0, 0.0, _T("Hysteresis")); + m_pHysteresis->SetToolTip(wxString::Format(_("How much history of previous guide pulses should be applied\nDefault = " + "%.f%%, increase to smooth out guiding commands"), + DefaultHysteresis * 100.0)); + m_pHysteresis->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, + &GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnHysteresisSpinCtrl, this); + DoAdd(m_pHysteresis, _("Hys")); // Min move width = StringWidth(_T("00.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(""), wxPoint(-1, -1), - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + this, wxID_ANY, _T(""), wxPoint(-1, -1), wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); - m_pMinMove->SetToolTip(wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); - m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnMinMoveSpinCtrlDouble, this); - DoAdd(m_pMinMove,_("MnMo")); + m_pMinMove->SetToolTip( + wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); + m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, + &GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnMinMoveSpinCtrlDouble, this); + DoAdd(m_pMinMove, _("MnMo")); m_pHysteresis->SetValue(100.0 * m_pGuideAlgorithm->GetHysteresis()); m_pAggression->SetValue(100.0 * m_pGuideAlgorithm->GetAggression()); @@ -349,39 +344,29 @@ GuideAlgorithmHysteresisGraphControlPane(wxWindow *pParent, GuideAlgorithmHyster } } -GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisGraphControlPane:: -~GuideAlgorithmHysteresisGraphControlPane(void) -{ -} +GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::~GuideAlgorithmHysteresisGraphControlPane(void) { } -void GuideAlgorithmHysteresis:: -GuideAlgorithmHysteresisGraphControlPane::EnableDecControls(bool enable) +void GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::EnableDecControls(bool enable) { m_pAggression->Enable(enable); m_pHysteresis->Enable(enable); m_pMinMove->Enable(enable); } -void GuideAlgorithmHysteresis:: - GuideAlgorithmHysteresisGraphControlPane:: - OnAggressionSpinCtrl(wxSpinEvent& WXUNUSED(evt)) +void GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnAggressionSpinCtrl(wxSpinEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Hysteresis aggression", m_pAggression->GetValue()); } -void GuideAlgorithmHysteresis:: - GuideAlgorithmHysteresisGraphControlPane:: - OnHysteresisSpinCtrl(wxSpinEvent& WXUNUSED(evt)) +void GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnHysteresisSpinCtrl(wxSpinEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetHysteresis(this->m_pHysteresis->GetValue() / 100.0); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Hysteresis hysteresis", m_pHysteresis->GetValue()); } -void GuideAlgorithmHysteresis:: - GuideAlgorithmHysteresisGraphControlPane:: - OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& WXUNUSED(evt)) +void GuideAlgorithmHysteresis::GuideAlgorithmHysteresisGraphControlPane::OnMinMoveSpinCtrlDouble( + wxSpinDoubleEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Hysteresis minimum move", m_pMinMove->GetValue()); diff --git a/src/guide_algorithm_hysteresis.h b/src/guide_algorithm_hysteresis.h index 694f76326..0d04a0367 100644 --- a/src/guide_algorithm_hysteresis.h +++ b/src/guide_algorithm_hysteresis.h @@ -48,7 +48,6 @@ class GuideAlgorithmHysteresis : public GuideAlgorithm double m_lastMove; protected: - class GuideAlgorithmHysteresisConfigDialogPane : public ConfigDialogPane { GuideAlgorithmHysteresis *m_pGuideAlgorithm; @@ -69,7 +68,8 @@ class GuideAlgorithmHysteresis : public GuideAlgorithm class GuideAlgorithmHysteresisGraphControlPane : public GraphControlPane { public: - GuideAlgorithmHysteresisGraphControlPane(wxWindow *pParent, GuideAlgorithmHysteresis *pGuideAlgorithm, const wxString& label); + GuideAlgorithmHysteresisGraphControlPane( + wxWindow *pParent, GuideAlgorithmHysteresis *pGuideAlgorithm, const wxString& label); ~GuideAlgorithmHysteresisGraphControlPane(); void EnableDecControls(bool enable) override; @@ -95,7 +95,6 @@ class GuideAlgorithmHysteresis : public GuideAlgorithm friend class GraphLogWindow; public: - GuideAlgorithmHysteresis(Mount *pMount, GuideAxis axis); ~GuideAlgorithmHysteresis(); diff --git a/src/guide_algorithm_identity.cpp b/src/guide_algorithm_identity.cpp index 25f07ec70..948772755 100644 --- a/src/guide_algorithm_identity.cpp +++ b/src/guide_algorithm_identity.cpp @@ -45,18 +45,14 @@ GuideAlgorithmIdentity::GuideAlgorithmIdentity(Mount *pMount, GuideAxis axis) reset(); } -GuideAlgorithmIdentity::~GuideAlgorithmIdentity(void) -{ -} +GuideAlgorithmIdentity::~GuideAlgorithmIdentity(void) { } GUIDE_ALGORITHM GuideAlgorithmIdentity::Algorithm() const { return GUIDE_ALGORITHM_IDENTITY; } -void GuideAlgorithmIdentity::reset(void) -{ -} +void GuideAlgorithmIdentity::reset(void) { } // the default algorithm simply returns its input double GuideAlgorithmIdentity::result(double input) @@ -71,29 +67,16 @@ ConfigDialogPane *GuideAlgorithmIdentity::GetConfigDialogPane(wxWindow *pParent) return new GuideAlgorithmIdentityConfigDialogPane(pParent, this); } -GuideAlgorithmIdentity:: -GuideAlgorithmIdentityConfigDialogPane:: -GuideAlgorithmIdentityConfigDialogPane(wxWindow *pParent, GuideAlgorithmIdentity *pGuideAlgorithm) +GuideAlgorithmIdentity::GuideAlgorithmIdentityConfigDialogPane::GuideAlgorithmIdentityConfigDialogPane( + wxWindow *pParent, GuideAlgorithmIdentity *pGuideAlgorithm) : ConfigDialogPane(_("Guide Algorithm"), pParent) { m_pGuideAlgorithm = pGuideAlgorithm; - DoAdd(new wxStaticText(pParent, wxID_ANY, _("Nothing to Configure"),wxPoint(-1,-1),wxSize(-1,-1))); + DoAdd(new wxStaticText(pParent, wxID_ANY, _("Nothing to Configure"), wxPoint(-1, -1), wxSize(-1, -1))); } -GuideAlgorithmIdentity:: -GuideAlgorithmIdentityConfigDialogPane:: -~GuideAlgorithmIdentityConfigDialogPane(void) -{ -} +GuideAlgorithmIdentity::GuideAlgorithmIdentityConfigDialogPane::~GuideAlgorithmIdentityConfigDialogPane(void) { } -void GuideAlgorithmIdentity:: -GuideAlgorithmIdentityConfigDialogPane:: -LoadValues(void) -{ -} +void GuideAlgorithmIdentity::GuideAlgorithmIdentityConfigDialogPane::LoadValues(void) { } -void GuideAlgorithmIdentity:: -GuideAlgorithmIdentityConfigDialogPane:: -UnloadValues(void) -{ -} +void GuideAlgorithmIdentity::GuideAlgorithmIdentityConfigDialogPane::UnloadValues(void) { } diff --git a/src/guide_algorithm_identity.h b/src/guide_algorithm_identity.h index 06d71f1ae..6050894d2 100644 --- a/src/guide_algorithm_identity.h +++ b/src/guide_algorithm_identity.h @@ -46,6 +46,7 @@ class GuideAlgorithmIdentity : public GuideAlgorithm class GuideAlgorithmIdentityConfigDialogPane : public ConfigDialogPane { GuideAlgorithmIdentity *m_pGuideAlgorithm; + public: GuideAlgorithmIdentityConfigDialogPane(wxWindow *pParent, GuideAlgorithmIdentity *pGuideAlgorithm); ~GuideAlgorithmIdentityConfigDialogPane(); diff --git a/src/guide_algorithm_lowpass.cpp b/src/guide_algorithm_lowpass.cpp index e8f7a8716..b9812207b 100644 --- a/src/guide_algorithm_lowpass.cpp +++ b/src/guide_algorithm_lowpass.cpp @@ -1,66 +1,63 @@ /* -* guide_algorithm_lowpass.cpp -* PHD Guiding -* -* Created by Bret McKee -* Copyright (c) 2012 Bret McKee -* All rights reserved. -* -* Based upon work by Craig Stark. -* Copyright (c) 2006-2010 Craig Stark. -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * guide_algorithm_lowpass.cpp + * PHD Guiding + * + * Created by Bret McKee + * Copyright (c) 2012 Bret McKee + * All rights reserved. + * + * Based upon work by Craig Stark. + * Copyright (c) 2006-2010 Craig Stark. + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" -static const double DefaultMinMove = 0.2; +static const double DefaultMinMove = 0.2; static const double DefaultSlopeWeight = 5.0; GuideAlgorithmLowpass::GuideAlgorithmLowpass(Mount *pMount, GuideAxis axis) : GuideAlgorithm(pMount, axis) { - double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove); + double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove); SetMinMove(minMove); double slopeWeight = pConfig->Profile.GetDouble(GetConfigPath() + "/SlopeWeight", DefaultSlopeWeight); SetSlopeWeight(slopeWeight); - m_axisStats = WindowedAxisStats(0); // self-managed window + m_axisStats = WindowedAxisStats(0); // self-managed window m_timeBase = 0; reset(); } -GuideAlgorithmLowpass::~GuideAlgorithmLowpass(void) -{ - -} +GuideAlgorithmLowpass::~GuideAlgorithmLowpass(void) { } GUIDE_ALGORITHM GuideAlgorithmLowpass::Algorithm() const { @@ -76,7 +73,6 @@ void GuideAlgorithmLowpass::reset(void) { m_axisStats.AddGuideInfo(m_timeBase++, 0, 0); } - } double GuideAlgorithmLowpass::result(double input) @@ -92,7 +88,8 @@ double GuideAlgorithmLowpass::result(double input) if (fabs(dReturn) > fabs(input)) { - Debug.Write(wxString::Format("GuideAlgorithmLowpass::Result() input %.2f is < calculated value %.2f, using input\n", input, dReturn)); + Debug.Write(wxString::Format( + "GuideAlgorithmLowpass::Result() input %.2f is < calculated value %.2f, using input\n", input, dReturn)); dReturn = input; } @@ -118,7 +115,6 @@ bool GuideAlgorithmLowpass::SetMinMove(double minMove) } m_minMove = minMove; - } catch (const wxString& Msg) { @@ -194,10 +190,7 @@ bool GuideAlgorithmLowpass::SetParam(const wxString& name, double val) wxString GuideAlgorithmLowpass::GetSettingsSummary() const { // return a loggable summary of current mount settings - return wxString::Format("Slope weight = %.3f, Minimum move = %.3f\n", - GetSlopeWeight(), - GetMinMove() - ); + return wxString::Format("Slope weight = %.3f, Minimum move = %.3f\n", GetSlopeWeight(), GetMinMove()); } ConfigDialogPane *GuideAlgorithmLowpass::GetConfigDialogPane(wxWindow *pParent) @@ -205,9 +198,8 @@ ConfigDialogPane *GuideAlgorithmLowpass::GetConfigDialogPane(wxWindow *pParent) return new GuideAlgorithmLowpassConfigDialogPane(pParent, this); } -GuideAlgorithmLowpass:: - GuideAlgorithmLowpassConfigDialogPane:: - GuideAlgorithmLowpassConfigDialogPane(wxWindow *pParent, GuideAlgorithmLowpass *pGuideAlgorithm) +GuideAlgorithmLowpass::GuideAlgorithmLowpassConfigDialogPane::GuideAlgorithmLowpassConfigDialogPane( + wxWindow *pParent, GuideAlgorithmLowpass *pGuideAlgorithm) : ConfigDialogPane(_("Lowpass Guide Algorithm"), pParent) { int width; @@ -215,54 +207,44 @@ GuideAlgorithmLowpass:: m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("000.00")); - m_pSlopeWeight = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.5, _T("SlopeWeight")); + m_pSlopeWeight = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.5, _T("SlopeWeight")); m_pSlopeWeight->SetDigits(2); DoAdd(_("Slope Weight"), m_pSlopeWeight, wxString::Format(_("Weighting of slope parameter in lowpass auto-dec. Default = %.1f"), DefaultSlopeWeight)); width = StringWidth(_T("000.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); DoAdd(_("Minimum Move (pixels)"), m_pMinMove, wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); - + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); } -GuideAlgorithmLowpass:: - GuideAlgorithmLowpassConfigDialogPane:: - ~GuideAlgorithmLowpassConfigDialogPane(void) -{ -} +GuideAlgorithmLowpass::GuideAlgorithmLowpassConfigDialogPane::~GuideAlgorithmLowpassConfigDialogPane(void) { } -void GuideAlgorithmLowpass:: - GuideAlgorithmLowpassConfigDialogPane:: - LoadValues(void) +void GuideAlgorithmLowpass::GuideAlgorithmLowpassConfigDialogPane::LoadValues(void) { m_pSlopeWeight->SetValue(m_pGuideAlgorithm->GetSlopeWeight()); m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); } -void GuideAlgorithmLowpass:: - GuideAlgorithmLowpassConfigDialogPane:: - UnloadValues(void) +void GuideAlgorithmLowpass::GuideAlgorithmLowpassConfigDialogPane::UnloadValues(void) { m_pGuideAlgorithm->SetSlopeWeight(m_pSlopeWeight->GetValue()); m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); } -void GuideAlgorithmLowpass:: -GuideAlgorithmLowpassConfigDialogPane::OnImageScaleChange() +void GuideAlgorithmLowpass::GuideAlgorithmLowpassConfigDialogPane::OnImageScaleChange() { GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove); } -void GuideAlgorithmLowpass:: -GuideAlgorithmLowpassConfigDialogPane::EnableDecControls(bool enable) +void GuideAlgorithmLowpass::GuideAlgorithmLowpassConfigDialogPane::EnableDecControls(bool enable) { m_pMinMove->Enable(enable); m_pSlopeWeight->Enable(enable); @@ -273,9 +255,8 @@ GraphControlPane *GuideAlgorithmLowpass::GetGraphControlPane(wxWindow *pParent, return new GuideAlgorithmLowpassGraphControlPane(pParent, this, label); } -GuideAlgorithmLowpass:: - GuideAlgorithmLowpassGraphControlPane:: - GuideAlgorithmLowpassGraphControlPane(wxWindow *pParent, GuideAlgorithmLowpass *pGuideAlgorithm, const wxString& label) +GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::GuideAlgorithmLowpassGraphControlPane( + wxWindow *pParent, GuideAlgorithmLowpass *pGuideAlgorithm, const wxString& label) : GraphControlPane(pParent, label) { int width; @@ -283,20 +264,25 @@ GuideAlgorithmLowpass:: m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("000.00")); - m_pSlopeWeight = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.5, _T("SlopeWeight")); + m_pSlopeWeight = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.5, _T("SlopeWeight")); m_pSlopeWeight->SetDigits(2); - m_pSlopeWeight->SetToolTip(wxString::Format(_("Weighting of slope parameter in lowpass auto-dec. Default = %.1f"), DefaultSlopeWeight)); - m_pSlopeWeight->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::OnSlopeWeightSpinCtrlDouble, this); + m_pSlopeWeight->SetToolTip( + wxString::Format(_("Weighting of slope parameter in lowpass auto-dec. Default = %.1f"), DefaultSlopeWeight)); + m_pSlopeWeight->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, + &GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::OnSlopeWeightSpinCtrlDouble, this); DoAdd(m_pSlopeWeight, _("Sl W")); width = StringWidth(_T("000.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); - m_pMinMove->SetToolTip(wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); - m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::OnMinMoveSpinCtrlDouble, this); + m_pMinMove->SetToolTip( + wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); + m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, + &GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::OnMinMoveSpinCtrlDouble, this); DoAdd(m_pMinMove, _("MnMo")); m_pSlopeWeight->SetValue(m_pGuideAlgorithm->GetSlopeWeight()); @@ -310,30 +296,21 @@ GuideAlgorithmLowpass:: } } -GuideAlgorithmLowpass:: - GuideAlgorithmLowpassGraphControlPane:: - ~GuideAlgorithmLowpassGraphControlPane(void) -{ -} +GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::~GuideAlgorithmLowpassGraphControlPane(void) { } -void GuideAlgorithmLowpass:: -GuideAlgorithmLowpassGraphControlPane::EnableDecControls(bool enable) +void GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::EnableDecControls(bool enable) { m_pSlopeWeight->Enable(enable); m_pMinMove->Enable(enable); } -void GuideAlgorithmLowpass:: - GuideAlgorithmLowpassGraphControlPane:: - OnSlopeWeightSpinCtrlDouble(wxSpinDoubleEvent& evt) +void GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::OnSlopeWeightSpinCtrlDouble(wxSpinDoubleEvent& evt) { m_pGuideAlgorithm->SetSlopeWeight(m_pSlopeWeight->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Low-pass slope weight", m_pSlopeWeight->GetValue()); } -void GuideAlgorithmLowpass:: - GuideAlgorithmLowpassGraphControlPane:: - OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& evt) +void GuideAlgorithmLowpass::GuideAlgorithmLowpassGraphControlPane::OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& evt) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Low-pass minimum move", m_pMinMove->GetValue()); diff --git a/src/guide_algorithm_lowpass.h b/src/guide_algorithm_lowpass.h index 57a6e5f6a..9bbb79fbd 100644 --- a/src/guide_algorithm_lowpass.h +++ b/src/guide_algorithm_lowpass.h @@ -117,4 +117,3 @@ inline double GuideAlgorithmLowpass::GetSlopeWeight() const } #endif /* GUIDE_ALGORITHM_LOWPASS_H_INCLUDED */ - diff --git a/src/guide_algorithm_lowpass2.cpp b/src/guide_algorithm_lowpass2.cpp index 0074bce79..9bfe93bc3 100644 --- a/src/guide_algorithm_lowpass2.cpp +++ b/src/guide_algorithm_lowpass2.cpp @@ -50,16 +50,13 @@ GuideAlgorithmLowpass2::GuideAlgorithmLowpass2(Mount *pMount, GuideAxis axis) double aggr = pConfig->Profile.GetDouble(GetConfigPath() + "/Aggressiveness", DefaultAggressiveness); SetAggressiveness(aggr); - m_axisStats = WindowedAxisStats(HISTORY_SIZE); // Auto-windowed + m_axisStats = WindowedAxisStats(HISTORY_SIZE); // Auto-windowed m_timeBase = 0; reset(); } -GuideAlgorithmLowpass2::~GuideAlgorithmLowpass2(void) -{ - -} +GuideAlgorithmLowpass2::~GuideAlgorithmLowpass2(void) { } GUIDE_ALGORITHM GuideAlgorithmLowpass2::Algorithm() const { @@ -75,17 +72,17 @@ void GuideAlgorithmLowpass2::reset(void) double GuideAlgorithmLowpass2::result(double input) { - m_axisStats.AddGuideInfo(m_timeBase++, input, 0); // AxisStats instance is auto-windowed + m_axisStats.AddGuideInfo(m_timeBase++, input, 0); // AxisStats instance is auto-windowed unsigned int numpts = m_axisStats.GetCount(); double dReturn; double attenuation = m_aggressiveness / 100.; double newSlope = 0; if (numpts < 4) - dReturn = input * attenuation; // Don't fall behind while we're figuring things out + dReturn = input * attenuation; // Don't fall behind while we're figuring things out else { - if (fabs(input) > 4.0 * m_minMove) // Outlier deflection - dump the history + if (fabs(input) > 4.0 * m_minMove) // Outlier deflection - dump the history { dReturn = input * attenuation; reset(); @@ -96,19 +93,20 @@ double GuideAlgorithmLowpass2::result(double input) { double intcpt; m_axisStats.GetLinearFitResults(&newSlope, &intcpt); - dReturn = newSlope * (double)numpts * attenuation; + dReturn = newSlope * (double) numpts * attenuation; // Don't return a result that will push the star further in the wrong direction if (input * dReturn < 0) dReturn = 0; } } - if (fabs(dReturn) > fabs(input)) // Keep guide pulses below magnitude of last deflection + if (fabs(dReturn) > fabs(input)) // Keep guide pulses below magnitude of last deflection { - Debug.Write(wxString::Format("GuideAlgorithmLowpass2::Result() input %.2f is < calculated value %.2f, using input\n", input, dReturn)); + Debug.Write(wxString::Format( + "GuideAlgorithmLowpass2::Result() input %.2f is < calculated value %.2f, using input\n", input, dReturn)); dReturn = input * attenuation; m_rejects++; - if (m_rejects > 3) // 3-in-a-row, our slope is not useful + if (m_rejects > 3) // 3-in-a-row, our slope is not useful { reset(); Debug.Write("Lowpass2 history cleared, 3 successive rejected correction values\n"); @@ -120,7 +118,8 @@ double GuideAlgorithmLowpass2::result(double input) if (fabs(input) < m_minMove) dReturn = 0.0; - Debug.Write(wxString::Format("GuideAlgorithmLowpass2::Result() returns %.2f from input %.2f, slope = %.2f\n", dReturn, input, newSlope)); + Debug.Write(wxString::Format( + "GuideAlgorithmLowpass2::Result() returns %.2f from input %.2f, slope = %.2f\n", dReturn, input, newSlope)); return dReturn; } @@ -136,7 +135,6 @@ bool GuideAlgorithmLowpass2::SetMinMove(double minMove) } m_minMove = minMove; - } catch (const wxString& Msg) { @@ -217,15 +215,11 @@ ConfigDialogPane *GuideAlgorithmLowpass2::GetConfigDialogPane(wxWindow *pParent) wxString GuideAlgorithmLowpass2::GetSettingsSummary() const { // return a loggable summary of current mount settings - return wxString::Format("Aggressiveness = %.3f, Minimum move = %.3f\n", - GetAggressiveness(), - GetMinMove() - ); + return wxString::Format("Aggressiveness = %.3f, Minimum move = %.3f\n", GetAggressiveness(), GetMinMove()); } -GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2ConfigDialogPane:: -GuideAlgorithmLowpass2ConfigDialogPane(wxWindow *pParent, GuideAlgorithmLowpass2 *pGuideAlgorithm) +GuideAlgorithmLowpass2::GuideAlgorithmLowpass2ConfigDialogPane::GuideAlgorithmLowpass2ConfigDialogPane( + wxWindow *pParent, GuideAlgorithmLowpass2 *pGuideAlgorithm) : ConfigDialogPane(_("Lowpass2 Guide Algorithm"), pParent) { int width; @@ -235,52 +229,44 @@ GuideAlgorithmLowpass2ConfigDialogPane(wxWindow *pParent, GuideAlgorithmLowpass2 m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("000.00")); - m_pAggressiveness = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 100.0, 0.0, _T("Aggressiveness")); + m_pAggressiveness = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, + 0.0, 100.0, 0.0, _T("Aggressiveness")); DoAdd(_("Aggressiveness"), m_pAggressiveness, - wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggressiveness)); + wxString::Format( + _("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggressiveness)); width = StringWidth(_T("000.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); DoAdd(_("Minimum Move (pixels)"), m_pMinMove, wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); } -GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2ConfigDialogPane:: -~GuideAlgorithmLowpass2ConfigDialogPane(void) -{ -} +GuideAlgorithmLowpass2::GuideAlgorithmLowpass2ConfigDialogPane::~GuideAlgorithmLowpass2ConfigDialogPane(void) { } -void GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2ConfigDialogPane:: -LoadValues(void) +void GuideAlgorithmLowpass2::GuideAlgorithmLowpass2ConfigDialogPane::LoadValues(void) { m_pAggressiveness->SetValue(m_pGuideAlgorithm->GetAggressiveness()); m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); } -void GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2ConfigDialogPane:: -UnloadValues(void) +void GuideAlgorithmLowpass2::GuideAlgorithmLowpass2ConfigDialogPane::UnloadValues(void) { m_pGuideAlgorithm->SetAggressiveness(m_pAggressiveness->GetValue()); m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); } -void GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2ConfigDialogPane::OnImageScaleChange() +void GuideAlgorithmLowpass2::GuideAlgorithmLowpass2ConfigDialogPane::OnImageScaleChange() { GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove); } -void GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2ConfigDialogPane::EnableDecControls(bool enable) +void GuideAlgorithmLowpass2::GuideAlgorithmLowpass2ConfigDialogPane::EnableDecControls(bool enable) { m_pAggressiveness->Enable(enable); m_pMinMove->Enable(enable); @@ -291,29 +277,33 @@ GraphControlPane *GuideAlgorithmLowpass2::GetGraphControlPane(wxWindow *pParent, return new GuideAlgorithmLowpass2GraphControlPane(pParent, this, label); } -GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2GraphControlPane:: -GuideAlgorithmLowpass2GraphControlPane(wxWindow *pParent, GuideAlgorithmLowpass2 *pGuideAlgorithm, const wxString& label) -: GraphControlPane(pParent, label) +GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::GuideAlgorithmLowpass2GraphControlPane( + wxWindow *pParent, GuideAlgorithmLowpass2 *pGuideAlgorithm, const wxString& label) + : GraphControlPane(pParent, label) { int width; m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("000.00")); - m_pAggressiveness = pFrame->MakeSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 100.0, 0.0, _T("Aggressiveness")); - m_pAggressiveness->SetToolTip(wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggressiveness)); - m_pAggressiveness->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::OnAggrSpinCtrl, this); + m_pAggressiveness = pFrame->MakeSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 100.0, 0.0, _T("Aggressiveness")); + m_pAggressiveness->SetToolTip(wxString::Format( + _("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggressiveness)); + m_pAggressiveness->Bind( + wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::OnAggrSpinCtrl, this); DoAdd(m_pAggressiveness, _("Agg")); width = StringWidth(_T("000.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); - m_pMinMove->SetToolTip(wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); - m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::OnMinMoveSpinCtrlDouble, this); + m_pMinMove->SetToolTip( + wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); + m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, + &GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::OnMinMoveSpinCtrlDouble, this); DoAdd(m_pMinMove, _("MnMo")); m_pAggressiveness->SetValue(m_pGuideAlgorithm->GetAggressiveness()); @@ -327,30 +317,21 @@ GuideAlgorithmLowpass2GraphControlPane(wxWindow *pParent, GuideAlgorithmLowpass2 } } -GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2GraphControlPane:: -~GuideAlgorithmLowpass2GraphControlPane(void) -{ -} +GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::~GuideAlgorithmLowpass2GraphControlPane(void) { } -void GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2GraphControlPane::EnableDecControls(bool enable) +void GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::EnableDecControls(bool enable) { m_pAggressiveness->Enable(enable); m_pMinMove->Enable(enable); } -void GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2GraphControlPane:: -OnAggrSpinCtrl(wxSpinEvent& evt) +void GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::OnAggrSpinCtrl(wxSpinEvent& evt) { m_pGuideAlgorithm->SetAggressiveness(m_pAggressiveness->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Low-pass2 aggressiveness", m_pAggressiveness->GetValue()); } -void GuideAlgorithmLowpass2:: -GuideAlgorithmLowpass2GraphControlPane:: -OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& evt) +void GuideAlgorithmLowpass2::GuideAlgorithmLowpass2GraphControlPane::OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& evt) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Low-pass2 minimum move", m_pMinMove->GetValue()); diff --git a/src/guide_algorithm_lowpass2.h b/src/guide_algorithm_lowpass2.h index 4417d5f12..30811c564 100644 --- a/src/guide_algorithm_lowpass2.h +++ b/src/guide_algorithm_lowpass2.h @@ -57,6 +57,7 @@ class GuideAlgorithmLowpass2 : public GuideAlgorithm GuideAlgorithmLowpass2 *m_pGuideAlgorithm; wxSpinCtrl *m_pAggressiveness; wxSpinCtrlDouble *m_pMinMove; + public: GuideAlgorithmLowpass2ConfigDialogPane(wxWindow *pParent, GuideAlgorithmLowpass2 *pGuideAlgorithm); ~GuideAlgorithmLowpass2ConfigDialogPane(); @@ -70,7 +71,8 @@ class GuideAlgorithmLowpass2 : public GuideAlgorithm class GuideAlgorithmLowpass2GraphControlPane : public GraphControlPane { public: - GuideAlgorithmLowpass2GraphControlPane(wxWindow *pParent, GuideAlgorithmLowpass2 *pGuideAlgorithm, const wxString& label); + GuideAlgorithmLowpass2GraphControlPane( + wxWindow *pParent, GuideAlgorithmLowpass2 *pGuideAlgorithm, const wxString& label); ~GuideAlgorithmLowpass2GraphControlPane(); void EnableDecControls(bool enable) override; diff --git a/src/guide_algorithm_resistswitch.cpp b/src/guide_algorithm_resistswitch.cpp index cc1404378..351a45346 100644 --- a/src/guide_algorithm_resistswitch.cpp +++ b/src/guide_algorithm_resistswitch.cpp @@ -1,41 +1,41 @@ /* -* guide_algorithm_resistswitch.cpp -* PHD Guiding -* -* Created by Bret McKee -* Copyright (c) 2012 Bret McKee -* All rights reserved. -* -* Based upon work by Craig Stark. -* Copyright (c) 2006-2010 Craig Stark. -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * guide_algorithm_resistswitch.cpp + * PHD Guiding + * + * Created by Bret McKee + * Copyright (c) 2012 Bret McKee + * All rights reserved. + * + * Based upon work by Craig Stark. + * Copyright (c) 2006-2010 Craig Stark. + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" @@ -45,7 +45,7 @@ static const double DefaultAggression = 1.0; GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitch(Mount *pMount, GuideAxis axis) : GuideAlgorithm(pMount, axis) { - double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove); + double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove); SetMinMove(minMove); double aggr = pConfig->Profile.GetDouble(GetConfigPath() + "/aggression", DefaultAggression); @@ -57,9 +57,7 @@ GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitch(Mount *pMount, GuideAxis reset(); } -GuideAlgorithmResistSwitch::~GuideAlgorithmResistSwitch(void) -{ -} +GuideAlgorithmResistSwitch::~GuideAlgorithmResistSwitch(void) { } GUIDE_ALGORITHM GuideAlgorithmResistSwitch::Algorithm() const { @@ -112,7 +110,8 @@ double GuideAlgorithmResistSwitch::result(double input) double thresh = 3.0 * m_minMove; if (sign(input) != m_currentSide && fabs(input) > thresh) { - Debug.Write(wxString::Format("resist switch: large excursion: input %.2f thresh %.2f direction from %d to %d\n", input, thresh, m_currentSide, sign(input))); + Debug.Write(wxString::Format("resist switch: large excursion: input %.2f thresh %.2f direction from %d to %d\n", + input, thresh, m_currentSide, sign(input))); // force switch m_currentSide = 0; unsigned int i; @@ -154,7 +153,8 @@ double GuideAlgorithmResistSwitch::result(double input) throw THROW_INFO("Not getting worse"); } - Debug.Write(wxString::Format("switching direction from %d to %d - decHistory=%d oldest=%.2f newest=%.2f\n", m_currentSide, sign(decHistory), decHistory, oldest, newest)); + Debug.Write(wxString::Format("switching direction from %d to %d - decHistory=%d oldest=%.2f newest=%.2f\n", + m_currentSide, sign(decHistory), decHistory, oldest, newest)); m_currentSide = sign(decHistory); } @@ -227,7 +227,8 @@ bool GuideAlgorithmResistSwitch::SetAggression(double aggr) pConfig->Profile.SetDouble(GetConfigPath() + "/aggression", m_aggression); - Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetAggression() returns %d, m_aggression=%.2f\n", bError, m_aggression)); + Debug.Write( + wxString::Format("GuideAlgorithmResistSwitch::SetAggression() returns %d, m_aggression=%.2f\n", bError, m_aggression)); return bError; } @@ -268,7 +269,8 @@ bool GuideAlgorithmResistSwitch::SetParam(const wxString& name, double val) if (name == "minMove") err = SetMinMove(val); - else if (name == "fastSwitch") { + else if (name == "fastSwitch") + { SetFastSwitchEnabled(val != 0.0); err = false; } @@ -283,8 +285,8 @@ bool GuideAlgorithmResistSwitch::SetParam(const wxString& name, double val) wxString GuideAlgorithmResistSwitch::GetSettingsSummary() const { // return a loggable summary of current mount settings - return wxString::Format("Minimum move = %.3f Aggression = %.f%% FastSwitch = %s\n", - GetMinMove(), GetAggression() * 100.0, GetFastSwitchEnabled() ? "enabled" : "disabled"); + return wxString::Format("Minimum move = %.3f Aggression = %.f%% FastSwitch = %s\n", GetMinMove(), GetAggression() * 100.0, + GetFastSwitchEnabled() ? "enabled" : "disabled"); } ConfigDialogPane *GuideAlgorithmResistSwitch::GetConfigDialogPane(wxWindow *pParent) @@ -292,9 +294,8 @@ ConfigDialogPane *GuideAlgorithmResistSwitch::GetConfigDialogPane(wxWindow *pPar return new GuideAlgorithmResistSwitchConfigDialogPane(pParent, this); } -GuideAlgorithmResistSwitch:: - GuideAlgorithmResistSwitchConfigDialogPane:: - GuideAlgorithmResistSwitchConfigDialogPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm) +GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchConfigDialogPane::GuideAlgorithmResistSwitchConfigDialogPane( + wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm) : ConfigDialogPane(_("ResistSwitch Guide Algorithm"), pParent) { int width; @@ -302,56 +303,51 @@ GuideAlgorithmResistSwitch:: m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("000")); - m_pAggression = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, _T("Aggressiveness")); + m_pAggression = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, + 100.0, 100.0, _T("Aggressiveness")); DoAdd(_("Aggressiveness"), m_pAggression, - wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggression * 100.0)); + wxString::Format( + _("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggression * 100.0)); width = StringWidth(_T("00.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + pParent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); DoAdd(_("Minimum Move (pixels)"), m_pMinMove, wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); m_pFastSwitch = new wxCheckBox(pParent, wxID_ANY, _("Fast switch for large deflections")); - DoAdd(m_pFastSwitch, _("Ordinarily the Resist Switch algortithm waits several frames before switching direction. With Fast Switch enabled PHD2 will switch direction immediately if it sees a very large deflection. Enable this option if your mount has a substantial amount of backlash and PHD2 sometimes overcorrects.")); + DoAdd(m_pFastSwitch, + _("Ordinarily the Resist Switch algortithm waits several frames before switching direction. With Fast Switch enabled " + "PHD2 will switch direction immediately if it sees a very large deflection. Enable this option if your mount has a " + "substantial amount of backlash and PHD2 sometimes overcorrects.")); } -GuideAlgorithmResistSwitch:: - GuideAlgorithmResistSwitchConfigDialogPane:: - ~GuideAlgorithmResistSwitchConfigDialogPane(void) -{ -} +GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchConfigDialogPane::~GuideAlgorithmResistSwitchConfigDialogPane(void) { } -void GuideAlgorithmResistSwitch:: - GuideAlgorithmResistSwitchConfigDialogPane:: - LoadValues(void) +void GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchConfigDialogPane::LoadValues(void) { m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0); m_pFastSwitch->SetValue(m_pGuideAlgorithm->GetFastSwitchEnabled()); } -void GuideAlgorithmResistSwitch:: - GuideAlgorithmResistSwitchConfigDialogPane:: - UnloadValues(void) +void GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchConfigDialogPane::UnloadValues(void) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0); m_pGuideAlgorithm->SetFastSwitchEnabled(m_pFastSwitch->GetValue()); } -void GuideAlgorithmResistSwitch:: -GuideAlgorithmResistSwitchConfigDialogPane::OnImageScaleChange() +void GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchConfigDialogPane::OnImageScaleChange() { GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove); } -void GuideAlgorithmResistSwitch:: -GuideAlgorithmResistSwitchConfigDialogPane::EnableDecControls(bool enable) +void GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchConfigDialogPane::EnableDecControls(bool enable) { m_pAggression->Enable(enable); m_pMinMove->Enable(enable); @@ -363,9 +359,8 @@ GraphControlPane *GuideAlgorithmResistSwitch::GetGraphControlPane(wxWindow *pPar return new GuideAlgorithmResistSwitchGraphControlPane(pParent, this, label); } -GuideAlgorithmResistSwitch:: - GuideAlgorithmResistSwitchGraphControlPane:: - GuideAlgorithmResistSwitchGraphControlPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm, const wxString& label) +GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::GuideAlgorithmResistSwitchGraphControlPane( + wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm, const wxString& label) : GraphControlPane(pParent, label) { int width; @@ -374,21 +369,26 @@ GuideAlgorithmResistSwitch:: // Aggression width = StringWidth(_T("000")); - m_pAggression = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, _T("Aggressiveness")); - m_pAggression->SetToolTip(wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggression * 100.0)); - m_pAggression->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnAggressionSpinCtrl, this); + m_pAggression = pFrame->MakeSpinCtrl( + this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, _T("Aggressiveness")); + m_pAggression->SetToolTip(wxString::Format( + _("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggression * 100.0)); + m_pAggression->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, + &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnAggressionSpinCtrl, this); DoAdd(m_pAggression, _T("Agr")); m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0); // Min move width = StringWidth(_T("00.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); - m_pMinMove->SetToolTip(wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); - m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnMinMoveSpinCtrlDouble, this); + m_pMinMove->SetToolTip( + wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); + m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, + &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnMinMoveSpinCtrlDouble, this); DoAdd(m_pMinMove, _("MnMo")); m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); @@ -400,30 +400,22 @@ GuideAlgorithmResistSwitch:: } } -GuideAlgorithmResistSwitch:: - GuideAlgorithmResistSwitchGraphControlPane:: - ~GuideAlgorithmResistSwitchGraphControlPane(void) -{ -} +GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::~GuideAlgorithmResistSwitchGraphControlPane(void) { } -void GuideAlgorithmResistSwitch:: -GuideAlgorithmResistSwitchGraphControlPane::EnableDecControls(bool enable) +void GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::EnableDecControls(bool enable) { m_pAggression->Enable(enable); m_pMinMove->Enable(enable); } -void GuideAlgorithmResistSwitch:: - GuideAlgorithmResistSwitchGraphControlPane:: - OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& WXUNUSED(evt)) +void GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnMinMoveSpinCtrlDouble( + wxSpinDoubleEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch minimum move", m_pMinMove->GetValue()); } -void GuideAlgorithmResistSwitch:: - GuideAlgorithmResistSwitchGraphControlPane:: - OnAggressionSpinCtrl(wxSpinEvent& WXUNUSED(evt)) +void GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnAggressionSpinCtrl(wxSpinEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch aggression", m_pAggression->GetValue()); diff --git a/src/guide_algorithm_resistswitch.h b/src/guide_algorithm_resistswitch.h index 9eb06772c..3296aa6a2 100644 --- a/src/guide_algorithm_resistswitch.h +++ b/src/guide_algorithm_resistswitch.h @@ -48,7 +48,7 @@ class GuideAlgorithmResistSwitch : public GuideAlgorithm double m_minMove; double m_aggression; bool m_fastSwitchEnabled; - int m_currentSide; + int m_currentSide; protected: class GuideAlgorithmResistSwitchConfigDialogPane : public ConfigDialogPane @@ -71,7 +71,8 @@ class GuideAlgorithmResistSwitch : public GuideAlgorithm class GuideAlgorithmResistSwitchGraphControlPane : public GraphControlPane { public: - GuideAlgorithmResistSwitchGraphControlPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm, const wxString& label); + GuideAlgorithmResistSwitchGraphControlPane( + wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm, const wxString& label); ~GuideAlgorithmResistSwitchGraphControlPane(); void EnableDecControls(bool enable) override; diff --git a/src/guide_algorithm_zfilter.cpp b/src/guide_algorithm_zfilter.cpp index e0fd501cb..afdac07a3 100644 --- a/src/guide_algorithm_zfilter.cpp +++ b/src/guide_algorithm_zfilter.cpp @@ -1,44 +1,44 @@ /* -* guide_algorithm_zfilter.cpp -* PHD Guiding -* -* Created by Ken Self -* Copyright (c) 2018 Ken Self -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * guide_algorithm_zfilter.cpp + * PHD Guiding + * + * Created by Ken Self + * Copyright (c) 2018 Ken Self + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" static const double DefaultMinMove = 0.1; static const double DefaultExpFactor = 2.0; GuideAlgorithmZFilter::GuideAlgorithmZFilter(Mount *pMount, GuideAxis axis) - : GuideAlgorithm(pMount, axis), - m_pFactory(nullptr) + : GuideAlgorithm(pMount, axis) + , m_pFactory(nullptr) { m_expFactor = DefaultExpFactor; m_design = BESSEL; @@ -72,18 +72,18 @@ void GuideAlgorithmZFilter::reset() double GuideAlgorithmZFilter::result(double input) { - double dReturn=0; + double dReturn = 0; -// Digital filter designed by mkfilter/mkshape/gencode A.J. Fisher + // Digital filter designed by mkfilter/mkshape/gencode A.J. Fisher double gain = m_gain; -// Shift readings and results + // Shift readings and results m_xv.insert(m_xv.begin(), (input + m_sumCorr) / gain); // Add total guide output to input to get uncorrected waveform m_xv.pop_back(); m_yv.insert(m_yv.begin(), 0.0); m_yv.pop_back(); -// Calculate filtered value + // Calculate filtered value for (int i = 0; i < m_xcoeff.size(); i++) { m_yv.at(0) += m_xv.at(i) * m_xcoeff.at(i); @@ -92,7 +92,7 @@ double GuideAlgorithmZFilter::result(double input) { m_yv.at(0) += m_yv.at(i) * m_ycoeff.at(i); } - dReturn = m_yv.at(0) - m_sumCorr; // Return the difference from the uncorrected waveform + dReturn = m_yv.at(0) - m_sumCorr; // Return the difference from the uncorrected waveform if (fabs(dReturn) < m_minMove) { @@ -100,16 +100,17 @@ double GuideAlgorithmZFilter::result(double input) } m_sumCorr += dReturn; -/* wxString msg = "GuideAlgorithmZFilter::m_xv "; - for (int i = 0; ixcoeffs; m_ycoeff = m_pFactory->ycoeffs; - Debug.Write(wxString::Format("GuideAlgorithmZFilter::type=%s order=%d, corner=%lf, gain=%lg\n", - m_pFactory->getname(), m_order, m_pFactory->corner(), m_gain)); + Debug.Write(wxString::Format("GuideAlgorithmZFilter::type=%s order=%d, corner=%lf, gain=%lg\n", m_pFactory->getname(), + m_order, m_pFactory->corner(), m_gain)); wxString msg = wxString::Format("GuideAlgorithmZFilter::m_xcoeffs:"); for (int it = 0; it < m_xcoeff.size(); it++) { @@ -179,7 +179,6 @@ bool GuideAlgorithmZFilter::SetMinMove(double minMove) } m_minMove = minMove; - } catch (const wxString& Msg) { @@ -206,7 +205,6 @@ bool GuideAlgorithmZFilter::SetExpFactor(double expFactor) } m_expFactor = expFactor; - } catch (const wxString& Msg) { @@ -258,8 +256,8 @@ bool GuideAlgorithmZFilter::SetParam(const wxString& name, double val) wxString GuideAlgorithmZFilter::GetSettingsSummary() const { // return a loggable summary of current mount settings - return wxString::Format("Type=%s-%d, Exp-factor=%.1f, Minimum move = %.3f\n", - m_pFactory->getname(), m_order, m_pFactory->corner() / 4.0, GetMinMove()); + return wxString::Format("Type=%s-%d, Exp-factor=%.1f, Minimum move = %.3f\n", m_pFactory->getname(), m_order, + m_pFactory->corner() / 4.0, GetMinMove()); } ConfigDialogPane *GuideAlgorithmZFilter::GetConfigDialogPane(wxWindow *pParent) @@ -267,63 +265,53 @@ ConfigDialogPane *GuideAlgorithmZFilter::GetConfigDialogPane(wxWindow *pParent) return new GuideAlgorithmZFilterConfigDialogPane(pParent, this); } -GuideAlgorithmZFilter:: - GuideAlgorithmZFilterConfigDialogPane:: - GuideAlgorithmZFilterConfigDialogPane(wxWindow *pParent, GuideAlgorithmZFilter *pGuideAlgorithm) +GuideAlgorithmZFilter::GuideAlgorithmZFilterConfigDialogPane::GuideAlgorithmZFilterConfigDialogPane( + wxWindow *pParent, GuideAlgorithmZFilter *pGuideAlgorithm) : ConfigDialogPane(_("ZFilter Guide Algorithm"), pParent) { m_pGuideAlgorithm = pGuideAlgorithm; int width; width = StringWidth(_T("00.0")); - m_pExpFactor = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 20.0, 2.0, 1.0, _T("ExpFactor")); + m_pExpFactor = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, + 1.0, 20.0, 2.0, 1.0, _T("ExpFactor")); m_pExpFactor->SetDigits(1); DoAdd(_("Exposure Factor"), m_pExpFactor, wxString::Format(_("Multiplied by exposure time gives the equivalent exposure time after filtering. " - "Default = %.1f"), DefaultExpFactor)); + "Default = %.1f"), + DefaultExpFactor)); width = StringWidth(_T("000.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble( + pParent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05, _T("MinMove")); m_pMinMove->SetDigits(2); DoAdd(_("Minimum Move (pixels)"), m_pMinMove, wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); - + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); } -GuideAlgorithmZFilter:: - GuideAlgorithmZFilterConfigDialogPane:: - ~GuideAlgorithmZFilterConfigDialogPane() -{ -} +GuideAlgorithmZFilter::GuideAlgorithmZFilterConfigDialogPane::~GuideAlgorithmZFilterConfigDialogPane() { } -void GuideAlgorithmZFilter:: - GuideAlgorithmZFilterConfigDialogPane:: - LoadValues() +void GuideAlgorithmZFilter::GuideAlgorithmZFilterConfigDialogPane::LoadValues() { m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); m_pExpFactor->SetValue(m_pGuideAlgorithm->GetExpFactor()); } -void GuideAlgorithmZFilter:: - GuideAlgorithmZFilterConfigDialogPane:: - UnloadValues() +void GuideAlgorithmZFilter::GuideAlgorithmZFilterConfigDialogPane::UnloadValues() { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); m_pGuideAlgorithm->SetExpFactor(m_pExpFactor->GetValue()); } -void GuideAlgorithmZFilter:: -GuideAlgorithmZFilterConfigDialogPane::OnImageScaleChange() +void GuideAlgorithmZFilter::GuideAlgorithmZFilterConfigDialogPane::OnImageScaleChange() { GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove); } -void GuideAlgorithmZFilter:: -GuideAlgorithmZFilterConfigDialogPane::EnableDecControls(bool enable) +void GuideAlgorithmZFilter::GuideAlgorithmZFilterConfigDialogPane::EnableDecControls(bool enable) { m_pExpFactor->Enable(enable); m_pMinMove->Enable(enable); @@ -334,9 +322,8 @@ GraphControlPane *GuideAlgorithmZFilter::GetGraphControlPane(wxWindow *pParent, return new GuideAlgorithmZFilterGraphControlPane(pParent, this, label); } -GuideAlgorithmZFilter:: - GuideAlgorithmZFilterGraphControlPane:: - GuideAlgorithmZFilterGraphControlPane(wxWindow *pParent, GuideAlgorithmZFilter *pGuideAlgorithm, const wxString& label) +GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::GuideAlgorithmZFilterGraphControlPane( + wxWindow *pParent, GuideAlgorithmZFilter *pGuideAlgorithm, const wxString& label) : GraphControlPane(pParent, label) { int width; @@ -344,24 +331,29 @@ GuideAlgorithmZFilter:: m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("00.0")); - m_pExpFactor = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 20.0, 2.0, 1.0, _T("ExpFactor")); + m_pExpFactor = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 1.0, 20.0, 2.0, 1.0, _T("ExpFactor")); m_pExpFactor->SetDigits(1); m_pExpFactor->SetToolTip( wxString::Format(_("Multiplied by exposure time gives the equivalent expsoure time after filtering. " - "Default = %.1f"), DefaultExpFactor)); - m_pExpFactor->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::OnExpFactorSpinCtrlDouble, this); + "Default = %.1f"), + DefaultExpFactor)); + m_pExpFactor->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, + &GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::OnExpFactorSpinCtrlDouble, this); DoAdd(m_pExpFactor, _("XFac")); m_pExpFactor->SetValue(m_pGuideAlgorithm->GetExpFactor()); width = StringWidth(_T("000.00")); - m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05, _T("MinMove")); + m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.05, _T("MinMove")); m_pMinMove->SetDigits(2); - m_pMinMove->SetToolTip(wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" - "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); - m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::OnMinMoveSpinCtrlDouble, this); + m_pMinMove->SetToolTip( + wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" + "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), + DefaultMinMove)); + m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, + &GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::OnMinMoveSpinCtrlDouble, this); DoAdd(m_pMinMove, _("MnMo")); m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); @@ -371,33 +363,23 @@ GuideAlgorithmZFilter:: m_pExpFactor->Enable(currDecGuideMode != DEC_NONE); m_pMinMove->Enable(currDecGuideMode != DEC_NONE); } - } -GuideAlgorithmZFilter:: - GuideAlgorithmZFilterGraphControlPane:: - ~GuideAlgorithmZFilterGraphControlPane() -{ -} +GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::~GuideAlgorithmZFilterGraphControlPane() { } -void GuideAlgorithmZFilter:: -GuideAlgorithmZFilterGraphControlPane::EnableDecControls(bool enable) +void GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::EnableDecControls(bool enable) { m_pMinMove->Enable(enable); m_pExpFactor->Enable(enable); } -void GuideAlgorithmZFilter:: -GuideAlgorithmZFilterGraphControlPane:: -OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& evt) +void GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& evt) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " ZFilter minimum move", m_pMinMove->GetValue()); } -void GuideAlgorithmZFilter:: -GuideAlgorithmZFilterGraphControlPane:: -OnExpFactorSpinCtrlDouble(wxSpinDoubleEvent& evt) +void GuideAlgorithmZFilter::GuideAlgorithmZFilterGraphControlPane::OnExpFactorSpinCtrlDouble(wxSpinDoubleEvent& evt) { m_pGuideAlgorithm->SetExpFactor(m_pExpFactor->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " ZFilter exposure factor", m_pExpFactor->GetValue()); diff --git a/src/guide_algorithm_zfilter.h b/src/guide_algorithm_zfilter.h index bd1444a02..5b050376f 100644 --- a/src/guide_algorithm_zfilter.h +++ b/src/guide_algorithm_zfilter.h @@ -40,7 +40,7 @@ class GuideAlgorithmZFilter : public GuideAlgorithm { FILTER_DESIGN m_design; - std::vector m_xv, m_yv; // Historical values up to m_order + std::vector m_xv, m_yv; // Historical values up to m_order std::vector m_xcoeff, m_ycoeff; int m_order; double m_gain; @@ -49,6 +49,7 @@ class GuideAlgorithmZFilter : public GuideAlgorithm double m_expFactor; ZFilterFactory *m_pFactory; + protected: class GuideAlgorithmZFilterConfigDialogPane : public ConfigDialogPane { diff --git a/src/guide_algorithms.h b/src/guide_algorithms.h index 15a52aa91..92e3c5557 100644 --- a/src/guide_algorithms.h +++ b/src/guide_algorithms.h @@ -42,7 +42,7 @@ enum GUIDE_ALGORITHM { - GUIDE_ALGORITHM_NONE=-1, + GUIDE_ALGORITHM_NONE = -1, GUIDE_ALGORITHM_IDENTITY, GUIDE_ALGORITHM_HYSTERESIS, GUIDE_ALGORITHM_LOWPASS, diff --git a/src/guider.cpp b/src/guider.cpp index 10bb6c5df..7a65b1dba 100644 --- a/src/guider.cpp +++ b/src/guider.cpp @@ -39,7 +39,7 @@ #include "guiding_assistant.h" // un-comment to log star deflections to a file -//#define CAPTURE_DEFLECTIONS +// #define CAPTURE_DEFLECTIONS struct DeflectionLogger { @@ -97,8 +97,8 @@ inline void DeflectionLogger::Log(const PHD_Point&) { } #endif // CAPTURE_DEFLECTIONS -static const int DefaultOverlayMode = OVERLAY_NONE; -static const bool DefaultScaleImage = true; +static const int DefaultOverlayMode = OVERLAY_NONE; +static const bool DefaultScaleImage = true; // clang-format off wxBEGIN_EVENT_TABLE(Guider, wxWindow) @@ -137,27 +137,37 @@ static void LoadBookmarks(std::vector *vec) static const wxStringCharType *StateStr(GUIDER_STATE st) { - switch (st) { - case STATE_UNINITIALIZED: return wxS("UNINITIALIZED"); - case STATE_SELECTING: return wxS("SELECTING"); - case STATE_SELECTED: return wxS("SELECTED"); - case STATE_CALIBRATING_PRIMARY: return wxS("CALIBRATING_PRIMARY"); - case STATE_CALIBRATING_SECONDARY: return wxS("CALIBRATING_SECONDARY"); - case STATE_CALIBRATED: return wxS("CALIBRATED"); - case STATE_GUIDING: return wxS("GUIDING"); - case STATE_STOP: return wxS("STOP"); - default: return wxS("??"); + switch (st) + { + case STATE_UNINITIALIZED: + return wxS("UNINITIALIZED"); + case STATE_SELECTING: + return wxS("SELECTING"); + case STATE_SELECTED: + return wxS("SELECTED"); + case STATE_CALIBRATING_PRIMARY: + return wxS("CALIBRATING_PRIMARY"); + case STATE_CALIBRATING_SECONDARY: + return wxS("CALIBRATING_SECONDARY"); + case STATE_CALIBRATED: + return wxS("CALIBRATED"); + case STATE_GUIDING: + return wxS("GUIDING"); + case STATE_STOP: + return wxS("STOP"); + default: + return wxS("??"); } } -Guider::Guider(wxWindow *parent, int xSize, int ySize) : - wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE) +Guider::Guider(wxWindow *parent, int xSize, int ySize) + : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE) { m_state = STATE_UNINITIALIZED; Debug.Write(wxString::Format("guider state => %s\n", StateStr(m_state))); m_scaleFactor = 1.0; m_showBookmarks = true; - m_displayedImage = new wxImage(XWinSize,YWinSize,true); + m_displayedImage = new wxImage(XWinSize, YWinSize, true); m_paused = PAUSE_NONE; m_starFoundTimestamp = 0; m_avgDistanceNeedReset = false; @@ -190,7 +200,7 @@ Guider::Guider(wxWindow *parent, int xSize, int ySize) : m_polarAlignCircleCorrection = 1.0; SetBackgroundStyle(wxBG_STYLE_CUSTOM); - SetBackgroundColour(wxColour((unsigned char) 30, (unsigned char) 30,(unsigned char) 30)); + SetBackgroundColour(wxColour((unsigned char) 30, (unsigned char) 30, (unsigned char) 30)); s_deflectionLogger.Init(); } @@ -288,15 +298,15 @@ bool Guider::SetOverlayMode(int overlayMode) { switch (overlayMode) { - case OVERLAY_NONE: - case OVERLAY_BULLSEYE: - case OVERLAY_GRID_FINE: - case OVERLAY_GRID_COARSE: - case OVERLAY_RADEC: - case OVERLAY_SLIT: - break; - default: - throw ERROR_INFO("invalid overlayMode"); + case OVERLAY_NONE: + case OVERLAY_BULLSEYE: + case OVERLAY_GRID_FINE: + case OVERLAY_GRID_COARSE: + case OVERLAY_RADEC: + case OVERLAY_SLIT: + break; + default: + throw ERROR_INFO("invalid overlayMode"); } m_overlayMode = (OVERLAY_MODE) overlayMode; @@ -348,32 +358,32 @@ void Guider::SetOverlaySlitCoords(const wxPoint& center, const wxSize& size, int { if (angle != 0) { - double a = -radians((double)angle); + double a = -radians((double) angle); double s = sin(a); double c = cos(a); - double cx = (double)center.x; - double cy = (double)center.y; + double cx = (double) center.x; + double cy = (double) center.y; double x, y; - x = +(double)size.GetWidth() / 2.0; - y = +(double)size.GetHeight() / 2.0; - m_overlaySlitCoords.corners[0].x = cx + (int)floor(x * c - y * s); - m_overlaySlitCoords.corners[0].y = cy + (int)floor(x * s + y * c); - - x = -(double)size.GetWidth() / 2.0; - y = +(double)size.GetHeight() / 2.0; - m_overlaySlitCoords.corners[1].x = cx + (int)floor(x * c - y * s); - m_overlaySlitCoords.corners[1].y = cy + (int)floor(x * s + y * c); - - x = -(double)size.GetWidth() / 2.0; - y = -(double)size.GetHeight() / 2.0; - m_overlaySlitCoords.corners[2].x = cx + (int)floor(x * c - y * s); - m_overlaySlitCoords.corners[2].y = cy + (int)floor(x * s + y * c); - - x = +(double)size.GetWidth() / 2.0; - y = -(double)size.GetHeight() / 2.0; - m_overlaySlitCoords.corners[3].x = cx + (int)floor(x * c - y * s); - m_overlaySlitCoords.corners[3].y = cy + (int)floor(x * s + y * c); + x = +(double) size.GetWidth() / 2.0; + y = +(double) size.GetHeight() / 2.0; + m_overlaySlitCoords.corners[0].x = cx + (int) floor(x * c - y * s); + m_overlaySlitCoords.corners[0].y = cy + (int) floor(x * s + y * c); + + x = -(double) size.GetWidth() / 2.0; + y = +(double) size.GetHeight() / 2.0; + m_overlaySlitCoords.corners[1].x = cx + (int) floor(x * c - y * s); + m_overlaySlitCoords.corners[1].y = cy + (int) floor(x * s + y * c); + + x = -(double) size.GetWidth() / 2.0; + y = -(double) size.GetHeight() / 2.0; + m_overlaySlitCoords.corners[2].x = cx + (int) floor(x * c - y * s); + m_overlaySlitCoords.corners[2].y = cy + (int) floor(x * s + y * c); + + x = +(double) size.GetWidth() / 2.0; + y = -(double) size.GetHeight() / 2.0; + m_overlaySlitCoords.corners[3].x = cx + (int) floor(x * c - y * s); + m_overlaySlitCoords.corners[3].y = cy + (int) floor(x * s + y * c); } else { @@ -446,25 +456,24 @@ bool Guider::PaintHelper(wxAutoBufferedPaintDCBase& dc, wxMemoryDC& memDC) m_pCurrentImage->CopyToImage(&m_displayedImage, blevel, wlevel, pFrame->Stretch_gamma); } - int imageWidth = m_displayedImage->GetWidth(); - int imageHeight = m_displayedImage->GetHeight(); + int imageWidth = m_displayedImage->GetWidth(); + int imageHeight = m_displayedImage->GetHeight(); // scale the image if necessary if (imageWidth != XWinSize || imageHeight != YWinSize) { // The image is not the exact right size -- figure out what to do. - double xScaleFactor = imageWidth / (double)XWinSize; - double yScaleFactor = imageHeight / (double)YWinSize; + double xScaleFactor = imageWidth / (double) XWinSize; + double yScaleFactor = imageHeight / (double) YWinSize; int newWidth = imageWidth; int newHeight = imageHeight; - double newScaleFactor = (xScaleFactor > yScaleFactor) ? - xScaleFactor : - yScaleFactor; + double newScaleFactor = (xScaleFactor > yScaleFactor) ? xScaleFactor : yScaleFactor; -// Debug.Write(wxString::Format("xScaleFactor=%.2f, yScaleFactor=%.2f, newScaleFactor=%.2f\n", xScaleFactor, -// yScaleFactor, newScaleFactor)); + // Debug.Write(wxString::Format("xScaleFactor=%.2f, yScaleFactor=%.2f, newScaleFactor=%.2f\n", + // xScaleFactor, + // yScaleFactor, newScaleFactor)); // we rescale the image if: // - The image is either too big @@ -472,8 +481,7 @@ bool Guider::PaintHelper(wxAutoBufferedPaintDCBase& dc, wxMemoryDC& memDC) // than half the width of the window or // - The user has requested rescaling - if (xScaleFactor > 1.0 || yScaleFactor > 1.0 || - xScaleFactor < 0.45 || yScaleFactor < 0.45 || m_scaleImage) + if (xScaleFactor > 1.0 || yScaleFactor > 1.0 || xScaleFactor < 0.45 || yScaleFactor < 0.45 || m_scaleImage) { newWidth /= newScaleFactor; @@ -485,7 +493,7 @@ bool Guider::PaintHelper(wxAutoBufferedPaintDCBase& dc, wxMemoryDC& memDC) if (imageWidth != newWidth || imageHeight != newHeight) { -// Debug.Write(wxString::Format("Resizing image to %d,%d\n", newWidth, newHeight)); + // Debug.Write(wxString::Format("Resizing image to %d,%d\n", newWidth, newHeight)); if (newWidth > 0 && newHeight > 0) { @@ -512,144 +520,144 @@ bool Guider::PaintHelper(wxAutoBufferedPaintDCBase& dc, wxMemoryDC& memDC) if (m_overlayMode) { - dc.SetPen(wxPen(wxColor(200,50,50))); + dc.SetPen(wxPen(wxColor(200, 50, 50))); dc.SetBrush(*wxTRANSPARENT_BRUSH); switch (m_overlayMode) { - case OVERLAY_BULLSEYE: - { - int cx = XImgSize / 2; - int cy = YImgSize / 2; - dc.DrawCircle(cx,cy,25); - dc.DrawCircle(cx,cy,50); - dc.DrawCircle(cx,cy,100); - dc.DrawLine(0, cy, XImgSize, cy); - dc.DrawLine(cx, 0, cx, YImgSize); - break; - } - case OVERLAY_GRID_FINE: - case OVERLAY_GRID_COARSE: - { - int i; - int size = (m_overlayMode - 1) * 20; - for (i=size; iIsCalibrated() ? mount->xAngle() : 0.0; - double eAngle = wAngle + M_PI; - GuideParity raParity = mount->RAParity(); - if (raParity == GUIDE_PARITY_ODD) - { - // odd parity => West calibration pulses move scope East - // => star moves West - // => East vector is opposite direction from X calibration vector (West calibration direction) - eAngle += M_PI; - } - double cos_eangle = cos(eAngle); - double sin_eangle = sin(eAngle); - dc.SetPen(wxPen(pFrame->pGraphLog->GetRaOrDxColor(), 2, wxPENSTYLE_DOT)); - dc.DrawLine(ROUND(StarX * m_scaleFactor + r * cos_eangle), ROUND(StarY * m_scaleFactor + r * sin_eangle), - ROUND(StarX * m_scaleFactor - r * cos_eangle), ROUND(StarY * m_scaleFactor - r * sin_eangle)); - if (raParity != GUIDE_PARITY_UNKNOWN) - { - dc.SetTextForeground(pFrame->pGraphLog->GetRaOrDxColor()); - dc.DrawText(_("E"), - ROUND(StarX * m_scaleFactor + rlabel * cos_eangle) - 4, ROUND(StarY * m_scaleFactor + rlabel * sin_eangle) - 6); - } + double wAngle = mount->IsCalibrated() ? mount->xAngle() : 0.0; + double eAngle = wAngle + M_PI; + GuideParity raParity = mount->RAParity(); + if (raParity == GUIDE_PARITY_ODD) + { + // odd parity => West calibration pulses move scope East + // => star moves West + // => East vector is opposite direction from X calibration vector (West calibration direction) + eAngle += M_PI; + } + double cos_eangle = cos(eAngle); + double sin_eangle = sin(eAngle); + dc.SetPen(wxPen(pFrame->pGraphLog->GetRaOrDxColor(), 2, wxPENSTYLE_DOT)); + dc.DrawLine(ROUND(StarX * m_scaleFactor + r * cos_eangle), ROUND(StarY * m_scaleFactor + r * sin_eangle), + ROUND(StarX * m_scaleFactor - r * cos_eangle), ROUND(StarY * m_scaleFactor - r * sin_eangle)); + if (raParity != GUIDE_PARITY_UNKNOWN) + { + dc.SetTextForeground(pFrame->pGraphLog->GetRaOrDxColor()); + dc.DrawText(_("E"), ROUND(StarX * m_scaleFactor + rlabel * cos_eangle) - 4, + ROUND(StarY * m_scaleFactor + rlabel * sin_eangle) - 6); + } - double nAngle = mount->IsCalibrated() ? mount->yAngle() : M_PI / 2.0; - GuideParity decParity = mount->DecParity(); - if (decParity == GUIDE_PARITY_EVEN) - { - // even parity => North calibration pulses move scope North - // => star moves South - // => North vector is opposite direction from Y calibration vector (North calibration direction) - nAngle += M_PI; - } - double cos_nangle = cos(nAngle); - double sin_nangle = sin(nAngle); - dc.SetPen(wxPen(pFrame->pGraphLog->GetDecOrDyColor(), 2, wxPENSTYLE_DOT)); - dc.DrawLine(ROUND(StarX * m_scaleFactor + r * cos_nangle), ROUND(StarY * m_scaleFactor + r * sin_nangle), - ROUND(StarX * m_scaleFactor - r * cos_nangle), ROUND(StarY * m_scaleFactor - r * sin_nangle)); - if (decParity != GUIDE_PARITY_UNKNOWN) - { - dc.SetTextForeground(pFrame->pGraphLog->GetDecOrDyColor()); - dc.DrawText(_("N"), - ROUND(StarX * m_scaleFactor + rlabel * cos_nangle) - 4, ROUND(StarY * m_scaleFactor + rlabel * sin_nangle) - 6); - } + double nAngle = mount->IsCalibrated() ? mount->yAngle() : M_PI / 2.0; + GuideParity decParity = mount->DecParity(); + if (decParity == GUIDE_PARITY_EVEN) + { + // even parity => North calibration pulses move scope North + // => star moves South + // => North vector is opposite direction from Y calibration vector (North calibration direction) + nAngle += M_PI; + } + double cos_nangle = cos(nAngle); + double sin_nangle = sin(nAngle); + dc.SetPen(wxPen(pFrame->pGraphLog->GetDecOrDyColor(), 2, wxPENSTYLE_DOT)); + dc.DrawLine(ROUND(StarX * m_scaleFactor + r * cos_nangle), ROUND(StarY * m_scaleFactor + r * sin_nangle), + ROUND(StarX * m_scaleFactor - r * cos_nangle), ROUND(StarY * m_scaleFactor - r * sin_nangle)); + if (decParity != GUIDE_PARITY_UNKNOWN) + { + dc.SetTextForeground(pFrame->pGraphLog->GetDecOrDyColor()); + dc.DrawText(_("N"), ROUND(StarX * m_scaleFactor + rlabel * cos_nangle) - 4, + ROUND(StarY * m_scaleFactor + rlabel * sin_nangle) - 6); + } - wxGraphicsContext *gc = wxGraphicsContext::Create(dc); - gc->SetPen(wxPen(pFrame->pGraphLog->GetRaOrDxColor(), 1, wxPENSTYLE_DOT)); - double step = (double) YImgSize / 10.0; - - double MidX = (double) XImgSize / 2.0; - double MidY = (double) YImgSize / 2.0; - gc->Rotate(eAngle); - gc->GetTransform().TransformPoint(&MidX, &MidY); - gc->Rotate(-eAngle); - gc->Translate((double) XImgSize / 2.0 - MidX, (double) YImgSize / 2.0 - MidY); - gc->Rotate(eAngle); - for (int i = -2; i < 12; i++) { - gc->StrokeLine(0.0,step * (double) i, - (double) XImgSize, step * (double) i); - } + wxGraphicsContext *gc = wxGraphicsContext::Create(dc); + gc->SetPen(wxPen(pFrame->pGraphLog->GetRaOrDxColor(), 1, wxPENSTYLE_DOT)); + double step = (double) YImgSize / 10.0; + + double MidX = (double) XImgSize / 2.0; + double MidY = (double) YImgSize / 2.0; + gc->Rotate(eAngle); + gc->GetTransform().TransformPoint(&MidX, &MidY); + gc->Rotate(-eAngle); + gc->Translate((double) XImgSize / 2.0 - MidX, (double) YImgSize / 2.0 - MidY); + gc->Rotate(eAngle); + for (int i = -2; i < 12; i++) + { + gc->StrokeLine(0.0, step * (double) i, (double) XImgSize, step * (double) i); + } - MidX = (double) XImgSize / 2.0; - MidY = (double) YImgSize / 2.0; - gc->Rotate(-eAngle); - gc->Rotate(nAngle); - gc->GetTransform().TransformPoint(&MidX, &MidY); - gc->Rotate(-nAngle); - gc->Translate((double) XImgSize / 2.0 - MidX, (double) YImgSize / 2.0 - MidY); - gc->Rotate(nAngle); - gc->SetPen(wxPen(pFrame->pGraphLog->GetDecOrDyColor(),1,wxPENSTYLE_DOT)); - for (int i = -2; i < 12; i++) { - gc->StrokeLine(0.0,step * (double) i, - (double) XImgSize, step * (double) i); - } - delete gc; + MidX = (double) XImgSize / 2.0; + MidY = (double) YImgSize / 2.0; + gc->Rotate(-eAngle); + gc->Rotate(nAngle); + gc->GetTransform().TransformPoint(&MidX, &MidY); + gc->Rotate(-nAngle); + gc->Translate((double) XImgSize / 2.0 - MidX, (double) YImgSize / 2.0 - MidY); + gc->Rotate(nAngle); + gc->SetPen(wxPen(pFrame->pGraphLog->GetDecOrDyColor(), 1, wxPENSTYLE_DOT)); + for (int i = -2; i < 12; i++) + { + gc->StrokeLine(0.0, step * (double) i, (double) XImgSize, step * (double) i); } - break; + delete gc; } + break; + } - case OVERLAY_SLIT: - if (m_overlaySlitCoords.size.GetWidth() > 0 && m_overlaySlitCoords.size.GetHeight() > 0) + case OVERLAY_SLIT: + if (m_overlaySlitCoords.size.GetWidth() > 0 && m_overlaySlitCoords.size.GetHeight() > 0) + { + if (m_scaleFactor == 1.0) { - if (m_scaleFactor == 1.0) - { - dc.DrawLines(5, m_overlaySlitCoords.corners); - } - else + dc.DrawLines(5, m_overlaySlitCoords.corners); + } + else + { + wxPoint pt[5]; + for (int i = 0; i < 5; i++) { - wxPoint pt[5]; - for (int i = 0; i < 5; i++) - { - pt[i].x = (int) floor(m_overlaySlitCoords.corners[i].x * m_scaleFactor); - pt[i].y = (int) floor(m_overlaySlitCoords.corners[i].y * m_scaleFactor); - } - dc.DrawLines(5, pt); + pt[i].x = (int) floor(m_overlaySlitCoords.corners[i].x * m_scaleFactor); + pt[i].y = (int) floor(m_overlaySlitCoords.corners[i].y * m_scaleFactor); } + dc.DrawLines(5, pt); } - break; + } + break; - case OVERLAY_NONE: - break; + case OVERLAY_NONE: + break; } } @@ -659,7 +667,7 @@ bool Guider::PaintHelper(wxAutoBufferedPaintDCBase& dc, wxMemoryDC& memDC) for (DefectMap::const_iterator it = m_defectMapPreview->begin(); it != m_defectMapPreview->end(); ++it) { const wxPoint& pt = *it; - dc.DrawPoint((int)(pt.x * m_scaleFactor), (int)(pt.y * m_scaleFactor)); + dc.DrawPoint((int) (pt.x * m_scaleFactor), (int) (pt.y * m_scaleFactor)); } } @@ -671,19 +679,19 @@ bool Guider::PaintHelper(wxAutoBufferedPaintDCBase& dc, wxMemoryDC& memDC) switch (state) { - case STATE_UNINITIALIZED: - case STATE_SELECTING: - case STATE_SELECTED: - case STATE_STOP: - break; - case STATE_CALIBRATING_PRIMARY: - case STATE_CALIBRATING_SECONDARY: - dc.SetPen(wxPen(wxColor(255,255,0),1, wxPENSTYLE_DOT)); - break; - case STATE_CALIBRATED: - case STATE_GUIDING: - dc.SetPen(wxPen(wxColor(0,255,0))); - break; + case STATE_UNINITIALIZED: + case STATE_SELECTING: + case STATE_SELECTED: + case STATE_STOP: + break; + case STATE_CALIBRATING_PRIMARY: + case STATE_CALIBRATING_SECONDARY: + dc.SetPen(wxPen(wxColor(255, 255, 0), 1, wxPENSTYLE_DOT)); + break; + case STATE_CALIBRATED: + case STATE_GUIDING: + dc.SetPen(wxPen(wxColor(0, 255, 0))); + break; } dc.DrawLine(0, int(LockY * m_scaleFactor), XImgSize, int(LockY * m_scaleFactor)); @@ -695,10 +703,9 @@ bool Guider::PaintHelper(wxAutoBufferedPaintDCBase& dc, wxMemoryDC& memDC) { dc.SetBrush(*wxTRANSPARENT_BRUSH); wxPenStyle penStyle = m_polarAlignCircleCorrection == 1.0 ? wxPENSTYLE_DOT : wxPENSTYLE_SOLID; - dc.SetPen(wxPen(wxColor(255,0,255), 1, penStyle)); + dc.SetPen(wxPen(wxColor(255, 0, 255), 1, penStyle)); int radius = ROUND(m_polarAlignCircleRadius * m_polarAlignCircleCorrection * m_scaleFactor); - dc.DrawCircle(m_polarAlignCircleCenter.X * m_scaleFactor, - m_polarAlignCircleCenter.Y * m_scaleFactor, radius); + dc.DrawCircle(m_polarAlignCircleCenter.X * m_scaleFactor, m_polarAlignCircleCenter.Y * m_scaleFactor, radius); } // draw static polar align stuff @@ -732,9 +739,10 @@ void Guider::UpdateImageDisplay(usImage *pImage) pImage = m_pCurrentImage; } - Debug.Write(wxString::Format("UpdateImageDisplay: Size=(%d,%d) min=%u, max=%u, med=%u, FiltMin=%u, FiltMax=%u, Gamma=%.3f\n", - pImage->Size.x, pImage->Size.y, pImage->MinADU, pImage->MaxADU, pImage->MedianADU, - pImage->FiltMin, pImage->FiltMax, pFrame->Stretch_gamma)); + Debug.Write( + wxString::Format("UpdateImageDisplay: Size=(%d,%d) min=%u, max=%u, med=%u, FiltMin=%u, FiltMax=%u, Gamma=%.3f\n", + pImage->Size.x, pImage->Size.y, pImage->MinADU, pImage->MaxADU, pImage->MedianADU, pImage->FiltMin, pImage->FiltMax, + pFrame->Stretch_gamma)); Refresh(); Update(); @@ -935,23 +943,23 @@ void Guider::SetState(GUIDER_STATE newState) // ourselves into a good state to restart looping later switch (m_state) { - case STATE_UNINITIALIZED: - case STATE_SELECTING: - case STATE_SELECTED: - newState = m_state; - break; - case STATE_CALIBRATING_PRIMARY: - case STATE_CALIBRATING_SECONDARY: - // because we have done some moving here, we need to just - // start over... - newState = STATE_UNINITIALIZED; - break; - case STATE_CALIBRATED: - case STATE_GUIDING: - newState = STATE_SELECTED; - break; - case STATE_STOP: - break; + case STATE_UNINITIALIZED: + case STATE_SELECTING: + case STATE_SELECTED: + newState = m_state; + break; + case STATE_CALIBRATING_PRIMARY: + case STATE_CALIBRATING_SECONDARY: + // because we have done some moving here, we need to just + // start over... + newState = STATE_UNINITIALIZED; + break; + case STATE_CALIBRATED: + case STATE_GUIDING: + newState = STATE_SELECTED; + break; + case STATE_STOP: + break; } } @@ -967,77 +975,77 @@ void Guider::SetState(GUIDER_STATE newState) switch (requestedState) { - case STATE_UNINITIALIZED: - InvalidateLockPosition(); - InvalidateCurrentPosition(); - newState = STATE_SELECTING; - break; - case STATE_SELECTED: - break; - case STATE_CALIBRATING_PRIMARY: - if (!pMount->IsCalibrated()) - { - pMount->ResetErrorCount(); - if (pMount->BeginCalibration(CurrentPosition())) - { - newState = STATE_UNINITIALIZED; - Debug.Write(ERROR_INFO("pMount->BeginCalibration failed")); - } - else - { - GuideLog.StartCalibration(pMount); - EvtServer.NotifyStartCalibration(pMount); - } - break; - } - // fall through - case STATE_CALIBRATING_SECONDARY: - if (!pSecondaryMount || !pSecondaryMount->IsConnected()) + case STATE_UNINITIALIZED: + InvalidateLockPosition(); + InvalidateCurrentPosition(); + newState = STATE_SELECTING; + break; + case STATE_SELECTED: + break; + case STATE_CALIBRATING_PRIMARY: + if (!pMount->IsCalibrated()) + { + pMount->ResetErrorCount(); + if (pMount->BeginCalibration(CurrentPosition())) { - newState = STATE_CALIBRATED; + newState = STATE_UNINITIALIZED; + Debug.Write(ERROR_INFO("pMount->BeginCalibration failed")); } - else if (!pSecondaryMount->IsCalibrated()) + else { - pSecondaryMount->ResetErrorCount(); - if (pSecondaryMount->BeginCalibration(CurrentPosition())) - { - newState = STATE_UNINITIALIZED; - Debug.Write(ERROR_INFO("pSecondaryMount->BeginCalibration failed")); - } - else - { - GuideLog.StartCalibration(pSecondaryMount); - EvtServer.NotifyStartCalibration(pSecondaryMount); - } + GuideLog.StartCalibration(pMount); + EvtServer.NotifyStartCalibration(pMount); } break; - case STATE_GUIDING: - assert(pMount); - - m_ditherRecenterRemaining.Invalidate(); // reset dither fast recenter state - - pMount->AdjustCalibrationForScopePointing(); - if (pSecondaryMount) - { - pSecondaryMount->AdjustCalibrationForScopePointing(); - } - - pFrame->UpdateStatusBarCalibrationStatus(); - - if (m_lockPosition.IsValid() && m_lockPosIsSticky) + } + // fall through + case STATE_CALIBRATING_SECONDARY: + if (!pSecondaryMount || !pSecondaryMount->IsConnected()) + { + newState = STATE_CALIBRATED; + } + else if (!pSecondaryMount->IsCalibrated()) + { + pSecondaryMount->ResetErrorCount(); + if (pSecondaryMount->BeginCalibration(CurrentPosition())) { - Debug.Write("keeping sticky lock position\n"); + newState = STATE_UNINITIALIZED; + Debug.Write(ERROR_INFO("pSecondaryMount->BeginCalibration failed")); } else { - SetLockPosition(CurrentPosition()); + GuideLog.StartCalibration(pSecondaryMount); + EvtServer.NotifyStartCalibration(pSecondaryMount); } - break; + } + break; + case STATE_GUIDING: + assert(pMount); - case STATE_SELECTING: - case STATE_CALIBRATED: - case STATE_STOP: - break; + m_ditherRecenterRemaining.Invalidate(); // reset dither fast recenter state + + pMount->AdjustCalibrationForScopePointing(); + if (pSecondaryMount) + { + pSecondaryMount->AdjustCalibrationForScopePointing(); + } + + pFrame->UpdateStatusBarCalibrationStatus(); + + if (m_lockPosition.IsValid() && m_lockPosIsSticky) + { + Debug.Write("keeping sticky lock position\n"); + } + else + { + SetLockPosition(CurrentPosition()); + } + break; + + case STATE_SELECTING: + case STATE_CALIBRATED: + case STATE_STOP: + break; } if (newState >= requestedState) @@ -1078,7 +1086,8 @@ void Guider::UpdateCurrentDistance(double distance, double distanceRA) } else { - static double const alpha_long = .045; // heavy smoothing, low weighting for latest sample .045 => 15 frame half-life + static double const alpha_long = + .045; // heavy smoothing, low weighting for latest sample .045 => 15 frame half-life m_avgDistanceLong += alpha_long * (distance - m_avgDistanceLong); m_avgDistanceLongRA += alpha_long * (distanceRA - m_avgDistanceLongRA); } @@ -1103,7 +1112,10 @@ void Guider::UpdateCurrentDistance(double distance, double distanceRA) inline static double CurrentError(time_t starFoundTimestamp, double avgDist) { - enum { THRESHOLD_SECONDS = 20 }; + enum + { + THRESHOLD_SECONDS = 20 + }; static double const LARGE_DISTANCE = 100.0; if (!starFoundTimestamp) @@ -1142,29 +1154,29 @@ void Guider::StopGuiding() // first, send a notification that we stopped switch (m_state) { - case STATE_UNINITIALIZED: - case STATE_SELECTING: - case STATE_SELECTED: - break; - case STATE_CALIBRATING_PRIMARY: - case STATE_CALIBRATING_SECONDARY: - case STATE_CALIBRATED: - EvtServer.NotifyCalibrationFailed(m_state == STATE_CALIBRATING_SECONDARY ? pSecondaryMount : pMount, - _("Calibration manually stopped")); - // fall through to notify guiding stopped - case STATE_GUIDING: - if ((!pMount || !pMount->IsBusy()) && (!pSecondaryMount || !pSecondaryMount->IsBusy())) - { - // Notify guiding stopped if there are no outstanding guide steps. The Guiding - // Stopped notification must come after the final GuideStep notification otherwise - // event server clients and the guide log will show the guide step happening after - // guiding stopped. + case STATE_UNINITIALIZED: + case STATE_SELECTING: + case STATE_SELECTED: + break; + case STATE_CALIBRATING_PRIMARY: + case STATE_CALIBRATING_SECONDARY: + case STATE_CALIBRATED: + EvtServer.NotifyCalibrationFailed( + m_state == STATE_CALIBRATING_SECONDARY ? pSecondaryMount : pMount, _("Calibration manually stopped")); + // fall through to notify guiding stopped + case STATE_GUIDING: + if ((!pMount || !pMount->IsBusy()) && (!pSecondaryMount || !pSecondaryMount->IsBusy())) + { + // Notify guiding stopped if there are no outstanding guide steps. The Guiding + // Stopped notification must come after the final GuideStep notification otherwise + // event server clients and the guide log will show the guide step happening after + // guiding stopped. - pFrame->NotifyGuidingStopped(); - } - break; - case STATE_STOP: - break; + pFrame->NotifyGuidingStopped(); + } + break; + case STATE_STOP: + break; } SetState(STATE_STOP); @@ -1204,7 +1216,8 @@ static void CheckCalibrationAutoLoad() if (!alreadyAsked) { - wxString msg = wxString::Format(_("Do you want to automatically restore this calibration whenever the profile is used?")); + wxString msg = + wxString::Format(_("Do you want to automatically restore this calibration whenever the profile is used?")); pFrame->Alert(msg, 0, "Auto-restore", &SetAutoLoad, 0, false, 0); pConfig->Profile.SetBoolean("/AlreadyAskedCalibAutoload", true); } @@ -1225,8 +1238,7 @@ void Guider::DisplayImage(usImage *img) UpdateImageDisplay(); } -inline static bool -IsLoopingState(GUIDER_STATE state) +inline static bool IsLoopingState(GUIDER_STATE state) { // returns true for looping, but non-guiding states switch (state) @@ -1299,7 +1311,7 @@ void Guider::UpdateGuideState(usImage *pImage, bool bStopping) GuiderOffset ofs; FrameDroppedInfo info; - if (UpdateCurrentPosition(pImage, &ofs, &info)) // true means error + if (UpdateCurrentPosition(pImage, &ofs, &info)) // true means error { info.frameNumber = pImage->FrameNum; info.time = pFrame->TimeSinceGuidingStarted(); @@ -1307,51 +1319,51 @@ void Guider::UpdateGuideState(usImage *pImage, bool bStopping) switch (m_state) { - case STATE_UNINITIALIZED: - case STATE_SELECTING: - EvtServer.NotifyLooping(pImage->FrameNum, nullptr, &info); - break; - case STATE_SELECTED: - // we had a current position and lost it - EvtServer.NotifyLooping(pImage->FrameNum, nullptr, &info); - if (!m_ignoreLostStarLooping) - { - SetState(STATE_UNINITIALIZED); - EvtServer.NotifyStarLost(info); - } - StaticPaTool::NotifyStarLost(); - break; - case STATE_CALIBRATING_PRIMARY: - case STATE_CALIBRATING_SECONDARY: - GuideLog.CalibrationFrameDropped(info); - Debug.Write("Star lost during calibration... blundering on\n"); - EvtServer.NotifyStarLost(info); - pFrame->StatusMsg(_("star lost")); - break; - case STATE_GUIDING: + case STATE_UNINITIALIZED: + case STATE_SELECTING: + EvtServer.NotifyLooping(pImage->FrameNum, nullptr, &info); + break; + case STATE_SELECTED: + // we had a current position and lost it + EvtServer.NotifyLooping(pImage->FrameNum, nullptr, &info); + if (!m_ignoreLostStarLooping) { - GuideLog.FrameDropped(info); + SetState(STATE_UNINITIALIZED); EvtServer.NotifyStarLost(info); - GuidingAssistant::NotifyFrameDropped(info); - pFrame->pGraphLog->AppendData(info); - - // allow guide algorithms to attempt dead reckoning - static GuiderOffset ZERO_OFS; - pFrame->SchedulePrimaryMove(pMount, ZERO_OFS, MOVEOPTS_DEDUCED_MOVE); - - wxColor prevColor = GetBackgroundColour(); - SetBackgroundColour(wxColour(64,0,0)); - ClearBackground(); - if (pFrame->GetBeepForLostStar()) - wxBell(); - wxMilliSleep(100); - SetBackgroundColour(prevColor); - break; } + StaticPaTool::NotifyStarLost(); + break; + case STATE_CALIBRATING_PRIMARY: + case STATE_CALIBRATING_SECONDARY: + GuideLog.CalibrationFrameDropped(info); + Debug.Write("Star lost during calibration... blundering on\n"); + EvtServer.NotifyStarLost(info); + pFrame->StatusMsg(_("star lost")); + break; + case STATE_GUIDING: + { + GuideLog.FrameDropped(info); + EvtServer.NotifyStarLost(info); + GuidingAssistant::NotifyFrameDropped(info); + pFrame->pGraphLog->AppendData(info); - case STATE_CALIBRATED: - case STATE_STOP: - break; + // allow guide algorithms to attempt dead reckoning + static GuiderOffset ZERO_OFS; + pFrame->SchedulePrimaryMove(pMount, ZERO_OFS, MOVEOPTS_DEDUCED_MOVE); + + wxColor prevColor = GetBackgroundColour(); + SetBackgroundColour(wxColour(64, 0, 0)); + ClearBackground(); + if (pFrame->GetBeepForLostStar()) + wxBell(); + wxMilliSleep(100); + SetBackgroundColour(prevColor); + break; + } + + case STATE_CALIBRATED: + case STATE_STOP: + break; } statusMessage = info.status; @@ -1385,137 +1397,136 @@ void Guider::UpdateGuideState(usImage *pImage, bool bStopping) switch (m_state) { - case STATE_SELECTING: - assert(CurrentPosition().IsValid()); - SetLockPosition(CurrentPosition()); - Debug.Write("CurrentPosition() valid, moving to STATE_SELECTED\n"); - EvtServer.NotifyStarSelected(CurrentPosition()); - SetState(STATE_SELECTED); - break; - case STATE_SELECTED: - if (!StaticPaTool::UpdateState()) + case STATE_SELECTING: + assert(CurrentPosition().IsValid()); + SetLockPosition(CurrentPosition()); + Debug.Write("CurrentPosition() valid, moving to STATE_SELECTED\n"); + EvtServer.NotifyStarSelected(CurrentPosition()); + SetState(STATE_SELECTED); + break; + case STATE_SELECTED: + if (!StaticPaTool::UpdateState()) + { + SetState(STATE_UNINITIALIZED); + statusMessage = _("Static PA rotation failed"); + throw ERROR_INFO("Static PA rotation failed"); + } + if (!PolarDriftTool::UpdateState()) + { + SetState(STATE_UNINITIALIZED); + statusMessage = _("Polar Drift PA drift failed"); + throw ERROR_INFO("Polar Drift PA drift failed"); + } + break; + case STATE_CALIBRATING_PRIMARY: + if (!pMount->IsCalibrated()) + { + if (pMount->UpdateCalibrationState(CurrentPosition())) { SetState(STATE_UNINITIALIZED); - statusMessage = _("Static PA rotation failed"); - throw ERROR_INFO("Static PA rotation failed"); + statusMessage = pMount->IsStepGuider() ? _("AO calibration failed") : _("calibration failed"); + throw ERROR_INFO("Calibration failed"); } - if (!PolarDriftTool::UpdateState()) + + if (!pMount->IsCalibrated()) { - SetState(STATE_UNINITIALIZED); - statusMessage = _("Polar Drift PA drift failed"); - throw ERROR_INFO("Polar Drift PA drift failed"); + break; } + } + + SetState(STATE_CALIBRATING_SECONDARY); + + if (m_state == STATE_CALIBRATING_SECONDARY) + { + // if we really have a secondary mount, and it isn't calibrated, + // we need to take another exposure before falling into the code + // below. If we don't have one, or it is calibrated, we can fall + // through. If we don't fall through, we end up displaying a frame + // which has the lockpoint in the wrong place, and while I thought I + // could live with it when I originally wrote the code, it bothered + // me so I did this. Ick. break; - case STATE_CALIBRATING_PRIMARY: - if (!pMount->IsCalibrated()) + } + + // Fall through + case STATE_CALIBRATING_SECONDARY: + if (pSecondaryMount && pSecondaryMount->IsConnected()) + { + if (!pSecondaryMount->IsCalibrated()) { - if (pMount->UpdateCalibrationState(CurrentPosition())) + if (pSecondaryMount->UpdateCalibrationState(CurrentPosition())) { SetState(STATE_UNINITIALIZED); - statusMessage = pMount->IsStepGuider() ? _("AO calibration failed") : _("calibration failed"); + statusMessage = _("calibration failed"); throw ERROR_INFO("Calibration failed"); } - - if (!pMount->IsCalibrated()) - { - break; - } } - SetState(STATE_CALIBRATING_SECONDARY); - - if (m_state == STATE_CALIBRATING_SECONDARY) + if (!pSecondaryMount->IsCalibrated()) { - // if we really have a secondary mount, and it isn't calibrated, - // we need to take another exposure before falling into the code - // below. If we don't have one, or it is calibrated, we can fall - // through. If we don't fall through, we end up displaying a frame - // which has the lockpoint in the wrong place, and while I thought I - // could live with it when I originally wrote the code, it bothered - // me so I did this. Ick. break; } + } + assert(!pSecondaryMount || !pSecondaryMount->IsConnected() || pSecondaryMount->IsCalibrated()); - // Fall through - case STATE_CALIBRATING_SECONDARY: - if (pSecondaryMount && pSecondaryMount->IsConnected()) - { - if (!pSecondaryMount->IsCalibrated()) - { - if (pSecondaryMount->UpdateCalibrationState(CurrentPosition())) - { - SetState(STATE_UNINITIALIZED); - statusMessage = _("calibration failed"); - throw ERROR_INFO("Calibration failed"); - } - } - - if (!pSecondaryMount->IsCalibrated()) - { - break; - } - } - assert(!pSecondaryMount || !pSecondaryMount->IsConnected() || pSecondaryMount->IsCalibrated()); - - SetState(STATE_CALIBRATED); - // fall through - case STATE_CALIBRATED: - assert(m_state == STATE_CALIBRATED); - SetState(STATE_GUIDING); - - pFrame->NotifyGuidingStarted(); + SetState(STATE_CALIBRATED); + // fall through + case STATE_CALIBRATED: + assert(m_state == STATE_CALIBRATED); + SetState(STATE_GUIDING); - // camera angle is known, so ok to calculate shift rate camera coords - UpdateLockPosShiftCameraCoords(); - if (LockPosShiftEnabled()) - GuideLog.NotifyLockShiftParams(m_lockPosShift, m_lockPosition.ShiftRate()); + pFrame->NotifyGuidingStarted(); - CheckCalibrationAutoLoad(); - break; - case STATE_GUIDING: - if (m_ditherRecenterRemaining.IsValid()) - { - // fast recenter after dither taking large steps and bypassing - // guide algorithms + // camera angle is known, so ok to calculate shift rate camera coords + UpdateLockPosShiftCameraCoords(); + if (LockPosShiftEnabled()) + GuideLog.NotifyLockShiftParams(m_lockPosShift, m_lockPosition.ShiftRate()); - PHD_Point step(wxMin(m_ditherRecenterRemaining.X, m_ditherRecenterStep.X), - wxMin(m_ditherRecenterRemaining.Y, m_ditherRecenterStep.Y)); + CheckCalibrationAutoLoad(); + break; + case STATE_GUIDING: + if (m_ditherRecenterRemaining.IsValid()) + { + // fast recenter after dither taking large steps and bypassing + // guide algorithms - Debug.Write(wxString::Format("dither recenter: remaining=(%.1f,%.1f) step=(%.1f,%.1f)\n", - m_ditherRecenterRemaining.X * m_ditherRecenterDir.x, - m_ditherRecenterRemaining.Y * m_ditherRecenterDir.y, - step.X * m_ditherRecenterDir.x, step.Y * m_ditherRecenterDir.y)); + PHD_Point step(wxMin(m_ditherRecenterRemaining.X, m_ditherRecenterStep.X), + wxMin(m_ditherRecenterRemaining.Y, m_ditherRecenterStep.Y)); - m_ditherRecenterRemaining -= step; - if (m_ditherRecenterRemaining.X < 0.5 && m_ditherRecenterRemaining.Y < 0.5) - { - // fast recenter is done - m_ditherRecenterRemaining.Invalidate(); - // reset distance tracker - m_avgDistanceNeedReset = true; - } + Debug.Write(wxString::Format("dither recenter: remaining=(%.1f,%.1f) step=(%.1f,%.1f)\n", + m_ditherRecenterRemaining.X * m_ditherRecenterDir.x, m_ditherRecenterRemaining.Y * m_ditherRecenterDir.y, + step.X * m_ditherRecenterDir.x, step.Y * m_ditherRecenterDir.y)); - ofs.mountOfs.SetXY(step.X * m_ditherRecenterDir.x, step.Y * m_ditherRecenterDir.y); - pMount->TransformMountCoordinatesToCameraCoordinates(ofs.mountOfs, ofs.cameraOfs); - pFrame->SchedulePrimaryMove(pMount, ofs, MOVEOPTS_RECOVERY_MOVE); - // let guide algorithms know about the direct move - pMount->NotifyDirectMove(ofs.mountOfs); - } - else if (m_measurementMode) - { - GuidingAssistant::NotifyBacklashStep(CurrentPosition()); - } - else + m_ditherRecenterRemaining -= step; + if (m_ditherRecenterRemaining.X < 0.5 && m_ditherRecenterRemaining.Y < 0.5) { - // ordinary guide step - s_deflectionLogger.Log(CurrentPosition()); - pFrame->SchedulePrimaryMove(pMount, ofs, MOVEOPTS_GUIDE_STEP); + // fast recenter is done + m_ditherRecenterRemaining.Invalidate(); + // reset distance tracker + m_avgDistanceNeedReset = true; } - break; - case STATE_UNINITIALIZED: - case STATE_STOP: - break; + ofs.mountOfs.SetXY(step.X * m_ditherRecenterDir.x, step.Y * m_ditherRecenterDir.y); + pMount->TransformMountCoordinatesToCameraCoordinates(ofs.mountOfs, ofs.cameraOfs); + pFrame->SchedulePrimaryMove(pMount, ofs, MOVEOPTS_RECOVERY_MOVE); + // let guide algorithms know about the direct move + pMount->NotifyDirectMove(ofs.mountOfs); + } + else if (m_measurementMode) + { + GuidingAssistant::NotifyBacklashStep(CurrentPosition()); + } + else + { + // ordinary guide step + s_deflectionLogger.Log(CurrentPosition()); + pFrame->SchedulePrimaryMove(pMount, ofs, MOVEOPTS_GUIDE_STEP); + } + break; + + case STATE_UNINITIALIZED: + case STATE_STOP: + break; } } catch (const wxString& Msg) @@ -1547,15 +1558,14 @@ bool Guider::ShiftLockPosition() { m_lockPosition.UpdateShift(); bool isValid = IsValidLockPosition(m_lockPosition); - Debug.Write(wxString::Format("ShiftLockPos: new pos = %.2f, %.2f valid=%d\n", - m_lockPosition.X, m_lockPosition.Y, isValid)); + Debug.Write(wxString::Format("ShiftLockPos: new pos = %.2f, %.2f valid=%d\n", m_lockPosition.X, m_lockPosition.Y, isValid)); return !isValid; } void Guider::SetLockPosShiftRate(const PHD_Point& rate, GRAPH_UNITS units, bool isMountCoords, bool updateToolWin) { - Debug.Write(wxString::Format("SetLockPosShiftRate: rate = %.2f,%.2f units = %d isMountCoords = %d\n", - rate.X, rate.Y, units, isMountCoords)); + Debug.Write(wxString::Format( + "SetLockPosShiftRate: rate = %.2f,%.2f units = %d isMountCoords = %d\n", rate.X, rate.Y, units, isMountCoords)); m_lockPosShift.shiftRate = rate; m_lockPosShift.shiftUnits = units; @@ -1608,8 +1618,8 @@ void Guider::UpdateLockPosShiftCameraCoords() { PHD_Point radec_rates = m_lockPosShift.shiftRate; - Debug.Write(wxString::Format("UpdateLockPosShiftCameraCoords: shift rate mount coords = %.2f,%.2f\n", - radec_rates.X, radec_rates.Y)); + Debug.Write(wxString::Format( + "UpdateLockPosShiftCameraCoords: shift rate mount coords = %.2f,%.2f\n", radec_rates.X, radec_rates.Y)); Mount *scope = TheScope(); if (scope) @@ -1628,7 +1638,8 @@ void Guider::UpdateLockPosShiftCameraCoords() if (decParity == GUIDE_PARITY_ODD) radec_rates.Y = -radec_rates.Y; - Debug.Write(wxString::Format("UpdateLockPosShiftCameraCoords: after parity adjustment: %.2f,%.2f\n", radec_rates.X, radec_rates.Y)); + Debug.Write(wxString::Format( + "UpdateLockPosShiftCameraCoords: after parity adjustment: %.2f,%.2f\n", radec_rates.X, radec_rates.Y)); } // account for scope declination @@ -1638,7 +1649,8 @@ void Guider::UpdateLockPosShiftCameraCoords() if (dec != UNKNOWN_DECLINATION) { radec_rates.X *= cos(dec); - Debug.Write(wxString::Format("UpdateLockPosShiftCameraCoords: RA shift rate adjusted for declination %.1f\n", degrees(dec))); + Debug.Write(wxString::Format( + "UpdateLockPosShiftCameraCoords: RA shift rate adjusted for declination %.1f\n", degrees(dec))); } } } @@ -1651,18 +1663,17 @@ void Guider::UpdateLockPosShiftCameraCoords() rate = m_lockPosShift.shiftRate; } - Debug.Write(wxString::Format("UpdateLockPosShiftCameraCoords: shift rate camera coords = %.2f,%.2f %s/hr\n", - rate.X, rate.Y, m_lockPosShift.shiftUnits == UNIT_ARCSEC ? "arcsec" : "pixels")); + Debug.Write(wxString::Format("UpdateLockPosShiftCameraCoords: shift rate camera coords = %.2f,%.2f %s/hr\n", rate.X, rate.Y, + m_lockPosShift.shiftUnits == UNIT_ARCSEC ? "arcsec" : "pixels")); // convert arc-seconds to pixels if (m_lockPosShift.shiftUnits == UNIT_ARCSEC) { rate /= pFrame->GetCameraPixelScale(); } - rate /= 3600.0; // per hour => per second + rate /= 3600.0; // per hour => per second - Debug.Write(wxString::Format("UpdateLockPosShiftCameraCoords: shift rate %.2g,%.2g px/sec\n", - rate.X, rate.Y)); + Debug.Write(wxString::Format("UpdateLockPosShiftCameraCoords: shift rate %.2g,%.2g px/sec\n", rate.X, rate.Y)); m_lockPosition.SetShiftRate(rate.X, rate.Y); } @@ -1679,7 +1690,7 @@ Guider::GuiderConfigDialogPane *Guider::GetConfigDialogPane(wxWindow *pParent) } Guider::GuiderConfigDialogPane::GuiderConfigDialogPane(wxWindow *pParent, Guider *pGuider) -: ConfigDialogPane(_("Guider Settings"), pParent) + : ConfigDialogPane(_("Guider Settings"), pParent) { m_pGuider = pGuider; } @@ -1719,16 +1730,17 @@ void Guider::GuiderConfigDialogPane::LayoutControls(Guider *pGuider, BrainCtrlId this->Add(pCalib, def_flags); this->Add(pShared, def_flags); Fit(m_pParent); - } -GuiderConfigDialogCtrlSet *Guider::GetConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +GuiderConfigDialogCtrlSet *Guider::GetConfigDialogCtrlSet( + wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) { return new GuiderConfigDialogCtrlSet(pParent, pGuider, pAdvancedDialog, CtrlMap); } -GuiderConfigDialogCtrlSet::GuiderConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog* pAdvancedDialog, BrainCtrlIdMap& CtrlMap) : -ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) +GuiderConfigDialogCtrlSet::GuiderConfigDialogCtrlSet( + wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) + : ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) { assert(pGuider); @@ -1737,8 +1749,11 @@ ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) m_pScaleImage = new wxCheckBox(GetParentWindow(AD_cbScaleImages), wxID_ANY, _("Always scale images")); AddCtrl(CtrlMap, AD_cbScaleImages, m_pScaleImage, _("Always scale images to fill window")); - m_pEnableFastRecenter = new wxCheckBox(GetParentWindow(AD_cbFastRecenter), wxID_ANY, _("Fast recenter after calibration or dither")); - AddCtrl(CtrlMap, AD_cbFastRecenter, m_pEnableFastRecenter, _("Speed up calibration and dithering by using larger guide pulses to return the star to the center position. Un-check to use the old, slower method of recentering after calibration or dither.")); + m_pEnableFastRecenter = + new wxCheckBox(GetParentWindow(AD_cbFastRecenter), wxID_ANY, _("Fast recenter after calibration or dither")); + AddCtrl(CtrlMap, AD_cbFastRecenter, m_pEnableFastRecenter, + _("Speed up calibration and dithering by using larger guide pulses to return the star to the center position. Un-check " + "to use the old, slower method of recentering after calibration or dither.")); } void GuiderConfigDialogCtrlSet::LoadValues() @@ -1773,35 +1788,35 @@ EXPOSED_STATE Guider::GetExposedState() switch (guider->GetState()) { - case STATE_UNINITIALIZED: - case STATE_STOP: - default: - rval = EXPOSED_STATE_NONE; - break; - - case STATE_SELECTING: - // only report "looping" if no star is selected - if (guider->CurrentPosition().IsValid()) - rval = EXPOSED_STATE_SELECTED; - else - rval = EXPOSED_STATE_LOOPING; - break; + case STATE_UNINITIALIZED: + case STATE_STOP: + default: + rval = EXPOSED_STATE_NONE; + break; - case STATE_SELECTED: - case STATE_CALIBRATED: + case STATE_SELECTING: + // only report "looping" if no star is selected + if (guider->CurrentPosition().IsValid()) rval = EXPOSED_STATE_SELECTED; - break; + else + rval = EXPOSED_STATE_LOOPING; + break; - case STATE_CALIBRATING_PRIMARY: - case STATE_CALIBRATING_SECONDARY: - rval = EXPOSED_STATE_CALIBRATING; - break; + case STATE_SELECTED: + case STATE_CALIBRATED: + rval = EXPOSED_STATE_SELECTED; + break; - case STATE_GUIDING: - if (guider->IsLocked()) - rval = EXPOSED_STATE_GUIDING_LOCKED; - else - rval = EXPOSED_STATE_GUIDING_LOST; + case STATE_CALIBRATING_PRIMARY: + case STATE_CALIBRATING_SECONDARY: + rval = EXPOSED_STATE_CALIBRATING; + break; + + case STATE_GUIDING: + if (guider->IsLocked()) + rval = EXPOSED_STATE_GUIDING_LOCKED; + else + rval = EXPOSED_STATE_GUIDING_LOST; } Debug.Write(wxString::Format("case statement mapped state %d to %d\n", guider->GetState(), rval)); @@ -1860,8 +1875,8 @@ void Guider::DeleteAllBookmarks() { if (m_bookmarks.size()) { - bool confirmed = ConfirmDialog::Confirm(_("Are you sure you want to delete all Bookmarks?"), - "/delete_all_bookmarks_ok"); + bool confirmed = + ConfirmDialog::Confirm(_("Are you sure you want to delete all Bookmarks?"), "/delete_all_bookmarks_ok"); if (confirmed) { m_bookmarks.clear(); @@ -1877,8 +1892,7 @@ void Guider::DeleteAllBookmarks() static bool IsClose(const wxRealPoint& p1, const wxRealPoint& p2, double tolerance) { - return fabs(p1.x - p2.x) <= tolerance && - fabs(p1.y - p2.y) <= tolerance; + return fabs(p1.x - p2.x) <= tolerance && fabs(p1.y - p2.y) <= tolerance; } static std::vector::iterator FindBookmark(const wxRealPoint& pos, std::vector& vec) diff --git a/src/guider.h b/src/guider.h index d234ab7bb..ae6bd5951 100644 --- a/src/guider.h +++ b/src/guider.h @@ -91,9 +91,9 @@ struct OverlaySlitCoords enum PauseType { - PAUSE_NONE, // not paused - PAUSE_GUIDING, // pause guide corrections but continue looping exposures - PAUSE_FULL, // pause guide corrections and pause looping exposures + PAUSE_NONE, // not paused + PAUSE_GUIDING, // pause guide corrections but continue looping exposures + PAUSE_FULL, // pause guide corrections and pause looping exposures }; struct LockPosShiftParams @@ -122,11 +122,10 @@ class GuiderConfigDialogCtrlSet : public ConfigDialogCtrlSet wxCheckBox *m_pScaleImage; public: - GuiderConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog* pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + GuiderConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); virtual ~GuiderConfigDialogCtrlSet() {}; virtual void LoadValues(); virtual void UnloadValues(); - }; struct GuiderOffset @@ -149,11 +148,11 @@ class Guider : public wxWindow PHD_Point m_ditherRecenterStep; wxPoint m_ditherRecenterDir; PHD_Point m_ditherRecenterRemaining; - time_t m_starFoundTimestamp; // timestamp when star was last found - double m_avgDistance; // averaged distance for distance reporting - double m_avgDistanceRA; // averaged distance, RA only - double m_avgDistanceLong; // averaged distance, more smoothed - double m_avgDistanceLongRA; // averaged distance, more smoothed, RA only + time_t m_starFoundTimestamp; // timestamp when star was last found + double m_avgDistance; // averaged distance for distance reporting + double m_avgDistanceRA; // averaged distance, RA only + double m_avgDistanceLong; // averaged distance, more smoothed + double m_avgDistanceLongRA; // averaged distance, more smoothed, RA only unsigned int m_avgDistanceCnt; bool m_avgDistanceNeedReset; GUIDER_STATE m_state; @@ -167,7 +166,7 @@ class Guider : public wxWindow double m_minStarHFD; double m_minAFStarSNR; double m_maxStarHFD; - unsigned int m_autoSelDownsample; // downsample factor for star auto-selection, 0=Auto + unsigned int m_autoSelDownsample; // downsample factor for star auto-selection, 0=Auto protected: int m_searchRegion; // how far u/d/l/r do we do the initial search for a star @@ -194,8 +193,9 @@ class Guider : public wxWindow OVERLAY_MODE GetOverlayMode() const; public: - virtual GuiderConfigDialogPane *GetConfigDialogPane(wxWindow *pParent)= 0; - virtual GuiderConfigDialogCtrlSet *GetConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + virtual GuiderConfigDialogPane *GetConfigDialogPane(wxWindow *pParent) = 0; + virtual GuiderConfigDialogCtrlSet *GetConfigDialogCtrlSet( + wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); protected: Guider(wxWindow *parent, int xSize, int ySize); @@ -246,7 +246,7 @@ class Guider : public wxWindow void StartGuiding(); void StopGuiding(); - void UpdateGuideState(usImage *pImage, bool bStopping=false); + void UpdateGuideState(usImage *pImage, bool bStopping = false); void DisplayImage(usImage *img); bool SetScaleImage(bool newScaleValue); @@ -272,7 +272,8 @@ class Guider : public wxWindow void SetMinStarHFD(double val); double GetMaxStarHFD() const; void SetMaxStarHFD(double val); - // 'AF' methods deal with SNR threshold used only during Auto-Find - lets user specify a higher than default SNR floor for populating a multi-star list. Normal 'find' methods do not use this property + // 'AF' methods deal with SNR threshold used only during Auto-Find - lets user specify a higher than default SNR floor for + // populating a multi-star list. Normal 'find' methods do not use this property void SetAFMinStarSNR(double val); double GetAFMinStarSNR() const; @@ -284,6 +285,7 @@ class Guider : public wxWindow // their operation private: virtual void InvalidateLockPosition(); + public: virtual void LoadProfileSettings(); @@ -292,6 +294,7 @@ class Guider : public wxWindow virtual bool IsValidLockPosition(const PHD_Point& pt) = 0; virtual bool IsValidSecondaryStarPosition(const PHD_Point& pt) = 0; virtual void InvalidateCurrentPosition(bool fullReset = false) = 0; + private: virtual bool UpdateCurrentPosition(const usImage *pImage, GuiderOffset *ofs, FrameDroppedInfo *errorInfo) = 0; virtual bool SetCurrentPosition(const usImage *pImage, const PHD_Point& position) = 0; diff --git a/src/guider_multistar.cpp b/src/guider_multistar.cpp index 40a1732de..1359a12d3 100644 --- a/src/guider_multistar.cpp +++ b/src/guider_multistar.cpp @@ -46,12 +46,15 @@ #include #if ((wxMAJOR_VERSION < 3) && (wxMINOR_VERSION < 9)) -#define wxPENSTYLE_DOT wxDOT +# define wxPENSTYLE_DOT wxDOT #endif class MassChecker { - enum { DefaultTimeWindowMs = 22500 }; + enum + { + DefaultTimeWindowMs = 22500 + }; struct Entry { @@ -60,8 +63,8 @@ class MassChecker }; std::deque m_data; - double m_highMass; // high-water mark - double m_lowMass; // low-water mark + double m_highMass; // high-water mark + double m_lowMass; // low-water mark unsigned long m_timeWindow; double *m_tmp; size_t m_tmpSize; @@ -69,22 +72,18 @@ class MassChecker bool m_isAutoExposure; public: - MassChecker() - : m_highMass(0.), - m_lowMass(9e99), - m_tmp(0), - m_tmpSize(0), - m_exposure(0), - m_isAutoExposure(false) + : m_highMass(0.) + , m_lowMass(9e99) + , m_tmp(0) + , m_tmpSize(0) + , m_exposure(0) + , m_isAutoExposure(false) { SetTimeWindow(DefaultTimeWindowMs); } - ~MassChecker() - { - delete[] m_tmp; - } + ~MassChecker() { delete[] m_tmp; } void SetTimeWindow(unsigned int milliseconds) { @@ -110,10 +109,7 @@ class MassChecker } } - double AdjustedMass(double mass) const - { - return m_isAutoExposure ? mass / (double) m_exposure : mass; - } + double AdjustedMass(double mass) const { return m_isAutoExposure ? mass / (double) m_exposure : mass; } void AppendData(double mass) { @@ -191,7 +187,8 @@ class MassChecker static const double DefaultMassChangeThreshold = 0.5; -enum { +enum +{ MIN_SEARCH_REGION = 7, DEFAULT_SEARCH_REGION = 15, MAX_SEARCH_REGION = 50, @@ -209,13 +206,15 @@ wxEND_EVENT_TABLE(); // Define a constructor for the guide canvas GuiderMultiStar::GuiderMultiStar(wxWindow *parent) - : Guider(parent, XWinSize, YWinSize), - m_massChecker(new MassChecker()), - m_stabilizing(false), m_multiStarMode(true), m_lastPrimaryDistance(0), - m_lockPositionMoved(false), - m_maxStars(DEFAULT_MAX_STAR_COUNT), - m_stabilitySigmaX(DEFAULT_STABILITY_SIGMAX), - m_lastStarsUsed(0) + : Guider(parent, XWinSize, YWinSize) + , m_massChecker(new MassChecker()) + , m_stabilizing(false) + , m_multiStarMode(true) + , m_lastPrimaryDistance(0) + , m_lockPositionMoved(false) + , m_maxStars(DEFAULT_MAX_STAR_COUNT) + , m_stabilitySigmaX(DEFAULT_STABILITY_SIGMAX) + , m_lastStarsUsed(0) { SetState(STATE_UNINITIALIZED); m_primaryDistStats = new DescriptiveStats(); @@ -235,7 +234,8 @@ void GuiderMultiStar::SetMultiStarMode(bool val) if (val && !oldVal) { m_primaryDistStats->ClearAll(); - if (GetState() >= STATE_SELECTED) // If we have a single star, need to force an auto-find to be sure we have the right secondary stars + if (GetState() >= + STATE_SELECTED) // If we have a single star, need to force an auto-find to be sure we have the right secondary stars { StopGuiding(); InvalidateCurrentPosition(true); @@ -270,11 +270,11 @@ void GuiderMultiStar::LoadProfileSettings() { Guider::LoadProfileSettings(); - double massChangeThreshold = pConfig->Profile.GetDouble("/guider/onestar/MassChangeThreshold", - DefaultMassChangeThreshold); + double massChangeThreshold = pConfig->Profile.GetDouble("/guider/onestar/MassChangeThreshold", DefaultMassChangeThreshold); SetMassChangeThreshold(massChangeThreshold); - bool massChangeThreshEnabled = pConfig->Profile.GetBoolean("/guider/onestar/MassChangeThresholdEnabled", massChangeThreshold != 1.0); + bool massChangeThreshEnabled = + pConfig->Profile.GetBoolean("/guider/onestar/MassChangeThresholdEnabled", massChangeThreshold != 1.0); SetMassChangeThresholdEnabled(massChangeThreshEnabled); bool tolerateJumps = pConfig->Profile.GetBoolean("/guider/onestar/TolerateJumpsEnabled", false); @@ -383,7 +383,7 @@ bool GuiderMultiStar::SetCurrentPosition(const usImage *pImage, const PHD_Point& double x = position.X; double y = position.Y; - Debug.Write(wxString::Format("SetCurrentPosition(%.2f,%.2f)\n", x, y )); + Debug.Write(wxString::Format("SetCurrentPosition(%.2f,%.2f)\n", x, y)); if ((x <= 0) || (x >= pImage->Size.x)) { @@ -396,8 +396,8 @@ bool GuiderMultiStar::SetCurrentPosition(const usImage *pImage, const PHD_Point& } m_massChecker->Reset(); - bError = !m_primaryStar.Find(pImage, m_searchRegion, x, y, pFrame->GetStarFindMode(), - GetMinStarHFD(), GetMaxStarHFD(), pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE); + bError = !m_primaryStar.Find(pImage, m_searchRegion, x, y, pFrame->GetStarFindMode(), GetMinStarHFD(), GetMaxStarHFD(), + pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE); } catch (const wxString& Msg) { @@ -414,12 +414,18 @@ static wxString StarStatusStr(const Star& star) switch (star.GetError()) { - case Star::STAR_LOWSNR: return _("Star lost - low SNR"); - case Star::STAR_LOWMASS: return _("Star lost - low mass"); - case Star::STAR_LOWHFD: return _("Star lost - low HFD"); - case Star::STAR_TOO_NEAR_EDGE: return _("Star too near edge"); - case Star::STAR_MASSCHANGE: return _("Star lost - mass changed"); - default: return _("No star found"); + case Star::STAR_LOWSNR: + return _("Star lost - low SNR"); + case Star::STAR_LOWMASS: + return _("Star lost - low mass"); + case Star::STAR_LOWHFD: + return _("Star lost - low HFD"); + case Star::STAR_TOO_NEAR_EDGE: + return _("Star too near edge"); + case Star::STAR_MASSCHANGE: + return _("Star lost - mass changed"); + default: + return _("No star found"); } } @@ -479,8 +485,8 @@ bool GuiderMultiStar::AutoSelect(const wxRect& roi) m_massChecker->Reset(); - if (!m_primaryStar.Find(image, m_searchRegion, newStar.X, newStar.Y, Star::FIND_CENTROID, GetMinStarHFD(), GetMaxStarHFD(), - pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE)) + if (!m_primaryStar.Find(image, m_searchRegion, newStar.X, newStar.Y, Star::FIND_CENTROID, GetMinStarHFD(), + GetMaxStarHFD(), pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE)) { throw ERROR_INFO("Unable to find"); } @@ -535,30 +541,32 @@ bool GuiderMultiStar::AutoSelect(const wxRect& roi) inline static wxRect SubframeRect(const PHD_Point& pos, int halfwidth) { - return wxRect(ROUND(pos.X) - halfwidth, - ROUND(pos.Y) - halfwidth, - 2 * halfwidth + 1, - 2 * halfwidth + 1); + return wxRect(ROUND(pos.X) - halfwidth, ROUND(pos.Y) - halfwidth, 2 * halfwidth + 1, 2 * halfwidth + 1); } wxRect GuiderMultiStar::GetBoundingBox() const { - enum { SUBFRAME_BOUNDARY_PX = 0 }; + enum + { + SUBFRAME_BOUNDARY_PX = 0 + }; GUIDER_STATE state = GetState(); bool subframe; PHD_Point pos; - switch (state) { + switch (state) + { case STATE_SELECTED: case STATE_CALIBRATING_PRIMARY: case STATE_CALIBRATING_SECONDARY: subframe = m_primaryStar.WasFound(); pos = CurrentPosition(); break; - case STATE_GUIDING: { - subframe = m_primaryStar.WasFound(); // true; + case STATE_GUIDING: + { + subframe = m_primaryStar.WasFound(); // true; // As long as the star is close to the lock position, keep the subframe // at the lock position. Otherwise, follow the star. double dist = CurrentPosition().Distance(LockPosition()); @@ -611,9 +619,15 @@ struct DistanceChecker wxLongLong_t m_expires; double m_forceTolerance; - enum { WAIT_INTERVAL_MS = 5000 }; + enum + { + WAIT_INTERVAL_MS = 5000 + }; - DistanceChecker() : m_state(ST_GUIDING) { } + DistanceChecker() + : m_state(ST_GUIDING) + { + } void Activate() { @@ -628,7 +642,10 @@ struct DistanceChecker static bool _CheckDistance(double distance, bool raOnly, double tolerance) { - enum { MIN_FRAMES_FOR_STATS = 10 }; + enum + { + MIN_FRAMES_FOR_STATS = 10 + }; Guider *guider = pFrame->pGuider; if (!guider->IsGuiding() || guider->IsPaused() || PhdController::IsSettling() || guider->CurrentErrorFrameCount() < MIN_FRAMES_FOR_STATS) @@ -640,7 +657,7 @@ struct DistanceChecker if (distance > threshold) { Debug.Write(wxString::Format("DistanceChecker: reject for large offset (%.2f > %.2f) avgDist = %.2f count = %u\n", - distance, threshold, avgDist, guider->CurrentErrorFrameCount())); + distance, threshold, avgDist, guider->CurrentErrorFrameCount())); return false; } return true; @@ -702,7 +719,7 @@ wxString GuiderMultiStar::GetStarCount() const { // no weird displays if stars are being removed from list return wxString::Format("%u/%u", wxMin(m_starsUsed, static_cast(m_guideStars.size())), - static_cast(m_guideStars.size())); + static_cast(m_guideStars.size())); } // Private method to build compact logging string for how secondary stars were used @@ -760,12 +777,14 @@ bool GuiderMultiStar::RefineOffset(const usImage *pImage, GuiderOffset *pOffset) { PHD_Point expectedLoc = m_primaryStar + pGS->offsetFromPrimary; bool found; - if (IsValidSecondaryStarPosition (expectedLoc)) - found = pGS->Find(pImage, m_searchRegion, expectedLoc.X, expectedLoc.Y, pFrame->GetStarFindMode(), - GetMinStarHFD(), GetMaxStarHFD(), pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE); + if (IsValidSecondaryStarPosition(expectedLoc)) + found = pGS->Find(pImage, m_searchRegion, expectedLoc.X, expectedLoc.Y, + pFrame->GetStarFindMode(), GetMinStarHFD(), GetMaxStarHFD(), + pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE); else found = pGS->Find(pImage, m_searchRegion, pGS->X, pGS->Y, pFrame->GetStarFindMode(), - GetMinStarHFD(), GetMaxStarHFD(), pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE); + GetMinStarHFD(), GetMaxStarHFD(), pCamera->GetSaturationADU(), + Star::FIND_LOGGING_VERBOSE); if (found) { pGS->referencePoint.X = pGS->X; @@ -775,18 +794,19 @@ bool GuiderMultiStar::RefineOffset(const usImage *pImage, GuiderOffset *pOffset) } else { - // Don't need to update reference point, lost star will continue to use the offsetFromPrimary location for possible recovery + // Don't need to update reference point, lost star will continue to use the + // offsetFromPrimary location for possible recovery pGS->wasLost = true; ++pGS; } } - return false; // All the secondary stars reference points reflect current positions + return false; // All the secondary stars reference points reflect current positions } } } } else - m_stabilizing = true; // get some data for primary star movement + m_stabilizing = true; // get some data for primary star movement if (!m_stabilizing && m_guideStars.size() > 1 && (sumX != 0 || sumY != 0)) { @@ -805,8 +825,8 @@ bool GuiderMultiStar::RefineOffset(const usImage *pImage, GuiderOffset *pOffset) } else // Look for it where we last found it - found = pGS->Find(pImage, m_searchRegion, pGS->X, pGS->Y, pFrame->GetStarFindMode(), - GetMinStarHFD(), GetMaxStarHFD(), pCamera->GetSaturationADU(), Star::FIND_LOGGING_MINIMAL); + found = pGS->Find(pImage, m_searchRegion, pGS->X, pGS->Y, pFrame->GetStarFindMode(), GetMinStarHFD(), + GetMaxStarHFD(), pCamera->GetSaturationADU(), Star::FIND_LOGGING_MINIMAL); if (found) { double dX = pGS->X - pGS->referencePoint.X; @@ -844,7 +864,8 @@ bool GuiderMultiStar::RefineOffset(const usImage *pImage, GuiderOffset *pOffset) AppendStarUse(secondaryInfo, Iter_Inx(pGS), dX, dY, 0, "R"); } else - AppendStarUse(secondaryInfo, Iter_Inx(pGS), dX, dY, 0, "M" + std::to_string(pGS->missCount)); + AppendStarUse( + secondaryInfo, Iter_Inx(pGS), dX, dY, 0, "M" + std::to_string(pGS->missCount)); ++pGS; continue; } @@ -863,7 +884,7 @@ bool GuiderMultiStar::RefineOffset(const usImage *pImage, GuiderOffset *pOffset) AppendStarUse(secondaryInfo, Iter_Inx(pGS), dX, dY, wt, "U"); } - else // exactly zero on both axes, probably a hot pixel, drop it + else // exactly zero on both axes, probably a hot pixel, drop it { AppendStarUse(secondaryInfo, Iter_Inx(pGS), 0, 0, 0, "DZ"); pGS = m_guideStars.erase(pGS); @@ -880,22 +901,22 @@ bool GuiderMultiStar::RefineOffset(const usImage *pImage, GuiderOffset *pOffset) ++pGS; else erasures = false; - } // End of looping through secondary stars + } // End of looping through secondary stars Debug.Write(secondaryInfo + "\n"); if (averaged) { sumX = sumX / sumWeights; sumY = sumY / sumWeights; - if (hypot(sumX, sumY) < primaryDistance) // Apply average only if its smaller than single-star delta + if (hypot(sumX, sumY) < primaryDistance) // Apply average only if its smaller than single-star delta { pOffset->cameraOfs.X = sumX; pOffset->cameraOfs.Y = sumY; refined = true; } - Debug.Write(wxString::Format("%s, %d included, MultiStar: {%0.2f, %0.2f}, one-star: {%0.2f, %0.2f}\n", (refined ? "refined" : "single-star"), - validStars, sumX, sumY, - origOffset.cameraOfs.X, origOffset.cameraOfs.Y)); + Debug.Write(wxString::Format("%s, %d included, MultiStar: {%0.2f, %0.2f}, one-star: {%0.2f, %0.2f}\n", + (refined ? "refined" : "single-star"), validStars, sumX, sumY, origOffset.cameraOfs.X, + origOffset.cameraOfs.Y)); } } } @@ -932,8 +953,8 @@ bool GuiderMultiStar::UpdateCurrentPosition(const usImage *pImage, GuiderOffset { Star newStar(m_primaryStar); - if (!newStar.Find(pImage, m_searchRegion, pFrame->GetStarFindMode(), GetMinStarHFD(), - GetMaxStarHFD(), pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE)) + if (!newStar.Find(pImage, m_searchRegion, pFrame->GetStarFindMode(), GetMinStarHFD(), GetMaxStarHFD(), + pCamera->GetSaturationADU(), Star::FIND_LOGGING_VERBOSE)) { errorInfo->starError = newStar.GetError(); errorInfo->starMass = 0.0; @@ -967,7 +988,8 @@ bool GuiderMultiStar::UpdateCurrentPosition(const usImage *pImage, GuiderOffset errorInfo->status = StarStatusStr(m_primaryStar); pFrame->StatusMsg(wxString::Format(_("Mass: %.f vs %.f"), newStar.Mass, limits[1])); - Debug.Write(wxString::Format("UpdateCurrentPosition: star mass new=%.1f exp=%.1f thresh=%.0f%% limits=(%.1f, %.1f, %.1f)\n", + Debug.Write(wxString::Format( + "UpdateCurrentPosition: star mass new=%.1f exp=%.1f thresh=%.0f%% limits=(%.1f, %.1f, %.1f)\n", newStar.Mass, limits[1], m_massChangeThreshold * 100., limits[0], limits[2], limits[3])); m_massChecker->AppendData(newStar.Mass); @@ -1021,7 +1043,7 @@ bool GuiderMultiStar::UpdateCurrentPosition(const usImage *pImage, GuiderOffset if (m_multiStarMode && m_guideStars.size() > 1) { if (RefineOffset(pImage, ofs)) - distance = hypot(ofs->cameraOfs.X, ofs->cameraOfs.Y); // Distance is reported to server clients + distance = hypot(ofs->cameraOfs.X, ofs->cameraOfs.Y); // Distance is reported to server clients } else m_starsUsed = 1; @@ -1070,9 +1092,7 @@ bool GuiderMultiStar::IsValidLockPosition(const PHD_Point& pt) if (!pImage) return false; // this is a bit ugly as it is tightly coupled to Star::Find - return pt.X >= 1 + m_searchRegion && - pt.X + 1 + m_searchRegion < pImage->Size.GetX() && - pt.Y >= 1 + m_searchRegion && + return pt.X >= 1 + m_searchRegion && pt.X + 1 + m_searchRegion < pImage->Size.GetX() && pt.Y >= 1 + m_searchRegion && pt.Y + 1 + m_searchRegion < pImage->Size.GetY(); } @@ -1081,22 +1101,19 @@ bool GuiderMultiStar::IsValidSecondaryStarPosition(const PHD_Point& pt) const usImage *pImage = CurrentImage(); if (!pImage) return false; - // As above, tightly coupled to Star::Find but with somewhat relaxed constraints. Find handles cases where search region is only partly within image - return pt.X >= 5 && - pt.X + 5 < pImage->Size.GetX() && - pt.Y >= 5 && - pt.Y + 5 < pImage->Size.GetY(); + // As above, tightly coupled to Star::Find but with somewhat relaxed constraints. Find handles cases where search region is + // only partly within image + return pt.X >= 5 && pt.X + 5 < pImage->Size.GetX() && pt.Y >= 5 && pt.Y + 5 < pImage->Size.GetY(); } -void GuiderMultiStar::OnLClick(wxMouseEvent &mevent) +void GuiderMultiStar::OnLClick(wxMouseEvent& mevent) { try { if (mevent.GetModifiers() == wxMOD_CONTROL) { double const scaleFactor = ScaleFactor(); - wxRealPoint pt((double) mevent.m_x / scaleFactor, - (double) mevent.m_y / scaleFactor); + wxRealPoint pt((double) mevent.m_x / scaleFactor, (double) mevent.m_y / scaleFactor); ToggleBookmark(pt); m_showBookmarks = true; pFrame->bookmarks_menu->Check(MENU_BOOKMARKS_SHOW, GetBookmarksShown()); @@ -1119,7 +1136,8 @@ void GuiderMultiStar::OnLClick(wxMouseEvent &mevent) } else { - if ((mevent.m_x <= m_searchRegion) || (mevent.m_x + m_searchRegion >= XWinSize) || (mevent.m_y <= m_searchRegion) || (mevent.m_y + m_searchRegion >= YWinSize)) + if ((mevent.m_x <= m_searchRegion) || (mevent.m_x + m_searchRegion >= XWinSize) || (mevent.m_y <= m_searchRegion) || + (mevent.m_y + m_searchRegion >= YWinSize)) { mevent.Skip(); throw THROW_INFO("Skipping event because click outside of search region"); @@ -1199,10 +1217,9 @@ void GuiderMultiStar::OnPaint(wxPaintEvent& event) dc.SetPen(wxPen(wxColour(0, 255, 255), 1, wxPENSTYLE_SOLID)); dc.SetBrush(*wxTRANSPARENT_BRUSH); - for (std::vector::const_iterator it = m_bookmarks.begin(); - it != m_bookmarks.end(); ++it) + for (std::vector::const_iterator it = m_bookmarks.begin(); it != m_bookmarks.end(); ++it) { - wxPoint p((int)(it->x * m_scaleFactor), (int)(it->y * m_scaleFactor)); + wxPoint p((int) (it->x * m_scaleFactor), (int) (it->y * m_scaleFactor)); dc.DrawCircle(p, 3); dc.DrawCircle(p, 6); dc.DrawCircle(p, 12); @@ -1224,10 +1241,9 @@ void GuiderMultiStar::OnPaint(wxPaintEvent& event) m_lastStarsUsed = wxMin(m_guideStars.size(), (size_t) DEFAULT_MAX_STAR_COUNT); } - for (std::vector::const_iterator it = m_guideStars.begin() + 1; - it != m_guideStars.end(); ++it) + for (std::vector::const_iterator it = m_guideStars.begin() + 1; it != m_guideStars.end(); ++it) { - wxPoint pt((int)(it->referencePoint.X * m_scaleFactor), (int)(it->referencePoint.Y * m_scaleFactor)); + wxPoint pt((int) (it->referencePoint.X * m_scaleFactor), (int) (it->referencePoint.Y * m_scaleFactor)); dc.DrawCircle(pt, 6); starsPlotted++; if (starsPlotted == m_maxStars) @@ -1243,24 +1259,24 @@ void GuiderMultiStar::OnPaint(wxPaintEvent& event) if (state == STATE_SELECTED) { if (FoundStar) - dc.SetPen(wxPen(wxColour(100,255,90), 1, wxPENSTYLE_SOLID)); // Draw the box around the star + dc.SetPen(wxPen(wxColour(100, 255, 90), 1, wxPENSTYLE_SOLID)); // Draw the box around the star else - dc.SetPen(wxPen(wxColour(230,130,30), 1, wxPENSTYLE_DOT)); + dc.SetPen(wxPen(wxColour(230, 130, 30), 1, wxPENSTYLE_DOT)); DrawBox(dc, m_primaryStar, m_searchRegion, m_scaleFactor); } else if (state == STATE_CALIBRATING_PRIMARY || state == STATE_CALIBRATING_SECONDARY) { // in the calibration process - dc.SetPen(wxPen(wxColour(32,196,32), 1, wxPENSTYLE_SOLID)); // Draw the box around the star + dc.SetPen(wxPen(wxColour(32, 196, 32), 1, wxPENSTYLE_SOLID)); // Draw the box around the star DrawBox(dc, m_primaryStar, m_searchRegion, m_scaleFactor); } else if (state == STATE_CALIBRATED || state == STATE_GUIDING) { // locked and guiding if (FoundStar) - dc.SetPen(wxPen(wxColour(32,196,32), 1, wxPENSTYLE_SOLID)); // Draw the box around the star + dc.SetPen(wxPen(wxColour(32, 196, 32), 1, wxPENSTYLE_SOLID)); // Draw the box around the star else - dc.SetPen(wxPen(wxColour(230,130,30), 1, wxPENSTYLE_DOT)); + dc.SetPen(wxPen(wxColour(230, 130, 30), 1, wxPENSTYLE_DOT)); DrawBox(dc, m_primaryStar, m_searchRegion, m_scaleFactor); } } @@ -1278,20 +1294,20 @@ void GuiderMultiStar::SaveStarFITS() usImage tmpimg; wxString imgLogDirectory; - tmpimg.Init(60,60); - int start_x = ROUND(StarX)-30; - int start_y = ROUND(StarY)-30; + tmpimg.Init(60, 60); + int start_x = ROUND(StarX) - 30; + int start_y = ROUND(StarY) - 30; if ((start_x + 60) > pImage->Size.GetWidth()) start_x = pImage->Size.GetWidth() - 60; if ((start_y + 60) > pImage->Size.GetHeight()) start_y = pImage->Size.GetHeight() - 60; - int x,y, width; + int x, y, width; width = pImage->Size.GetWidth(); unsigned short *usptr = tmpimg.ImageData; for (y = 0; y < 60; y++) { for (x = 0; x < 60; x++, usptr++) - *usptr = *(pImage->ImageData + (y + start_y)*width + (x + start_x)); + *usptr = *(pImage->ImageData + (y + start_y) * width + (x + start_x)); } imgLogDirectory = Debug.GetLogDir() + PATHSEPSTR + "PHD2_Stars"; @@ -1299,8 +1315,8 @@ void GuiderMultiStar::SaveStarFITS() wxFileName::Mkdir(imgLogDirectory, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); wxString fname = imgLogDirectory + PATHSEPSTR + "PHD_GuideStar" + wxDateTime::Now().Format(_T("_%j_%H%M%S")) + ".fit"; - fitsfile *fptr; // FITS file pointer - int status = 0; // CFITSIO status value MUST be initialized to zero! + fitsfile *fptr; // FITS file pointer + int status = 0; // CFITSIO status value MUST be initialized to zero! PHD_fits_create_file(&fptr, fname, false, &status); @@ -1354,7 +1370,6 @@ Guider::GuiderConfigDialogPane *GuiderMultiStar::GetConfigDialogPane(wxWindow *p GuiderMultiStar::GuiderMultiStarConfigDialogPane::GuiderMultiStarConfigDialogPane(wxWindow *pParent, GuiderMultiStar *pGuider) : GuiderConfigDialogPane(pParent, pGuider) { - } void GuiderMultiStar::GuiderMultiStarConfigDialogPane::LayoutControls(Guider *pGuider, BrainCtrlIdMap& CtrlMap) @@ -1362,103 +1377,110 @@ void GuiderMultiStar::GuiderMultiStarConfigDialogPane::LayoutControls(Guider *pG GuiderConfigDialogPane::LayoutControls(pGuider, CtrlMap); } -GuiderConfigDialogCtrlSet* GuiderMultiStar::GetConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +GuiderConfigDialogCtrlSet *GuiderMultiStar::GetConfigDialogCtrlSet( + wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) { return new GuiderMultiStarConfigDialogCtrlSet(pParent, pGuider, pAdvancedDialog, CtrlMap); } -GuiderMultiStarConfigDialogCtrlSet::GuiderMultiStarConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +GuiderMultiStarConfigDialogCtrlSet::GuiderMultiStarConfigDialogCtrlSet( + wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) : GuiderConfigDialogCtrlSet(pParent, pGuider, pAdvancedDialog, CtrlMap) { - assert(pGuider); - m_pGuiderMultiStar = static_cast(pGuider); - - int width; - - width = StringWidth(_T("0000")); - m_pSearchRegion = pFrame->MakeSpinCtrl(GetParentWindow(AD_szStarTracking), wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, MIN_SEARCH_REGION, MAX_SEARCH_REGION, DEFAULT_SEARCH_REGION, _T("Search")); - wxSizer *pSearchRegion = MakeLabeledControl(AD_szStarTracking, _("Search region (pixels)"), m_pSearchRegion, - _("How many pixels (up/down/left/right) do we examine to find the star? Default = 15")); - - wxStaticBoxSizer *pStarMass = new wxStaticBoxSizer(wxHORIZONTAL, GetParentWindow(AD_szStarTracking), _("Star Mass Detection")); - m_pEnableStarMassChangeThresh = new wxCheckBox(GetParentWindow(AD_szStarTracking), STAR_MASS_ENABLE, _("Enable")); - m_pEnableStarMassChangeThresh->SetToolTip(_("Check to enable star mass change detection. When enabled, " - "PHD skips frames when the guide star mass changes by an amount greater than the setting for 'tolerance'.")); - - GetParentWindow(AD_szStarTracking)->Bind(wxEVT_COMMAND_CHECKBOX_CLICKED, &GuiderMultiStarConfigDialogCtrlSet::OnStarMassEnableChecked, this, STAR_MASS_ENABLE); - - width = StringWidth(_T("100.0")); - m_pMassChangeThreshold = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szStarTracking), wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 10.0, 100.0, 0.0, 1.0, _T("MassChangeThreshold")); - m_pMassChangeThreshold->SetDigits(1); - wxSizer *pTolerance = MakeLabeledControl(AD_szStarTracking, _("Tolerance"), m_pMassChangeThreshold, - _("When star mass change detection is enabled, this is the tolerance for star mass changes between frames, in percent. " - "Larger values are more tolerant (less sensitive) to star mass changes. Valid range is 10-100, default is 50. " - "If star mass change detection is not enabled then this setting is ignored.")); - pStarMass->Add(m_pEnableStarMassChangeThresh, wxSizerFlags(0).Border(wxTOP, 3)); - pStarMass->Add(pTolerance, wxSizerFlags(0).Border(wxLEFT, 40)); - - width = StringWidth(_("65535")); - - double minHFD = pGuider->GetMinStarHFDFloor(); - m_MinHFD = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szStarTracking), wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, minHFD, 10.0, pGuider->GetMinStarHFDFloor(), 0.5); - m_MinHFD->SetDigits(1); - wxSizer *pHFD = MakeLabeledControl(AD_szStarTracking, _("Minimum star HFD (pixels)"), m_MinHFD, - _("The minimum star HFD (size) that will be used for identifying a guide star. " - "This setting can be used to prevent PHD2 from guiding on a hot pixel. " - "Use the Star Profile Tool to measure the HFD of a hot pixel and set the min HFD threshold " - "a bit higher. When the HFD falls below this level, the hot pixel will be ignored.")); - - m_MaxHFD = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szStarTracking), wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, minHFD + 2.0, 10.0, 5.0, 0.5); - m_MaxHFD->SetDigits(1); - wxSizer *pMaxHFD = MakeLabeledControl(AD_szStarTracking, _("Maximum star HFD (pixels)"), m_MaxHFD, - _("The maximum star HFD that will be used for identifying a guide star. " - "This setting can be used to prevent PHD2 from choosing a large clump of sensor noise, adjacent faint stars, " - "internal reflections, or comet heads as guide stars.")); - - wxString ary[] = { _("Auto"), _T("1"), _T("2"), _T("3") }; - m_autoSelDownsample = new wxChoice(GetParentWindow(AD_szStarTracking), wxID_ANY, wxDefaultPosition, wxDefaultSize, WXSIZEOF(ary), ary); - wxSizer *dsamp = MakeLabeledControl(AD_szStarTracking, _("Auto-selection frame downsample"), m_autoSelDownsample, - _("Downsampling factor for star auto-selection camera frames. Choose a value greater than 1 if star " - "auto-selection is failing to recognize misshapen guide stars.")); - - m_pBeepForLostStarCtrl = new wxCheckBox(GetParentWindow(AD_cbBeepForLostStar), wxID_ANY, _("Beep on lost star")); - m_pBeepForLostStarCtrl->SetToolTip(_("Issue an audible alarm any time the guide star is lost")); - - m_pUseMultiStars = new wxCheckBox(GetParentWindow(AD_szStarTracking), MULTI_STAR_ENABLE, _("Use multiple stars")); - m_pUseMultiStars->SetToolTip(_("Use multiple guide stars if they are available")); - GetParentWindow(AD_szStarTracking)->Bind(wxEVT_COMMAND_CHECKBOX_CLICKED, &GuiderMultiStarConfigDialogCtrlSet::OnMultiStarChecked, this, MULTI_STAR_ENABLE); - width = StringWidth(_T("100.0")); - - m_MinSNR = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szStarTracking), wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 6.0, 200.0, 6.0, 2.0); - m_MinSNR->SetDigits(0); - wxSizer *pSNR = MakeLabeledControl(AD_szStarTracking, _("Minimum star SNR for AutoFind"), m_MinSNR, - _("The minimum star SNR that will be used for auto-selecting guide stars. " - "This setting can be used to discourage PHD2 from choosing a guide star you know will be too faint for sustained guiding. " - "This setting applies to both the primary guide star and candidate secondary stars in multi-star guiding. " - "If this constraint cannot be met, a saturated or near-saturated star may be selected.")); - - wxFlexGridSizer *pTrackingParams = new wxFlexGridSizer(3, 2, 8, 15); - pTrackingParams->Add(pSearchRegion, wxSizerFlags(0).Border(wxTOP, 12)); - pTrackingParams->Add(pStarMass, wxSizerFlags(0).Border(wxLEFT, 75)); - pTrackingParams->Add(pHFD, wxSizerFlags().Border(wxTOP, 3)); - pTrackingParams->Add(pSNR, wxSizerFlags().Border(wxLEFT, 75)); - pTrackingParams->Add(pMaxHFD, wxSizerFlags().Border(wxTOP, 4)); - pTrackingParams->Add(m_pUseMultiStars, wxSizerFlags(0).Border(wxLEFT, 75)); - pTrackingParams->Add(m_pBeepForLostStarCtrl, wxSizerFlags().Border(wxTOP, 3)); - pTrackingParams->Add(dsamp, wxSizerFlags().Border(wxTOP, 3).Right()); - - AddGroup(CtrlMap, AD_szStarTracking, pTrackingParams); + assert(pGuider); + m_pGuiderMultiStar = static_cast(pGuider); + + int width; + + width = StringWidth(_T("0000")); + m_pSearchRegion = pFrame->MakeSpinCtrl(GetParentWindow(AD_szStarTracking), wxID_ANY, _T(" "), wxDefaultPosition, + wxSize(width, -1), wxSP_ARROW_KEYS, MIN_SEARCH_REGION, MAX_SEARCH_REGION, DEFAULT_SEARCH_REGION, _T("Search")); + wxSizer *pSearchRegion = MakeLabeledControl(AD_szStarTracking, _("Search region (pixels)"), m_pSearchRegion, + _("How many pixels (up/down/left/right) do we examine to find the star? Default = 15")); + + wxStaticBoxSizer *pStarMass = + new wxStaticBoxSizer(wxHORIZONTAL, GetParentWindow(AD_szStarTracking), _("Star Mass Detection")); + m_pEnableStarMassChangeThresh = new wxCheckBox(GetParentWindow(AD_szStarTracking), STAR_MASS_ENABLE, _("Enable")); + m_pEnableStarMassChangeThresh->SetToolTip( + _("Check to enable star mass change detection. When enabled, " + "PHD skips frames when the guide star mass changes by an amount greater than the setting for 'tolerance'.")); + + GetParentWindow(AD_szStarTracking) + ->Bind(wxEVT_COMMAND_CHECKBOX_CLICKED, &GuiderMultiStarConfigDialogCtrlSet::OnStarMassEnableChecked, this, + STAR_MASS_ENABLE); + + width = StringWidth(_T("100.0")); + m_pMassChangeThreshold = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szStarTracking), wxID_ANY, wxEmptyString, + wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 10.0, 100.0, 0.0, 1.0, _T("MassChangeThreshold")); + m_pMassChangeThreshold->SetDigits(1); + wxSizer *pTolerance = MakeLabeledControl(AD_szStarTracking, _("Tolerance"), m_pMassChangeThreshold, + _("When star mass change detection is enabled, this is the tolerance for star mass changes between frames, in percent. " + "Larger values are more tolerant (less sensitive) to star mass changes. Valid range is 10-100, default is 50. " + "If star mass change detection is not enabled then this setting is ignored.")); + pStarMass->Add(m_pEnableStarMassChangeThresh, wxSizerFlags(0).Border(wxTOP, 3)); + pStarMass->Add(pTolerance, wxSizerFlags(0).Border(wxLEFT, 40)); + + width = StringWidth(_("65535")); + + double minHFD = pGuider->GetMinStarHFDFloor(); + m_MinHFD = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szStarTracking), wxID_ANY, wxEmptyString, wxDefaultPosition, + wxSize(width, -1), wxSP_ARROW_KEYS, minHFD, 10.0, pGuider->GetMinStarHFDFloor(), 0.5); + m_MinHFD->SetDigits(1); + wxSizer *pHFD = MakeLabeledControl(AD_szStarTracking, _("Minimum star HFD (pixels)"), m_MinHFD, + _("The minimum star HFD (size) that will be used for identifying a guide star. " + "This setting can be used to prevent PHD2 from guiding on a hot pixel. " + "Use the Star Profile Tool to measure the HFD of a hot pixel and set the min HFD threshold " + "a bit higher. When the HFD falls below this level, the hot pixel will be ignored.")); + + m_MaxHFD = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szStarTracking), wxID_ANY, wxEmptyString, wxDefaultPosition, + wxSize(width, -1), wxSP_ARROW_KEYS, minHFD + 2.0, 10.0, 5.0, 0.5); + m_MaxHFD->SetDigits(1); + wxSizer *pMaxHFD = MakeLabeledControl(AD_szStarTracking, _("Maximum star HFD (pixels)"), m_MaxHFD, + _("The maximum star HFD that will be used for identifying a guide star. " + "This setting can be used to prevent PHD2 from choosing a large clump of sensor noise, adjacent faint stars, " + "internal reflections, or comet heads as guide stars.")); + + wxString ary[] = { _("Auto"), _T("1"), _T("2"), _T("3") }; + m_autoSelDownsample = + new wxChoice(GetParentWindow(AD_szStarTracking), wxID_ANY, wxDefaultPosition, wxDefaultSize, WXSIZEOF(ary), ary); + wxSizer *dsamp = MakeLabeledControl(AD_szStarTracking, _("Auto-selection frame downsample"), m_autoSelDownsample, + _("Downsampling factor for star auto-selection camera frames. Choose a value greater than 1 if star " + "auto-selection is failing to recognize misshapen guide stars.")); + + m_pBeepForLostStarCtrl = new wxCheckBox(GetParentWindow(AD_cbBeepForLostStar), wxID_ANY, _("Beep on lost star")); + m_pBeepForLostStarCtrl->SetToolTip(_("Issue an audible alarm any time the guide star is lost")); + + m_pUseMultiStars = new wxCheckBox(GetParentWindow(AD_szStarTracking), MULTI_STAR_ENABLE, _("Use multiple stars")); + m_pUseMultiStars->SetToolTip(_("Use multiple guide stars if they are available")); + GetParentWindow(AD_szStarTracking) + ->Bind( + wxEVT_COMMAND_CHECKBOX_CLICKED, &GuiderMultiStarConfigDialogCtrlSet::OnMultiStarChecked, this, MULTI_STAR_ENABLE); + width = StringWidth(_T("100.0")); + + m_MinSNR = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szStarTracking), wxID_ANY, wxEmptyString, wxDefaultPosition, + wxSize(width, -1), wxSP_ARROW_KEYS, 6.0, 200.0, 6.0, 2.0); + m_MinSNR->SetDigits(0); + wxSizer *pSNR = MakeLabeledControl(AD_szStarTracking, _("Minimum star SNR for AutoFind"), m_MinSNR, + _("The minimum star SNR that will be used for auto-selecting guide stars. " + "This setting can be used to discourage PHD2 from choosing a guide star you know will be too faint for sustained " + "guiding. " + "This setting applies to both the primary guide star and candidate secondary stars in multi-star guiding. " + "If this constraint cannot be met, a saturated or near-saturated star may be selected.")); + + wxFlexGridSizer *pTrackingParams = new wxFlexGridSizer(3, 2, 8, 15); + pTrackingParams->Add(pSearchRegion, wxSizerFlags(0).Border(wxTOP, 12)); + pTrackingParams->Add(pStarMass, wxSizerFlags(0).Border(wxLEFT, 75)); + pTrackingParams->Add(pHFD, wxSizerFlags().Border(wxTOP, 3)); + pTrackingParams->Add(pSNR, wxSizerFlags().Border(wxLEFT, 75)); + pTrackingParams->Add(pMaxHFD, wxSizerFlags().Border(wxTOP, 4)); + pTrackingParams->Add(m_pUseMultiStars, wxSizerFlags(0).Border(wxLEFT, 75)); + pTrackingParams->Add(m_pBeepForLostStarCtrl, wxSizerFlags().Border(wxTOP, 3)); + pTrackingParams->Add(dsamp, wxSizerFlags().Border(wxTOP, 3).Right()); + + AddGroup(CtrlMap, AD_szStarTracking, pTrackingParams); } -GuiderMultiStarConfigDialogCtrlSet::~GuiderMultiStarConfigDialogCtrlSet() -{ - -} +GuiderMultiStarConfigDialogCtrlSet::~GuiderMultiStarConfigDialogCtrlSet() { } void GuiderMultiStarConfigDialogCtrlSet::LoadValues() { @@ -1492,10 +1514,7 @@ void GuiderMultiStarConfigDialogCtrlSet::UnloadValues() GuiderConfigDialogCtrlSet::UnloadValues(); } -void GuiderMultiStarConfigDialogCtrlSet::OnMultiStarChecked(wxCommandEvent& evt) -{ - -} +void GuiderMultiStarConfigDialogCtrlSet::OnMultiStarChecked(wxCommandEvent& evt) { } void GuiderMultiStarConfigDialogCtrlSet::OnStarMassEnableChecked(wxCommandEvent& event) { m_pMassChangeThreshold->Enable(event.IsChecked()); diff --git a/src/guider_multistar.h b/src/guider_multistar.h index 63594ebfa..a0b22d8fc 100644 --- a/src/guider_multistar.h +++ b/src/guider_multistar.h @@ -51,7 +51,8 @@ class GuiderConfigDialogCtrlSet; class GuiderMultiStarConfigDialogCtrlSet : public GuiderConfigDialogCtrlSet { public: - GuiderMultiStarConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + GuiderMultiStarConfigDialogCtrlSet( + wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); virtual ~GuiderMultiStarConfigDialogCtrlSet(); GuiderMultiStar *m_pGuiderMultiStar; @@ -96,8 +97,7 @@ class GuiderMultiStar : public Guider class GuiderMultiStarConfigDialogPane : public GuiderConfigDialogPane { protected: - - public: + public: GuiderMultiStarConfigDialogPane(wxWindow *pParent, GuiderMultiStar *pGuider); ~GuiderMultiStarConfigDialogPane() {}; @@ -112,7 +112,7 @@ class GuiderMultiStar : public Guider bool SetMassChangeThreshold(double starMassChangeThreshold); bool SetTolerateJumps(bool enable, double threshold); bool SetSearchRegion(int searchRegion); - bool RefineOffset(const usImage *pImage, GuiderOffset* pOffset); + bool RefineOffset(const usImage *pImage, GuiderOffset *pOffset); friend class GuiderMultiStarConfigDialogPane; friend class GuiderMultiStarConfigDialogCtrlSet; @@ -137,7 +137,8 @@ class GuiderMultiStar : public Guider wxString GetSettingsSummary() const override; Guider::GuiderConfigDialogPane *GetConfigDialogPane(wxWindow *pParent) override; - GuiderConfigDialogCtrlSet *GetConfigDialogCtrlSet(wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) override; + GuiderConfigDialogCtrlSet *GetConfigDialogCtrlSet( + wxWindow *pParent, Guider *pGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) override; void LoadProfileSettings() override; @@ -155,32 +156,27 @@ class GuiderMultiStar : public Guider wxDECLARE_EVENT_TABLE(); }; -inline int -GuiderMultiStar::GetMaxMovePixels() const +inline int GuiderMultiStar::GetMaxMovePixels() const { return m_searchRegion; } -inline const Star& -GuiderMultiStar::PrimaryStar() const +inline const Star& GuiderMultiStar::PrimaryStar() const { return m_primaryStar; } -inline bool -GuiderMultiStar::GetMultiStarMode() const +inline bool GuiderMultiStar::GetMultiStarMode() const { return m_multiStarMode; } -inline bool -GuiderMultiStar::IsLocked() const +inline bool GuiderMultiStar::IsLocked() const { return m_primaryStar.WasFound(); } -inline const PHD_Point& -GuiderMultiStar::CurrentPosition() const +inline const PHD_Point& GuiderMultiStar::CurrentPosition() const { return m_primaryStar; } diff --git a/src/guiding_assistant.cpp b/src/guiding_assistant.cpp index 36306037b..58b28455b 100644 --- a/src/guiding_assistant.cpp +++ b/src/guiding_assistant.cpp @@ -1,36 +1,36 @@ /* -* guiding_assistant.cpp -* PHD Guiding -* -* Created by Andy Galasso and Bruce Waddington -* Copyright (c) 2015 Andy Galasso and Bruce Waddington -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * guiding_assistant.cpp + * PHD Guiding + * + * Created by Andy Galasso and Bruce Waddington + * Copyright (c) 2015 Andy Galasso and Bruce Waddington + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #include "guiding_assistant.h" @@ -97,26 +97,30 @@ struct SampleWait : public wxDialog void OnCancel(wxCommandEvent& event); }; -SampleWait::SampleWait(int SecondsLeft, bool BltNeeded) : wxDialog(pFrame, wxID_ANY, _("Extended Sampling")) +SampleWait::SampleWait(int SecondsLeft, bool BltNeeded) + : wxDialog(pFrame, wxID_ANY, _("Extended Sampling")) { - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); - wxBoxSizer* amtSizer = new wxBoxSizer(wxHORIZONTAL); - wxStaticText* explanation = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT); + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *amtSizer = new wxBoxSizer(wxHORIZONTAL); + wxStaticText *explanation = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT); wxString msg; if (BltNeeded) - msg = _("Additional data sampling is being done to better meaure Dec drift. Backlash testing \nwill start automatically when sampling is completed."); + msg = _("Additional data sampling is being done to better meaure Dec drift. Backlash testing \nwill start " + "automatically when sampling is completed."); else - msg = _("Additional sampling is being done for accurate measurements. Results will be shown when sampling is complete."); + msg = + _("Additional sampling is being done for accurate measurements. Results will be shown when sampling is complete."); explanation->SetLabelText(msg); MakeBold(explanation); - wxStaticText* countDownLabel = new wxStaticText(this, wxID_ANY, _("Seconds remaining: "), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT); + wxStaticText *countDownLabel = + new wxStaticText(this, wxID_ANY, _("Seconds remaining: "), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT); m_SecondsLeft = SecondsLeft; m_CountdownAmount = new wxStaticText(this, wxID_ANY, std::to_string(wxMax(0, m_SecondsLeft))); amtSizer->Add(countDownLabel, wxSizerFlags(0).Border(wxALL, 8)); amtSizer->Add(m_CountdownAmount, wxSizerFlags(0).Border(wxALL, 8)); - wxButton* cancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); + wxButton *cancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); cancelBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(SampleWait::OnCancel), nullptr, this); - wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); + wxBoxSizer *btnSizer = new wxBoxSizer(wxHORIZONTAL); btnSizer->Add(cancelBtn, wxSizerFlags(0).Border(wxALL, 8).Center()); vSizer->Add(explanation, wxSizerFlags(0).Border(wxALL, 8).Center()); @@ -164,11 +168,15 @@ struct GuidingAsstWin : public wxDialog STATE_MEASURING = 2, STATE_STOPPED = 3 }; - enum DlgConstants {MAX_BACKLASH_COMP = 3000, GA_MIN_SAMPLING_PERIOD = 120}; + enum DlgConstants + { + MAX_BACKLASH_COMP = 3000, + GA_MIN_SAMPLING_PERIOD = 120 + }; wxButton *m_start; wxButton *m_stop; - OptionsButton* btnReviewPrev; + OptionsButton *btnReviewPrev; wxTextCtrl *m_report; wxStaticText *m_instructions; wxGrid *m_statusgrid; @@ -214,7 +222,7 @@ struct GuidingAsstWin : public wxDialog wxStaticText *m_calibration_msg; wxStaticText *m_binning_msg; wxStaticText *m_decAlgo_msg; - double m_ra_minmove_rec; // recommended value + double m_ra_minmove_rec; // recommended value double m_dec_minmove_rec; // recommended value double m_min_exp_rec; double m_max_exp_rec; @@ -237,10 +245,10 @@ struct GuidingAsstWin : public wxDialog double sumSNR; double sumMass; double m_lastTime; - double maxRateRA; // arc-sec per second - double decDriftPerMin; // px per minute - double decCorrectedRMS; // RMS of drift-corrected Dec dataset - double alignmentError; // arc-minutes + double maxRateRA; // arc-sec per second + double decDriftPerMin; // px per minute + double decCorrectedRMS; // RMS of drift-corrected Dec dataset + double alignmentError; // arc-minutes double m_backlashPx; int m_backlashMs; double m_backlashSigmaMs; @@ -250,7 +258,7 @@ struct GuidingAsstWin : public wxDialog bool m_savePrimaryMountEnabled; bool m_saveSecondaryMountEnabled; bool m_measurementsTaken; - int m_origSubFrames; + int m_origSubFrames; bool m_suspectCalibration; bool inBLTWrapUp = false; bool origMultistarMode; @@ -280,13 +288,11 @@ struct GuidingAsstWin : public wxDialog void OnReviewPrevious(wxCommandEvent& event); void OnGAReviewSelection(wxCommandEvent& evt); - wxStaticText *AddRecommendationBtn(const wxString& msg, - void (GuidingAsstWin::* handler)(wxCommandEvent&), - wxButton **ppButton); + wxStaticText *AddRecommendationBtn( + const wxString& msg, void (GuidingAsstWin::*handler)(wxCommandEvent&), wxButton **ppButton); wxStaticText *AddRecommendationMsg(const wxString& msg); - void FillResultCell(wxGrid *pGrid, const wxGridCellCoords& loc, double pxVal, - double asVal, const wxString& units1, const wxString& units2, - const wxString& extraInfo = wxEmptyString); + void FillResultCell(wxGrid *pGrid, const wxGridCellCoords& loc, double pxVal, double asVal, const wxString& units1, + const wxString& units2, const wxString& extraInfo = wxEmptyString); void UpdateInfo(const GuideStepInfo& info); void DisplayStaticResults(const GADetails& details); void FillInstructions(DialogState eState); @@ -297,8 +303,8 @@ struct GuidingAsstWin : public wxDialog void EndBacklashTest(bool completed); void BacklashError(); void StatsReset(); - void LoadGAResults(const wxString& TimeStamp, GADetails* Details); - void SaveGAResults(const wxString* AllRecommendations); + void LoadGAResults(const wxString& TimeStamp, GADetails *Details); + void SaveGAResults(const wxString *AllRecommendations); int GetGAHistoryCount(); void GetMinMoveRecs(double& RecRA, double& RecDec); bool LikelyBacklash(const CalibrationDetails& calDetails); @@ -316,14 +322,22 @@ struct GridTooltipInfo : public wxObject wxGrid *grid; int gridNum; wxGridCellCoords prevCoords; - GridTooltipInfo(wxGrid *g, int i) : grid(g), gridNum(i) { } + GridTooltipInfo(wxGrid *g, int i) + : grid(g) + , gridNum(i) + { + } }; struct TextWrapper { wxWindow *win; int width; - TextWrapper(wxWindow *win_, int width_) : win(win_), width(width_) { } + TextWrapper(wxWindow *win_, int width_) + : win(win_) + , width(width_) + { + } wxString Wrap(const wxString& text) const { struct Wrapper : public wxTextWrapper @@ -339,13 +353,13 @@ struct TextWrapper // Constructor GuidingAsstWin::GuidingAsstWin() - : wxDialog(pFrame, wxID_ANY, wxGetTranslation(_("Guiding Assistant"))), - m_measuring(false), - m_guideOutputDisabled(false), - m_measurementsTaken(false), - m_origSubFrames(-1), - m_backlashTool(nullptr), - m_flushConfig(false) + : wxDialog(pFrame, wxID_ANY, wxGetTranslation(_("Guiding Assistant"))) + , m_measuring(false) + , m_guideOutputDisabled(false) + , m_measurementsTaken(false) + , m_origSubFrames(-1) + , m_backlashTool(nullptr) + , m_flushConfig(false) { // Sizer hierarchy: // m_vSizer has {instructions, vResultsSizer, m_gaStatus, btnSizer} @@ -353,24 +367,24 @@ GuidingAsstWin::GuidingAsstWin() // hTopSizer has {status_group, displacement_group} // hBottomSizer has {other_group, m_recommendation_group} m_vSizer = new wxBoxSizer(wxVERTICAL); - wxBoxSizer* vResultsSizer = new wxBoxSizer(wxVERTICAL); - wxBoxSizer* hTopSizer = new wxBoxSizer(wxHORIZONTAL); // Measurement status and high-frequency results - wxBoxSizer* hBottomSizer = new wxBoxSizer(wxHORIZONTAL); // Low-frequency results and recommendations + wxBoxSizer *vResultsSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *hTopSizer = new wxBoxSizer(wxHORIZONTAL); // Measurement status and high-frequency results + wxBoxSizer *hBottomSizer = new wxBoxSizer(wxHORIZONTAL); // Low-frequency results and recommendations - m_instructions = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(700, 50), wxALIGN_LEFT | wxST_NO_AUTORESIZE); + m_instructions = + new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(700, 50), wxALIGN_LEFT | wxST_NO_AUTORESIZE); MakeBold(m_instructions); m_vSizer->Add(m_instructions, wxSizerFlags(0).Border(wxALL, 8)); // Grids have either 3 or 4 columns, so compute width of largest label as scaling term for column widths - double minLeftCol = StringWidth(this, - _(" -999.99 px/min (-999.99 arc-sec/min )")) + 6; - double minRightCol = 1.25 * (StringWidth(this, - _(" 9.99 px ( 9.99 arc-sec)")) + 6); + double minLeftCol = StringWidth(this, _(" -999.99 px/min (-999.99 arc-sec/min )")) + 6; + double minRightCol = 1.25 * (StringWidth(this, _(" 9.99 px ( 9.99 arc-sec)")) + 6); // Start of status group wxStaticBoxSizer *status_group = new wxStaticBoxSizer(wxVERTICAL, this, _("Measurement Status")); m_statusgrid = new wxGrid(this, wxID_ANY); m_statusgrid->CreateGrid(3, 4); - m_statusgrid->GetGridWindow()->Bind(wxEVT_MOTION, &GuidingAsstWin::OnMouseMove, this, wxID_ANY, wxID_ANY, new GridTooltipInfo(m_statusgrid, 1)); + m_statusgrid->GetGridWindow()->Bind( + wxEVT_MOTION, &GuidingAsstWin::OnMouseMove, this, wxID_ANY, wxID_ANY, new GridTooltipInfo(m_statusgrid, 1)); m_statusgrid->SetRowLabelSize(1); m_statusgrid->SetColLabelSize(1); m_statusgrid->EnableEditing(false); @@ -395,9 +409,9 @@ GuidingAsstWin::GuidingAsstWin() m_statusgrid->SetCellValue(row, col++, _("Sample count")); m_samplecount_loc.Set(row, col++); - //StartRow(row, col); - //m_statusgrid->SetCellValue(_("Frequency cut-off:"), row, col++); // Leave out for now, probably not useful to users - //m_hfcutoff_loc.Set(row, col++); + // StartRow(row, col); + // m_statusgrid->SetCellValue(_("Frequency cut-off:"), row, col++); // Leave out for now, probably not useful to users + // m_hfcutoff_loc.Set(row, col++); status_group->Add(m_statusgrid); hTopSizer->Add(status_group, wxSizerFlags(0).Border(wxALL, 8)); @@ -407,7 +421,8 @@ GuidingAsstWin::GuidingAsstWin() wxStaticBoxSizer *displacement_group = new wxStaticBoxSizer(wxVERTICAL, this, _("High-frequency Star Motion")); m_displacementgrid = new wxGrid(this, wxID_ANY); m_displacementgrid->CreateGrid(3, 2); - m_displacementgrid->GetGridWindow()->Bind(wxEVT_MOTION, &GuidingAsstWin::OnMouseMove, this, wxID_ANY, wxID_ANY, new GridTooltipInfo(m_displacementgrid, 2)); + m_displacementgrid->GetGridWindow()->Bind( + wxEVT_MOTION, &GuidingAsstWin::OnMouseMove, this, wxID_ANY, wxID_ANY, new GridTooltipInfo(m_displacementgrid, 2)); m_displacementgrid->SetRowLabelSize(1); m_displacementgrid->SetColLabelSize(1); m_displacementgrid->EnableEditing(false); @@ -435,7 +450,8 @@ GuidingAsstWin::GuidingAsstWin() wxStaticBoxSizer *other_group = new wxStaticBoxSizer(wxVERTICAL, this, _("Other Star Motion")); m_othergrid = new wxGrid(this, wxID_ANY); m_othergrid->CreateGrid(9, 2); - m_othergrid->GetGridWindow()->Bind(wxEVT_MOTION, &GuidingAsstWin::OnMouseMove, this, wxID_ANY, wxID_ANY, new GridTooltipInfo(m_othergrid, 3)); + m_othergrid->GetGridWindow()->Bind( + wxEVT_MOTION, &GuidingAsstWin::OnMouseMove, this, wxID_ANY, wxID_ANY, new GridTooltipInfo(m_othergrid, 3)); m_othergrid->SetRowLabelSize(1); m_othergrid->SetColLabelSize(1); m_othergrid->EnableEditing(false); @@ -503,13 +519,13 @@ GuidingAsstWin::GuidingAsstWin() m_recommend_group->Add(m_recommendgrid, wxSizerFlags(1).Expand()); // Add buttons for viewing the Dec backlash graph or getting help - wxBoxSizer* hBtnSizer = new wxBoxSizer(wxHORIZONTAL); + wxBoxSizer *hBtnSizer = new wxBoxSizer(wxHORIZONTAL); m_graphBtn = new wxButton(this, wxID_ANY, _("Show Backlash Graph")); m_graphBtn->SetToolTip(_("Show graph of backlash measurement points")); m_graphBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(GuidingAsstWin::OnGraph), nullptr, this); m_graphBtn->Enable(false); hBtnSizer->Add(m_graphBtn, wxSizerFlags(0).Border(wxALL, 5)); - wxButton* helpBtn = new wxButton(this, wxID_ANY, _("Help")); + wxButton *helpBtn = new wxButton(this, wxID_ANY, _("Help")); helpBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(GuidingAsstWin::OnHelp), nullptr, this); hBtnSizer->Add(50, 0); hBtnSizer->Add(helpBtn, wxSizerFlags(0).Border(wxALL, 5)); @@ -523,8 +539,10 @@ GuidingAsstWin::GuidingAsstWin() // End of recommendations m_backlashCB = new wxCheckBox(this, wxID_ANY, _("Measure Declination Backlash")); - m_backlashCB->SetToolTip(_("PHD2 will move the guide star a considerable distance north, then south to measure backlash. Be sure the selected star has " - "plenty of room to move in the north direction. If the guide star is lost, increase the size of the search region to at least 20 px")); + m_backlashCB->SetToolTip(_("PHD2 will move the guide star a considerable distance north, then south to measure backlash. " + "Be sure the selected star has " + "plenty of room to move in the north direction. If the guide star is lost, increase the size " + "of the search region to at least 20 px")); if (TheScope()) { m_backlashCB->SetValue(!pMount->HasHPEncoders()); @@ -541,9 +559,9 @@ GuidingAsstWin::GuidingAsstWin() m_vSizer->Add(m_gaStatus, wxSizerFlags(0).Border(wxALL, 8).Center()); wxBoxSizer *btnSizer = new wxBoxSizer(wxHORIZONTAL); - btnSizer->Add(10, 0); // a little spacing left of Start button + btnSizer->Add(10, 0); // a little spacing left of Start button btnSizer->Add(m_backlashCB, wxSizerFlags(0).Border(wxALL, 8)); - btnSizer->Add(40, 0); // Put a spacer between the button and checkbox + btnSizer->Add(40, 0); // Put a spacer between the button and checkbox m_start = new wxButton(this, wxID_ANY, _("Start"), wxDefaultPosition, wxDefaultSize, 0); m_start->SetToolTip(_("Start measuring (disables guiding)")); @@ -590,7 +608,7 @@ GuidingAsstWin::GuidingAsstWin() reviewMode = false; if (pFrame->pGuider->IsGuiding()) { - OnStart(dummy); // Auto-start if we're already guiding + OnStart(dummy); // Auto-start if we're already guiding } } @@ -615,38 +633,64 @@ static bool GetGridToolTip(int gridNum, const wxGridCellCoords& coords, wxString if (gridNum > 1 && col != 0) return false; - else - if (col != 0 && col != 2) + else if (col != 0 && col != 2) return false; switch (gridNum * 100 + coords.GetRow()) { - // status grid - case 101: - { - if (col == 0) - *s = _("Signal-to-noise ratio; a measure of how well PHD2 can isolate the star from the sky/noise background"); - else - *s = _("Measure of overall star brightness. Consider using 'Auto-select Star' (Alt-S) to choose the star."); - break; - } + // status grid + case 101: + { + if (col == 0) + *s = _("Signal-to-noise ratio; a measure of how well PHD2 can isolate the star from the sky/noise background"); + else + *s = _("Measure of overall star brightness. Consider using 'Auto-select Star' (Alt-S) to choose the star."); + break; + } - // displacement grid - case 200: *s = _("Measure of typical high-frequency right ascension star movements; guiding usually cannot correct for fluctuations this small."); break; - case 201: *s = _("Measure of typical high-frequency declination star movements; guiding usually cannot correct for fluctuations this small."); break; - - // other grid - case 300: *s = _("Maximum sample-sample deflection seen in right ascension."); break; - case 301: *s = _("Maximum sample-sample deflection seen in declination."); break; - case 302: *s = _("Maximum peak-peak deflection seen in right ascension during sampling period."); break; - case 303: *s = _("Estimated overall drift rate in right ascension."); break; - case 304: *s = _("Maximum drift rate in right ascension during sampling period."); break; - case 305: *s = _("Exposure time to keep maximum RA drift below the recommended min-move level."); break; - case 306: *s = _("Estimated overall drift rate in declination."); break; - case 307: *s = _("Estimated declination backlash if test was completed. Results are time to clear backlash (ms) and corresponding gear angle (arc-sec). Uncertainty estimate is one unit of standard deviation"); break; - case 308: *s = _("Estimate of polar alignment error. If the scope declination is unknown, the value displayed is a lower bound and the actual error may be larger."); break; - - default: return false; + // displacement grid + case 200: + *s = _("Measure of typical high-frequency right ascension star movements; guiding usually cannot correct for " + "fluctuations this small."); + break; + case 201: + *s = _("Measure of typical high-frequency declination star movements; guiding usually cannot correct for fluctuations " + "this small."); + break; + + // other grid + case 300: + *s = _("Maximum sample-sample deflection seen in right ascension."); + break; + case 301: + *s = _("Maximum sample-sample deflection seen in declination."); + break; + case 302: + *s = _("Maximum peak-peak deflection seen in right ascension during sampling period."); + break; + case 303: + *s = _("Estimated overall drift rate in right ascension."); + break; + case 304: + *s = _("Maximum drift rate in right ascension during sampling period."); + break; + case 305: + *s = _("Exposure time to keep maximum RA drift below the recommended min-move level."); + break; + case 306: + *s = _("Estimated overall drift rate in declination."); + break; + case 307: + *s = _("Estimated declination backlash if test was completed. Results are time to clear backlash (ms) and " + "corresponding gear angle (arc-sec). Uncertainty estimate is one unit of standard deviation"); + break; + case 308: + *s = _("Estimate of polar alignment error. If the scope declination is unknown, the value displayed is a lower bound " + "and the actual error may be larger."); + break; + + default: + return false; } return true; @@ -679,15 +723,18 @@ void GuidingAsstWin::FillInstructions(DialogState eState) break; case STATE_START_READY: if (!m_measurementsTaken) - instr = _("Click Start to begin measurements. Guiding will be disabled during this time so the star will move around."); + instr = _( + "Click Start to begin measurements. Guiding will be disabled during this time so the star will move around."); else instr = m_instructions->GetLabel(); break; case STATE_MEASURING: - instr = _("Guiding output is disabled and star movement is being measured. Click Stop after 2 minutes (longer if you're measuring RA tracking accuracy of the mount)."); + instr = _("Guiding output is disabled and star movement is being measured. Click Stop after 2 minutes (longer if " + "you're measuring RA tracking accuracy of the mount)."); break; case STATE_STOPPED: - instr = _("Guiding has been resumed. Look at the recommendations and make any desired changes. Click Start to repeat the measurements, or close the window to continue guiding."); + instr = _("Guiding has been resumed. Look at the recommendations and make any desired changes. Click Start to repeat " + "the measurements, or close the window to continue guiding."); break; } m_instructions->SetLabel(instr); @@ -729,22 +776,20 @@ void GuidingAsstWin::BacklashStep(const PHD_Point& camLoc) double bltGearAngle = (m_backlashPx * pFrame->GetCameraPixelScale()); double bltGearAngleSigma = (bltSigmaPx * pFrame->GetCameraPixelScale()); wxString preamble = ((m_backlashMs >= 5000 || qual == BacklashTool::MEASUREMENT_TOO_FEW_NORTH) ? ">=" : ""); - wxString outStr, outStrTr; // untranslated and translated + wxString outStr, outStrTr; // untranslated and translated if (qual == BacklashTool::MEASUREMENT_VALID) { - outStr = wxString::Format("%s %d +/- %0.0f ms (%0.1f +/- %0.1f arc-sec)", - preamble, wxMax(0, m_backlashMs), m_backlashSigmaMs, - wxMax(0, bltGearAngle), bltGearAngleSigma); - outStrTr = wxString::Format("%s %d +/- %0.0f %s (%0.1f +/- %0.1f %s)", - preamble, wxMax(0, m_backlashMs), m_backlashSigmaMs, _("ms"), - wxMax(0, bltGearAngle), bltGearAngleSigma, _("arc-sec")); + outStr = wxString::Format("%s %d +/- %0.0f ms (%0.1f +/- %0.1f arc-sec)", preamble, + wxMax(0, m_backlashMs), m_backlashSigmaMs, wxMax(0, bltGearAngle), bltGearAngleSigma); + outStrTr = + wxString::Format("%s %d +/- %0.0f %s (%0.1f +/- %0.1f %s)", preamble, wxMax(0, m_backlashMs), + m_backlashSigmaMs, _("ms"), wxMax(0, bltGearAngle), bltGearAngleSigma, _("arc-sec")); } else { - outStr = wxString::Format("%s %d +/- ms (test impaired)", - preamble, wxMax(0, m_backlashMs)); - outStrTr = wxString::Format("%s %d +/- %s", - preamble, wxMax(0, m_backlashMs), _("ms (test impaired)")); + outStr = wxString::Format("%s %d +/- ms (test impaired)", preamble, wxMax(0, m_backlashMs)); + outStrTr = + wxString::Format("%s %d +/- %s", preamble, wxMax(0, m_backlashMs), _("ms (test impaired)")); } m_othergrid->SetCellValue(m_backlash_loc, outStrTr); HighlightCell(m_othergrid, m_backlash_loc); @@ -829,10 +874,10 @@ void GuidingAsstWin::OnDecMinMove(wxCommandEvent& event) void GuidingAsstWin::OnDecAlgoChange(wxCommandEvent& event) { if (pMount->IsStepGuider()) - return; // should never happen + return; // should never happen pMount->SetGuidingEnabled(false); // Need to make algo change through AD UI controls to keep everything in-synch - Mount::MountConfigDialogPane* currMountPane = pFrame->pAdvancedDialog->GetCurrentMountPane(); + Mount::MountConfigDialogPane *currMountPane = pFrame->pAdvancedDialog->GetCurrentMountPane(); currMountPane->ChangeYAlgorithm("Lowpass2"); Debug.Write("GuideAssistant changed Dec algo to Lowpass2\n"); GuideAlgorithm *decAlgo = pMount->GetYGuideAlgorithm(); @@ -845,7 +890,8 @@ void GuidingAsstWin::OnDecAlgoChange(wxCommandEvent& event) double newAggr = 80.0; decAlgo->SetParam("aggressiveness", newAggr); decAlgo->SetParam("minMove", m_dec_minmove_rec); - Debug.Write(wxString::Format("GuideAssistant set Lowpass2 aggressiveness = %0.2f, min-move = %0.2f\n", newAggr, m_dec_minmove_rec)); + Debug.Write( + wxString::Format("GuideAssistant set Lowpass2 aggressiveness = %0.2f, min-move = %0.2f\n", newAggr, m_dec_minmove_rec)); pFrame->pGraphLog->UpdateControls(); pMount->SetGuidingEnabled(true); pFrame->NotifyGuidingParam("Declination algorithm", wxString("Lowpass2")); @@ -872,12 +918,13 @@ void GuidingAsstWin::OnGraph(wxCommandEvent& event) if (reviewMode) m_backlashTool->ShowGraph(this, gaDetails.BLTNorthMoves, gaDetails.BLTSouthMoves, gaDetails.BLTMsmtPulse); else - m_backlashTool->ShowGraph(this, m_backlashTool->GetNorthSteps(), m_backlashTool->GetSouthSteps(), m_backlashTool->GetBLTMsmtPulseSize()); + m_backlashTool->ShowGraph( + this, m_backlashTool->GetNorthSteps(), m_backlashTool->GetSouthSteps(), m_backlashTool->GetBLTMsmtPulseSize()); } void GuidingAsstWin::OnHelp(wxCommandEvent& event) { - pFrame->help->Display("Tools.htm#Guiding_Assistant"); // named anchors in help file are not subject to translation + pFrame->help->Display("Tools.htm#Guiding_Assistant"); // named anchors in help file are not subject to translation } static wxString SizedMsg(const wxString& msg) @@ -889,9 +936,8 @@ static wxString SizedMsg(const wxString& msg) } // Adds a recommendation string and a button bound to the passed event handler -wxStaticText *GuidingAsstWin::AddRecommendationBtn(const wxString& msg, - void (GuidingAsstWin::* handler)(wxCommandEvent&), - wxButton **ppButton) +wxStaticText *GuidingAsstWin::AddRecommendationBtn( + const wxString& msg, void (GuidingAsstWin::*handler)(wxCommandEvent&), wxButton **ppButton) { wxStaticText *rec_label; @@ -926,29 +972,26 @@ void GuidingAsstWin::LogResults() wxString str; Debug.Write("Guiding Assistant results follow:\n"); str = wxString::Format("SNR=%s, Samples=%s, Elapsed Time=%s, RA HPF-RMS=%s, Dec HPF-RMS=%s, Total HPF-RMS=%s\n", - m_statusgrid->GetCellValue(m_snr_loc), m_statusgrid->GetCellValue(m_samplecount_loc), m_statusgrid->GetCellValue(m_elapsedtime_loc), - m_displacementgrid->GetCellValue(m_ra_rms_loc), + m_statusgrid->GetCellValue(m_snr_loc), m_statusgrid->GetCellValue(m_samplecount_loc), + m_statusgrid->GetCellValue(m_elapsedtime_loc), m_displacementgrid->GetCellValue(m_ra_rms_loc), m_displacementgrid->GetCellValue(m_dec_rms_loc), m_displacementgrid->GetCellValue(m_total_rms_loc)); GuideLog.NotifyGAResult(str); Debug.Write(str); str = wxString::Format("RA Peak=%s, RA Peak-Peak %s, RA Drift Rate=%s, Max RA Drift Rate=%s, Drift-Limiting Exp=%s\n", - m_othergrid->GetCellValue(m_ra_peak_loc), - m_othergrid->GetCellValue(m_ra_peakpeak_loc), m_othergrid->GetCellValue(m_ra_drift_loc), - m_othergrid->GetCellValue(m_ra_peak_drift_loc), - m_othergrid->GetCellValue(m_ra_drift_exp_loc) - ); + m_othergrid->GetCellValue(m_ra_peak_loc), m_othergrid->GetCellValue(m_ra_peakpeak_loc), + m_othergrid->GetCellValue(m_ra_drift_loc), m_othergrid->GetCellValue(m_ra_peak_drift_loc), + m_othergrid->GetCellValue(m_ra_drift_exp_loc)); GuideLog.NotifyGAResult(str); Debug.Write(str); - str = wxString::Format("Dec Drift Rate=%s, Dec Peak=%s, PA Error=%s\n", - m_othergrid->GetCellValue(m_dec_drift_loc), m_othergrid->GetCellValue(m_dec_peak_loc), - m_othergrid->GetCellValue(m_pae_loc)); + str = wxString::Format("Dec Drift Rate=%s, Dec Peak=%s, PA Error=%s\n", m_othergrid->GetCellValue(m_dec_drift_loc), + m_othergrid->GetCellValue(m_dec_peak_loc), m_othergrid->GetCellValue(m_pae_loc)); GuideLog.NotifyGAResult(str); Debug.Write(str); } // Get info regarding any saved GA sessions that include a BLT -static void GetBLTHistory(const std::vector&Timestamps, int* oldestBLTInx, int* BLTCount) +static void GetBLTHistory(const std::vector& Timestamps, int *oldestBLTInx, int *BLTCount) { int oldestInx = -1; int bltCount = 0; @@ -996,7 +1039,7 @@ static void TrimGAHistory(bool FreshBLT, int HistoryDepth) } // Save the results from the most recent GA run in the profile -void GuidingAsstWin::SaveGAResults(const wxString* AllRecommendations) +void GuidingAsstWin::SaveGAResults(const wxString *AllRecommendations) { wxString prefix = "/GA/" + startStr; @@ -1025,7 +1068,7 @@ void GuidingAsstWin::SaveGAResults(const wxString* AllRecommendations) if (m_backlashRecommendedMs > 0) pConfig->Profile.SetString(prefix + "/BLT_pulse", std::to_string(m_backlashMs)); pConfig->Profile.SetString(prefix + "/recommendations", *AllRecommendations); - bool freshBLT = m_backlashTool && m_backlashTool->IsGraphable(); // Just did a BLT that is viewable + bool freshBLT = m_backlashTool && m_backlashTool->IsGraphable(); // Just did a BLT that is viewable if (freshBLT) { pConfig->Profile.SetInt(prefix + "/BLT_MsmtPulse", m_backlashTool->GetBLTMsmtPulseSize()); @@ -1053,10 +1096,10 @@ void GuidingAsstWin::SaveGAResults(const wxString* AllRecommendations) } // Reload GA results for the passed timestamp -void GuidingAsstWin::LoadGAResults(const wxString& TimeStamp, GADetails* Details) +void GuidingAsstWin::LoadGAResults(const wxString& TimeStamp, GADetails *Details) { wxString prefix = "/GA/" + TimeStamp; - *Details = {}; // Reset all vars + *Details = {}; // Reset all vars Details->TimeStamp = pConfig->Profile.GetString(prefix + "/timestamp", wxEmptyString); Details->SNR = pConfig->Profile.GetString(prefix + "/snr", wxEmptyString); Details->StarMass = pConfig->Profile.GetString(prefix + "/star_mass", wxEmptyString); @@ -1107,10 +1150,10 @@ void GuidingAsstWin::LoadGAResults(const wxString& TimeStamp, GADetails* Details } } -// Compute a drift-corrected value for Dec RMS and use that as a seeing estimate. For long GA runs, compute values for overlapping -// 2-minute intervals and use the smallest result -// Perform suitable sanity checks, revert to default "smart" recommendations if things look wonky -void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double&RecDec) +// Compute a drift-corrected value for Dec RMS and use that as a seeing estimate. For long GA runs, compute values for +// overlapping 2-minute intervals and use the smallest result Perform suitable sanity checks, revert to default "smart" +// recommendations if things look wonky +void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double& RecDec) { AxisStats decVals; double bestEstimate = 1000; @@ -1120,20 +1163,21 @@ void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double&RecDec) double selRSquared = 0; double selSlope = 0; double correctedRMS; - const int MEASUREMENT_WINDOW_SIZE = 120; // seconds + const int MEASUREMENT_WINDOW_SIZE = 120; // seconds const int WINDOW_ADJUSTMENT = MEASUREMENT_WINDOW_SIZE / 2; int lastInx = m_decAxisStats.GetCount() - 1; double pxscale = pFrame->GetCameraPixelScale(); StarDisplacement val = m_decAxisStats.GetEntry(0); double tStart = val.DeltaTime; - double multiplier_ra; // 65% of Dec recommendation, but 100% for encoder mounts - double multiplier_dec = (pxscale < 1.5) ? 1.28 : 1.65; // 20% or 10% activity target based on normal distribution + double multiplier_ra; // 65% of Dec recommendation, but 100% for encoder mounts + double multiplier_dec = (pxscale < 1.5) ? 1.28 : 1.65; // 20% or 10% activity target based on normal distribution double minMoveFloor = 0.1; try { - if (m_decAxisStats.GetLastEntry().DeltaTime - tStart > 1.2 * MEASUREMENT_WINDOW_SIZE) //Long GA run, more than 2.4 minutes + if (m_decAxisStats.GetLastEntry().DeltaTime - tStart > + 1.2 * MEASUREMENT_WINDOW_SIZE) // Long GA run, more than 2.4 minutes { bool done = false; int inx = 0; @@ -1141,18 +1185,21 @@ void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double&RecDec) { val = m_decAxisStats.GetEntry(inx); decVals.AddGuideInfo(val.DeltaTime, val.StarPos, 0); - // Compute the minimum sigma for sliding, overlapping 2-min elapsed time intervals. Include the final interval if it's >= 1.6 minutes - if (val.DeltaTime - tStart >= MEASUREMENT_WINDOW_SIZE || (inx == lastInx && val.DeltaTime - tStart >= 0.8 * MEASUREMENT_WINDOW_SIZE)) + // Compute the minimum sigma for sliding, overlapping 2-min elapsed time intervals. Include the final interval + // if it's >= 1.6 minutes + if (val.DeltaTime - tStart >= MEASUREMENT_WINDOW_SIZE || + (inx == lastInx && val.DeltaTime - tStart >= 0.8 * MEASUREMENT_WINDOW_SIZE)) { if (decVals.GetCount() > 1) { double simpleSigma = decVals.GetSigma(); rSquared = decVals.GetLinearFitResults(&slope, &intcpt, &correctedRMS); - // If there is little drift relative to the random movements, the drift-correction is irrelevant and can actually degrade the result. So don't use the drift-corrected - // RMS unless it's smaller than the simple sigma + // If there is little drift relative to the random movements, the drift-correction is irrelevant and can + // actually degrade the result. So don't use the drift-corrected RMS unless it's smaller than the + // simple sigma if (correctedRMS < simpleSigma) { - if (correctedRMS < bestEstimate) // Keep track of the smallest value seen + if (correctedRMS < bestEstimate) // Keep track of the smallest value seen { bestEstimate = correctedRMS; selRSquared = rSquared; @@ -1161,7 +1208,8 @@ void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double&RecDec) } else bestEstimate = wxMin(bestEstimate, simpleSigma); - Debug.Write(wxString::Format("GA long series, window start=%0.0f, window end=%0.0f, Uncorrected RMS=%0.3f, Drift=%0.3f, Corrected RMS=%0.3f, R-sq=%0.3f\n", + Debug.Write(wxString::Format("GA long series, window start=%0.0f, window end=%0.0f, Uncorrected " + "RMS=%0.3f, Drift=%0.3f, Corrected RMS=%0.3f, R-sq=%0.3f\n", tStart, val.DeltaTime, simpleSigma, slope * 60, correctedRMS, rSquared)); } // Move the start of the next window earlier by 1 minute @@ -1178,22 +1226,24 @@ void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double&RecDec) } done = (inx > lastInx); } - Debug.Write(wxString::Format("Full uncorrected RMS=%0.3fpx, Selected Dec drift=%0.3f px/min, Best seeing estimate=%0.3fpx, R-sq=%0.3f\n", + Debug.Write(wxString::Format( + "Full uncorrected RMS=%0.3fpx, Selected Dec drift=%0.3f px/min, Best seeing estimate=%0.3fpx, R-sq=%0.3f\n", m_decAxisStats.GetSigma(), selSlope * 60, bestEstimate, selRSquared)); } - else // Normal GA run of <= 2.4 minutes, just use the entire interval for stats + else // Normal GA run of <= 2.4 minutes, just use the entire interval for stats { if (m_decAxisStats.GetCount() > 1) { double simpleSigma = m_decAxisStats.GetSigma(); rSquared = m_decAxisStats.GetLinearFitResults(&slope, &intcpt, &correctedRMS); - // If there is little drift relative to the random movements, the drift-correction is irrelevant and can actually degrade the result. So don't use the drift-corrected - // RMS unless it's smaller than the simple sigma + // If there is little drift relative to the random movements, the drift-correction is irrelevant and can + // actually degrade the result. So don't use the drift-corrected RMS unless it's smaller than the simple sigma if (correctedRMS < simpleSigma) bestEstimate = correctedRMS; else bestEstimate = simpleSigma; - Debug.Write(wxString::Format("Uncorrected Dec RMS=%0.3fpx, Dec drift=%0.3f px/min, Best seeing estimate=%0.3fpx, R-sq=%0.3f\n", + Debug.Write(wxString::Format( + "Uncorrected Dec RMS=%0.3fpx, Dec drift=%0.3f px/min, Best seeing estimate=%0.3fpx, R-sq=%0.3f\n", simpleSigma, slope * 60, bestEstimate, rSquared)); } } @@ -1210,7 +1260,7 @@ void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double&RecDec) double const unit = 0.05; double roundUpEst = std::max(round(bestEstimate * multiplier_dec / unit + 0.5) * unit, 0.05); // Now apply a sanity check - there are still numerous things that could have gone wrong during the GA - if (pxscale * roundUpEst <= 1.25) // Min-move below 1.25 arc-sec is credible + if (pxscale * roundUpEst <= 1.25) // Min-move below 1.25 arc-sec is credible { RecDec = roundUpEst; RecRA = wxMax(minMoveFloor, RecDec * multiplier_ra); @@ -1219,9 +1269,11 @@ void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double&RecDec) else { // Just reiterate the estimates made in the new-profile-wiz - RecDec = GuideAlgorithm::SmartDefaultMinMove(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); + RecDec = + GuideAlgorithm::SmartDefaultMinMove(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); RecRA = wxMax(minMoveFloor, RecDec * multiplier_ra); - Debug.Write(wxString::Format("GA Min-Move calcs failed sanity-check, DecEst=%0.3f, Dec-HPF-Sigma=%0.3f\n", roundUpEst, m_hpfDecStats.GetSigma())); + Debug.Write(wxString::Format("GA Min-Move calcs failed sanity-check, DecEst=%0.3f, Dec-HPF-Sigma=%0.3f\n", + roundUpEst, m_hpfDecStats.GetSigma())); Debug.Write(wxString::Format("GA Min-Move recs reverting to smart defaults, RA=%0.3f, Dec=%0.3f\n", RecRA, RecDec)); } } @@ -1235,12 +1287,12 @@ void GuidingAsstWin::GetMinMoveRecs(double& RecRA, double&RecDec) } } -// See if the mount probably has large Dec backlash, using either blt results or from inference. If so, we should relax the recommendations regarding -// polar alignment error +// See if the mount probably has large Dec backlash, using either blt results or from inference. If so, we should relax the +// recommendations regarding polar alignment error bool GuidingAsstWin::LikelyBacklash(const CalibrationDetails& calDetails) { bool likely = false; - BacklashComp* blc = TheScope()->GetBacklashComp(); // Always valid + BacklashComp *blc = TheScope()->GetBacklashComp(); // Always valid try { @@ -1293,28 +1345,28 @@ void GuidingAsstWin::MakeRecommendations() GetMinMoveRecs(m_ra_minmove_rec, m_dec_minmove_rec); // Refine the drift-limiting exposure value based on the ra_min_move recommendation - m_othergrid->SetCellValue(m_ra_drift_exp_loc, maxRateRA <= 0.0 ? _(" ") : - wxString::Format("%6.1f %s ", m_ra_minmove_rec / maxRateRA, (_("s")))); + m_othergrid->SetCellValue( + m_ra_drift_exp_loc, maxRateRA <= 0.0 ? _(" ") : wxString::Format("%6.1f %s ", m_ra_minmove_rec / maxRateRA, (_("s")))); - LogResults(); // Dump the raw statistics + LogResults(); // Dump the raw statistics // REMINDER: Any new recommendations must also be done in 'DisplayStaticRecommendations' // Clump the no-button messages at the top // ideal exposure ranges in general double rarms = m_hpfRAStats.GetSigma(); - double multiplier_ra = 1.0; // 66% prediction interval + double multiplier_ra = 1.0; // 66% prediction interval double ideal_min_exposure = 2.0; double ideal_max_exposure = 4.0; // adjust the min-exposure downward if drift limiting exposure is lower; then adjust range accordingly double drift_exp; if (maxRateRA > 0) - drift_exp = ceil((multiplier_ra * rarms / maxRateRA) / 0.5) * 0.5; // Rounded up to nearest 0.5 sec + drift_exp = ceil((multiplier_ra * rarms / maxRateRA) / 0.5) * 0.5; // Rounded up to nearest 0.5 sec else drift_exp = ideal_min_exposure; double min_rec_range = 2.0; double pxscale = pFrame->GetCameraPixelScale(); - m_min_exp_rec = std::max(1.0, std::min(drift_exp, ideal_min_exposure)); // smaller of drift and ideal, never less than 1.0 + m_min_exp_rec = std::max(1.0, std::min(drift_exp, ideal_min_exposure)); // smaller of drift and ideal, never less than 1.0 if (drift_exp > m_min_exp_rec) { @@ -1332,7 +1384,8 @@ void GuidingAsstWin::MakeRecommendations() wxString allRecommendations; // Always make a recommendation on exposure times - wxString msg = wxString::Format(_("Try to keep your exposure times in the range of %.1fs to %.1fs"), m_min_exp_rec, m_max_exp_rec); + wxString msg = + wxString::Format(_("Try to keep your exposure times in the range of %.1fs to %.1fs"), m_min_exp_rec, m_max_exp_rec); allRecommendations += "Exp:" + msg + "\n"; m_exposure_msg = AddRecommendationMsg(msg); Debug.Write(wxString::Format("Recommendation: %s\n", msg)); @@ -1359,7 +1412,7 @@ void GuidingAsstWin::MakeRecommendations() GuideLog.NotifyGAResult(logStr); } // SNR - if ((sumSNR / (double)m_lpfRAStats.GetCount()) < 10.0) + if ((sumSNR / (double) m_lpfRAStats.GetCount()) < 10.0) { wxString msg(_("Consider using a brighter star for the test or increasing the exposure time")); allRecommendations += "Star:" + msg + "\n"; @@ -1381,9 +1434,9 @@ void GuidingAsstWin::MakeRecommendations() } else { - msg = alignmentError < 10.0 ? - _("Polar alignment error > 5 arc-min; that could probably be improved.") : - _("Polar alignment error > 10 arc-min; try using the Drift Align tool to improve alignment."); + msg = alignmentError < 10.0 + ? _("Polar alignment error > 5 arc-min; that could probably be improved.") + : _("Polar alignment error > 10 arc-min; try using the Drift Align tool to improve alignment."); } if (msg != "") { @@ -1437,7 +1490,7 @@ void GuidingAsstWin::MakeRecommendations() if (m_backlashMs > 0) { - m_backlashRecommendedMs = (int)(floor(m_backlashMs / 10) * 10); // round down to nearest 10ms + m_backlashRecommendedMs = (int) (floor(m_backlashMs / 10) * 10); // round down to nearest 10ms m_backlashRecommendedMs = wxMax(m_backlashRecommendedMs, 10); } else @@ -1448,15 +1501,15 @@ void GuidingAsstWin::MakeRecommendations() if (pMount->HasHPEncoders()) msg = _("Mount has absolute encoders, no compensation needed"); else - msg = _("Backlash is small, no compensation needed"); // assume it was a small measurement error + msg = _("Backlash is small, no compensation needed"); // assume it was a small measurement error smallBacklash = true; } else if (m_backlashMs <= MAX_BACKLASH_COMP) msg = wxString::Format(_("Try starting with a Dec backlash compensation of %d ms"), m_backlashRecommendedMs); else { - msg = wxString::Format(_("Backlash is >= %d ms; you may need to guide in only one Dec direction (currently %s)"), m_backlashMs, - decDriftPerMin >= 0 ? _("South") : _("North")); + msg = wxString::Format(_("Backlash is >= %d ms; you may need to guide in only one Dec direction (currently %s)"), + m_backlashMs, decDriftPerMin >= 0 ? _("South") : _("North")); } allRecommendations += "BLT:" + msg + "\n"; m_backlash_msg = AddRecommendationBtn(msg, &GuidingAsstWin::OnDecBacklash, &m_decBacklashButton); @@ -1467,11 +1520,11 @@ void GuidingAsstWin::MakeRecommendations() } bool hasEncoders = pMount->HasHPEncoders(); - if (hasEncoders || smallBacklash) // Uses encoders or has zero backlash + if (hasEncoders || smallBacklash) // Uses encoders or has zero backlash { GuideAlgorithm *decAlgo = pMount->GetYGuideAlgorithm(); wxString algoChoice = decAlgo->GetGuideAlgorithmClassName(); - if (algoChoice == "ResistSwitch") // automatically rules out AO's + if (algoChoice == "ResistSwitch") // automatically rules out AO's { wxString msgText = _("Try using Lowpass2 for Dec guiding"); allRecommendations += "DecAlgo:" + msgText + "\n"; @@ -1500,7 +1553,7 @@ void GuidingAsstWin::DisplayStaticRecommendations(const GADetails& details) bool done = false; size_t end; - m_recommendgrid->Clear(true); // Always start fresh, delete any child buttons + m_recommendgrid->Clear(true); // Always start fresh, delete any child buttons while (!done) { end = allRecs.find_first_of("\n"); @@ -1622,13 +1675,13 @@ void GuidingAsstWin::OnReviewPrevious(wxCommandEvent& event) std::vector entryNames; entryNames = pConfig->Profile.GetGroupNames("/GA"); - wxMenu* reviewList = new wxMenu(); + wxMenu *reviewList = new wxMenu(); for (int inx = 0; inx < entryNames.size(); inx++) { reviewList->Append(GA_REVIEW_ITEMS_BASE + inx, entryNames[inx]); } - PopupMenu(reviewList, btnReviewPrev->GetPosition().x, - btnReviewPrev->GetPosition().y + btnReviewPrev->GetSize().GetHeight()); + PopupMenu( + reviewList, btnReviewPrev->GetPosition().x, btnReviewPrev->GetPosition().y + btnReviewPrev->GetSize().GetHeight()); wxDELETE(reviewList); } @@ -1657,7 +1710,8 @@ void GuidingAsstWin::DoStop(const wxString& status) if (m_guideOutputDisabled) { - Debug.Write(wxString::Format("GuidingAssistant: Re-enabling guide output (%d, %d)\n", m_savePrimaryMountEnabled, m_saveSecondaryMountEnabled)); + Debug.Write(wxString::Format( + "GuidingAssistant: Re-enabling guide output (%d, %d)\n", m_savePrimaryMountEnabled, m_saveSecondaryMountEnabled)); if (pMount) pMount->SetGuidingEnabled(m_savePrimaryMountEnabled); @@ -1665,7 +1719,7 @@ void GuidingAsstWin::DoStop(const wxString& status) pSecondaryMount->SetGuidingEnabled(m_saveSecondaryMountEnabled); m_guideOutputDisabled = false; - pFrame->pGuider->SetMultiStarMode(origMultistarMode); // may force an auto-find to refresh secondary star data + pFrame->pGuider->SetMultiStarMode(origMultistarMode); // may force an auto-find to refresh secondary star data pFrame->SetVariableDelayConfig(origVarDelayConfig.enabled, origVarDelayConfig.shortDelay, origVarDelayConfig.longDelay); } @@ -1700,7 +1754,7 @@ void GuidingAsstWin::EndBacklashTest(bool completed) if (!completed) { wxCommandEvent dummy; - OnAppStateNotify(dummy); // Make sure UI is in synch + OnAppStateNotify(dummy); // Make sure UI is in synch } DoStop(); } @@ -1720,7 +1774,7 @@ void GuidingAsstWin::OnStop(wxCommandEvent& event) m_gaStatus->SetLabel(wxEmptyString); if (longEnough && performBLT) { - if (!m_measuringBacklash) // Run the backlash test after the sampling was completed + if (!m_measuringBacklash) // Run the backlash test after the sampling was completed { m_measuringBacklash = true; if (m_origSubFrames == -1) @@ -1730,7 +1784,7 @@ void GuidingAsstWin::OnStop(wxCommandEvent& event) m_gaStatus->SetLabelText(_("Measuring backlash... ") + m_backlashTool->GetLastStatus()); Layout(); GetSizer()->Fit(this); - m_backlashCB->Enable(false); // Don't let user turn it off once we've started + m_backlashCB->Enable(false); // Don't let user turn it off once we've started m_measuring = false; m_backlashTool->StartMeasurement(decDriftPerMin); m_instructions->SetLabel(_("Measuring backlash... ")); @@ -1791,8 +1845,8 @@ void GuidingAsstWin::OnClose(wxCloseEvent& evt) Destroy(); } -void GuidingAsstWin::FillResultCell(wxGrid *pGrid, const wxGridCellCoords& loc, double pxVal, double asVal, const wxString& units1, const wxString& units2, - const wxString& extraInfo) +void GuidingAsstWin::FillResultCell(wxGrid *pGrid, const wxGridCellCoords& loc, double pxVal, double asVal, + const wxString& units1, const wxString& units2, const wxString& extraInfo) { pGrid->SetCellValue(loc, wxString::Format("%6.2f %s (%6.2f %s %s)", pxVal, units1, asVal, units2, extraInfo)); } @@ -1848,7 +1902,7 @@ void GuidingAsstWin::UpdateInfo(const GuideStepInfo& info) } // Update the time measures wxLongLong_t elapsedms = ::wxGetUTCTimeMillis().GetValue() - m_startTime; - m_elapsedSecs = (double)elapsedms / 1000.0; + m_elapsedSecs = (double) elapsedms / 1000.0; // add offset info to various stats accumulations m_hpfRAStats.AddValue(m_raHPF.AddValue(ra)); double prevRAlpf = m_raLPF.GetCurrentLPF(); @@ -1882,7 +1936,7 @@ void GuidingAsstWin::UpdateInfo(const GuideStepInfo& info) m_lastTime = info.time; sumSNR += info.starSNR; sumMass += info.starMass; - double n = (double)m_lpfRAStats.GetCount(); + double n = (double) m_lpfRAStats.GetCount(); wxString SEC(_("s")); wxString MSEC(_("ms")); @@ -1895,10 +1949,11 @@ void GuidingAsstWin::UpdateInfo(const GuideStepInfo& info) wxString ARCSECPERSEC(_("arc-sec/sec")); m_statusgrid->SetCellValue(m_timestamp_loc, startStr); - m_statusgrid->SetCellValue(m_exposuretime_loc, wxString::Format("%g%s", (double)pFrame->RequestedExposureDuration() / 1000.0, SEC)); + m_statusgrid->SetCellValue( + m_exposuretime_loc, wxString::Format("%g%s", (double) pFrame->RequestedExposureDuration() / 1000.0, SEC)); m_statusgrid->SetCellValue(m_snr_loc, wxString::Format("%.1f", sumSNR / n)); m_statusgrid->SetCellValue(m_starmass_loc, wxString::Format("%.1f", sumMass / n)); - m_statusgrid->SetCellValue(m_elapsedtime_loc, wxString::Format("%u%s", (unsigned int)(elapsedms / 1000), SEC)); + m_statusgrid->SetCellValue(m_elapsedtime_loc, wxString::Format("%u%s", (unsigned int) (elapsedms / 1000), SEC)); m_statusgrid->SetCellValue(m_samplecount_loc, wxString::Format("%.0f", n)); if (n > 1) @@ -1927,19 +1982,22 @@ void GuidingAsstWin::UpdateInfo(const GuideStepInfo& info) FillResultCell(m_displacementgrid, m_ra_rms_loc, rarms, rarms * pxscale, PX, ARCSEC); FillResultCell(m_displacementgrid, m_dec_rms_loc, decrms, decrms * pxscale, PX, ARCSEC); FillResultCell(m_displacementgrid, m_total_rms_loc, combined, combined * pxscale, PX, ARCSEC); - FillResultCell(m_othergrid, m_ra_peak_loc, - m_raAxisStats.GetMaxDelta(), m_raAxisStats.GetMaxDelta() * pxscale, PX, ARCSEC); - FillResultCell(m_othergrid, m_dec_peak_loc, - m_decAxisStats.GetMaxDelta(), m_decAxisStats.GetMaxDelta() * pxscale, PX, ARCSEC); + FillResultCell( + m_othergrid, m_ra_peak_loc, m_raAxisStats.GetMaxDelta(), m_raAxisStats.GetMaxDelta() * pxscale, PX, ARCSEC); + FillResultCell( + m_othergrid, m_dec_peak_loc, m_decAxisStats.GetMaxDelta(), m_decAxisStats.GetMaxDelta() * pxscale, PX, ARCSEC); double raPkPk = m_lpfRAStats.GetMaximum() - m_lpfRAStats.GetMinimum(); FillResultCell(m_othergrid, m_ra_peakpeak_loc, raPkPk, raPkPk * pxscale, PX, ARCSEC); - double raDriftRate = (ra - m_startPos.X) / m_elapsedSecs * 60.0; // Raw max-min, can't smooth this one reliably + double raDriftRate = (ra - m_startPos.X) / m_elapsedSecs * 60.0; // Raw max-min, can't smooth this one reliably FillResultCell(m_othergrid, m_ra_drift_loc, raDriftRate, raDriftRate * pxscale, PXPERMIN, ARCSECPERMIN); FillResultCell(m_othergrid, m_ra_peak_drift_loc, maxRateRA, maxRateRA * pxscale, PXPERSEC, ARCSECPERSEC); - m_othergrid->SetCellValue(m_ra_drift_exp_loc, maxRateRA <= 0.0 ? _(" ") : - wxString::Format("%6.1f %s ", 1.3 * rarms / maxRateRA, SEC)); // Will get revised when min-move is computed + m_othergrid->SetCellValue(m_ra_drift_exp_loc, + maxRateRA <= 0.0 + ? _(" ") + : wxString::Format("%6.1f %s ", 1.3 * rarms / maxRateRA, SEC)); // Will get revised when min-move is computed FillResultCell(m_othergrid, m_dec_drift_loc, decDriftPerMin, decDriftPerMin * pxscale, PXPERMIN, ARCSECPERMIN); - m_othergrid->SetCellValue(m_pae_loc, wxString::Format("%s %.1f %s", declination == UNKNOWN_DECLINATION ? "> " : "", alignmentError, ARCMIN)); + m_othergrid->SetCellValue( + m_pae_loc, wxString::Format("%s %.1f %s", declination == UNKNOWN_DECLINATION ? "> " : "", alignmentError, ARCMIN)); } } diff --git a/src/guiding_assistant.h b/src/guiding_assistant.h index 320fd44e8..b29c24ce4 100644 --- a/src/guiding_assistant.h +++ b/src/guiding_assistant.h @@ -1,36 +1,36 @@ /* -* guiding_assistant.h -* PHD Guiding -* -* Created by Andy Galasso -* Copyright (c) 2015 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * guiding_assistant.h + * PHD Guiding + * + * Created by Andy Galasso + * Copyright (c) 2015 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef GUIDING_ASSISTANT_INCLUDED #define GUIDING_ASSISTANT_INCLUDED diff --git a/src/guiding_stats.cpp b/src/guiding_stats.cpp index fd114b525..748c7b3da 100644 --- a/src/guiding_stats.cpp +++ b/src/guiding_stats.cpp @@ -1,37 +1,37 @@ /* -* guiding_stats.cpp -* PHD2 Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2018 Bruce Waddington -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * guiding_stats.cpp + * PHD2 Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2018 Bruce Waddington + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #include @@ -45,17 +45,14 @@ // differences, which can lead to things like negative variances // See: http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance -// DescriptiveStats is used for non-windowed datasets. Max, min, sigma and variance are computed on-the-fly as values are added to dataset -// Applicable to any double values, no semantic assumptions made. Does not retain a list of values +// DescriptiveStats is used for non-windowed datasets. Max, min, sigma and variance are computed on-the-fly as values are added +// to dataset Applicable to any double values, no semantic assumptions made. Does not retain a list of values DescriptiveStats::DescriptiveStats() { ClearAll(); } -DescriptiveStats::~DescriptiveStats() -{ - -} +DescriptiveStats::~DescriptiveStats() { } // Add a new double value, update stats void DescriptiveStats::AddValue(double Val) @@ -183,8 +180,8 @@ double DescriptiveStats::GetMaxDelta() return 0.; } -// Applies a high-pass filter to a stream of data, one sample point at a time. Samples are not retained, client can use DescriptiveStats or AxisStats -// on the filtered data values +// Applies a high-pass filter to a stream of data, one sample point at a time. Samples are not retained, client can use +// DescriptiveStats or AxisStats on the filtered data values HighPassFilter::HighPassFilter(double CutoffPeriod, double SamplePeriod) { alphaCutoff = CutoffPeriod / (CutoffPeriod + std::max(1.0, SamplePeriod)); @@ -276,9 +273,7 @@ AxisStats::AxisStats() InitializeScalars(); } -AxisStats::~AxisStats() -{ -} +AxisStats::~AxisStats() { } void AxisStats::ClearAll() { @@ -355,7 +350,7 @@ void AxisStats::AddGuideInfo(double DeltaT, double StarPos, double GuideAmt) if (newDelta >= maxDelta) { maxDelta = newDelta; - maxDeltaInx = guidingEntries.size(); // where the entry is going to go - furthest down in list among equals + maxDeltaInx = guidingEntries.size(); // where the entry is going to go - furthest down in list among equals } } @@ -475,7 +470,7 @@ double AxisStats::GetMedian() const double rslt = 0.; // Need a copy of guidingEntries to do a sort - std::vector sortedEntries; + std::vector sortedEntries; for (auto pGS = guidingEntries.begin(); pGS != guidingEntries.end(); ++pGS) { @@ -543,7 +538,8 @@ double AxisStats::GetLinearFitResults(double *Slope, double *Intercept, double * double currentMean = 0.; double slope = ((numVals * sumXY) - (sumX * sumY)) / ((numVals * sumXSq) - (sumX * sumX)); - //double constrainedSlope = sumXY / sumXSq; // Possible future use, slope value if intercept is constrained to be zero + // double constrainedSlope = sumXY / sumXSq; // Possible future use, slope value if intercept is constrained to be + // zero double intcpt = (sumY - (slope * sumX)) / numVals; if (Sigma) @@ -578,18 +574,17 @@ double AxisStats::GetLinearFitResults(double *Slope, double *Intercept, double * return rSquared; } -WindowedAxisStats::WindowedAxisStats(int AutoWindowSize) : AxisStats() +WindowedAxisStats::WindowedAxisStats(int AutoWindowSize) + : AxisStats() { autoWindowing = AutoWindowSize > 0; windowSize = AutoWindowSize; } -WindowedAxisStats::~WindowedAxisStats() -{ - -} +WindowedAxisStats::~WindowedAxisStats() { } -// Change the auto-window size - trim older entries if necessary. Setting size to zero disables auto-windowing but does not discard data +// Change the auto-window size - trim older entries if necessary. Setting size to zero disables auto-windowing but does not +// discard data bool WindowedAxisStats::ChangeWindowSize(unsigned int NewSize) { bool success = false; @@ -625,7 +620,7 @@ bool WindowedAxisStats::ChangeWindowSize(unsigned int NewSize) // entry[0] (the oldest) is actually removed. void WindowedAxisStats::AdjustMinMaxValues() { - StarDisplacement target = guidingEntries.front(); // Entry that's about to be removed + StarDisplacement target = guidingEntries.front(); // Entry that's about to be removed bool recalNeeded = false; double prev = target.StarPos; @@ -643,7 +638,8 @@ void WindowedAxisStats::AdjustMinMaxValues() if (recalNeeded) { - for (auto pGS = guidingEntries.begin() + 1; pGS != guidingEntries.end(); ++pGS) // Dont start at zero, that will be removed + for (auto pGS = guidingEntries.begin() + 1; pGS != guidingEntries.end(); + ++pGS) // Dont start at zero, that will be removed { StarDisplacement entry = *pGS; minDisplacement = std::min(minDisplacement, entry.StarPos); @@ -680,7 +676,7 @@ void WindowedAxisStats::RemoveOldestEntry() axisReversals--; if (target.Guided) axisMoves--; - AdjustMinMaxValues(); // Will process list only if required + AdjustMinMaxValues(); // Will process list only if required guidingEntries.pop_front(); maxDeltaInx--; } diff --git a/src/guiding_stats.h b/src/guiding_stats.h index e9a144d10..29412c231 100644 --- a/src/guiding_stats.h +++ b/src/guiding_stats.h @@ -1,76 +1,76 @@ /* -* guiding_stats.h -* PHD2 Guiding -* -* Created by Bruce Waddington -* Copyright (c) 2018 Bruce Waddington -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Bret McKee, Dad Dog Development, -* Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * guiding_stats.h + * PHD2 Guiding + * + * Created by Bruce Waddington + * Copyright (c) 2018 Bruce Waddington + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Bret McKee, Dad Dog Development, + * Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef _GUIDING_STATS_H #define _GUIDING_STATS_H #include -// DescriptiveStats is used for basic statistics. Max, min, sigma and variance are computed on-the-fly as values are added to a dataset -// Applicable to any double values, no semantic assumptions made. Does not retain a list of values +// DescriptiveStats is used for basic statistics. Max, min, sigma and variance are computed on-the-fly as values are added to a +// dataset Applicable to any double values, no semantic assumptions made. Does not retain a list of values class DescriptiveStats { private: int count; - double runningS; // S denotes square of deltas from mean (variance) + double runningS; // S denotes square of deltas from mean (variance) double newS; - double runningMean; // current mean of dataset + double runningMean; // current mean of dataset double newMean; - double minValue; // current min value of dataset - double maxValue; // current max value of dataset - double lastValue; // for clients to easily compute deltas - double maxDelta; // max absolute (delta(value)) + double minValue; // current min value of dataset + double maxValue; // current max value of dataset + double lastValue; // for clients to easily compute deltas + double maxDelta; // max absolute (delta(value)) public: DescriptiveStats(); ~DescriptiveStats(); - void AddValue(double Val); // Add a double value to the dataset - void ClearAll(); // Start over, reset all variables - unsigned int GetCount(); // Returns the count of the dataset - double GetLastValue(); // Returns the immediately previous value added to the dataset - double GetMean(); // Returns the mean value of the dataset - double GetSum(); // Sum of all added vars - double GetMinimum(); // Returns the min value - double GetMaximum(); // Returns the max value - double GetVariance(); // Variance for those who need it - double GetSigma(); // Returns the standard deviation - double GetPopulationSigma(); // Population sigma ('n' vs 'n-1') - double GetMaxDelta(); // Returns max of absolute delta(new - previous) values + void AddValue(double Val); // Add a double value to the dataset + void ClearAll(); // Start over, reset all variables + unsigned int GetCount(); // Returns the count of the dataset + double GetLastValue(); // Returns the immediately previous value added to the dataset + double GetMean(); // Returns the mean value of the dataset + double GetSum(); // Sum of all added vars + double GetMinimum(); // Returns the min value + double GetMaximum(); // Returns the max value + double GetVariance(); // Variance for those who need it + double GetSigma(); // Returns the standard deviation + double GetPopulationSigma(); // Population sigma ('n' vs 'n-1') + double GetMaxDelta(); // Returns max of absolute delta(new - previous) values }; -// High and Low pass filters can be used to filter a stream of data elements that can then be added to DescriptiveStats or AxisStats -// A low-pass filter will attenuate (dampen) high-frequency elements, a high-pass filter will do the opposite +// High and Low pass filters can be used to filter a stream of data elements that can then be added to DescriptiveStats or +// AxisStats A low-pass filter will attenuate (dampen) high-frequency elements, a high-pass filter will do the opposite // Examples: use a low-pass filter to emphasize low-frequency data fluctuations such as a slow linear drift // use a high-pass filter to ignore linear drift but emphasize more rapid fluctuations // Neither class retains any history of the data, the client is responsble for using the HPF/LPF values as needed @@ -117,32 +117,33 @@ struct StarDisplacement StarDisplacement(double When, double Where); }; -// AxisStats and the StarDisplacement class can be used to collect and evaluate typical guiding data. Datasets can be windowed or not. -// Windowing means the data collection is limited to the most recent entries. -// Windowed datasets will be automatically trimmed if AutoWindowSize > 0 or can be manually trimmed by client using RemoveOldestEntry() +// AxisStats and the StarDisplacement class can be used to collect and evaluate typical guiding data. Datasets can be windowed +// or not. Windowing means the data collection is limited to the most recent entries. Windowed datasets will be +// automatically trimmed if AutoWindowSize > 0 or can be manually trimmed by client using RemoveOldestEntry() class AxisStats { protected: - std::deque guidingEntries; // queue of elements in dataset - unsigned int axisMoves; // number of times in window when guide pulse was non-zero - unsigned int axisReversals; // number of times in window when guide pulse caused a direction reversal - double prevMove; // value of guide pulse in next-to-last entry - double prevPosition; // value of guide star location in next-to-last entry + std::deque guidingEntries; // queue of elements in dataset + unsigned int axisMoves; // number of times in window when guide pulse was non-zero + unsigned int axisReversals; // number of times in window when guide pulse caused a direction reversal + double prevMove; // value of guide pulse in next-to-last entry + double prevPosition; // value of guide star location in next-to-last entry // Variables used to compute stats in windowed AxisStats - double sumX; // Sum of the x values (deltaT values) - double sumY; // Sum of the y values (star position) - double sumXY; // Sum of (x * y) - double sumXSq; // Sum of (x squared) - double sumYSq; // Sum of (y squared) + double sumX; // Sum of the x values (deltaT values) + double sumY; // Sum of the y values (star position) + double sumXY; // Sum of (x * y) + double sumXSq; // Sum of (x squared) + double sumYSq; // Sum of (y squared) // Variables needed for windowed or non-windowed versions - double maxDisplacement; // maximum star position value in current dataset - double minDisplacement; // minimum star position value in current dataset - double maxDelta; // maximum absolute delta of incremental star deltas + double maxDisplacement; // maximum star position value in current dataset + double minDisplacement; // minimum star position value in current dataset + double maxDelta; // maximum absolute delta of incremental star deltas int maxDeltaInx; void InitializeScalars(); public: - // Constructor for 3 types of instance: non-windowed, windowed with automatic trimming of size, windowed but with client controlling actual window size + // Constructor for 3 types of instance: non-windowed, windowed with automatic trimming of size, windowed but with client + // controlling actual window size AxisStats(); ~AxisStats(); @@ -157,7 +158,8 @@ class AxisStats // Return the count of elements in the dataset unsigned int GetCount() const; - // Get the last entry added to the dataset - useful if client needs to do difference operations for time, star position, or guide amount + // Get the last entry added to the dataset - useful if client needs to do difference operations for time, star position, or + // guide amount StarDisplacement GetLastEntry() const; // Get the maximum y value in the dataset @@ -178,14 +180,14 @@ class AxisStats unsigned int GetMoveCount() const; unsigned int GetReversalCount() const; - // Perform a linear fit on the star position values in the dataset. Return usual slope and y-intercept values along with "constrained slope" - - // the slope when the y-intercept is forced to zero. Optionally, apply the fit to the original data values and computed the - // standard deviation (Sigma) of the resulting drift-removed dataset. Drift-removed data values are discarded, original data elements are unmodified - // Example 1: do a linear fit during calibration to compute an angle - "Sigma" is not needed - // Example 2: do a linear fit on Dec values during a GA run - use the slope to compute a polar alignment error, use Sigma to estimate seeing of drift-corrected Dec values - // Returns a coefficient of determination, R-Squared, a form of correlation assessment - double GetLinearFitResults(double* Slope, double* Intercept, double* Sigma = NULL) const; - + // Perform a linear fit on the star position values in the dataset. Return usual slope and y-intercept values along with + // "constrained slope" - the slope when the y-intercept is forced to zero. Optionally, apply the fit to the original data + // values and computed the standard deviation (Sigma) of the resulting drift-removed dataset. Drift-removed data values are + // discarded, original data elements are unmodified Example 1: do a linear fit during calibration to compute an angle - + // "Sigma" is not needed Example 2: do a linear fit on Dec values during a GA run - use the slope to compute a polar + // alignment error, use Sigma to estimate seeing of drift-corrected Dec values Returns a coefficient of determination, + // R-Squared, a form of correlation assessment + double GetLinearFitResults(double *Slope, double *Intercept, double *Sigma = NULL) const; }; class WindowedAxisStats : public AxisStats @@ -199,7 +201,8 @@ class WindowedAxisStats : public AxisStats WindowedAxisStats(int AutoWindowSize); ~WindowedAxisStats(); - // Change the window size of an active dataset - all stats will be adjusted accordingly to reflect the most recent elements + // Change the window size of an active dataset - all stats will be adjusted accordingly to reflect the most recent + // elements bool ChangeWindowSize(unsigned int NewWSize); void RemoveOldestEntry(); void AddGuideInfo(double DeltaT, double StarPos, double GuideAmt); diff --git a/src/guidinglog.cpp b/src/guidinglog.cpp index ffb9dda61..3a580a6df 100644 --- a/src/guidinglog.cpp +++ b/src/guidinglog.cpp @@ -43,24 +43,24 @@ const int RetentionPeriod = 60; GuidingLog::GuidingLog() - : - m_enabled(false), - m_keepFile(false), - m_isGuiding(false) + : m_enabled(false) + , m_keepFile(false) + , m_isGuiding(false) { } -GuidingLog::~GuidingLog() -{ -} +GuidingLog::~GuidingLog() { } static wxString PierSideStr(PierSide p) { switch (p) { - case PIER_SIDE_EAST: return "East"; - case PIER_SIDE_WEST: return "West"; - default: return "Unknown"; + case PIER_SIDE_EAST: + return "East"; + case PIER_SIDE_WEST: + return "West"; + default: + return "Unknown"; } } @@ -68,9 +68,12 @@ static wxString ParityStr(int p) { switch (p) { - case GUIDE_PARITY_EVEN: return "Even"; - case GUIDE_PARITY_ODD: return "Odd"; - default: return "N/A"; + case GUIDE_PARITY_EVEN: + return "Even"; + case GUIDE_PARITY_ODD: + return "Odd"; + default: + return "N/A"; } } @@ -119,8 +122,7 @@ static void GetAltAz(double Latitude, double HA, double Dec, double& Altitude, d // Now get azimuth - alternative formula using zSin avoids div-by-zero conditions double As = cos(decRadians) * sin(haRadians) / zSin; - double Ac = (sin(latRadians) * cos(decRadians) * cos(haRadians) - cos(latRadians) * - sin(decRadians)) / zSin; + double Ac = (sin(latRadians) * cos(decRadians) * cos(haRadians) - cos(latRadians) * sin(decRadians)) / zSin; // atan2 doesn't want both params = 0 if (Ac == 0.0 && As == 0.0) { @@ -152,7 +154,8 @@ static wxString PointingInfo() } else { - rslt = wxString::Format("RA/Dec = Unknown, Hour angle = Unknown, Pier side = Unknown, Rotator pos = %s, ", RotatorPosStr()); + rslt = wxString::Format( + "RA/Dec = Unknown, Hour angle = Unknown, Pier side = Unknown, Rotator pos = %s, ", RotatorPosStr()); pointingError = true; } if (pPointingSource && !pointingError && !pPointingSource->GetSiteLatLong(&latitude, &longitude)) @@ -193,11 +196,8 @@ static void GuidingHeader(wxFFile& file) const Star& star = pFrame->pGuider->PrimaryStar(); file.Write(wxString::Format("Lock position = %.3f, %.3f, Star position = %.3f, %.3f, HFD = %.2f px\n", - pFrame->pGuider->LockPosition().X, - pFrame->pGuider->LockPosition().Y, - pFrame->pGuider->CurrentPosition().X, - pFrame->pGuider->CurrentPosition().Y, - star.HFD)); + pFrame->pGuider->LockPosition().X, pFrame->pGuider->LockPosition().Y, pFrame->pGuider->CurrentPosition().X, + pFrame->pGuider->CurrentPosition().Y, star.HFD)); file.Write("Frame,Time,mount,dx,dy,RARawDistance,DECRawDistance,RAGuideDistance,DECGuideDistance," "RADuration,RADirection,DECDuration,DECDirection,XStep,YStep,StarMass,SNR,ErrorCode\n"); @@ -208,9 +208,8 @@ static void WriteSummaryInfo(wxFFile& file, const GuideLogSummaryInfo& summary) if (!summary.valid) return; - file.Write(wxString::Format("Log Summary: calcnt:%u gcnt:%u gdur:%.f gacnt:%u\n", - summary.cal_cnt, summary.guide_cnt, summary.guide_dur, - summary.ga_cnt)); + file.Write(wxString::Format("Log Summary: calcnt:%u gcnt:%u gdur:%.f gacnt:%u\n", summary.cal_cnt, summary.guide_cnt, + summary.guide_dur, summary.ga_cnt)); } void GuideLogSummaryInfo::LoadSummaryInfo(wxFFile& file) @@ -220,11 +219,25 @@ void GuideLogSummaryInfo::LoadSummaryInfo(wxFFile& file) wxFFileInputStream is(file); if (is.IsOk()) { - struct RestorePos { + struct RestorePos + { wxFFile& f; wxFileOffset o; - RestorePos(wxFFile& f_) : f(f_) { o = f.Tell(); } - ~RestorePos() { try { f.Seek(o); } catch (...) {} } + RestorePos(wxFFile& f_) + : f(f_) + { + o = f.Tell(); + } + ~RestorePos() + { + try + { + f.Seek(o); + } + catch (...) + { + } + } } restore(file); wxFileOffset ofs = wxMax(file.Length() - 128, 0LL); is.SeekI(ofs); @@ -282,7 +295,8 @@ void GuidingLog::EnableLogging() assert(m_file.IsOpened()); - m_file.Write(_T("PHD2 version ") FULLVER _T(" [") PHD_OSNAME _T("]") _T(", Log version ") GUIDELOG_VERSION _T(". Log enabled at ") + + m_file.Write(_T("PHD2 version ") FULLVER _T(" [") PHD_OSNAME _T("]") + _T(", Log version ") GUIDELOG_VERSION _T(". Log enabled at ") + logFileTime.Format(_T("%Y-%m-%d %H:%M:%S")) + "\n"); m_enabled = true; @@ -343,9 +357,9 @@ bool GuidingLog::ChangeDirLog(const wxString& newdir) ok = false; } - if (enabled) // if SetLogDir failed, no harm no foul, stay with original. Otherwise + if (enabled) // if SetLogDir failed, no harm no foul, stay with original. Otherwise { - EnableLogging(); // start fresh... + EnableLogging(); // start fresh... } return ok; @@ -400,7 +414,7 @@ void GuidingLog::CloseGuideLog() m_enabled = false; - if (!m_keepFile) // Delete the file if nothing useful was logged + if (!m_keepFile) // Delete the file if nothing useful was logged { wxRemove(m_fileName); } @@ -443,11 +457,8 @@ void GuidingLog::StartCalibration(const Mount *pCalibrationMount) const Star& star = pFrame->pGuider->PrimaryStar(); m_file.Write(wxString::Format("Lock position = %.3f, %.3f, Star position = %.3f, %.3f, HFD = %.2f px\n", - pFrame->pGuider->LockPosition().X, - pFrame->pGuider->LockPosition().Y, - pFrame->pGuider->CurrentPosition().X, - pFrame->pGuider->CurrentPosition().Y, - star.HFD)); + pFrame->pGuider->LockPosition().X, pFrame->pGuider->LockPosition().Y, pFrame->pGuider->CurrentPosition().X, + pFrame->pGuider->CurrentPosition().Y, star.HFD)); m_file.Write("Direction,Step,dx,dy,x,y,Dist\n"); @@ -465,7 +476,8 @@ void GuidingLog::CalibrationFailed(const Mount *pCalibrationMount, const wxStrin assert(m_file.IsOpened()); - m_file.Write(msg); m_file.Write("\n"); + m_file.Write(msg); + m_file.Write("\n"); Flush(); } @@ -477,25 +489,22 @@ void GuidingLog::CalibrationStep(const CalibrationStepInfo& info) assert(m_file.IsOpened()); // Direction,Step,dx,dy,x,y,Dist - m_file.Write(wxString::Format("%s,%d,%.3f,%.3f,%.3f,%.3f,%.3f\n", - info.direction, - info.stepNumber, - info.dx, info.dy, - info.pos.X, info.pos.Y, - info.dist)); + m_file.Write(wxString::Format("%s,%d,%.3f,%.3f,%.3f,%.3f,%.3f\n", info.direction, info.stepNumber, info.dx, info.dy, + info.pos.X, info.pos.Y, info.dist)); Flush(); } -void GuidingLog::CalibrationDirectComplete(const Mount *pCalibrationMount, const wxString& direction, double angle, double rate, int parity) +void GuidingLog::CalibrationDirectComplete( + const Mount *pCalibrationMount, const wxString& direction, double angle, double rate, int parity) { if (!m_enabled) return; assert(m_file.IsOpened()); - m_file.Write(wxString::Format("%s calibration complete. Angle = %.1f deg, Rate = %.3f px/sec, Parity = %s\n", - direction, degrees(angle), rate * 1000.0, ParityStr(parity))); + m_file.Write(wxString::Format("%s calibration complete. Angle = %.1f deg, Rate = %.3f px/sec, Parity = %s\n", direction, + degrees(angle), rate * 1000.0, ParityStr(parity))); Flush(); } @@ -559,12 +568,9 @@ void GuidingLog::GuideStep(const GuideStepInfo& step) assert(m_file.IsOpened()); - m_file.Write(wxString::Format("%d,%.3f,\"%s\",%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,", - step.frameNumber, step.time, - step.mount->IsStepGuider() ? "AO" : "Mount", - step.cameraOffset.X, step.cameraOffset.Y, - step.mountOffset.X, step.mountOffset.Y, - step.guideDistanceRA, step.guideDistanceDec)); + m_file.Write(wxString::Format("%d,%.3f,\"%s\",%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,", step.frameNumber, step.time, + step.mount->IsStepGuider() ? "AO" : "Mount", step.cameraOffset.X, step.cameraOffset.Y, step.mountOffset.X, + step.mountOffset.Y, step.guideDistanceRA, step.guideDistanceDec)); if (step.mount->IsStepGuider()) { @@ -574,13 +580,12 @@ void GuidingLog::GuideStep(const GuideStepInfo& step) } else { - m_file.Write(wxString::Format("%d,%s,%d,%s,,,", - step.durationRA, step.durationRA > 0 ? step.mount->DirectionChar((GUIDE_DIRECTION)step.directionRA) : "", - step.durationDec, step.durationDec > 0 ? step.mount->DirectionChar((GUIDE_DIRECTION)step.directionDec): "")); + m_file.Write(wxString::Format("%d,%s,%d,%s,,,", step.durationRA, + step.durationRA > 0 ? step.mount->DirectionChar((GUIDE_DIRECTION) step.directionRA) : "", step.durationDec, + step.durationDec > 0 ? step.mount->DirectionChar((GUIDE_DIRECTION) step.directionDec) : "")); } - m_file.Write(wxString::Format("%.f,%.2f,%d\n", - step.starMass, step.starSNR, step.starError)); + m_file.Write(wxString::Format("%.f,%.2f,%d\n", step.starMass, step.starSNR, step.starError)); Flush(); } @@ -592,8 +597,8 @@ void GuidingLog::FrameDropped(const FrameDroppedInfo& info) assert(m_file.IsOpened()); - m_file.Write(wxString::Format("%d,%.3f,\"DROP\",,,,,,,,,,,,,%.f,%.2f,%d,\"%s\"\n", - info.frameNumber, info.time, info.starMass, info.starSNR, info.starError, info.status)); + m_file.Write(wxString::Format("%d,%.3f,\"DROP\",,,,,,,,,,,,,%.f,%.2f,%d,\"%s\"\n", info.frameNumber, info.time, + info.starMass, info.starSNR, info.starError, info.status)); Flush(); } @@ -616,8 +621,8 @@ void GuidingLog::NotifyGuidingDithered(Guider *guider, double dx, double dy) if (!m_enabled || !m_isGuiding) return; - m_file.Write(wxString::Format("INFO: DITHER by %.3f, %.3f, new lock pos = %.3f, %.3f\n", - dx, dy, guider->LockPosition().X, guider->LockPosition().Y)); + m_file.Write(wxString::Format( + "INFO: DITHER by %.3f, %.3f, new lock pos = %.3f, %.3f\n", dx, dy, guider->LockPosition().X, guider->LockPosition().Y)); Flush(); } @@ -653,8 +658,8 @@ void GuidingLog::NotifySetLockPosition(Guider *guider) if (!m_enabled || !m_isGuiding) return; - m_file.Write(wxString::Format("INFO: SET LOCK POSITION, new lock pos = %.3f, %.3f\n", - guider->LockPosition().X, guider->LockPosition().Y)); + m_file.Write(wxString::Format( + "INFO: SET LOCK POSITION, new lock pos = %.3f, %.3f\n", guider->LockPosition().X, guider->LockPosition().Y)); Flush(); @@ -670,12 +675,10 @@ void GuidingLog::NotifyLockShiftParams(const LockPosShiftParams& shiftParams, co if (shiftParams.shiftEnabled) { details = wxString::Format("%s rate (%.2f,%.2f) %s/hr (%.2f,%.2f) px/hr", - shiftParams.shiftIsMountCoords ? "RA,Dec" : "X,Y", - shiftParams.shiftRate.IsValid() ? shiftParams.shiftRate.X : 0.0, - shiftParams.shiftRate.IsValid() ? shiftParams.shiftRate.Y : 0.0, - shiftParams.shiftUnits == UNIT_ARCSEC ? "arc-sec" : "pixels", - cameraRate.IsValid() ? cameraRate.X * 3600.0 : 0.0, - cameraRate.IsValid() ? cameraRate.Y * 3600.0 : 0.0); + shiftParams.shiftIsMountCoords ? "RA,Dec" : "X,Y", shiftParams.shiftRate.IsValid() ? shiftParams.shiftRate.X : 0.0, + shiftParams.shiftRate.IsValid() ? shiftParams.shiftRate.Y : 0.0, + shiftParams.shiftUnits == UNIT_ARCSEC ? "arc-sec" : "pixels", cameraRate.IsValid() ? cameraRate.X * 3600.0 : 0.0, + cameraRate.IsValid() ? cameraRate.Y * 3600.0 : 0.0); } m_file.Write(wxString::Format("INFO: LOCK SHIFT, enabled = %d %s\n", shiftParams.shiftEnabled, details)); @@ -700,10 +703,9 @@ void GuidingLog::NotifyManualGuide(const Mount *mount, int direction, int durati if (!m_enabled || !m_isGuiding) return; - m_file.Write(wxString::Format("INFO: Manual guide (%s) %s %d %s\n", - mount->IsStepGuider() ? "AO" : "Mount", - mount->DirectionStr(static_cast(direction)), duration, - mount->IsStepGuider() ? (duration != 1 ? "steps" : "step") : "ms")); + m_file.Write(wxString::Format("INFO: Manual guide (%s) %s %d %s\n", mount->IsStepGuider() ? "AO" : "Mount", + mount->DirectionStr(static_cast(direction)), duration, + mount->IsStepGuider() ? (duration != 1 ? "steps" : "step") : "ms")); Flush(); m_keepFile = true; diff --git a/src/guidinglog.h b/src/guidinglog.h index dbae59f8b..3cbd45714 100644 --- a/src/guidinglog.h +++ b/src/guidinglog.h @@ -53,10 +53,18 @@ struct CalibrationStepInfo double dist; wxString msg; - CalibrationStepInfo(Mount *mount_, const wxString& dir_, int stepNumber_, double dx_, - double dy_, const PHD_Point& pos_, double dist_, const wxString& msg_ = wxEmptyString) - : mount(mount_), direction(dir_), stepNumber(stepNumber_), dx(dx_), dy(dy_), pos(pos_), - dist(dist_), msg(msg_) { } + CalibrationStepInfo(Mount *mount_, const wxString& dir_, int stepNumber_, double dx_, double dy_, const PHD_Point& pos_, + double dist_, const wxString& msg_ = wxEmptyString) + : mount(mount_) + , direction(dir_) + , stepNumber(stepNumber_) + , dx(dx_) + , dy(dy_) + , pos(pos_) + , dist(dist_) + , msg(msg_) + { + } }; struct GuideStepInfo @@ -143,8 +151,8 @@ class GuidingLog : public Logger void StartCalibration(const Mount *pCalibrationMount); void CalibrationFailed(const Mount *pCalibrationMount, const wxString& msg); void CalibrationStep(const CalibrationStepInfo& info); - void CalibrationDirectComplete(const Mount *pCalibrationMount, const wxString& direction, - double angle, double rate, int parity); + void CalibrationDirectComplete( + const Mount *pCalibrationMount, const wxString& direction, double angle, double rate, int parity); void CalibrationComplete(const Mount *pCalibrationMount); void GuidingStarted(); diff --git a/src/image_math.cpp b/src/image_math.cpp index 708d992bc..df78e5ee6 100644 --- a/src/image_math.cpp +++ b/src/image_math.cpp @@ -41,7 +41,7 @@ #include -int dbl_sort_func (double *first, double *second) +int dbl_sort_func(double *first, double *second) { if (*first < *second) return -1; @@ -64,7 +64,7 @@ double CalcSlope(const ArrayOfDbl& y) for (int x = 0; x < nn; x++) { - s_xy += (double)(x + 1) * y[x]; + s_xy += (double) (x + 1) * y[x]; s_y += y[x]; } @@ -114,17 +114,17 @@ bool QuickLRecon(usImage& img) for (int x = 0; x <= RW - 2; x++) { - t = img.ImageData[IX(x , y )]; - t += img.ImageData[IX(x + 1, y )]; - t += img.ImageData[IX(x , y + 1)]; + t = img.ImageData[IX(x, y)]; + t += img.ImageData[IX(x + 1, y)]; + t += img.ImageData[IX(x, y + 1)]; t += img.ImageData[IX(x + 1, y + 1)]; - *d++ = (unsigned short)(t >> 2); + *d++ = (unsigned short) (t >> 2); } // last col - t = img.ImageData[IX(RW - 1, y )]; + t = img.ImageData[IX(RW - 1, y)]; t += img.ImageData[IX(RW - 1, y + 1)]; - *d = (unsigned short)(t >> 1); + *d = (unsigned short) (t >> 1); } // last row @@ -133,9 +133,9 @@ bool QuickLRecon(usImage& img) for (int x = 0; x <= RW - 2; x++) { - t = img.ImageData[IX(x , RH - 1)]; + t = img.ImageData[IX(x, RH - 1)]; t += img.ImageData[IX(x + 1, RH - 1)]; - *d++ = (unsigned short)(t >> 1); + *d++ = (unsigned short) (t >> 1); } // bottom-right pixel @@ -184,34 +184,58 @@ inline static unsigned short median9(const unsigned short l[9]) unsigned short l0 = l[0], l1 = l[1], l2 = l[2], l3 = l[3], l4 = l[4]; unsigned short x; x = l[5]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); - if (x < l4) swap(x, l4); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); + if (x < l4) + swap(x, l4); x = l[6]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); - if (x < l4) swap(x, l4); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); + if (x < l4) + swap(x, l4); x = l[7]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); - if (x < l4) swap(x, l4); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); + if (x < l4) + swap(x, l4); x = l[8]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); - if (x < l4) swap(x, l4); - - if (l1 > l0) l0 = l1; - if (l2 > l0) l0 = l2; - if (l3 > l0) l0 = l3; - if (l4 > l0) l0 = l4; + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); + if (x < l4) + swap(x, l4); + + if (l1 > l0) + l0 = l1; + if (l2 > l0) + l0 = l2; + if (l3 > l0) + l0 = l3; + if (l4 > l0) + l0 = l4; return l0; } @@ -222,34 +246,55 @@ inline static unsigned short median8(const unsigned short l[8]) unsigned short x; x = l[5]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); - if (x < l4) swap(x, l4); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); + if (x < l4) + swap(x, l4); x = l[6]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); - if (x < l4) swap(x, l4); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); + if (x < l4) + swap(x, l4); x = l[7]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); - if (x < l4) swap(x, l4); - - if (l2 > l0) swap(l2, l0); - if (l2 > l1) swap(l2, l1); - - if (l3 > l0) swap(l3, l0); - if (l3 > l1) swap(l3, l1); - - if (l4 > l0) swap(l4, l0); - if (l4 > l1) swap(l4, l1); - - return (unsigned short)(((unsigned int) l0 + (unsigned int) l1) / 2); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); + if (x < l4) + swap(x, l4); + + if (l2 > l0) + swap(l2, l0); + if (l2 > l1) + swap(l2, l1); + + if (l3 > l0) + swap(l3, l0); + if (l3 > l1) + swap(l3, l1); + + if (l4 > l0) + swap(l4, l0); + if (l4 > l1) + swap(l4, l1); + + return (unsigned short) (((unsigned int) l0 + (unsigned int) l1) / 2); } inline static unsigned short median6(const unsigned short l[6]) @@ -258,23 +303,35 @@ inline static unsigned short median6(const unsigned short l[6]) unsigned short x; x = l[4]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); x = l[5]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - if (x < l3) swap(x, l3); - - if (l2 > l0) swap(l2, l0); - if (l2 > l1) swap(l2, l1); - - if (l3 > l0) swap(l3, l0); - if (l3 > l1) swap(l3, l1); - - return (unsigned short)(((unsigned int) l0 + (unsigned int) l1) / 2); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + if (x < l3) + swap(x, l3); + + if (l2 > l0) + swap(l2, l0); + if (l2 > l1) + swap(l2, l1); + + if (l3 > l0) + swap(l3, l0); + if (l3 > l1) + swap(l3, l1); + + return (unsigned short) (((unsigned int) l0 + (unsigned int) l1) / 2); } inline static unsigned short median5(const unsigned short l[5]) @@ -282,16 +339,24 @@ inline static unsigned short median5(const unsigned short l[5]) unsigned short l0 = l[0], l1 = l[1], l2 = l[2]; unsigned short x; x = l[3]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); x = l[4]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - - if (l1 > l0) l0 = l1; - if (l2 > l0) l0 = l2; + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + + if (l1 > l0) + l0 = l1; + if (l2 > l0) + l0 = l2; return l0; } @@ -301,22 +366,30 @@ inline static unsigned short median4(const unsigned short l[4]) unsigned short l0 = l[0], l1 = l[1], l2 = l[2]; unsigned short x; x = l[3]; - if (x < l0) swap(x, l0); - if (x < l1) swap(x, l1); - if (x < l2) swap(x, l2); - - if (l2 > l0) swap(l2, l0); - if (l2 > l1) swap(l2, l1); - - return (unsigned short)(((unsigned int) l0 + (unsigned int) l1) / 2); + if (x < l0) + swap(x, l0); + if (x < l1) + swap(x, l1); + if (x < l2) + swap(x, l2); + + if (l2 > l0) + swap(l2, l0); + if (l2 > l1) + swap(l2, l1); + + return (unsigned short) (((unsigned int) l0 + (unsigned int) l1) / 2); } inline static unsigned short median3(const unsigned short l[3]) { unsigned short l0 = l[0], l1 = l[1], l2 = l[2]; - if (l2 < l0) swap(l2, l0); - if (l2 < l1) swap(l2, l1); - if (l1 > l0) l0 = l1; + if (l2 < l0) + swap(l2, l0); + if (l2 < l1) + swap(l2, l1); + if (l1 > l0) + l0 = l1; return l0; } @@ -347,10 +420,10 @@ void Median3(unsigned short *dst, const unsigned short *src, const wxSize& size, for (int x = 1; x <= RW - 2; x++) { a[0] = src[IX(x - 1, 0)]; - a[1] = src[IX(x, 0)]; + a[1] = src[IX(x, 0)]; a[2] = src[IX(x + 1, 0)]; a[3] = src[IX(x - 1, 1)]; - a[4] = src[IX(x, 1)]; + a[4] = src[IX(x, 1)]; a[5] = src[IX(x + 1, 1)]; *d++ = median6(a); } @@ -369,8 +442,8 @@ void Median3(unsigned short *dst, const unsigned short *src, const wxSize& size, // leftmost pixel a[0] = src[IX(0, y - 1)]; a[1] = src[IX(1, y - 1)]; - a[2] = src[IX(0, y )]; - a[3] = src[IX(1, y )]; + a[2] = src[IX(0, y)]; + a[3] = src[IX(1, y)]; a[4] = src[IX(0, y + 1)]; a[5] = src[IX(1, y + 1)]; *d++ = median6(a); @@ -378,13 +451,13 @@ void Median3(unsigned short *dst, const unsigned short *src, const wxSize& size, for (int x = 1; x <= RW - 2; x++) { a[0] = src[IX(x - 1, y - 1)]; - a[1] = src[IX(x , y - 1)]; + a[1] = src[IX(x, y - 1)]; a[2] = src[IX(x + 1, y - 1)]; - a[3] = src[IX(x - 1, y )]; - a[4] = src[IX(x , y )]; - a[5] = src[IX(x + 1, y )]; + a[3] = src[IX(x - 1, y)]; + a[4] = src[IX(x, y)]; + a[5] = src[IX(x + 1, y)]; a[6] = src[IX(x - 1, y + 1)]; - a[7] = src[IX(x , y + 1)]; + a[7] = src[IX(x, y + 1)]; a[8] = src[IX(x + 1, y + 1)]; *d++ = median9(a); } @@ -392,8 +465,8 @@ void Median3(unsigned short *dst, const unsigned short *src, const wxSize& size, // rightmost pixel a[0] = src[IX(RW - 2, y - 1)]; a[1] = src[IX(RW - 1, y - 1)]; - a[2] = src[IX(RW - 2, y )]; - a[3] = src[IX(RW - 1, y )]; + a[2] = src[IX(RW - 2, y)]; + a[3] = src[IX(RW - 1, y)]; a[4] = src[IX(RW - 2, y + 1)]; a[5] = src[IX(RW - 1, y + 1)]; *d++ = median6(a); @@ -413,10 +486,10 @@ void Median3(unsigned short *dst, const unsigned short *src, const wxSize& size, for (int x = 1; x <= RW - 2; x++) { a[0] = src[IX(x - 1, RH - 2)]; - a[1] = src[IX(x , RH - 2)]; + a[1] = src[IX(x, RH - 2)]; a[2] = src[IX(x + 1, RH - 2)]; a[3] = src[IX(x - 1, RH - 1)]; - a[4] = src[IX(x , RH - 1)]; + a[4] = src[IX(x, RH - 1)]; a[5] = src[IX(x + 1, RH - 1)]; *d++ = median6(a); } @@ -439,24 +512,24 @@ static unsigned short MedianBorderingPixels(const usImage& img, int x, int y) if (x > 0 && y > 0 && x < xsize - 1 && y < ysize - 1) { - array[0] = img.ImageData[(x-1) + (y-1) * xsize]; - array[1] = img.ImageData[(x) + (y-1) * xsize]; - array[2] = img.ImageData[(x+1) + (y-1) * xsize]; - array[3] = img.ImageData[(x-1) + (y) * xsize]; - array[4] = img.ImageData[(x+1) + (y) * xsize]; - array[5] = img.ImageData[(x-1) + (y+1) * xsize]; - array[6] = img.ImageData[(x) + (y+1) * xsize]; - array[7] = img.ImageData[(x+1) + (y+1) * xsize]; + array[0] = img.ImageData[(x - 1) + (y - 1) * xsize]; + array[1] = img.ImageData[(x) + (y - 1) * xsize]; + array[2] = img.ImageData[(x + 1) + (y - 1) * xsize]; + array[3] = img.ImageData[(x - 1) + (y) *xsize]; + array[4] = img.ImageData[(x + 1) + (y) *xsize]; + array[5] = img.ImageData[(x - 1) + (y + 1) * xsize]; + array[6] = img.ImageData[(x) + (y + 1) * xsize]; + array[7] = img.ImageData[(x + 1) + (y + 1) * xsize]; return median8(array); } if (x == 0 && y > 0 && y < ysize - 1) { // On left edge - array[0] = img.ImageData[(x) + (y - 1) * xsize]; - array[1] = img.ImageData[(x) + (y + 1) * xsize]; + array[0] = img.ImageData[(x) + (y - 1) * xsize]; + array[1] = img.ImageData[(x) + (y + 1) * xsize]; array[2] = img.ImageData[(x + 1) + (y - 1) * xsize]; - array[3] = img.ImageData[(x + 1) + (y) * xsize]; + array[3] = img.ImageData[(x + 1) + (y) *xsize]; array[4] = img.ImageData[(x + 1) + (y + 1) * xsize]; return median5(array); } @@ -464,10 +537,10 @@ static unsigned short MedianBorderingPixels(const usImage& img, int x, int y) if (x == xsize - 1 && y > 0 && y < ysize - 1) { // On right edge - array[0] = img.ImageData[(x) + (y - 1) * xsize]; - array[1] = img.ImageData[(x) + (y + 1) * xsize]; + array[0] = img.ImageData[(x) + (y - 1) * xsize]; + array[1] = img.ImageData[(x) + (y + 1) * xsize]; array[2] = img.ImageData[(x - 1) + (y - 1) * xsize]; - array[3] = img.ImageData[(x - 1) + (y) * xsize]; + array[3] = img.ImageData[(x - 1) + (y) *xsize]; array[4] = img.ImageData[(x - 1) + (y + 1) * xsize]; return median5(array); } @@ -475,10 +548,10 @@ static unsigned short MedianBorderingPixels(const usImage& img, int x, int y) if (y == 0 && x > 0 && x < xsize - 1) { // On bottom edge - array[0] = img.ImageData[(x - 1) + (y) * xsize]; + array[0] = img.ImageData[(x - 1) + (y) *xsize]; array[1] = img.ImageData[(x - 1) + (y + 1) * xsize]; - array[2] = img.ImageData[(x) + (y + 1) * xsize]; - array[3] = img.ImageData[(x + 1) + (y) * xsize]; + array[2] = img.ImageData[(x) + (y + 1) * xsize]; + array[3] = img.ImageData[(x + 1) + (y) *xsize]; array[4] = img.ImageData[(x + 1) + (y + 1) * xsize]; return median5(array); } @@ -486,10 +559,10 @@ static unsigned short MedianBorderingPixels(const usImage& img, int x, int y) if (y == ysize - 1 && x > 0 && x < xsize - 1) { // On top edge - array[0] = img.ImageData[(x - 1) + (y) * xsize]; + array[0] = img.ImageData[(x - 1) + (y) *xsize]; array[1] = img.ImageData[(x - 1) + (y - 1) * xsize]; - array[2] = img.ImageData[(x) + (y - 1) * xsize]; - array[3] = img.ImageData[(x + 1) + (y) * xsize]; + array[2] = img.ImageData[(x) + (y - 1) * xsize]; + array[3] = img.ImageData[(x + 1) + (y) *xsize]; array[4] = img.ImageData[(x + 1) + (y - 1) * xsize]; return median5(array); } @@ -497,29 +570,29 @@ static unsigned short MedianBorderingPixels(const usImage& img, int x, int y) if (x == 0 && y == 0) { // At lower left corner - array[0] = img.ImageData[(x + 1) + (y) * xsize]; - array[1] = img.ImageData[(x) + (y + 1) * xsize]; + array[0] = img.ImageData[(x + 1) + (y) *xsize]; + array[1] = img.ImageData[(x) + (y + 1) * xsize]; array[2] = img.ImageData[(x + 1) + (y + 1) * xsize]; } else if (x == 0 && y == ysize - 1) { // At upper left corner - array[0] = img.ImageData[(x + 1) + (y) * xsize]; - array[1] = img.ImageData[(x) + (y - 1) * xsize]; + array[0] = img.ImageData[(x + 1) + (y) *xsize]; + array[1] = img.ImageData[(x) + (y - 1) * xsize]; array[2] = img.ImageData[(x + 1) + (y - 1) * xsize]; } else if (x == xsize - 1 && y == ysize - 1) { // At upper right corner - array[0] = img.ImageData[(x - 1) + (y) * xsize]; - array[1] = img.ImageData[(x) + (y - 1) * xsize]; + array[0] = img.ImageData[(x - 1) + (y) *xsize]; + array[1] = img.ImageData[(x) + (y - 1) * xsize]; array[2] = img.ImageData[(x - 1) + (y - 1) * xsize]; } else if (x == xsize - 1 && y == 0) { // At lower right corner - array[0] = img.ImageData[(x - 1) + (y) * xsize]; - array[1] = img.ImageData[(x) + (y + 1) * xsize]; + array[0] = img.ImageData[(x - 1) + (y) *xsize]; + array[1] = img.ImageData[(x) + (y + 1) * xsize]; array[2] = img.ImageData[(x - 1) + (y + 1) * xsize]; } else @@ -551,10 +624,10 @@ bool SquarePixels(usImage& img, float xsize, float ysize) // if X > Y, when viewing stock, Y is unnaturally stretched, so stretch X to match double ratio = ysize / xsize; - int newsize = ROUND((double) tempimg.Size.GetWidth() / ratio); // make new image correct size - img.Init(newsize,tempimg.Size.GetHeight()); + int newsize = ROUND((double) tempimg.Size.GetWidth() / ratio); // make new image correct size + img.Init(newsize, tempimg.Size.GetHeight()); unsigned short *optr = img.ImageData; - int linesize = tempimg.Size.GetWidth(); // size of an original line + int linesize = tempimg.Size.GetWidth(); // size of an original line for (int y = 0; y < img.Size.GetHeight(); y++) { for (int x = 0; x < newsize; x++, optr++) @@ -565,7 +638,8 @@ bool SquarePixels(usImage& img, float xsize, float ysize) if (ind2 > (tempimg.Size.GetWidth() - 1)) ind2 = tempimg.Size.GetWidth() - 1; double weight = ceil(oldposition) - oldposition; - *optr = (unsigned short) (((float) *(tempimg.ImageData + y*linesize + ind1) * weight) + ((float) *(tempimg.ImageData + y*linesize + ind1) * (1.0 - weight))); + *optr = (unsigned short) (((float) *(tempimg.ImageData + y * linesize + ind1) * weight) + + ((float) *(tempimg.ImageData + y * linesize + ind1) * (1.0 - weight))); } } @@ -584,7 +658,7 @@ bool Subtract(usImage& light, const usImage& dark) unsigned int left, top, width, height; unsigned short median_light, median_dark; - median_light = light.MedianADU; // median of frame or subframe + median_light = light.MedianADU; // median of frame or subframe if (!light.Subframe.IsEmpty()) { @@ -619,13 +693,12 @@ bool Subtract(usImage& light, const usImage& dark) if (median_dark > median_light) { // dark was brighter than light - light.Pedestal = median_dark - median_light; // Needed for saturation detection in find-star + light.Pedestal = median_dark - median_light; // Needed for saturation detection in find-star } unsigned short *pl0 = &light.Pixel(left, top); const unsigned short *pd0 = &dark.Pixel(left, top); - for (unsigned int r = 0; r < height; - r++, pl0 += light.Size.GetWidth(), pd0 += light.Size.GetWidth()) + for (unsigned int r = 0; r < height; r++, pl0 += light.Size.GetWidth(), pd0 += light.Size.GetWidth()) { unsigned short *const endl = pl0 + width; unsigned short *pl; @@ -633,8 +706,10 @@ bool Subtract(usImage& light, const usImage& dark) for (pl = pl0, pd = pd0; pl < endl; pl++, pd++) { int newval = (int) *pl + light.Pedestal - (int) *pd; - if (newval < 0) newval = 0; // hot pixel in dark frame isn't present in light frame - else if (newval > 65535) newval = 65535; + if (newval < 0) + newval = 0; // hot pixel in dark frame isn't present in light frame + else if (newval > 65535) + newval = 65535; *pl = (unsigned short) newval; } } @@ -791,7 +866,10 @@ static void GetImageStats(ImageStatsWork& w, const usImage& img, const wxRect& w void DefectMapDarks::BuildFilteredDark() { - enum { WINDOW = 15 }; + enum + { + WINDOW = 15 + }; filteredDark.Init(masterDark.Size); MedianFilter(filteredDark, masterDark, WINDOW); } @@ -838,7 +916,12 @@ struct BadPx int v; BadPx(); - BadPx(int x_, int y_, int v_) : x(x_), y(y_), v(v_) { } + BadPx(int x_, int y_, int v_) + : x(x_) + , y(y_) + , v(v_) + { + } bool operator<(const BadPx& rhs) const { return v < rhs.v; } }; @@ -860,12 +943,12 @@ struct DefectMapBuilderImpl bool threshValid; DefectMapBuilderImpl() - : - darks(0), - aggrCold(100), - aggrHot(100), - threshValid(false) - { } + : darks(0) + , aggrCold(100) + , aggrHot(100) + , threshValid(false) + { + } }; DefectMapBuilder::DefectMapBuilder() @@ -881,7 +964,7 @@ DefectMapBuilder::~DefectMapBuilder() inline static double AggrToSigma(int val) { // Aggressiveness of 0 to 100 maps to signma factor from 8.0 to 0.125 - return exp2(3.0 - (6.0 / 100.0) * (double)val); + return exp2(3.0 - (6.0 / 100.0) * (double) val); } void DefectMapBuilder::Init(DefectMapDarks& darks) @@ -890,17 +973,17 @@ void DefectMapBuilder::Init(DefectMapDarks& darks) Debug.AddLine("DefectMapBuilder: Init"); - ::GetImageStats(m_impl->w, darks.masterDark, - wxRect(0, 0, darks.masterDark.Size.GetWidth(), darks.masterDark.Size.GetHeight())); + ::GetImageStats( + m_impl->w, darks.masterDark, wxRect(0, 0, darks.masterDark.Size.GetWidth(), darks.masterDark.Size.GetHeight())); const ImageStats& stats = m_impl->w.stats; Debug.Write(wxString::Format("DefectMapBuilder: Dark N = %u Mean = %.f Median = %d Standard Deviation = %.f MAD=%d\n", - darks.masterDark.NPixels, stats.mean, stats.median, stats.stdev, stats.mad)); + darks.masterDark.NPixels, stats.mean, stats.median, stats.stdev, stats.mad)); // load potential defects - int thresh = (int)(AggrToSigma(100) * stats.stdev); + int thresh = (int) (AggrToSigma(100) * stats.stdev); Debug.Write(wxString::Format("DefectMapBuilder: load potential defects thresh = %d\n", thresh)); @@ -954,8 +1037,8 @@ static void FindThresh(DefectMapBuilderImpl *impl) int coldThresh = (int) (multCold * impl->w.stats.stdev); int hotThresh = (int) (multHot * impl->w.stats.stdev); - Debug.Write(wxString::Format("DefectMap: find thresholds aggr:(%d,%d) sigma:(%.1f,%.1f) px:(%+d,%+d)\n", - impl->aggrCold, impl->aggrHot, multCold, multHot, -coldThresh, hotThresh)); + Debug.Write(wxString::Format("DefectMap: find thresholds aggr:(%d,%d) sigma:(%.1f,%.1f) px:(%+d,%+d)\n", impl->aggrCold, + impl->aggrHot, multCold, multHot, -coldThresh, hotThresh)); impl->coldPxThresh = impl->coldPx.lower_bound(BadPx(0, 0, coldThresh)); impl->hotPxThresh = impl->hotPx.lower_bound(BadPx(0, 0, hotThresh)); @@ -980,7 +1063,8 @@ int DefectMapBuilder::GetHotPixelCnt() const return m_impl->hotPxSelected; } -inline static unsigned int emit_defects(DefectMap& defectMap, BadPxSet::const_iterator p0, BadPxSet::const_iterator p1, double stdev, int sign, bool verbose) +inline static unsigned int emit_defects( + DefectMap& defectMap, BadPxSet::const_iterator p0, BadPxSet::const_iterator p1, double stdev, int sign, bool verbose) { unsigned int cnt = 0; for (BadPxSet::const_iterator it = p0; it != p1; ++it, ++cnt) @@ -988,7 +1072,8 @@ inline static unsigned int emit_defects(DefectMap& defectMap, BadPxSet::const_it if (verbose) { int v = sign * it->v; - Debug.Write(wxString::Format("DefectMap: defect @ (%d, %d) val = %d (%+.1f sigma)\n", it->x, it->y, v, stdev > 0.1 ? (double)v / stdev : 0.0)); + Debug.Write(wxString::Format("DefectMap: defect @ (%d, %d) val = %d (%+.1f sigma)\n", it->x, it->y, v, + stdev > 0.1 ? (double) v / stdev : 0.0)); } defectMap.push_back(wxPoint(it->x, it->y)); } @@ -1017,13 +1102,14 @@ void DefectMapBuilder::BuildDefectMap(DefectMap& defectMap, bool verbose) const info.push_back(wxString::Format("Median: %d", stats.median)); info.push_back(wxString::Format("MAD: %d", stats.mad)); - int deltaCold = (int)(multCold * stats.stdev); - int deltaHot = (int)(multHot * stats.stdev); + int deltaCold = (int) (multCold * stats.stdev); + int deltaHot = (int) (multHot * stats.stdev); info.push_back(wxString::Format("DeltaCold: %+d", -deltaCold)); info.push_back(wxString::Format("DeltaHot: %+d", deltaHot)); - if (verbose) Debug.Write(wxString::Format("DefectMap: deltaCold = %+d deltaHot = %+d\n", -deltaCold, deltaHot)); + if (verbose) + Debug.Write(wxString::Format("DefectMap: deltaCold = %+d deltaHot = %+d\n", -deltaCold, deltaHot)); FindThresh(m_impl); @@ -1031,7 +1117,9 @@ void DefectMapBuilder::BuildDefectMap(DefectMap& defectMap, bool verbose) const unsigned int nr_cold = emit_defects(defectMap, m_impl->coldPxThresh, m_impl->coldPx.end(), stats.stdev, -1, verbose); unsigned int nr_hot = emit_defects(defectMap, m_impl->hotPxThresh, m_impl->hotPx.end(), stats.stdev, +1, verbose); - if (verbose) Debug.Write(wxString::Format("New defect map created, count=%d (cold=%d, hot=%d)\n", defectMap.size(), nr_cold, nr_hot)); + if (verbose) + Debug.Write( + wxString::Format("New defect map created, count=%d (cold=%d, hot=%d)\n", defectMap.size(), nr_cold, nr_hot)); } const wxArrayString& DefectMapBuilder::GetMapInfo() const @@ -1096,7 +1184,8 @@ bool DefectMap::ImportFromProfile(int srcId, int destId) rslt = wxCopyFile(sourceName, destName, true); if (rslt != 1) { - Debug.Write(wxString::Format("DefectMap::ImportFromProfile failed on defect map copy of %s to %s\n", sourceName, destName)); + Debug.Write( + wxString::Format("DefectMap::ImportFromProfile failed on defect map copy of %s to %s\n", sourceName, destName)); return false; } sourceName = DefectMapMasterPath(srcId); @@ -1104,7 +1193,8 @@ bool DefectMap::ImportFromProfile(int srcId, int destId) rslt = wxCopyFile(sourceName, destName, true); if (rslt != 1) { - Debug.Write(wxString::Format("DefectMap::ImportFromProfile failed on defect map master dark copy of %s to %s\n", sourceName, destName)); + Debug.Write(wxString::Format( + "DefectMap::ImportFromProfile failed on defect map master dark copy of %s to %s\n", sourceName, destName)); return false; } sourceName = DefectMapFilterPath(srcId); @@ -1112,7 +1202,8 @@ bool DefectMap::ImportFromProfile(int srcId, int destId) rslt = wxCopyFile(sourceName, destName, true); if (rslt != 1) { - Debug.Write(wxString::Format("DefectMap::ImportFromProfile failed on defect map master filtered dark copy of %s to %s\n", sourceName, destName)); + Debug.Write(wxString::Format( + "DefectMap::ImportFromProfile failed on defect map master filtered dark copy of %s to %s\n", sourceName, destName)); return false; } return (true); @@ -1134,7 +1225,7 @@ bool DefectMap::DefectMapExists(int profileId, bool showAlert) else { fitsfile *fptr; - int status = 0; // CFITSIO status value MUST be initialized to zero! + int status = 0; // CFITSIO status value MUST be initialized to zero! if (PHD_fits_open_diskfile(&fptr, fName, READONLY, &status) == 0) { @@ -1144,8 +1235,10 @@ bool DefectMap::DefectMapExists(int profileId, bool showAlert) bOk = true; else { - Debug.AddLine(wxString::Format("BPM check: failed geometry check - fits status = %d, cam dimensions = {%d,%d}, " - " BPM dimensions = {%d,%d}", status, sensorSize.x, sensorSize.y, fsize[0], fsize[1])); + Debug.AddLine( + wxString::Format("BPM check: failed geometry check - fits status = %d, cam dimensions = {%d,%d}, " + " BPM dimensions = {%d,%d}", + status, sensorSize.x, sensorSize.y, fsize[0], fsize[1])); if (showAlert) pFrame->Alert(_("Bad-pixel map does not match the camera in this profile - it needs to be replaced.")); } diff --git a/src/image_math.h b/src/image_math.h index aad0ed6ad..ada079172 100644 --- a/src/image_math.h +++ b/src/image_math.h @@ -40,6 +40,7 @@ class DefectMap : public std::vector { int m_profileId; DefectMap(int profileId); + public: static void DeleteDefectMap(int profileId); static bool DefectMapExists(int profileId, bool showAlert); @@ -50,7 +51,6 @@ class DefectMap : public std::vector void Save(const wxArrayString& mapInfo) const; bool FindDefect(const wxPoint& pt) const; void AddDefect(const wxPoint& pt); - }; extern bool QuickLRecon(usImage& img); @@ -87,7 +87,6 @@ class DefectMapBuilder DefectMapBuilderImpl *m_impl; public: - DefectMapBuilder(); ~DefectMapBuilder(); @@ -165,11 +164,9 @@ static void BinPixels(T *dst, const T *src, const wxSize& srcsize, unsigned int { for (int srcx = 0; srcx < srcw; srcx += 2) { - *dstp++ = - ((unsigned int) src[srcy * srcw + srcx] + - (unsigned int) src[srcy * srcw + srcx + 1] + - (unsigned int) src[(srcy + 1) * srcw + srcx] + - (unsigned int) src[(srcy + 1) * srcw + srcx + 1]) / 4; + *dstp++ = ((unsigned int) src[srcy * srcw + srcx] + (unsigned int) src[srcy * srcw + srcx + 1] + + (unsigned int) src[(srcy + 1) * srcw + srcx] + (unsigned int) src[(srcy + 1) * srcw + srcx + 1]) / + 4; } } } @@ -182,15 +179,12 @@ static void BinPixels(T *dst, const T *src, const wxSize& srcsize, unsigned int for (int srcx = 0; srcx < tw; srcx += 3) { *dstp++ = - ((unsigned int) src[srcy * srcw + srcx] + - (unsigned int) src[srcy * srcw + srcx + 1] + - (unsigned int) src[srcy * srcw + srcx + 2] + - (unsigned int) src[(srcy + 1) * srcw + srcx] + - (unsigned int) src[(srcy + 1) * srcw + srcx + 1] + - (unsigned int) src[(srcy + 1) * srcw + srcx + 2] + - (unsigned int) src[(srcy + 2) * srcw + srcx] + - (unsigned int) src[(srcy + 2) * srcw + srcx + 1] + - (unsigned int) src[(srcy + 2) * srcw + srcx + 2]) / 9; + ((unsigned int) src[srcy * srcw + srcx] + (unsigned int) src[srcy * srcw + srcx + 1] + + (unsigned int) src[srcy * srcw + srcx + 2] + (unsigned int) src[(srcy + 1) * srcw + srcx] + + (unsigned int) src[(srcy + 1) * srcw + srcx + 1] + (unsigned int) src[(srcy + 1) * srcw + srcx + 2] + + (unsigned int) src[(srcy + 2) * srcw + srcx] + (unsigned int) src[(srcy + 2) * srcw + srcx + 1] + + (unsigned int) src[(srcy + 2) * srcw + srcx + 2]) / + 9; } } } @@ -201,22 +195,15 @@ static void BinPixels(T *dst, const T *src, const wxSize& srcsize, unsigned int for (int srcx = 0; srcx < srcw; srcx += 4) { *dstp++ = - ((unsigned int) src[srcy * srcw + srcx] + - (unsigned int) src[srcy * srcw + srcx + 1] + - (unsigned int) src[srcy * srcw + srcx + 2] + - (unsigned int) src[srcy * srcw + srcx + 3] + - (unsigned int) src[(srcy + 1) * srcw + srcx] + - (unsigned int) src[(srcy + 1) * srcw + srcx + 1] + - (unsigned int) src[(srcy + 1) * srcw + srcx + 2] + - (unsigned int) src[(srcy + 1) * srcw + srcx + 3] + - (unsigned int) src[(srcy + 2) * srcw + srcx] + - (unsigned int) src[(srcy + 2) * srcw + srcx + 1] + - (unsigned int) src[(srcy + 2) * srcw + srcx + 2] + - (unsigned int) src[(srcy + 2) * srcw + srcx + 3] + - (unsigned int) src[(srcy + 3) * srcw + srcx] + - (unsigned int) src[(srcy + 3) * srcw + srcx + 1] + - (unsigned int) src[(srcy + 3) * srcw + srcx + 2] + - (unsigned int) src[(srcy + 3) * srcw + srcx + 3]) / 16; + ((unsigned int) src[srcy * srcw + srcx] + (unsigned int) src[srcy * srcw + srcx + 1] + + (unsigned int) src[srcy * srcw + srcx + 2] + (unsigned int) src[srcy * srcw + srcx + 3] + + (unsigned int) src[(srcy + 1) * srcw + srcx] + (unsigned int) src[(srcy + 1) * srcw + srcx + 1] + + (unsigned int) src[(srcy + 1) * srcw + srcx + 2] + (unsigned int) src[(srcy + 1) * srcw + srcx + 3] + + (unsigned int) src[(srcy + 2) * srcw + srcx] + (unsigned int) src[(srcy + 2) * srcw + srcx + 1] + + (unsigned int) src[(srcy + 2) * srcw + srcx + 2] + (unsigned int) src[(srcy + 2) * srcw + srcx + 3] + + (unsigned int) src[(srcy + 3) * srcw + srcx] + (unsigned int) src[(srcy + 3) * srcw + srcx + 1] + + (unsigned int) src[(srcy + 3) * srcw + srcx + 2] + (unsigned int) src[(srcy + 3) * srcw + srcx + 3]) / + 16; } } } @@ -224,16 +211,12 @@ static void BinPixels(T *dst, const T *src, const wxSize& srcsize, unsigned int inline static void BinPixels8(void *dst, const void *src, const wxSize& srcsize, unsigned int binning) { - BinPixels(static_cast(dst), - static_cast(src), - srcsize, binning); + BinPixels(static_cast(dst), static_cast(src), srcsize, binning); } inline static void BinPixels16(void *dst, const void *src, const wxSize& srcsize, unsigned int binning) { - BinPixels(static_cast(dst), - static_cast(src), - srcsize, binning); + BinPixels(static_cast(dst), static_cast(src), srcsize, binning); } #endif diff --git a/src/imagelogger.cpp b/src/imagelogger.cpp index 9f4defe67..c826f5b5b 100644 --- a/src/imagelogger.cpp +++ b/src/imagelogger.cpp @@ -35,7 +35,10 @@ #include "phd.h" #include "imagelogger.h" -enum { SAVE_IMAGES = 2 }; // number of images to log preceding and following the trigger image +enum +{ + SAVE_IMAGES = 2 +}; // number of images to log preceding and following the trigger image struct IL { @@ -158,12 +161,12 @@ void ImageLogger::GetSettings(ImageLoggerSettings *settings) void ImageLogger::ApplySettings(const ImageLoggerSettings& settings) { - Debug.Write(wxString::Format("ImgLogger: Settings LogEnabled=%d Log Rel=%d, %.2f Log Px=%d, %.2f LogFrameDrop=%d LogAutoSel=%d NextN=%d\n", - settings.loggingEnabled, - settings.logFramesOverThreshRel, settings.logFramesOverThreshRel ? settings.guideErrorThreshRel : 0., - settings.logFramesOverThreshPx, settings.logFramesOverThreshPx ? settings.guideErrorThreshPx : 0., - settings.logFramesDropped, settings.logAutoSelectFrames, - settings.logNextNFrames ? settings.logNextNFramesCount : 0)); + Debug.Write(wxString::Format( + "ImgLogger: Settings LogEnabled=%d Log Rel=%d, %.2f Log Px=%d, %.2f LogFrameDrop=%d LogAutoSel=%d NextN=%d\n", + settings.loggingEnabled, settings.logFramesOverThreshRel, + settings.logFramesOverThreshRel ? settings.guideErrorThreshRel : 0., settings.logFramesOverThreshPx, + settings.logFramesOverThreshPx ? settings.guideErrorThreshPx : 0., settings.logFramesDropped, + settings.logAutoSelectFrames, settings.logNextNFrames ? settings.logNextNFramesCount : 0)); s_il.settings = settings; if (settings.loggingEnabled && settings.logNextNFrames && s_il.imagesToLog < settings.logNextNFramesCount) @@ -187,10 +190,11 @@ void ImageLogger::LogImageStarDeselected(const usImage *img) void ImageLogger::LogImage(const usImage *img, const FrameDroppedInfo& info) { - if (s_il.settings.loggingEnabled && s_il.settings.logFramesDropped && - pFrame->pGuider->IsCalibratingOrGuiding() && !pFrame->pGuider->IsPaused()) + if (s_il.settings.loggingEnabled && s_il.settings.logFramesDropped && pFrame->pGuider->IsCalibratingOrGuiding() && + !pFrame->pGuider->IsPaused()) { - Debug.Write(wxString::Format("ImgLogger: star lost (%d) frame %u event %u\n", info.starError, img->FrameNum, s_il.eventNumber)); + Debug.Write( + wxString::Format("ImgLogger: star lost (%d) frame %u event %u\n", info.starError, img->FrameNum, s_il.eventNumber)); s_il.BeginLogging(img, "StarLost"); return; } @@ -201,10 +205,12 @@ void ImageLogger::LogImage(const usImage *img, const FrameDroppedInfo& info) void ImageLogger::LogImage(const usImage *img, double distance) { if (s_il.settings.loggingEnabled && (s_il.settings.logFramesOverThreshRel || s_il.settings.logFramesOverThreshPx) && - pFrame->pGuider->IsGuiding() && !pFrame->pGuider->IsPaused() && - !PhdController::IsSettling()) + pFrame->pGuider->IsGuiding() && !pFrame->pGuider->IsPaused() && !PhdController::IsSettling()) { - enum { MIN_FRAMES_FOR_STATS = 10 }; + enum + { + MIN_FRAMES_FOR_STATS = 10 + }; unsigned int frameCount = pFrame->pGuider->CurrentErrorFrameCount(); if (frameCount >= MIN_FRAMES_FOR_STATS) @@ -228,8 +234,9 @@ void ImageLogger::LogImage(const usImage *img, double distance) if (logit) { - Debug.Write(wxString::Format("ImgLogger: large offset frame %u event %u dist px %.2f vs %.2f rel %.2f vs %.2f cur %.2f\n", - img->FrameNum, s_il.eventNumber, distance, threshPx, relErr, threshRel, curErr)); + Debug.Write(wxString::Format( + "ImgLogger: large offset frame %u event %u dist px %.2f vs %.2f rel %.2f vs %.2f cur %.2f\n", img->FrameNum, + s_il.eventNumber, distance, threshPx, relErr, threshRel, curErr)); s_il.BeginLogging(img, "LargeOffset"); return; diff --git a/src/imagelogger.h b/src/imagelogger.h index f8b982ad4..d1ded632d 100644 --- a/src/imagelogger.h +++ b/src/imagelogger.h @@ -47,16 +47,20 @@ struct ImageLoggerSettings double guideErrorThreshPx; // pixel error theshold unsigned int logNextNFramesCount; - ImageLoggerSettings() : - loggingEnabled(false), logFramesOverThreshRel(false), logFramesOverThreshPx(false), - logFramesDropped(false), logAutoSelectFrames(false), logNextNFrames(false) - { } + ImageLoggerSettings() + : loggingEnabled(false) + , logFramesOverThreshRel(false) + , logFramesOverThreshPx(false) + , logFramesDropped(false) + , logAutoSelectFrames(false) + , logNextNFrames(false) + { + } }; class ImageLogger { public: - static void Init(); static void Destroy(); diff --git a/src/indi_gui.cpp b/src/indi_gui.cpp index 15f9eb39a..1b3b946f9 100644 --- a/src/indi_gui.cpp +++ b/src/indi_gui.cpp @@ -26,7 +26,7 @@ *******************************************************************************/ #ifdef _WIN32 -#pragma warning(disable: 4996) +# pragma warning(disable : 4996) #endif #include "phd.h" @@ -42,39 +42,39 @@ */ class IndiStatus : public wxLed { - public: - IndiStatus(wxWindow *parent, wxWindowID id, IPState state) : wxLed(parent, id) - { - SetState(state); - Enable(); - } +public: + IndiStatus(wxWindow *parent, wxWindowID id, IPState state) + : wxLed(parent, id) + { + SetState(state); + Enable(); + } - void SetState(int state) + void SetState(int state) + { + static const char indi_state[4][6] = { + "Idle", + "Ok", + "Busy", + "Alert", + }; + switch (state) { - static const char indi_state[4][6] = - { - "Idle", - "Ok", - "Busy", - "Alert", - }; - switch(state) - { - case IPS_IDLE: - SetColor("808080"); - break; - case IPS_OK: - SetColor("008000"); - break; - case IPS_BUSY: - SetColor("FFFF00"); - break; - case IPS_ALERT: - SetColor("FF0000"); - break; - } - SetToolTip(wxString::FromAscii(indi_state[state])); + case IPS_IDLE: + SetColor("808080"); + break; + case IPS_OK: + SetColor("008000"); + break; + case IPS_BUSY: + SetColor("FFFF00"); + break; + case IPS_ALERT: + SetColor("FF0000"); + break; } + SetToolTip(wxString::FromAscii(indi_state[state])); + } }; /* @@ -82,11 +82,11 @@ class IndiStatus : public wxLed */ class IndiDev { - public: - wxNotebook *page; - INDI::BaseDevice dp; - PtrHash groups; - PtrHash properties; +public: + wxNotebook *page; + INDI::BaseDevice dp; + PtrHash groups; + PtrHash properties; }; /* @@ -94,17 +94,17 @@ class IndiDev */ class IndiProp { - public: - wxString PropName; - PtrHash ctrl; - PtrHash entry; - IndiStatus *state; - wxStaticText *name; - wxPanel *page; - wxPanel *panel; - wxGridBagSizer *gbs; - INDI::Property property; - IndiDev *idev; +public: + wxString PropName; + PtrHash ctrl; + PtrHash entry; + IndiStatus *state; + wxStaticText *name; + wxPanel *page; + wxPanel *panel; + wxGridBagSizer *gbs; + INDI::Property property; + IndiDev *idev; }; enum @@ -114,8 +114,8 @@ enum SWITCH_COMBOBOX, }; -#define POS(r, c) wxGBPosition(r,c) -#define SPAN(r, c) wxGBSpan(r,c) +#define POS(r, c) wxGBPosition(r, c) +#define SPAN(r, c) wxGBSpan(r, c) wxDEFINE_EVENT(INDIGUI_THREAD_NEWDEVICE_EVENT, wxThreadEvent); wxDEFINE_EVENT(INDIGUI_THREAD_NEWPROPERTY_EVENT, wxThreadEvent); @@ -170,13 +170,15 @@ void IndiGui::removeProperty(INDI::Property property) { if (property) { - wxString devname = wxString::FromAscii(property.getDeviceName()); - wxString groupname = wxString::FromAscii(property.getGroupName()); - wxString propname = wxString::FromAscii(property.getName()); - IndiDev *indiDev = (IndiDev *)devlist[devname]; - if (!indiDev) return; - IndiProp *indiProp = (IndiProp *)indiDev->properties[propname]; - if (!indiProp) return; + wxString devname = wxString::FromAscii(property.getDeviceName()); + wxString groupname = wxString::FromAscii(property.getGroupName()); + wxString propname = wxString::FromAscii(property.getName()); + IndiDev *indiDev = (IndiDev *) devlist[devname]; + if (!indiDev) + return; + IndiProp *indiProp = (IndiProp *) indiDev->properties[propname]; + if (!indiProp) + return; wxThreadEvent *event = new wxThreadEvent(wxEVT_THREAD, INDIGUI_THREAD_REMOVEPROPERTY_EVENT); event->SetExtraLong((long) indiProp); @@ -223,15 +225,15 @@ void IndiGui::serverDisconnected(int exit_code) void IndiGui::OnNewDeviceFromThread(wxThreadEvent& event) { auto dp = event.GetPayload(); - //printf("newdevice from thread %s \n",dp->getDeviceName()); + // printf("newdevice from thread %s \n",dp->getDeviceName()); auto name = dp.getDeviceName(); - wxString devname = wxString::FromAscii(dp.getDeviceName()); + wxString devname = wxString::FromAscii(dp.getDeviceName()); IndiDev *indiDev = new IndiDev(); wxPanel *panel = new wxPanel(parent_notebook); indiDev->page = new wxNotebook(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNB_TOP); wxBoxSizer *nb_sizer = new wxBoxSizer(wxVERTICAL); panel->SetSizer(nb_sizer); - nb_sizer->Add(indiDev->page, 1, wxEXPAND | wxALL); + nb_sizer->Add(indiDev->page, 1, wxEXPAND | wxALL); parent_notebook->AddPage(panel, devname); indiDev->dp = dp; devlist[devname] = indiDev; @@ -244,20 +246,21 @@ void IndiGui::OnNewDeviceFromThread(wxThreadEvent& event) void IndiGui::OnNewPropertyFromThread(wxThreadEvent& event) { auto property = event.GetPayload(); - //printf("newproperty from thread %s %s %s\n",property->getDeviceName(),property->getGroupName(),property->getName()); - wxString devname = wxString::FromAscii(property.getDeviceName()); - wxString groupname = wxString::FromAscii(property.getGroupName()); - wxString propname = wxString::FromAscii(property.getName()); + // printf("newproperty from thread %s %s %s\n",property->getDeviceName(),property->getGroupName(),property->getName()); + wxString devname = wxString::FromAscii(property.getDeviceName()); + wxString groupname = wxString::FromAscii(property.getGroupName()); + wxString propname = wxString::FromAscii(property.getName()); IndiProp *indiProp = new IndiProp(); wxPanel *page; wxGridBagSizer *gbs; int next_free_row; - IndiDev *indiDev = (IndiDev *)devlist[devname]; - if (! indiDev) return; + IndiDev *indiDev = (IndiDev *) devlist[devname]; + if (!indiDev) + return; indiProp->idev = indiDev; - page = (wxPanel *)indiDev->groups[groupname]; + page = (wxPanel *) indiDev->groups[groupname]; if (!page) { page = new wxPanel(indiDev->page); @@ -266,7 +269,7 @@ void IndiGui::OnNewPropertyFromThread(wxThreadEvent& event) indiDev->groups[groupname] = page; } - gbs = (wxGridBagSizer *)page->GetSizer(); + gbs = (wxGridBagSizer *) page->GetSizer(); gbs->Layout(); next_free_row = gbs->GetRows(); BuildPropWidget(property, page, indiProp); @@ -288,41 +291,42 @@ void IndiGui::OnNewPropertyFromThread(wxThreadEvent& event) void IndiGui::BuildPropWidget(INDI::Property property, wxPanel *parent, IndiProp *indiProp) { - wxString propname = wxString::FromAscii(property.getName()); - wxString proplbl = wxString::FromAscii(property.getLabel()); - if (! proplbl) proplbl = propname; + wxString propname = wxString::FromAscii(property.getName()); + wxString proplbl = wxString::FromAscii(property.getLabel()); + if (!proplbl) + proplbl = propname; auto proptype = property.getType(); indiProp->page = parent; indiProp->panel = new wxPanel(parent); - indiProp->gbs = new wxGridBagSizer(0, 20); + indiProp->gbs = new wxGridBagSizer(0, 20); indiProp->panel->SetSizer(indiProp->gbs); indiProp->state = new IndiStatus(parent, wxID_ANY, property.getState()); - indiProp->name = new wxStaticText(parent, wxID_ANY, proplbl); + indiProp->name = new wxStaticText(parent, wxID_ANY, proplbl); indiProp->PropName = propname; indiProp->property = property; switch (proptype) { - case INDI_TEXT: - CreateTextWidget(property, indiProp); - break; - case INDI_SWITCH: - CreateSwitchWidget(property, indiProp); - break; - case INDI_NUMBER: - CreateNumberWidget(property, indiProp); - break; - case INDI_LIGHT: - CreateLightWidget(property, indiProp); - break; - case INDI_BLOB: - CreateBlobWidget(property, indiProp); - break; - case INDI_UNKNOWN: - CreateUnknowWidget(property, indiProp); - break; + case INDI_TEXT: + CreateTextWidget(property, indiProp); + break; + case INDI_SWITCH: + CreateSwitchWidget(property, indiProp); + break; + case INDI_NUMBER: + CreateNumberWidget(property, indiProp); + break; + case INDI_LIGHT: + CreateLightWidget(property, indiProp); + break; + case INDI_BLOB: + CreateBlobWidget(property, indiProp); + break; + case INDI_UNKNOWN: + CreateUnknowWidget(property, indiProp); + break; } indiProp->gbs->Layout(); } @@ -342,20 +346,20 @@ int IndiGui::GetSwitchType(ISwitchVectorProperty *svp) void IndiGui::CreateSwitchWidget(INDI::Property property, IndiProp *indiProp) { - //printf("CreateSwitchWidget\n"); + // printf("CreateSwitchWidget\n"); int guitype = GetSwitchType(property.getSwitch()); switch (guitype) { - case SWITCH_COMBOBOX: - CreateSwitchCombobox(property.getSwitch(), indiProp); - break; - case SWITCH_CHECKBOX: - CreateSwitchCheckbox(property.getSwitch(), indiProp); - break; - case SWITCH_BUTTON: - CreateSwitchButton(property.getSwitch(), indiProp); - break; + case SWITCH_COMBOBOX: + CreateSwitchCombobox(property.getSwitch(), indiProp); + break; + case SWITCH_CHECKBOX: + CreateSwitchCheckbox(property.getSwitch(), indiProp); + break; + case SWITCH_BUTTON: + CreateSwitchButton(property.getSwitch(), indiProp); + break; } } @@ -368,7 +372,7 @@ void IndiGui::CreateSwitchCombobox(ISwitchVectorProperty *svp, IndiProp *indiPro int idx = 0; for (int i = 0; i < svp->nsp; i++) { - if(svp->sp[i].s == ISS_ON) + if (svp->sp[i].s == ISS_ON) idx = i; indiProp->ctrl[wxString::FromAscii(svp->sp[i].name)] = (void *) (intptr_t) i; wxString swlbl = wxString::FromAscii(svp->sp[i].label); @@ -379,11 +383,10 @@ void IndiGui::CreateSwitchCombobox(ISwitchVectorProperty *svp, IndiProp *indiPro wxChoice *combo = new wxChoice(p, wxID_ANY, wxDefaultPosition, wxDefaultSize, svp->nsp, choices); combo->SetSelection(idx); combo->SetClientData(indiProp); - Connect(combo->GetId(), wxEVT_COMMAND_CHOICE_SELECTED, - wxCommandEventHandler(IndiGui::SetComboboxEvent)); + Connect(combo->GetId(), wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(IndiGui::SetComboboxEvent)); gbs->Add(combo, POS(0, 0), SPAN(1, 1), wxALIGN_LEFT | wxALL); indiProp->ctrl[wxString::FromAscii(svp->name)] = (void *) combo; - delete [] choices; + delete[] choices; } void IndiGui::CreateSwitchCheckbox(ISwitchVectorProperty *svp, IndiProp *indiProp) @@ -400,8 +403,7 @@ void IndiGui::CreateSwitchCheckbox(ISwitchVectorProperty *svp, IndiProp *indiPro if (svp->sp[pos].s == ISS_ON) button->SetValue(true); button->SetClientData(indiProp); - Connect(button->GetId(), wxEVT_COMMAND_CHECKBOX_CLICKED, - wxCommandEventHandler(IndiGui::SetCheckboxEvent)); + Connect(button->GetId(), wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(IndiGui::SetCheckboxEvent)); gbs->Add(button, POS(pos / 4, pos % 4), SPAN(1, 1), wxALIGN_LEFT | wxALL); } } @@ -420,8 +422,7 @@ void IndiGui::CreateSwitchButton(ISwitchVectorProperty *svp, IndiProp *indiProp) if (svp->sp[pos].s == ISS_ON) button->SetValue(true); button->SetClientData(indiProp); - Connect(button->GetId(), wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, - wxCommandEventHandler(IndiGui::SetToggleButtonEvent)); + Connect(button->GetId(), wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, wxCommandEventHandler(IndiGui::SetToggleButtonEvent)); if (!allow_connect_disconnect && strcmp(svp->name, "CONNECTION") == 0) { button->Enable(false); @@ -439,8 +440,8 @@ void IndiGui::CreateTextWidget(INDI::Property property, IndiProp *indiProp) int pos; for (pos = 0; pos < tvp->ntp; pos++) { - gbs->Add(new wxStaticText(p, wxID_ANY, wxString::FromAscii(tvp->tp[pos].label)), - POS(pos, 0), SPAN(1, 1), wxALIGN_LEFT | wxALL); + gbs->Add(new wxStaticText(p, wxID_ANY, wxString::FromAscii(tvp->tp[pos].label)), POS(pos, 0), SPAN(1, 1), + wxALIGN_LEFT | wxALL); wxStaticText *value = new wxStaticText(p, wxID_ANY, wxString::FromAscii(tvp->tp[pos].text)); indiProp->ctrl[wxString::FromAscii(tvp->tp[pos].name)] = value; @@ -470,8 +471,8 @@ void IndiGui::CreateNumberWidget(INDI::Property property, IndiProp *indiProp) int pos; for (pos = 0; pos < nvp->nnp; pos++) { - gbs->Add(new wxStaticText(p, wxID_ANY, wxString::FromAscii(nvp->np[pos].label)), - POS(pos, 0), SPAN(1, 1), wxALIGN_LEFT | wxALL); + gbs->Add(new wxStaticText(p, wxID_ANY, wxString::FromAscii(nvp->np[pos].label)), POS(pos, 0), SPAN(1, 1), + wxALIGN_LEFT | wxALL); wxStaticText *value = new wxStaticText(p, wxID_ANY, wxString::Format(_T("%f"), nvp->np[pos].value)); indiProp->ctrl[wxString::FromAscii(nvp->np[pos].name)] = value; @@ -494,17 +495,17 @@ void IndiGui::CreateNumberWidget(INDI::Property property, IndiProp *indiProp) void IndiGui::CreateLightWidget(INDI::Property property, IndiProp *indiProp) { - //printf("IndiGui: Unimplemented CreateLightWidget\n"); + // printf("IndiGui: Unimplemented CreateLightWidget\n"); } void IndiGui::CreateBlobWidget(INDI::Property property, IndiProp *indiProp) { - //printf("IndiGui: Unimplemented CreateBlobWidget\n"); + // printf("IndiGui: Unimplemented CreateBlobWidget\n"); } void IndiGui::CreateUnknowWidget(INDI::Property property, IndiProp *indiProp) { - //printf("IndiGui: Unimplemented CreateUnknowWidget\n"); + // printf("IndiGui: Unimplemented CreateUnknowWidget\n"); } void IndiGui::OnUpdatePropertyFromThread(wxThreadEvent& event) @@ -513,88 +514,88 @@ void IndiGui::OnUpdatePropertyFromThread(wxThreadEvent& event) switch (property.getType()) { - case INDI_NUMBER: + case INDI_NUMBER: + { + auto nvp = property.getNumber(); + wxString devname = wxString::FromAscii(nvp->device); + wxString propname = wxString::FromAscii(nvp->name); + IndiDev *indiDev = (IndiDev *) devlist[devname]; + IndiProp *indiProp = (IndiProp *) indiDev->properties[propname]; + for (int i = 0; i < nvp->nnp; i++) { - auto nvp = property.getNumber(); - wxString devname = wxString::FromAscii(nvp->device); - wxString propname = wxString::FromAscii(nvp->name); - IndiDev *indiDev = (IndiDev *) devlist[devname]; - IndiProp *indiProp = (IndiProp *) indiDev->properties[propname]; - for (int i = 0; i < nvp->nnp; i++) + void *st = indiProp->ctrl[wxString::FromAscii(nvp->np[i].name)]; + wxStaticText *ctrl = (wxStaticText *) st; + ctrl->SetLabel(wxString::Format(wxT("%f"), nvp->np[i].value)); + } + indiProp->state->SetState(nvp->s); + } + break; + + case INDI_TEXT: + { + auto tvp = property.getText(); + wxString devname = wxString::FromAscii(tvp->device); + wxString propname = wxString::FromAscii(tvp->name); + IndiDev *indiDev = (IndiDev *) devlist[devname]; + IndiProp *indiProp = (IndiProp *) indiDev->properties[propname]; + for (int i = 0; i < tvp->ntp; i++) + { + void *st = indiProp->ctrl[wxString::FromAscii(tvp->tp[i].name)]; + wxStaticText *ctrl = (wxStaticText *) st; + ctrl->SetLabel(wxString::Format(wxT("%s"), tvp->tp[i].text)); + } + indiProp->state->SetState(tvp->s); + } + break; + + case INDI_SWITCH: + { + auto svp = property.getSwitch(); + wxString devname = wxString::FromAscii(svp->device); + wxString propname = wxString::FromAscii(svp->name); + int swtype = GetSwitchType(svp); + IndiDev *indiDev = (IndiDev *) devlist[devname]; + IndiProp *indiProp = (IndiProp *) indiDev->properties[propname]; + switch (swtype) + { + case SWITCH_COMBOBOX: + { + int idx = 0; + for (int i = 0; i < svp->nsp; i++) { - void *st = indiProp->ctrl[wxString::FromAscii(nvp->np[i].name)]; - wxStaticText *ctrl = (wxStaticText *)st; - ctrl->SetLabel(wxString::Format(wxT("%f"), nvp->np[i].value)); + if (svp->sp[i].s == ISS_ON) + idx = i; } - indiProp->state->SetState(nvp->s); + void *st = indiProp->ctrl[wxString::FromAscii(svp->name)]; + wxChoice *combo = (wxChoice *) st; + combo->SetSelection(idx); + break; } - break; - - case INDI_TEXT: + case SWITCH_CHECKBOX: { - auto tvp = property.getText(); - wxString devname = wxString::FromAscii(tvp->device); - wxString propname = wxString::FromAscii(tvp->name); - IndiDev *indiDev = (IndiDev *) devlist[devname]; - IndiProp *indiProp = (IndiProp *) indiDev->properties[propname]; - for (int i = 0; i < tvp->ntp; i++) + for (int i = 0; i < svp->nsp; i++) { - void *st = indiProp->ctrl[wxString::FromAscii(tvp->tp[i].name)]; - wxStaticText *ctrl = (wxStaticText *)st; - ctrl->SetLabel(wxString::Format(wxT("%s"), tvp->tp[i].text)); + void *st = indiProp->ctrl[wxString::FromAscii(svp->sp[i].name)]; + wxCheckBox *button = (wxCheckBox *) st; + button->SetValue(svp->sp[i].s ? true : false); } - indiProp->state->SetState(tvp->s); + break; } - break; - - case INDI_SWITCH: + case SWITCH_BUTTON: { - auto svp = property.getSwitch(); - wxString devname = wxString::FromAscii(svp->device); - wxString propname = wxString::FromAscii(svp->name); - int swtype = GetSwitchType(svp); - IndiDev *indiDev = (IndiDev *) devlist[devname]; - IndiProp *indiProp = (IndiProp *) indiDev->properties[propname]; - switch (swtype) + for (int i = 0; i < svp->nsp; i++) { - case SWITCH_COMBOBOX: - { - int idx = 0; - for (int i = 0; i < svp->nsp; i++) - { - if (svp->sp[i].s == ISS_ON) - idx = i; - } - void *st = indiProp->ctrl[wxString::FromAscii(svp->name)]; - wxChoice *combo = (wxChoice *)st; - combo->SetSelection(idx); - break; - } - case SWITCH_CHECKBOX: - { - for (int i = 0; i < svp->nsp; i++) - { - void *st = indiProp->ctrl[wxString::FromAscii(svp->sp[i].name)]; - wxCheckBox *button = (wxCheckBox *) st; - button->SetValue(svp->sp[i].s ? true : false); - } - break; - } - case SWITCH_BUTTON: - { - for (int i = 0; i < svp->nsp; i++) - { - void *st = indiProp->ctrl[wxString::FromAscii(svp->sp[i].name)]; - wxToggleButton *button = (wxToggleButton *) st; - button->SetValue(svp->sp[i].s ? true : false); - } - break; - } + void *st = indiProp->ctrl[wxString::FromAscii(svp->sp[i].name)]; + wxToggleButton *button = (wxToggleButton *) st; + button->SetValue(svp->sp[i].s ? true : false); } + break; + } } + } + break; + default: break; - default: - break; } } @@ -607,56 +608,60 @@ void IndiGui::OnNewMessageFromThread(wxThreadEvent& event) void IndiGui::SetButtonEvent(wxCommandEvent& event) { - wxButton *button = (wxButton *)event.GetEventObject(); - if (!button) return; + wxButton *button = (wxButton *) event.GetEventObject(); + if (!button) + return; IndiProp *indiProp = (IndiProp *) button->GetClientData(); - if (!indiProp) return; + if (!indiProp) + return; switch (indiProp->property.getType()) { - case INDI_TEXT: + case INDI_TEXT: + { + ITextVectorProperty *tvp = indiProp->property.getText(); + for (int i = 0; i < tvp->ntp; i++) { - ITextVectorProperty *tvp = indiProp->property.getText(); - for (int i = 0; i < tvp->ntp; i++) + if (tvp->p != IP_RO) { - if (tvp->p != IP_RO) - { - wxTextCtrl *entry = (wxTextCtrl *)(indiProp->entry[wxString::FromAscii(tvp->tp[i].name)]); - size_t buf_size = strlen(tvp->tp[i].text) + 1; - snprintf(tvp->tp[i].text, buf_size, "%s", entry->GetLineText(0).mb_str().data()); - } + wxTextCtrl *entry = (wxTextCtrl *) (indiProp->entry[wxString::FromAscii(tvp->tp[i].name)]); + size_t buf_size = strlen(tvp->tp[i].text) + 1; + snprintf(tvp->tp[i].text, buf_size, "%s", entry->GetLineText(0).mb_str().data()); } - sendNewText(tvp); - break; } - case INDI_NUMBER: + sendNewText(tvp); + break; + } + case INDI_NUMBER: + { + INumberVectorProperty *nvp = indiProp->property.getNumber(); + for (int i = 0; i < nvp->nnp; i++) { - INumberVectorProperty *nvp = indiProp->property.getNumber(); - for (int i = 0; i < nvp->nnp; i++) + if (nvp->p != IP_RO) { - if (nvp->p != IP_RO) - { - wxTextCtrl *entry = (wxTextCtrl *)(indiProp->entry[wxString::FromAscii(nvp->np[i].name)]); - entry->GetLineText(0).ToDouble(&nvp->np[i].value); - } + wxTextCtrl *entry = (wxTextCtrl *) (indiProp->entry[wxString::FromAscii(nvp->np[i].name)]); + entry->GetLineText(0).ToDouble(&nvp->np[i].value); } - sendNewNumber(nvp); - break; } - default: - break; + sendNewNumber(nvp); + break; + } + default: + break; } } void IndiGui::SetToggleButtonEvent(wxCommandEvent& event) { - wxToggleButton *button = (wxToggleButton *)event.GetEventObject(); - if (!button) return; + wxToggleButton *button = (wxToggleButton *) event.GetEventObject(); + if (!button) + return; IndiProp *indiProp = (IndiProp *) button->GetClientData(); - if (!indiProp) return; + if (!indiProp) + return; ISwitchVectorProperty *svp = indiProp->property.getSwitch(); - if (!allow_connect_disconnect && strcmp(svp->name, "CONNECTION") == 0 ) + if (!allow_connect_disconnect && strcmp(svp->name, "CONNECTION") == 0) { // Prevent device disconnection from this window. // Use Gear manager instead. @@ -700,10 +705,12 @@ void IndiGui::SetToggleButtonEvent(wxCommandEvent& event) void IndiGui::SetComboboxEvent(wxCommandEvent& event) { - wxChoice *combo = (wxChoice *)event.GetEventObject(); - if (!combo) return; + wxChoice *combo = (wxChoice *) event.GetEventObject(); + if (!combo) + return; IndiProp *indiProp = (IndiProp *) combo->GetClientData(); - if (!indiProp) return; + if (!indiProp) + return; ISwitchVectorProperty *svp = indiProp->property.getSwitch(); int choice = combo->GetSelection(); for (int i = 0; i < svp->nsp; i++) @@ -718,10 +725,12 @@ void IndiGui::SetComboboxEvent(wxCommandEvent& event) void IndiGui::SetCheckboxEvent(wxCommandEvent& event) { - wxCheckBox *button = (wxCheckBox *)event.GetEventObject(); - if (!button) return; + wxCheckBox *button = (wxCheckBox *) event.GetEventObject(); + if (!button) + return; IndiProp *indiProp = (IndiProp *) button->GetClientData(); - if (!indiProp) return; + if (!indiProp) + return; ISwitchVectorProperty *svp = indiProp->property.getSwitch(); wxString b_name; @@ -748,10 +757,12 @@ void IndiGui::SetCheckboxEvent(wxCommandEvent& event) void IndiGui::OnRemovePropertyFromThread(wxThreadEvent& event) { - IndiProp *indiProp = (IndiProp *)event.GetExtraLong(); - if (!indiProp) return; + IndiProp *indiProp = (IndiProp *) event.GetExtraLong(); + if (!indiProp) + return; IndiDev *indiDev = (IndiDev *) indiProp->idev; - if (!indiDev) return; + if (!indiDev) + return; wxString propname = indiProp->PropName; for (int y = 0; y < indiProp->gbs->GetRows(); y++) @@ -803,7 +814,10 @@ void IndiGui::ShowIndiGui(IndiGui **ret, const wxString& host, long port, bool a { wxProgressDialog dlg(_("INDI"), _("Loading INDI properties..."), 0, nullptr, wxPD_APP_MODAL | wxPD_CAN_ABORT); - enum { IDLE_TIME_MS = 500 }; + enum + { + IDLE_TIME_MS = 500 + }; unsigned int i = 0; while (wxGetUTCTimeMillis().GetValue() - gui->m_lastUpdate.GetValue() < IDLE_TIME_MS) @@ -831,12 +845,10 @@ void IndiGui::ShowIndiGui(IndiGui **ret, const wxString& host, long port, bool a } IndiGui::IndiGui() - : - wxDialog(wxGetApp().GetTopWindow(), wxID_ANY, - _("INDI Options"), - wxDefaultPosition, wxSize(640, 400), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), - m_deleted(false), - m_holder(nullptr) + : wxDialog(wxGetApp().GetTopWindow(), wxID_ANY, _("INDI Options"), wxDefaultPosition, wxSize(640, 400), + wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) + , m_deleted(false) + , m_holder(nullptr) { panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_DOUBLE | wxTAB_TRAVERSAL); sizer = new wxBoxSizer(wxVERTICAL); diff --git a/src/indi_gui.h b/src/indi_gui.h index 471ac90ea..44ce9a3f0 100644 --- a/src/indi_gui.h +++ b/src/indi_gui.h @@ -57,72 +57,72 @@ class IndiProp; class IndiGui : public wxDialog, public INDI::BaseClient { - private: - // Main thread events called from INDI thread - void OnNewDeviceFromThread(wxThreadEvent& event); - void OnNewPropertyFromThread(wxThreadEvent& event); - void OnUpdatePropertyFromThread(wxThreadEvent& event); - void OnNewMessageFromThread(wxThreadEvent& event); - void OnRemovePropertyFromThread(wxThreadEvent& event); - - // Widget creation - void BuildPropWidget(INDI::Property property, wxPanel *parent, IndiProp *indiProp); - void CreateTextWidget(INDI::Property property, IndiProp *indiProp); - void CreateSwitchWidget(INDI::Property property, IndiProp *indiProp); - void CreateNumberWidget(INDI::Property property, IndiProp *indiProp); - void CreateLightWidget(INDI::Property property, IndiProp *indiProp); - void CreateBlobWidget(INDI::Property property, IndiProp *indiProp); - void CreateUnknowWidget(INDI::Property property, IndiProp *indiProp); - // More switch stuff - int GetSwitchType(ISwitchVectorProperty *svp); - void CreateSwitchCombobox(ISwitchVectorProperty *svp, IndiProp *indiProp); - void CreateSwitchCheckbox(ISwitchVectorProperty *svp, IndiProp *indiProp); - void CreateSwitchButton(ISwitchVectorProperty *svp, IndiProp *indiProp); - - // Button events - void SetButtonEvent(wxCommandEvent& event); - void SetComboboxEvent(wxCommandEvent& event); - void SetToggleButtonEvent(wxCommandEvent& event); - void SetCheckboxEvent(wxCommandEvent& event); - - void OnQuit(wxCloseEvent& event); - - void ConnectServer(const wxString& INDIhost, long INDIport); - bool allow_connect_disconnect; - - wxPanel *panel; - wxBoxSizer *sizer; - wxNotebook *parent_notebook; - wxTextCtrl *textbuffer; - wxLongLong m_lastUpdate; - - PtrHash devlist; - - bool m_deleted; - IndiGui **m_holder; - - wxDECLARE_EVENT_TABLE(); - - IndiGui(); - - protected: - ////////////////////////////////////////////////////////////////////// - // Functions running in the INDI client thread - ////////////////////////////////////////////////////////////////////// - void newDevice(INDI::BaseDevice dp) override; - void removeDevice(INDI::BaseDevice dp) override {}; - void newProperty(INDI::Property property) override; - void removeProperty(INDI::Property property) override; - void updateProperty(INDI::Property property) override; - void newMessage(INDI::BaseDevice dp, int messageID) override; - void serverConnected() override; - void serverDisconnected(int exit_code) override; - - public: - ~IndiGui(); - - static void ShowIndiGui(IndiGui **ret, const wxString& host, long port, bool allow_connect_disconnect, bool modal); - static void DestroyIndiGui(IndiGui **holder); +private: + // Main thread events called from INDI thread + void OnNewDeviceFromThread(wxThreadEvent& event); + void OnNewPropertyFromThread(wxThreadEvent& event); + void OnUpdatePropertyFromThread(wxThreadEvent& event); + void OnNewMessageFromThread(wxThreadEvent& event); + void OnRemovePropertyFromThread(wxThreadEvent& event); + + // Widget creation + void BuildPropWidget(INDI::Property property, wxPanel *parent, IndiProp *indiProp); + void CreateTextWidget(INDI::Property property, IndiProp *indiProp); + void CreateSwitchWidget(INDI::Property property, IndiProp *indiProp); + void CreateNumberWidget(INDI::Property property, IndiProp *indiProp); + void CreateLightWidget(INDI::Property property, IndiProp *indiProp); + void CreateBlobWidget(INDI::Property property, IndiProp *indiProp); + void CreateUnknowWidget(INDI::Property property, IndiProp *indiProp); + // More switch stuff + int GetSwitchType(ISwitchVectorProperty *svp); + void CreateSwitchCombobox(ISwitchVectorProperty *svp, IndiProp *indiProp); + void CreateSwitchCheckbox(ISwitchVectorProperty *svp, IndiProp *indiProp); + void CreateSwitchButton(ISwitchVectorProperty *svp, IndiProp *indiProp); + + // Button events + void SetButtonEvent(wxCommandEvent& event); + void SetComboboxEvent(wxCommandEvent& event); + void SetToggleButtonEvent(wxCommandEvent& event); + void SetCheckboxEvent(wxCommandEvent& event); + + void OnQuit(wxCloseEvent& event); + + void ConnectServer(const wxString& INDIhost, long INDIport); + bool allow_connect_disconnect; + + wxPanel *panel; + wxBoxSizer *sizer; + wxNotebook *parent_notebook; + wxTextCtrl *textbuffer; + wxLongLong m_lastUpdate; + + PtrHash devlist; + + bool m_deleted; + IndiGui **m_holder; + + wxDECLARE_EVENT_TABLE(); + + IndiGui(); + +protected: + ////////////////////////////////////////////////////////////////////// + // Functions running in the INDI client thread + ////////////////////////////////////////////////////////////////////// + void newDevice(INDI::BaseDevice dp) override; + void removeDevice(INDI::BaseDevice dp) override {}; + void newProperty(INDI::Property property) override; + void removeProperty(INDI::Property property) override; + void updateProperty(INDI::Property property) override; + void newMessage(INDI::BaseDevice dp, int messageID) override; + void serverConnected() override; + void serverDisconnected(int exit_code) override; + +public: + ~IndiGui(); + + static void ShowIndiGui(IndiGui **ret, const wxString& host, long port, bool allow_connect_disconnect, bool modal); + static void DestroyIndiGui(IndiGui **holder); }; #endif //_INDIGUI_H_ diff --git a/src/json_parser.cpp b/src/json_parser.cpp index 92c087927..32e1861c0 100644 --- a/src/json_parser.cpp +++ b/src/json_parser.cpp @@ -73,11 +73,11 @@ class block_allocator block *m_head; size_t m_blocksize; - block_allocator(const block_allocator &); - block_allocator &operator=(block_allocator &); + block_allocator(const block_allocator&); + block_allocator& operator=(block_allocator&); // exchange contents with rhs - void swap(block_allocator &rhs); + void swap(block_allocator& rhs); public: block_allocator(size_t blocksize); @@ -93,7 +93,9 @@ class block_allocator void free(); }; -block_allocator::block_allocator(size_t blocksize): m_head(0), m_blocksize(blocksize) +block_allocator::block_allocator(size_t blocksize) + : m_head(0) + , m_blocksize(blocksize) { } @@ -137,7 +139,7 @@ void *block_allocator::malloc(size_t size) size_t alloc_size = std::max(sizeof(block) + size, m_blocksize); // create new block - block *b = (block *)::malloc(alloc_size); + block *b = (block *) ::malloc(alloc_size); b->size = alloc_size; b->used = sizeof(block); b->next = m_head; @@ -304,7 +306,7 @@ static char *atof(char *first, char *last, float *out) static json_value *json_alloc(block_allocator *allocator) { - json_value *value = (json_value *)allocator->malloc(sizeof(json_value)); + json_value *value = (json_value *) allocator->malloc(sizeof(json_value)); memset(value, 0, sizeof(json_value)); return value; } @@ -322,20 +324,24 @@ static void json_append(json_value *lhs, json_value *rhs) } } -#define JSON_ERROR(it, desc) do { \ - *error_pos = it; \ - *error_desc = desc; \ - *error_line = 1 - escaped_newlines; \ - for (const char *c = it; c != source; --c) \ - if (*c == '\n') ++*error_line; \ - return 0; \ -} while (false) - -#define CHECK_TOP() if (!top) JSON_ERROR(it, "Unexpected character") - -static json_value *json_parse(char *source, const char **error_pos, - const char **error_desc, int *error_line, - block_allocator *allocator) +#define JSON_ERROR(it, desc) \ + do \ + { \ + *error_pos = it; \ + *error_desc = desc; \ + *error_line = 1 - escaped_newlines; \ + for (const char *c = it; c != source; --c) \ + if (*c == '\n') \ + ++*error_line; \ + return 0; \ + } while (false) + +#define CHECK_TOP() \ + if (!top) \ + JSON_ERROR(it, "Unexpected character") + +static json_value *json_parse( + char *source, const char **error_pos, const char **error_desc, int *error_line, block_allocator *allocator) { json_value *root = 0; json_value *top = 0; @@ -357,52 +363,52 @@ static json_value *json_parse(char *source, const char **error_pos, { case '{': case '[': - { - // create new value - json_value *object = json_alloc(allocator); + { + // create new value + json_value *object = json_alloc(allocator); - // name - object->name = name; - name = 0; + // name + object->name = name; + name = 0; - // type - object->type = (*it == '{') ? JSON_OBJECT : JSON_ARRAY; + // type + object->type = (*it == '{') ? JSON_OBJECT : JSON_ARRAY; - // skip open character - ++it; + // skip open character + ++it; - // set top and root - if (top) - { - json_append(top, object); - } - else if (!root) - { - root = object; - } - else - { - JSON_ERROR(it, "Second root. Only one root allowed"); - } - top = object; + // set top and root + if (top) + { + json_append(top, object); } - break; + else if (!root) + { + root = object; + } + else + { + JSON_ERROR(it, "Second root. Only one root allowed"); + } + top = object; + } + break; case '}': case ']': + { + if (!top || top->type != ((*it == '}') ? JSON_OBJECT : JSON_ARRAY)) { - if (!top || top->type != ((*it == '}') ? JSON_OBJECT : JSON_ARRAY)) - { - JSON_ERROR(it, "Mismatch closing brace/bracket"); - } + JSON_ERROR(it, "Mismatch closing brace/bracket"); + } - // skip close character - ++it; + // skip close character + ++it; - // set top - top = top->parent; - } - break; + // set top + top = top->parent; + } + break; case ':': if (!top || top->type != JSON_OBJECT || !name) @@ -418,160 +424,160 @@ static json_value *json_parse(char *source, const char **error_pos, break; case '"': - { - CHECK_TOP(); + { + CHECK_TOP(); - // skip '"' character - ++it; + // skip '"' character + ++it; - char *first = it; - char *last = it; - while (*it) + char *first = it; + char *last = it; + while (*it) + { + if ((unsigned char) *it < '\x20') { - if ((unsigned char)*it < '\x20') + JSON_ERROR(first, "Control characters not allowed in strings"); + } + else if (*it == '\\') + { + switch (it[1]) { - JSON_ERROR(first, "Control characters not allowed in strings"); - } - else if (*it == '\\') + case '"': + *last = '"'; + break; + case '\\': + *last = '\\'; + break; + case '/': + *last = '/'; + break; + case 'b': + *last = '\b'; + break; + case 'f': + *last = '\f'; + break; + case 'n': + *last = '\n'; + ++escaped_newlines; + break; + case 'r': + *last = '\r'; + break; + case 't': + *last = '\t'; + break; + case 'u': { - switch (it[1]) + unsigned int codepoint; + if (hatoui(it + 2, it + 6, &codepoint) != it + 6) { - case '"': - *last = '"'; - break; - case '\\': - *last = '\\'; - break; - case '/': - *last = '/'; - break; - case 'b': - *last = '\b'; - break; - case 'f': - *last = '\f'; - break; - case 'n': - *last = '\n'; - ++escaped_newlines; - break; - case 'r': - *last = '\r'; - break; - case 't': - *last = '\t'; - break; - case 'u': - { - unsigned int codepoint; - if (hatoui(it + 2, it + 6, &codepoint) != it + 6) - { - JSON_ERROR(it, "Bad unicode codepoint"); - } - - if (codepoint <= 0x7F) - { - *last = (char)codepoint; - } - else if (codepoint <= 0x7FF) - { - *last++ = (char)(0xC0 | (codepoint >> 6)); - *last = (char)(0x80 | (codepoint & 0x3F)); - } - else if (codepoint <= 0xFFFF) - { - *last++ = (char)(0xE0 | (codepoint >> 12)); - *last++ = (char)(0x80 | ((codepoint >> 6) & 0x3F)); - *last = (char)(0x80 | (codepoint & 0x3F)); - } - } - it += 4; - break; - default: - JSON_ERROR(first, "Unrecognized escape sequence"); + JSON_ERROR(it, "Bad unicode codepoint"); } - ++last; - it += 2; + if (codepoint <= 0x7F) + { + *last = (char) codepoint; + } + else if (codepoint <= 0x7FF) + { + *last++ = (char) (0xC0 | (codepoint >> 6)); + *last = (char) (0x80 | (codepoint & 0x3F)); + } + else if (codepoint <= 0xFFFF) + { + *last++ = (char) (0xE0 | (codepoint >> 12)); + *last++ = (char) (0x80 | ((codepoint >> 6) & 0x3F)); + *last = (char) (0x80 | (codepoint & 0x3F)); + } } - else if (*it == '"') - { - *last = 0; - ++it; + it += 4; break; + default: + JSON_ERROR(first, "Unrecognized escape sequence"); } - else - { - *last++ = *it++; - } - } - if (!name && top->type == JSON_OBJECT) + ++last; + it += 2; + } + else if (*it == '"') { - // field name in object - name = first; + *last = 0; + ++it; + break; } else { - // new string value - json_value *object = json_alloc(allocator); + *last++ = *it++; + } + } + + if (!name && top->type == JSON_OBJECT) + { + // field name in object + name = first; + } + else + { + // new string value + json_value *object = json_alloc(allocator); - object->name = name; - name = 0; + object->name = name; + name = 0; - object->type = JSON_STRING; - object->string_value = first; + object->type = JSON_STRING; + object->string_value = first; - json_append(top, object); - } + json_append(top, object); } - break; + } + break; case 'n': case 't': case 'f': - { - CHECK_TOP(); + { + CHECK_TOP(); - // new null/bool value - json_value *object = json_alloc(allocator); + // new null/bool value + json_value *object = json_alloc(allocator); - if (top->type == JSON_OBJECT && !name) - { - JSON_ERROR(it, "Missing name"); - } + if (top->type == JSON_OBJECT && !name) + { + JSON_ERROR(it, "Missing name"); + } - object->name = name; - name = 0; + object->name = name; + name = 0; - // null - if (it[0] == 'n' && it[1] == 'u' && it[2] == 'l' && it[3] == 'l') - { - object->type = JSON_NULL; - it += 4; - } - // true - else if (it[0] == 't' && it[1] == 'r' && it[2] == 'u' && it[3] == 'e') - { - object->type = JSON_BOOL; - object->int_value = 1; - it += 4; - } - // false - else if (it[0] == 'f' && it[1] == 'a' && it[2] == 'l' && it[3] == 's' && it[4] == 'e') - { - object->type = JSON_BOOL; - object->int_value = 0; - it += 5; - } - else - { - JSON_ERROR(it, "Unknown identifier"); - } - - json_append(top, object); + // null + if (it[0] == 'n' && it[1] == 'u' && it[2] == 'l' && it[3] == 'l') + { + object->type = JSON_NULL; + it += 4; + } + // true + else if (it[0] == 't' && it[1] == 'r' && it[2] == 'u' && it[3] == 'e') + { + object->type = JSON_BOOL; + object->int_value = 1; + it += 4; + } + // false + else if (it[0] == 'f' && it[1] == 'a' && it[2] == 'l' && it[3] == 's' && it[4] == 'e') + { + object->type = JSON_BOOL; + object->int_value = 0; + it += 5; + } + else + { + JSON_ERROR(it, "Unknown identifier"); } - break; + + json_append(top, object); + } + break; case '-': case '0': @@ -584,45 +590,45 @@ static json_value *json_parse(char *source, const char **error_pos, case '7': case '8': case '9': - { - CHECK_TOP(); - - // new number value - json_value *object = json_alloc(allocator); + { + CHECK_TOP(); - if (top->type == JSON_OBJECT && !name) - { - JSON_ERROR(it, "Missing name"); - } + // new number value + json_value *object = json_alloc(allocator); - object->name = name; - name = 0; + if (top->type == JSON_OBJECT && !name) + { + JSON_ERROR(it, "Missing name"); + } - object->type = JSON_INT; + object->name = name; + name = 0; - char *first = it; - while (*it != '\x20' && *it != '\x9' && *it != '\xD' && *it != '\xA' && *it != ',' && *it != ']' && *it != '}') - { - if (*it == '.' || *it == 'e' || *it == 'E') - { - object->type = JSON_FLOAT; - } - ++it; - } + object->type = JSON_INT; - if (object->type == JSON_INT && atoi(first, it, &object->int_value) != it) + char *first = it; + while (*it != '\x20' && *it != '\x9' && *it != '\xD' && *it != '\xA' && *it != ',' && *it != ']' && *it != '}') + { + if (*it == '.' || *it == 'e' || *it == 'E') { - JSON_ERROR(first, "Bad integer number"); + object->type = JSON_FLOAT; } + ++it; + } - if (object->type == JSON_FLOAT && atof(first, it, &object->float_value) != it) - { - JSON_ERROR(first, "Bad float number"); - } + if (object->type == JSON_INT && atoi(first, it, &object->int_value) != it) + { + JSON_ERROR(first, "Bad integer number"); + } - json_append(top, object); + if (object->type == JSON_FLOAT && atof(first, it, &object->float_value) != it) + { + JSON_ERROR(first, "Bad float number"); } - break; + + json_append(top, object); + } + break; default: JSON_ERROR(it, "Unexpected character"); @@ -661,8 +667,16 @@ struct JsonParserImpl const char *error_desc; int error_line; - JsonParserImpl() : alloc(4096), tmpbuf(nullptr) { } - ~JsonParserImpl() { if (tmpbuf) ::free(tmpbuf); } + JsonParserImpl() + : alloc(4096) + , tmpbuf(nullptr) + { + } + ~JsonParserImpl() + { + if (tmpbuf) + ::free(tmpbuf); + } }; JsonParser::JsonParser() diff --git a/src/json_parser.h b/src/json_parser.h index 7e7653f37..0cc34a63c 100644 --- a/src/json_parser.h +++ b/src/json_parser.h @@ -86,7 +86,8 @@ struct json_value json_type type; }; -#define json_for_each(_item, _container) for (const json_value *_item = _container->first_child; _item; _item = _item->next_sibling) +#define json_for_each(_item, _container) \ + for (const json_value *_item = _container->first_child; _item; _item = _item->next_sibling) struct JsonParserImpl; diff --git a/src/log_uploader.cpp b/src/log_uploader.cpp index fac3ba530..f27932719 100644 --- a/src/log_uploader.cpp +++ b/src/log_uploader.cpp @@ -59,7 +59,11 @@ struct WindowUpdateLocker { wxWindow *m_win; - WindowUpdateLocker(wxWindow *win) : m_win(win) { win->Freeze(); } + WindowUpdateLocker(wxWindow *win) + : m_win(win) + { + win->Freeze(); + } ~WindowUpdateLocker() { m_win->Thaw(); @@ -92,7 +96,7 @@ struct Session static std::vector s_session; // grid sort order defined by these maps between grid row and session index -static std::vector s_grid_row; // map session index to grid row +static std::vector s_grid_row; // map session index to grid row static std::vector s_session_idx; // map grid row => session index static bool s_include_empty; @@ -120,7 +124,7 @@ enum struct LogScanner { wxGrid *m_grid; - std::deque m_q; // indexes remaining to be checked + std::deque m_q; // indexes remaining to be checked std::ifstream m_ifs; wxDateTime m_guiding_starts; void Init(wxGrid *grid); @@ -155,10 +159,10 @@ static wxString FormatTimeSpan(const wxTimeSpan& dt) { int days = dt.GetDays(); if (days > 1) - return wxString::Format(_("%dd"), days); // 2d or more + return wxString::Format(_("%dd"), days); // 2d or more int hrs = dt.GetHours(); if (days == 1) - return wxString::Format(_("%dhr"), hrs); // 24-47h + return wxString::Format(_("%dhr"), hrs); // 24-47h // < 24h int mins = dt.GetMinutes(); mins -= hrs * 60; @@ -173,21 +177,21 @@ static wxString FormatTimeSpan(const wxTimeSpan& dt) static wxString FormatGuideFor(const Session& session) { - switch (session.summary_loaded) { - case ST_BEGIN: default: - return wxEmptyString; - case ST_LOADING: - return _("loading..."); - case ST_LOADED: - if (session.HasGuiding()) - { - // looks better in the grid with some padding - return " " + - FormatTimeSpan(wxTimeSpan(0 /* hrs */, 0 /* minutes */, session.summary.guide_dur)) + - " "; - } - else - return _("None"); + switch (session.summary_loaded) + { + case ST_BEGIN: + default: + return wxEmptyString; + case ST_LOADING: + return _("loading..."); + case ST_LOADED: + if (session.HasGuiding()) + { + // looks better in the grid with some padding + return " " + FormatTimeSpan(wxTimeSpan(0 /* hrs */, 0 /* minutes */, session.summary.guide_dur)) + " "; + } + else + return _("None"); } } @@ -251,8 +255,7 @@ static std::string GA_COMPLETE("INFO: GA Result - Dec Drift Rate="); inline static bool StartsWith(const std::string& s, const std::string& pfx) { - return s.length() >= pfx.length() && - s.compare(0, pfx.length(), pfx) == 0; + return s.length() >= pfx.length() && s.compare(0, pfx.length(), pfx) == 0; } bool LogScanner::DoWork(unsigned int millis) @@ -426,7 +429,8 @@ static int GetSortCol(wxGrid *grid) { int col = -1; for (int i = 0; i < grid->GetNumberCols(); i++) - if (grid->IsSortingBy(i)) { + if (grid->IsSortingBy(i)) + { col = i; break; } @@ -436,9 +440,14 @@ static int GetSortCol(wxGrid *grid) struct SessionCompare { bool asc; - SessionCompare(bool asc_) : asc(asc_) { } - bool operator()(int a, int b) const { - if (!asc) std::swap(a, b); + SessionCompare(bool asc_) + : asc(asc_) + { + } + bool operator()(int a, int b) const + { + if (!asc) + std::swap(a, b); return s_session[a].start < s_session[b].start; } }; @@ -626,7 +635,7 @@ static void LoadRecentUploads() static void SaveUploadInfo(const wxString& url, const wxDateTime& time) { - for (auto it = s_recent.begin(); it != s_recent.end(); ++it) + for (auto it = s_recent.begin(); it != s_recent.end(); ++it) { if (it->url == url) { @@ -634,7 +643,10 @@ static void SaveUploadInfo(const wxString& url, const wxDateTime& time) break; } } - enum { MAX_RECENT = 5 }; + enum + { + MAX_RECENT = 5 + }; while (s_recent.size() >= MAX_RECENT) s_recent.pop_front(); Uploaded t; @@ -656,17 +668,15 @@ static void SaveUploadInfo(const wxString& url, const wxDateTime& time) #define STEP3_TITLE_OK _("Upload Log Files - Upload complete") #define STEP3_TITLE_FAIL _("Upload Log Files - Upload not completed") -#define STEP1_MESSAGE _( \ - "When asking for help in the PHD2 Forum it is important to include your PHD2 logs. This tool will " \ - "help you upload your log files so they can be seen in the forum.\n" \ - "The first step is to select which files to upload.\n" \ -) +#define STEP1_MESSAGE \ + _("When asking for help in the PHD2 Forum it is important to include your PHD2 logs. This tool will " \ + "help you upload your log files so they can be seen in the forum.\n" \ + "The first step is to select which files to upload.\n") LogUploadDialog::LogUploadDialog(wxWindow *parent) - : - wxDialog(parent, wxID_ANY, STEP1_TITLE, wxDefaultPosition, wxSize(580, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), - m_step(1), - m_nrSelected(0) + : wxDialog(parent, wxID_ANY, STEP1_TITLE, wxDefaultPosition, wxSize(580, 480), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) + , m_step(1) + , m_nrSelected(0) { SetSizeHints(wxDefaultSize, wxDefaultSize); @@ -716,7 +726,8 @@ LogUploadDialog::LogUploadDialog(wxWindow *parent) m_grid->SetRowLabelSize(0); m_grid->SetRowLabelAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE); - m_recent = new wxHyperlinkCtrl(this, wxID_ANY, _("Recent uploads"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE); + m_recent = new wxHyperlinkCtrl( + this, wxID_ANY, _("Recent uploads"), wxEmptyString, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE); LoadRecentUploads(); if (s_recent.empty()) @@ -732,10 +743,10 @@ LogUploadDialog::LogUploadDialog(wxWindow *parent) m_includeEmpty = new wxCheckBox(this, wxID_ANY, _("Show logs with no guiding")); m_includeEmpty->SetToolTip(_("Show all available logs, including logs from nights when there was no guiding")); - wxBoxSizer *sizer0 = new wxBoxSizer(wxVERTICAL); // top-level sizer - wxBoxSizer *sizer1 = new wxBoxSizer(wxVERTICAL); // sizer containing the grid - wxBoxSizer *sizer2 = new wxBoxSizer(wxHORIZONTAL); // sizer containing the buttons below the grid - wxBoxSizer *sizer3 = new wxBoxSizer(wxHORIZONTAL); // sizer containing Recent uploads and Include empty checkbox + wxBoxSizer *sizer0 = new wxBoxSizer(wxVERTICAL); // top-level sizer + wxBoxSizer *sizer1 = new wxBoxSizer(wxVERTICAL); // sizer containing the grid + wxBoxSizer *sizer2 = new wxBoxSizer(wxHORIZONTAL); // sizer containing the buttons below the grid + wxBoxSizer *sizer3 = new wxBoxSizer(wxHORIZONTAL); // sizer containing Recent uploads and Include empty checkbox sizer1->Add(m_grid, 0, wxALL | wxEXPAND, 5); @@ -814,8 +825,7 @@ void LogUploadDialog::OnCellLeftClick(wxGridEvent& event) } int r; - if ((r = event.GetRow()) < s_session.size() && - event.GetCol() == COL_SELECT) + if ((r = event.GetRow()) < s_session.size() && event.GetCol() == COL_SELECT) { const Session& session = s_session[s_session_idx[r]]; if (session.has_guide || session.has_debug) @@ -859,15 +869,16 @@ struct AutoChdir m_prev = wxFileName::GetCwd(); wxFileName::SetCwd(dir); } - ~AutoChdir() - { - wxFileName::SetCwd(m_prev); - } + ~AutoChdir() { wxFileName::SetCwd(m_prev); } }; struct FileData { - FileData(const wxString& name, const wxDateTime& ts) : filename(name), timestamp(ts) { } + FileData(const wxString& name, const wxDateTime& ts) + : filename(name) + , timestamp(ts) + { + } wxString filename; wxDateTime timestamp; }; @@ -889,7 +900,12 @@ struct BgUpload : public RunInBg std::ostringstream m_response; UploadErr m_err; - BgUpload(wxWindow *parent) : RunInBg(parent, _("Upload"), _("Uploading log files ...")), m_curl(nullptr), m_err(UPL_INTERNAL_ERROR) {} + BgUpload(wxWindow *parent) + : RunInBg(parent, _("Upload"), _("Uploading log files ...")) + , m_curl(nullptr) + , m_err(UPL_INTERNAL_ERROR) + { + } ~BgUpload() override; bool Entry() override; }; @@ -973,9 +989,13 @@ static long QueryMaxSize(BgUpload *upload) upload->SetMessage(_("Connecting ...")); - int waitSecs[] = { 1, 5, 15, }; + int waitSecs[] = { + 1, + 5, + 15, + }; - for (int tries = 0; ; tries++) + for (int tries = 0;; tries++) { CURLcode res = curl_easy_perform(upload->m_curl); if (res == CURLE_OK) @@ -984,7 +1004,8 @@ static long QueryMaxSize(BgUpload *upload) if (tries < WXSIZEOF(waitSecs)) { int secs = waitSecs[tries]; - Debug.Write(wxString::Format("Upload log: get limits failed: %s, wait %ds for retry\n", curl_easy_strerror(res), secs)); + Debug.Write( + wxString::Format("Upload log: get limits failed: %s, wait %ds for retry\n", curl_easy_strerror(res), secs)); for (int i = secs; i > 0; --i) { upload->SetMessage(wxString::Format(_("Connection failed, will retry in %ds"), i)); @@ -1129,9 +1150,13 @@ bool BgUpload::Entry() // do the upload - int waitSecs[] = { 1, 5, 15, }; + int waitSecs[] = { + 1, + 5, + 15, + }; - for (int tries = 0; ; tries++) + for (int tries = 0;; tries++) { CURLcode res = curl_easy_perform(m_curl); if (res == CURLE_OK) @@ -1167,8 +1192,7 @@ bool BgUpload::Entry() curl_easy_getinfo(m_curl, CURLINFO_SPEED_UPLOAD_T, &speed_upload); curl_easy_getinfo(m_curl, CURLINFO_TOTAL_TIME, &total_time); - Debug.Write(wxString::Format("Upload log: %ld bytes/sec, %.3f seconds elapsed\n", - (long) speed_upload, total_time)); + Debug.Write(wxString::Format("Upload log: %ld bytes/sec, %.3f seconds elapsed\n", (long) speed_upload, total_time)); return true; } @@ -1196,8 +1220,8 @@ void LogUploadDialog::ConfirmUpload() else logs = _("Guide log"); - msg += wxString::Format("%-20s %-27s %s
", m_grid->GetCellValue(r, COL_NIGHTOF), - FormatTimestamp(session.start), logs); + msg += + wxString::Format("%-20s %-27s %s
", m_grid->GetCellValue(r, COL_NIGHTOF), FormatTimestamp(session.start), logs); } msg += ""; @@ -1259,7 +1283,7 @@ void LogUploadDialog::ExecUpload() JsonParser parser; if (parser.Parse(s)) { - json_for_each (n, parser.Root()) + json_for_each(n, parser.Root()) { if (!n->name) continue; @@ -1280,12 +1304,16 @@ void LogUploadDialog::ExecUpload() if (ok) { SaveUploadInfo(url, wxDateTime::Now()); - wxString msg = wxString::Format(_("The log files have been uploaded and can be accessed at this link:") + "
" - "
" - "%s

" + - _("You can share your log files in the PHD2 Forum by posting a message that includes the link. " - "Copy and paste the link into your forum post.") + "

" + - wxString::Format("", (unsigned int)(s_recent.size() - 1)) + _("Copy link to clipboard"), url); + wxString msg = wxString::Format(_("The log files have been uploaded and can be accessed at this link:") + + "
" + "
" + "%s

" + + _("You can share your log files in the
PHD2 Forum by posting a message that includes the " + "link. " + "Copy and paste the link into your forum post.") + + "

" + wxString::Format("", (unsigned int) (s_recent.size() - 1)) + + _("Copy link to clipboard"), + url); WindowUpdateLocker noUpdates(this); SetTitle(STEP3_TITLE_OK); m_html->SetPage(msg); @@ -1333,9 +1361,8 @@ void LogUploadDialog::OnRecentClicked(wxHyperlinkEvent& event) int i = s_recent.size() - 1; for (auto it = s_recent.rbegin(); it != s_recent.rend(); ++it, --i) { - os << "" << wxDateTime(it->when).Format() << "" - << "" << it->url << "" - << "Copy link"; + os << "" << wxDateTime(it->when).Format() << "" << "" << it->url << "" + << "Copy link"; } os << ""; diff --git a/src/log_uploader.h b/src/log_uploader.h index 493279abc..411442139 100644 --- a/src/log_uploader.h +++ b/src/log_uploader.h @@ -37,6 +37,7 @@ class LogUploader { LogUploader() = delete; + public: static void UploadLogs(); }; diff --git a/src/logger.cpp b/src/logger.cpp index 5ce71e59d..cd729b275 100644 --- a/src/logger.cpp +++ b/src/logger.cpp @@ -43,9 +43,7 @@ Logger::Logger() m_Initialized = false; } -Logger::~Logger() -{ -} +Logger::~Logger() { } // Default, safety-net implementation behind derived logger classes bool Logger::ChangeDirLog(const wxString& newdir) @@ -62,7 +60,7 @@ static wxString DefaultDir() if (!wxDirExists(rslt)) if (!wxFileName::Mkdir(rslt, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) - rslt = stdpath.GetDocumentsDir(); // should never happen + rslt = stdpath.GetDocumentsDir(); // should never happen return rslt; } @@ -80,17 +78,16 @@ const wxString& Logger::GetLogDir() { rslt = pConfig->Global.GetString("/frame/LogDir", wxEmptyString); if (rslt.empty()) - rslt = DefaultDir(); // user has never even looked at it - else - if (!wxDirExists(rslt)) // user might have deleted our old directories - { - // will build entire hierarchy if needed - if (!wxFileName::Mkdir(rslt, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) - rslt = DefaultDir(); - } + rslt = DefaultDir(); // user has never even looked at it + else if (!wxDirExists(rslt)) // user might have deleted our old directories + { + // will build entire hierarchy if needed + if (!wxFileName::Mkdir(rslt, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) + rslt = DefaultDir(); + } } else - rslt = DefaultDir(); // shouldn't ever happen + rslt = DefaultDir(); // shouldn't ever happen m_CurrentDir = rslt; m_Initialized = true; @@ -107,13 +104,13 @@ bool Logger::SetLogDir(const wxString& dir) wxString newdir(dir); bool bOk = true; - if (newdir.EndsWith(PATHSEPSTR)) // Need a standard form - no trailing separators + if (newdir.EndsWith(PATHSEPSTR)) // Need a standard form - no trailing separators { wxString stemp = PATHSEPSTR; newdir = newdir.substr(0, newdir.length() - stemp.length()); } - if (newdir.empty()) // Empty-string shorthand for "default location" + if (newdir.empty()) // Empty-string shorthand for "default location" { newdir = DefaultDir(); } @@ -147,7 +144,7 @@ void Logger::RemoveMatchingFiles(const wxString& filePattern, int DaysOld) try { wxArrayString results; - int numFiles = wxDir::GetAllFiles(GetLogDir(), &results, filePattern, wxDIR_FILES); // No sub-directories, just files + int numFiles = wxDir::GetAllFiles(GetLogDir(), &results, filePattern, wxDIR_FILES); // No sub-directories, just files for (int inx = 0; inx < numFiles; inx++) { @@ -155,12 +152,12 @@ void Logger::RemoveMatchingFiles(const wxString& filePattern, int DaysOld) if (stamp < oldestDate) { ++hitCount; - lastFile = results[inx]; // For error logging + lastFile = results[inx]; // For error logging wxRemoveFile(lastFile); } } } - catch (const wxString& Msg) // Eat the errors and press ahead, no place for UI here + catch (const wxString& Msg) // Eat the errors and press ahead, no place for UI here { Debug.Write(wxString::Format("Error cleaning up old log file %s: %s\n", lastFile, Msg)); } @@ -208,7 +205,7 @@ void Logger::RemoveOldDirectories(const wxString& filePattern, int DaysOld) } } } - catch (const wxString& Msg) // Eat the errors and press ahead, no place for UI here + catch (const wxString& Msg) // Eat the errors and press ahead, no place for UI here { Debug.Write(wxString::Format("Error removing old debug log directory %s: %s\n", subdir, Msg)); } diff --git a/src/logger.h b/src/logger.h index c363fa614..3c16228aa 100644 --- a/src/logger.h +++ b/src/logger.h @@ -41,12 +41,10 @@ class Logger bool m_Initialized; protected: - bool SetLogDir(const wxString& newdir); virtual bool ChangeDirLog(const wxString& newdir); public: - Logger(); virtual ~Logger(); diff --git a/src/manualcal_dialog.cpp b/src/manualcal_dialog.cpp index e3fac8991..f228b5896 100644 --- a/src/manualcal_dialog.cpp +++ b/src/manualcal_dialog.cpp @@ -51,32 +51,32 @@ ManualCalDialog::ManualCalDialog(const Calibration& cal) pGridSizer->Add(pLabel); pGridSizer->Add(m_binning); - pLabel = new wxStaticText(this,wxID_ANY, _("RA rate, px/sec (e.g. 5.0):")); - m_pXRate = new wxTextCtrl(this,wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); + pLabel = new wxStaticText(this, wxID_ANY, _("RA rate, px/sec (e.g. 5.0):")); + m_pXRate = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); m_pXRate->SetValue(wxString::Format("%.3f", cal.xRate * 1000.0)); pGridSizer->Add(pLabel); pGridSizer->Add(m_pXRate); - pLabel = new wxStaticText(this,wxID_ANY, _("Dec rate, px/sec (e.g. 5.0):")); - m_pYRate = new wxTextCtrl(this,wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); + pLabel = new wxStaticText(this, wxID_ANY, _("Dec rate, px/sec (e.g. 5.0):")); + m_pYRate = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); m_pYRate->SetValue(wxString::Format("%.3f", cal.yRate * 1000.0)); pGridSizer->Add(pLabel); pGridSizer->Add(m_pYRate); - pLabel = new wxStaticText(this,wxID_ANY, _("RA angle (degrees):")); - m_pXAngle = new wxTextCtrl(this,wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); + pLabel = new wxStaticText(this, wxID_ANY, _("RA angle (degrees):")); + m_pXAngle = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); m_pXAngle->SetValue(wxString::Format("%.1f", degrees(cal.xAngle))); pGridSizer->Add(pLabel); pGridSizer->Add(m_pXAngle); - pLabel = new wxStaticText(this,wxID_ANY, _("Dec angle (degrees):")); - m_pYAngle = new wxTextCtrl(this,wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); + pLabel = new wxStaticText(this, wxID_ANY, _("Dec angle (degrees):")); + m_pYAngle = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); m_pYAngle->SetValue(wxString::Format("%.1f", degrees(cal.yAngle))); pGridSizer->Add(pLabel); pGridSizer->Add(m_pYAngle); - pLabel = new wxStaticText(this,wxID_ANY, _("Declination (e.g. 2.1):")); - m_pDeclination = new wxTextCtrl(this,wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); + pLabel = new wxStaticText(this, wxID_ANY, _("Declination (e.g. 2.1):")); + m_pDeclination = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1)); double dec = cal.declination == UNKNOWN_DECLINATION ? 0.0 : cal.declination; m_pDeclination->SetValue(wxString::Format("%.1f", dec)); pGridSizer->Add(pLabel); @@ -85,7 +85,7 @@ ManualCalDialog::ManualCalDialog(const Calibration& cal) pVSizer->Add(pGridSizer, wxSizerFlags(0).Border(wxALL, 10)); pVSizer->Add(CreateButtonSizer(wxOK | wxCANCEL), wxSizerFlags(0).Right().Border(wxALL, 10)); - SetSizerAndFit (pVSizer); + SetSizerAndFit(pVSizer); m_pXRate->SetFocus(); } @@ -114,6 +114,4 @@ void ManualCalDialog::GetValues(Calibration *cal) cal->binning = m_binning->GetSelection() + 1; } -ManualCalDialog::~ManualCalDialog(void) -{ -} +ManualCalDialog::~ManualCalDialog(void) { } diff --git a/src/manualcal_dialog.h b/src/manualcal_dialog.h index a60d8df29..0c472a6ae 100644 --- a/src/manualcal_dialog.h +++ b/src/manualcal_dialog.h @@ -36,8 +36,7 @@ #ifndef ManualCalDialog_h_included #define ManualCalDialog_h_included -class ManualCalDialog : - public wxDialog +class ManualCalDialog : public wxDialog { private: wxChoice *m_binning; diff --git a/src/messagebox_proxy.cpp b/src/messagebox_proxy.cpp index cecb9da05..8ce33d8e0 100644 --- a/src/messagebox_proxy.cpp +++ b/src/messagebox_proxy.cpp @@ -74,7 +74,7 @@ int wxMessageBoxProxy::wxMessageBox(const wxString& message, const wxString& cap void MyFrame::OnMessageBoxProxy(wxCommandEvent& evt) { - wxMessageBoxProxy *pRequest = (wxMessageBoxProxy *)evt.GetClientData(); + wxMessageBoxProxy *pRequest = (wxMessageBoxProxy *) evt.GetClientData(); pRequest->showMessageBox(); } diff --git a/src/messagebox_proxy.h b/src/messagebox_proxy.h index 7137e866f..264d68f87 100644 --- a/src/messagebox_proxy.h +++ b/src/messagebox_proxy.h @@ -44,12 +44,13 @@ class wxMessageBoxProxy wxWindow *m_parent; int m_x; int m_y; - wxSemaphore m_semaphore; + wxSemaphore m_semaphore; int m_result; public: void showMessageBox(void); - int wxMessageBox(const wxString& message, const wxString& caption = "Message", int style = wxOK, wxWindow *parent = nullptr, int x = -1, int y = -1); + int wxMessageBox(const wxString& message, const wxString& caption = "Message", int style = wxOK, wxWindow *parent = nullptr, + int x = -1, int y = -1); }; #endif // MESSAGEBOX_PROXY_H_INCLUDED diff --git a/src/mount.cpp b/src/mount.cpp index da2d077a4..6fb9f68d8 100644 --- a/src/mount.cpp +++ b/src/mount.cpp @@ -49,34 +49,45 @@ enum inline static PierSide OppositeSide(PierSide p) { - switch (p) { - case PIER_SIDE_EAST: return PIER_SIDE_WEST; - case PIER_SIDE_WEST: return PIER_SIDE_EAST; - default: return PIER_SIDE_UNKNOWN; + switch (p) + { + case PIER_SIDE_EAST: + return PIER_SIDE_WEST; + case PIER_SIDE_WEST: + return PIER_SIDE_EAST; + default: + return PIER_SIDE_UNKNOWN; } } inline static bool IsOppositeSide(PierSide a, PierSide b) { - return (a == PIER_SIDE_EAST && b == PIER_SIDE_WEST) || - (a == PIER_SIDE_WEST && b == PIER_SIDE_EAST); + return (a == PIER_SIDE_EAST && b == PIER_SIDE_WEST) || (a == PIER_SIDE_WEST && b == PIER_SIDE_EAST); } inline static wxString PierSideStr(PierSide p) { - switch (p) { - case PIER_SIDE_EAST: return "East"; - case PIER_SIDE_WEST: return "West"; - default: return "Unknown"; + switch (p) + { + case PIER_SIDE_EAST: + return "East"; + case PIER_SIDE_WEST: + return "West"; + default: + return "Unknown"; } } inline static wxString PierSideStrTr(PierSide p, const wxString& unknown = _("Unknown")) { - switch (p) { - case PIER_SIDE_EAST: return _("East"); - case PIER_SIDE_WEST: return _("West"); - default: return unknown; + switch (p) + { + case PIER_SIDE_EAST: + return _("East"); + case PIER_SIDE_WEST: + return _("West"); + default: + return unknown; } } @@ -92,20 +103,30 @@ wxString Mount::PierSideStrTr(PierSide p) inline static const char *ParityStr(GuideParity par) { - switch (par) { - case GUIDE_PARITY_EVEN: return "+"; - case GUIDE_PARITY_ODD: return "-"; - case GUIDE_PARITY_UNKNOWN: return "?"; - default: case GUIDE_PARITY_UNCHANGED: return "x"; + switch (par) + { + case GUIDE_PARITY_EVEN: + return "+"; + case GUIDE_PARITY_ODD: + return "-"; + case GUIDE_PARITY_UNKNOWN: + return "?"; + default: + case GUIDE_PARITY_UNCHANGED: + return "x"; } } inline static GuideParity OppositeParity(GuideParity p) { - switch (p) { - case GUIDE_PARITY_EVEN: return GUIDE_PARITY_ODD; - case GUIDE_PARITY_ODD: return GUIDE_PARITY_EVEN; - default: return p; + switch (p) + { + case GUIDE_PARITY_EVEN: + return GUIDE_PARITY_ODD; + case GUIDE_PARITY_ODD: + return GUIDE_PARITY_EVEN; + default: + return p; } } @@ -151,7 +172,7 @@ static GUIDE_ALGORITHM GuideAlgorithmFromName(const wxString& s) return GUIDE_ALGORITHM_LOWPASS2; if (s == _("Resist Switch")) return GUIDE_ALGORITHM_RESIST_SWITCH; - if (s ==_("Predictive PEC")) + if (s == _("Predictive PEC")) return GUIDE_ALGORITHM_GAUSSIAN_PROCESS; if (s.StartsWith(_("ZFilter"))) return GUIDE_ALGORITHM_ZFILTER; @@ -203,8 +224,7 @@ void Mount::MountConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdM m_pDecBox = new wxStaticBoxSizer(wxVERTICAL, m_pParent, stepGuider ? _("AO Y-Axis") : _("Declination")); wxSizerFlags def_flags = wxSizerFlags(0).Border(wxALL, 5).Expand(); - static GUIDE_ALGORITHM const RA_ALGORITHMS[] = - { + static GUIDE_ALGORITHM const RA_ALGORITHMS[] = { GUIDE_ALGORITHM_HYSTERESIS, GUIDE_ALGORITHM_LOWPASS, GUIDE_ALGORITHM_LOWPASS2, @@ -212,16 +232,14 @@ void Mount::MountConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdM GUIDE_ALGORITHM_GAUSSIAN_PROCESS, GUIDE_ALGORITHM_ZFILTER, }; - static GUIDE_ALGORITHM const DEC_ALGORITHMS[] = - { + static GUIDE_ALGORITHM const DEC_ALGORITHMS[] = { GUIDE_ALGORITHM_HYSTERESIS, GUIDE_ALGORITHM_LOWPASS, GUIDE_ALGORITHM_LOWPASS2, GUIDE_ALGORITHM_RESIST_SWITCH, GUIDE_ALGORITHM_ZFILTER, }; - static GUIDE_ALGORITHM const AO_ALGORITHMS[] = - { + static GUIDE_ALGORITHM const AO_ALGORITHMS[] = { GUIDE_ALGORITHM_HYSTERESIS, GUIDE_ALGORITHM_LOWPASS, GUIDE_ALGORITHM_LOWPASS2, @@ -241,8 +259,7 @@ void Mount::MountConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdM } width = StringArrayWidth(&xAlgorithms[0], xAlgorithms.size()); - m_pXGuideAlgorithmChoice = new wxChoice(m_pParent, wxID_ANY, wxPoint(-1, -1), - wxSize(width + 35, -1), xAlgorithms); + m_pXGuideAlgorithmChoice = new wxChoice(m_pParent, wxID_ANY, wxPoint(-1, -1), wxSize(width + 35, -1), xAlgorithms); if (stepGuider) m_pXGuideAlgorithmChoice->SetToolTip(_("Which Guide Algorithm to use for X-axis")); @@ -258,7 +275,8 @@ void Mount::MountConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdM } else { - m_pXGuideAlgorithmConfigDialogPane = GetGuideAlgoDialogPane(m_pMount->m_pXGuideAlgorithm, m_pParent, Algo_RA_Layout_Height); + m_pXGuideAlgorithmConfigDialogPane = + GetGuideAlgoDialogPane(m_pMount->m_pXGuideAlgorithm, m_pParent, Algo_RA_Layout_Height); } m_pRABox->Add(m_pXGuideAlgorithmChoice, def_flags); m_pRABox->Add(m_pXGuideAlgorithmConfigDialogPane, def_flags); @@ -289,15 +307,15 @@ void Mount::MountConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdM } width = StringArrayWidth(&yAlgorithms[0], yAlgorithms.size()); - m_pYGuideAlgorithmChoice = new wxChoice(m_pParent, wxID_ANY, wxPoint(-1, -1), - wxSize(width + 35, -1), yAlgorithms); + m_pYGuideAlgorithmChoice = new wxChoice(m_pParent, wxID_ANY, wxPoint(-1, -1), wxSize(width + 35, -1), yAlgorithms); if (stepGuider) m_pYGuideAlgorithmChoice->SetToolTip(_("Which Guide Algorithm to use for Y-axis")); else m_pYGuideAlgorithmChoice->SetToolTip(_("Which Guide Algorithm to use for Declination")); - m_pParent->Connect(m_pYGuideAlgorithmChoice->GetId(), wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(Mount::MountConfigDialogPane::OnYAlgorithmSelected), 0, this); + m_pParent->Connect(m_pYGuideAlgorithmChoice->GetId(), wxEVT_COMMAND_CHOICE_SELECTED, + wxCommandEventHandler(Mount::MountConfigDialogPane::OnYAlgorithmSelected), 0, this); if (!m_pMount->m_pYGuideAlgorithm) { @@ -305,7 +323,8 @@ void Mount::MountConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdM } else { - m_pYGuideAlgorithmConfigDialogPane = GetGuideAlgoDialogPane(m_pMount->m_pYGuideAlgorithm, m_pParent, Algo_Dec_Layout_Height); + m_pYGuideAlgorithmConfigDialogPane = + GetGuideAlgoDialogPane(m_pMount->m_pYGuideAlgorithm, m_pParent, Algo_Dec_Layout_Height); } m_pDecBox->Add(m_pYGuideAlgorithmChoice, def_flags); m_pDecBox->Add(m_pYGuideAlgorithmConfigDialogPane, def_flags); @@ -333,9 +352,7 @@ void Mount::MountConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdM } } -Mount::MountConfigDialogPane::~MountConfigDialogPane() -{ -} +Mount::MountConfigDialogPane::~MountConfigDialogPane() { } void Mount::MountConfigDialogPane::ResetRAGuidingParams() { @@ -343,11 +360,11 @@ void Mount::MountConfigDialogPane::ResetRAGuidingParams() if (!m_pMount) return; GuideAlgorithm *currRAAlgo = m_pMount->m_pXGuideAlgorithm; - currRAAlgo->ResetParams(); // Default is to remove the Registry entries below the "X" or "Y" guide algo name - delete m_pMount->m_pXGuideAlgorithm; // force creation of a new algo instance + currRAAlgo->ResetParams(); // Default is to remove the Registry entries below the "X" or "Y" guide algo name + delete m_pMount->m_pXGuideAlgorithm; // force creation of a new algo instance m_pMount->m_pXGuideAlgorithm = nullptr; wxCommandEvent dummy; - OnXAlgorithmSelected(dummy); // Update the UI + OnXAlgorithmSelected(dummy); // Update the UI // Re-initialize any other RA guiding parameters not part of algos if (!m_pMount->IsStepGuider()) { @@ -438,7 +455,7 @@ void Mount::MountConfigDialogPane::OnYAlgorithmSelected(wxCommandEvent& evt) // For Dec algo change, enable algo controls based on current UI setting for Dec guide mode if (!m_pMount->IsStepGuider()) { - ScopeConfigDialogCtrlSet* pScopeCtrlSet = (ScopeConfigDialogCtrlSet*) m_pMount->currConfigDialogCtrlSet; + ScopeConfigDialogCtrlSet *pScopeCtrlSet = (ScopeConfigDialogCtrlSet *) m_pMount->currConfigDialogCtrlSet; DEC_GUIDE_MODE whichMode = pScopeCtrlSet->GetDecGuideModeUI(); EnableDecControls(whichMode != DEC_NONE); } @@ -525,15 +542,17 @@ void Mount::MountConfigDialogPane::Undo() OnYAlgorithmSelected(dummy); } } -MountConfigDialogCtrlSet *Mount::GetConfigDialogCtrlSet(wxWindow *pParent, Mount *mount, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +MountConfigDialogCtrlSet *Mount::GetConfigDialogCtrlSet( + wxWindow *pParent, Mount *mount, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) { return new MountConfigDialogCtrlSet(pParent, mount, pAdvancedDialog, CtrlMap); } // These are only controls that are exported to other panes - all the other dynamically updated controls are handled in // ConfigDialogPane -MountConfigDialogCtrlSet::MountConfigDialogCtrlSet(wxWindow *pParent, Mount *mount, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) : -ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) +MountConfigDialogCtrlSet::MountConfigDialogCtrlSet( + wxWindow *pParent, Mount *mount, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) + : ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) { bool enableCtrls = mount != nullptr; m_pMount = mount; @@ -541,13 +560,15 @@ ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) { if (!mount->IsStepGuider()) { - m_pClearCalibration = new wxCheckBox(GetParentWindow(AD_cbClearCalibration), wxID_ANY, _("Clear mount calibration")); + m_pClearCalibration = + new wxCheckBox(GetParentWindow(AD_cbClearCalibration), wxID_ANY, _("Clear mount calibration")); m_pClearCalibration->Enable(enableCtrls); AddCtrl(CtrlMap, AD_cbClearCalibration, m_pClearCalibration, _("Clear the current mount calibration data - calibration will be re-done when guiding is started")); m_pEnableGuide = new wxCheckBox(GetParentWindow(AD_cbEnableGuiding), wxID_ANY, _("Enable mount guide output")); AddCtrl(CtrlMap, AD_cbEnableGuiding, m_pEnableGuide, - _("Keep this checked for guiding. Un-check to disable all mount guide commands and allow the mount to run un-guided")); + _("Keep this checked for guiding. Un-check to disable all mount guide commands and allow the mount to run " + "un-guided")); } } } @@ -664,9 +685,7 @@ void Mount::SetGuidingEnabled(bool guidingEnabled) } } -void Mount::DeferPulseLimitAlertCheck() -{ -} +void Mount::DeferPulseLimitAlertCheck() { } GUIDE_ALGORITHM Mount::GetGuideAlgorithm(const GuideAlgorithm *pAlgorithm) { @@ -678,8 +697,10 @@ static GuideAlgorithm *MakeGaussianProcessGuideAlgo(Mount *mount, GuideAxis axis static bool s_gp_debug_inited; if (!s_gp_debug_inited) { - class PHD2DebugLogger : public GPDebug { - void Log(const char *format, ...) { + class PHD2DebugLogger : public GPDebug + { + void Log(const char *format, ...) + { va_list ap; va_start(ap, format); Debug.Write(wxString::FormatV(format + wxString("\n"), ap)); @@ -700,32 +721,32 @@ bool Mount::CreateGuideAlgorithm(int guideAlgorithm, Mount *mount, GuideAxis axi { switch (guideAlgorithm) { - case GUIDE_ALGORITHM_NONE: - case GUIDE_ALGORITHM_IDENTITY: - *ppAlgorithm = new GuideAlgorithmIdentity(mount, axis); - break; - case GUIDE_ALGORITHM_HYSTERESIS: - *ppAlgorithm = new GuideAlgorithmHysteresis(mount, axis); - break; - case GUIDE_ALGORITHM_LOWPASS: - *ppAlgorithm = new GuideAlgorithmLowpass(mount, axis); - break; - case GUIDE_ALGORITHM_LOWPASS2: - *ppAlgorithm = new GuideAlgorithmLowpass2(mount, axis); - break; - case GUIDE_ALGORITHM_RESIST_SWITCH: - *ppAlgorithm = new GuideAlgorithmResistSwitch(mount, axis); - break; - case GUIDE_ALGORITHM_GAUSSIAN_PROCESS: - *ppAlgorithm = MakeGaussianProcessGuideAlgo(mount, axis); - break; - case GUIDE_ALGORITHM_ZFILTER: - *ppAlgorithm = new GuideAlgorithmZFilter(mount, axis); - break; - - default: - throw ERROR_INFO("invalid guideAlgorithm"); - break; + case GUIDE_ALGORITHM_NONE: + case GUIDE_ALGORITHM_IDENTITY: + *ppAlgorithm = new GuideAlgorithmIdentity(mount, axis); + break; + case GUIDE_ALGORITHM_HYSTERESIS: + *ppAlgorithm = new GuideAlgorithmHysteresis(mount, axis); + break; + case GUIDE_ALGORITHM_LOWPASS: + *ppAlgorithm = new GuideAlgorithmLowpass(mount, axis); + break; + case GUIDE_ALGORITHM_LOWPASS2: + *ppAlgorithm = new GuideAlgorithmLowpass2(mount, axis); + break; + case GUIDE_ALGORITHM_RESIST_SWITCH: + *ppAlgorithm = new GuideAlgorithmResistSwitch(mount, axis); + break; + case GUIDE_ALGORITHM_GAUSSIAN_PROCESS: + *ppAlgorithm = MakeGaussianProcessGuideAlgo(mount, axis); + break; + case GUIDE_ALGORITHM_ZFILTER: + *ppAlgorithm = new GuideAlgorithmZFilter(mount, axis); + break; + + default: + throw ERROR_INFO("invalid guideAlgorithm"); + break; } } catch (const wxString& Msg) @@ -750,17 +771,17 @@ void Mount::TestTransforms() if (!bTested) { - for(int inverted=0;inverted<2;inverted++) + for (int inverted = 0; inverted < 2; inverted++) { // we test every 15 degrees, starting at -195 degrees and // ending at 375 degrees - for(int i=-13;i<14;i++) + for (int i = -13; i < 14; i++) { - double xAngle = ((double)i) * M_PI/12.0; + double xAngle = ((double) i) * M_PI / 12.0; double yAngle; - yAngle = xAngle+M_PI/2.0; + yAngle = xAngle + M_PI / 2.0; if (inverted) { @@ -773,17 +794,17 @@ void Mount::TestTransforms() xAngle = atan2(sin(xAngle), cos(xAngle)); yAngle = atan2(sin(yAngle), cos(yAngle)); - Debug.Write(wxString::Format("xidx=%.2f, yIdx=%.2f\n", xAngle/M_PI*180.0/15, yAngle/M_PI*180.0/15)); + Debug.Write(wxString::Format("xidx=%.2f, yIdx=%.2f\n", xAngle / M_PI * 180.0 / 15, yAngle / M_PI * 180.0 / 15)); SetCalibration(xAngle, yAngle, 1.0, 1.0); - for(int j=-13;j<14;j++) + for (int j = -13; j < 14; j++) { - double cameraAngle = ((double)i) * M_PI/12.0; + double cameraAngle = ((double) i) * M_PI / 12.0; cameraAngle = atan2(sin(cameraAngle), cos(cameraAngle)); PHD_Point p0(cos(cameraAngle), sin(cameraAngle)); - assert(fabs((p0.X*p0.X + p0.Y*p0.Y) - 1.00) < 0.01); + assert(fabs((p0.X * p0.X + p0.Y * p0.Y) - 1.00) < 0.01); double p0Angle = p0.Angle(); assert(fabs(cameraAngle - p0Angle) < 0.01); @@ -795,7 +816,7 @@ void Mount::TestTransforms() assert(false); } - assert(fabs((p1.X*p1.X + p1.Y*p1.Y) - 1.00) < 0.01); + assert(fabs((p1.X * p1.X + p1.Y * p1.Y) - 1.00) < 0.01); double adjustedCameraAngle = cameraAngle - xAngle; @@ -819,8 +840,8 @@ void Mount::TestTransforms() } double p2Angle = p2.Angle(); - //assert(fabs(p0Angle - p2Angle) < 0.01); - assert(fabs((p2.X*p2.X + p2.Y*p2.Y) - 1.00) < 0.01); + // assert(fabs(p0Angle - p2Angle) < 0.01); + assert(fabs((p2.X * p2.X + p2.Y * p2.Y) - 1.00) < 0.01); assert(fabs(p0.X - p2.X) < 0.01); assert(fabs(p0.Y - p2.Y) < 0.01); } @@ -889,7 +910,8 @@ bool Mount::FlipCalibration() bool decFlipRequired = CalibrationFlipRequiresDecFlip(); - Debug.Write(wxString::Format("FlipCalibration before: x=%.1f, y=%.1f decFlipRequired=%d sideOfPier=%s rotAngle=%s parity=%s/%s\n", + Debug.Write(wxString::Format( + "FlipCalibration before: x=%.1f, y=%.1f decFlipRequired=%d sideOfPier=%s rotAngle=%s parity=%s/%s\n", degrees(origX), degrees(origY), decFlipRequired, ::PierSideStr(m_cal.pierSide), RotAngleStr(m_cal.rotatorAngle), ParityStr(m_cal.raGuideParity), ParityStr(m_cal.decGuideParity))); @@ -915,8 +937,8 @@ bool Mount::FlipCalibration() // For mounts with CalibrationFlipRequiresDecFlip, the parity does not change after the flip. GuideParity newDecParity = decFlipRequired ? m_cal.decGuideParity : OppositeParity(m_cal.decGuideParity); - Debug.Write(wxString::Format("FlipCalibration after: x=%.1f y=%.1f sideOfPier=%s parity=%s/%s\n", - degrees(newX), degrees(newY), ::PierSideStr(newPierSide), ParityStr(m_cal.raGuideParity), ParityStr(newDecParity))); + Debug.Write(wxString::Format("FlipCalibration after: x=%.1f y=%.1f sideOfPier=%s parity=%s/%s\n", degrees(newX), + degrees(newY), ::PierSideStr(newPierSide), ParityStr(m_cal.raGuideParity), ParityStr(newDecParity))); Calibration cal(m_cal); cal.xAngle = newX; @@ -926,9 +948,8 @@ bool Mount::FlipCalibration() SetCalibration(cal); - pFrame->StatusMsg(wxString::Format(_("CAL: %s(%.f,%.f)->%s(%.f,%.f)"), - ::PierSideStrTr(priorPierSide, wxEmptyString), degrees(origX), degrees(origY), - ::PierSideStrTr(newPierSide, wxEmptyString), degrees(newX), degrees(newY))); + pFrame->StatusMsg(wxString::Format(_("CAL: %s(%.f,%.f)->%s(%.f,%.f)"), ::PierSideStrTr(priorPierSide, wxEmptyString), + degrees(origX), degrees(origY), ::PierSideStrTr(newPierSide, wxEmptyString), degrees(newX), degrees(newY))); } catch (const wxString& Msg) { @@ -974,8 +995,7 @@ Mount::MOVE_RESULT Mount::MoveOffset(GuiderOffset *ofs, unsigned int moveOptions return result; ofs->mountOfs.SetXY(xDistance, yDistance); - Debug.Write(wxString::Format("Dead-reckoning move xDistance=%.2f yDistance=%.2f\n", - xDistance, yDistance)); + Debug.Write(wxString::Format("Dead-reckoning move xDistance=%.2f yDistance=%.2f\n", xDistance, yDistance)); } else { @@ -992,8 +1012,8 @@ Mount::MOVE_RESULT Mount::MoveOffset(GuiderOffset *ofs, unsigned int moveOptions xDistance = ofs->mountOfs.X; yDistance = ofs->mountOfs.Y; - Debug.Write(wxString::Format("Moving (%.2f, %.2f) raw xDistance=%.2f yDistance=%.2f\n", - ofs->cameraOfs.X, ofs->cameraOfs.Y, xDistance, yDistance)); + Debug.Write(wxString::Format("Moving (%.2f, %.2f) raw xDistance=%.2f yDistance=%.2f\n", ofs->cameraOfs.X, + ofs->cameraOfs.Y, xDistance, yDistance)); // Let BLC track the raw offsets in Dec if (m_backlashComp) @@ -1116,8 +1136,8 @@ Mount::MOVE_RESULT Mount::MoveOffset(GuiderOffset *ofs, unsigned int moveOptions * */ -bool Mount::TransformCameraCoordinatesToMountCoordinates(const PHD_Point& cameraVectorEndpoint, - PHD_Point& mountVectorEndpoint, bool logged) +bool Mount::TransformCameraCoordinatesToMountCoordinates( + const PHD_Point& cameraVectorEndpoint, PHD_Point& mountVectorEndpoint, bool logged) { bool bError = false; @@ -1128,26 +1148,26 @@ bool Mount::TransformCameraCoordinatesToMountCoordinates(const PHD_Point& camera throw ERROR_INFO("invalid cameraVectorEndPoint"); } - double hyp = cameraVectorEndpoint.Distance(); + double hyp = cameraVectorEndpoint.Distance(); double cameraTheta = cameraVectorEndpoint.Angle(); - double xAngle = cameraTheta - m_cal.xAngle; // xAngle measures RA axis rotation vs camera X axis, positive is CW from x axis + double xAngle = + cameraTheta - m_cal.xAngle; // xAngle measures RA axis rotation vs camera X axis, positive is CW from x axis double yAngle = cameraTheta - (m_cal.xAngle + m_yAngleError); // m_yAngleError is the orthogonality error // Convert theta and hyp into X and Y - mountVectorEndpoint.SetXY( - cos(xAngle) * hyp, - sin(yAngle) * hyp - ); + mountVectorEndpoint.SetXY(cos(xAngle) * hyp, sin(yAngle) * hyp); if (logged) { Debug.Write(wxString::Format("CameraToMount -- cameraTheta (%.2f) - m_xAngle (%.2f) = xAngle (%.2f = %.2f)\n", cameraTheta, m_cal.xAngle, xAngle, norm_angle(xAngle))); - Debug.Write(wxString::Format("CameraToMount -- cameraTheta (%.2f) - (m_xAngle (%.2f) + m_yAngleError (%.2f)) = yAngle (%.2f = %.2f)\n", + Debug.Write(wxString::Format( + "CameraToMount -- cameraTheta (%.2f) - (m_xAngle (%.2f) + m_yAngleError (%.2f)) = yAngle (%.2f = %.2f)\n", cameraTheta, m_cal.xAngle, m_yAngleError, yAngle, norm_angle(yAngle))); - Debug.Write(wxString::Format("CameraToMount -- cameraX=%.2f cameraY=%.2f hyp=%.2f cameraTheta=%.2f mountX=%.2f mountY=%.2f, mountTheta=%.2f\n", + Debug.Write(wxString::Format("CameraToMount -- cameraX=%.2f cameraY=%.2f hyp=%.2f cameraTheta=%.2f mountX=%.2f " + "mountY=%.2f, mountTheta=%.2f\n", cameraVectorEndpoint.X, cameraVectorEndpoint.Y, hyp, cameraTheta, mountVectorEndpoint.X, mountVectorEndpoint.Y, mountVectorEndpoint.Angle())); } @@ -1162,8 +1182,8 @@ bool Mount::TransformCameraCoordinatesToMountCoordinates(const PHD_Point& camera return bError; } -bool Mount::TransformMountCoordinatesToCameraCoordinates(const PHD_Point& mountVectorEndpoint, - PHD_Point& cameraVectorEndpoint, bool logged) +bool Mount::TransformMountCoordinatesToCameraCoordinates( + const PHD_Point& mountVectorEndpoint, PHD_Point& cameraVectorEndpoint, bool logged) { bool bError = false; @@ -1184,16 +1204,14 @@ bool Mount::TransformMountCoordinatesToCameraCoordinates(const PHD_Point& mountV double xAngle = mountTheta + m_cal.xAngle; - cameraVectorEndpoint.SetXY( - cos(xAngle) * hyp, - sin(xAngle) * hyp - ); + cameraVectorEndpoint.SetXY(cos(xAngle) * hyp, sin(xAngle) * hyp); if (logged) { Debug.Write(wxString::Format("MountToCamera -- mountTheta (%.2f) + m_xAngle (%.2f) = xAngle (%.2f = %.2f)\n", mountTheta, m_cal.xAngle, xAngle, norm_angle(xAngle))); - Debug.Write(wxString::Format("MountToCamera -- mountX=%.2f mountY=%.2f hyp=%.2f mountTheta=%.2f cameraX=%.2f, cameraY=%.2f cameraTheta=%.2f\n", + Debug.Write(wxString::Format("MountToCamera -- mountX=%.2f mountY=%.2f hyp=%.2f mountTheta=%.2f cameraX=%.2f, " + "cameraY=%.2f cameraTheta=%.2f\n", mountVectorEndpoint.X, mountVectorEndpoint.Y, hyp, mountTheta, cameraVectorEndpoint.X, cameraVectorEndpoint.Y, cameraVectorEndpoint.Angle())); } @@ -1243,7 +1261,8 @@ void Mount::AdjustCalibrationForScopePointing() double newRotatorAngle = Rotator::RotatorPosition(); unsigned short binning = pCamera->Binning; - Debug.AddLine(wxString::Format("AdjustCalibrationForScopePointing (%s): current dec=%s pierSide=%d, cal dec=%s pierSide=%d rotAngle=%s bin=%hu", + Debug.AddLine(wxString::Format( + "AdjustCalibrationForScopePointing (%s): current dec=%s pierSide=%d, cal dec=%s pierSide=%d rotAngle=%s bin=%hu", GetMountClassName(), DeclinationStr(newDeclination), newPierSide, DeclinationStr(m_cal.declination), m_cal.pierSide, RotAngleStr(newRotatorAngle), binning)); @@ -1259,12 +1278,16 @@ void Mount::AdjustCalibrationForScopePointing() double currDecSpeed; if (!pPointingSource->GetGuideRates(&currRASpeed, &currDecSpeed)) { - if (fabs(1.0 - currRASpeed / calDetails.raGuideSpeed) > 0.05 || fabs(1.0 - currDecSpeed / calDetails.decGuideSpeed) > 0.05) + if (fabs(1.0 - currRASpeed / calDetails.raGuideSpeed) > 0.05 || + fabs(1.0 - currDecSpeed / calDetails.decGuideSpeed) > 0.05) { - pFrame->Alert(_("Mount guide speeds are different from those used in last calibration. Do a new calibration or reset mount guide speed settings to previous values. ")); - Debug.Write(wxString::Format("Guide speeds have changed since calibration. Orig RA = %0.1f, Orig Dec = %0.1f, " - "Curr RA = %0.1f, Curr Dec = %0.1f, Units are arc-sec/sec\n", calDetails.raGuideSpeed * 3600.0, calDetails.decGuideSpeed * 3600.0, - currRASpeed * 3600.0, currDecSpeed * 3600.0)); + pFrame->Alert(_("Mount guide speeds are different from those used in last calibration. Do a new " + "calibration or reset mount guide speed settings to previous values. ")); + Debug.Write( + wxString::Format("Guide speeds have changed since calibration. Orig RA = %0.1f, Orig Dec = %0.1f, " + "Curr RA = %0.1f, Curr Dec = %0.1f, Units are arc-sec/sec\n", + calDetails.raGuideSpeed * 3600.0, calDetails.decGuideSpeed * 3600.0, currRASpeed * 3600.0, + currDecSpeed * 3600.0)); } } } @@ -1272,37 +1295,39 @@ void Mount::AdjustCalibrationForScopePointing() if (newPierSide != PIER_SIDE_UNKNOWN && m_cal.pierSide == PIER_SIDE_UNKNOWN) { - pFrame->Alert(_("Current calibration did not have side-of-pier information, so PHD2 can't automatically correct for meridian flips. " - "You should do a fresh calibration to correct this problem.")); + pFrame->Alert(_("Current calibration did not have side-of-pier information, so PHD2 can't automatically correct for " + "meridian flips. " + "You should do a fresh calibration to correct this problem.")); } - // Compensate for binning or pixel size changes. At least one cam driver (ASCOM/Lodestar) can lie about the binning while changing - // the reported pixel size + // Compensate for binning or pixel size changes. At least one cam driver (ASCOM/Lodestar) can lie about the binning while + // changing the reported pixel size double scaleAdjustment = 1.0; if (fabs(pCamera->GetCameraPixelSize() - GuideCamera::GetProfilePixelSize()) >= 1.0) { // Punt on this, it probably means the user-supplied pixel size doesn't match what the camera is reporting - pFrame->Alert(_("Profile pixel size doesn't match camera-reported pixel size. Re-calibrate to restore correct guiding.")); - Debug.Write(wxString::Format("Camera pixel size changed from %0.1f to %0.1f\n", - GuideCamera::GetProfilePixelSize(), pCamera->GetCameraPixelSize())); + pFrame->Alert( + _("Profile pixel size doesn't match camera-reported pixel size. Re-calibrate to restore correct guiding.")); + Debug.Write(wxString::Format("Camera pixel size changed from %0.1f to %0.1f\n", GuideCamera::GetProfilePixelSize(), + pCamera->GetCameraPixelSize())); scaleAdjustment = pCamera->GetCameraPixelSize() / GuideCamera::GetProfilePixelSize(); pCamera->SetCameraPixelSize(pCamera->GetCameraPixelSize()); } - // The following won't happen unless the camera binning is changed outside the AD UI. Goal is to revert to baseline guiding params - // while keeping the UI consistent with the apparent image scale + // The following won't happen unless the camera binning is changed outside the AD UI. Goal is to revert to baseline guiding + // params while keeping the UI consistent with the apparent image scale if (binning != m_cal.binning && m_cal.isValid) { Calibration cal(m_cal); scaleAdjustment *= binning / m_cal.binning; - double adj = (double)m_cal.binning / (double)binning; + double adj = (double) m_cal.binning / (double) binning; cal.xRate *= adj; cal.yRate *= adj; cal.binning = binning; - Debug.Write(wxString::Format("Binning %hu -> %hu, rates (%.3f, %.3f) -> (%.3f, %.3f)\n", - m_cal.binning, binning, m_cal.xRate * 1000., m_cal.yRate * 1000., cal.xRate * 1000., cal.yRate * 1000.)); + Debug.Write(wxString::Format("Binning %hu -> %hu, rates (%.3f, %.3f) -> (%.3f, %.3f)\n", m_cal.binning, binning, + m_cal.xRate * 1000., m_cal.yRate * 1000., cal.xRate * 1000., cal.yRate * 1000.)); SetCalibration(cal); } @@ -1311,13 +1336,14 @@ void Mount::AdjustCalibrationForScopePointing() if (fabs(scaleAdjustment - 1.0) >= 0.01) { Debug.Write("Mount::AdjustCalibrationForScopePointing: imageScaleRatio changed\n"); - pFrame->HandleImageScaleChange(); // Clear calibration, get the various UIs sorted out + pFrame->HandleImageScaleChange(); // Clear calibration, get the various UIs sorted out } if (IsOppositeSide(newPierSide, m_cal.pierSide)) { Debug.AddLine(wxString::Format("Guiding starts on opposite side of pier: calibration data " - "side is %s, current side is %s", ::PierSideStr(m_cal.pierSide), ::PierSideStr(newPierSide))); + "side is %s, current side is %s", + ::PierSideStr(m_cal.pierSide), ::PierSideStr(newPierSide))); FlipCalibration(); } @@ -1335,7 +1361,8 @@ void Mount::AdjustCalibrationForScopePointing() if (fabs(da) > 0.05) { - Debug.Write(wxString::Format("New rotator position %.1f deg, prev = %.1f deg, delta = %.1f deg\n", newRotatorAngle, m_cal.rotatorAngle, da)); + Debug.Write(wxString::Format("New rotator position %.1f deg, prev = %.1f deg, delta = %.1f deg\n", + newRotatorAngle, m_cal.rotatorAngle, da)); da = radians(da); @@ -1354,8 +1381,8 @@ void Mount::AdjustCalibrationForScopePointing() // update the calibration data in the registry. The adjusted x_Rate is never persisted bool deccomp = false; - if (newDeclination != m_cal.declination && - newDeclination != UNKNOWN_DECLINATION && m_cal.declination != UNKNOWN_DECLINATION) + if (newDeclination != m_cal.declination && newDeclination != UNKNOWN_DECLINATION && + m_cal.declination != UNKNOWN_DECLINATION) { // avoid division by zero and gross errors. If the user didn't calibrate // somewhere near the celestial equator, we don't do this @@ -1375,8 +1402,8 @@ void Mount::AdjustCalibrationForScopePointing() m_xRate = (m_cal.xRate / cos(m_cal.declination)) * cos(newDeclination); deccomp = true; - Debug.Write(wxString::Format("Dec comp: XRate %.3f -> %.3f for dec %.1f -> dec %.1f\n", - m_cal.xRate * 1000.0, m_xRate * 1000.0, degrees(m_cal.declination), degrees(newDeclination))); + Debug.Write(wxString::Format("Dec comp: XRate %.3f -> %.3f for dec %.1f -> dec %.1f\n", m_cal.xRate * 1000.0, + m_xRate * 1000.0, degrees(m_cal.declination), degrees(newDeclination))); } } if (!deccomp && m_xRate != m_cal.xRate) @@ -1417,9 +1444,7 @@ bool Mount::HasSetupDialog() const return false; } -void Mount::SetupDialog() -{ -} +void Mount::SetupDialog() { } const wxString& Mount::Name() const { @@ -1444,26 +1469,40 @@ wxPoint Mount::GetAoMaxPos() const const char *Mount::DirectionStr(GUIDE_DIRECTION d) const { // these are used internally in the guide log and event server and are not translated - switch (d) { - case NONE: return "None"; - case NORTH: return "North"; - case SOUTH: return "South"; - case EAST: return "East"; - case WEST: return "West"; - default: return "?"; + switch (d) + { + case NONE: + return "None"; + case NORTH: + return "North"; + case SOUTH: + return "South"; + case EAST: + return "East"; + case WEST: + return "West"; + default: + return "?"; } } const char *Mount::DirectionChar(GUIDE_DIRECTION d) const { // these are used internally in the guide log and event server and are not translated - switch (d) { - case NONE: return "-"; - case NORTH: return "N"; - case SOUTH: return "S"; - case EAST: return "E"; - case WEST: return "W"; - default: return "?"; + switch (d) + { + case NONE: + return "-"; + case NORTH: + return "N"; + case SOUTH: + return "S"; + case EAST: + return "E"; + case WEST: + return "W"; + default: + return "?"; } } @@ -1508,7 +1547,8 @@ void Mount::ClearCalibration() void Mount::SetCalibration(const Calibration& cal) { - Debug.Write(wxString::Format("Mount::SetCalibration (%s) -- xAngle=%.1f yAngle=%.1f xRate=%.3f yRate=%.3f bin=%hu dec=%s pierSide=%d par=%s/%s rotAng=%s\n", + Debug.Write(wxString::Format("Mount::SetCalibration (%s) -- xAngle=%.1f yAngle=%.1f xRate=%.3f yRate=%.3f bin=%hu dec=%s " + "pierSide=%d par=%s/%s rotAng=%s\n", GetMountClassName(), degrees(cal.xAngle), degrees(cal.yAngle), cal.xRate * 1000.0, cal.yRate * 1000.0, cal.binning, DeclinationStr(cal.declination), cal.pierSide, ParityStr(cal.raGuideParity), ParityStr(cal.decGuideParity), RotAngleStr(cal.rotatorAngle))); @@ -1526,15 +1566,15 @@ void Mount::SetCalibration(const Calibration& cal) m_cal.rotatorAngle = cal.rotatorAngle; m_cal.isValid = true; - m_xRate = cal.xRate; + m_xRate = cal.xRate; // the angles are more difficult because we have to turn yAngle into a yError. m_cal.xAngle = cal.xAngle; m_cal.yAngle = cal.yAngle; m_yAngleError = norm_angle(cal.xAngle - cal.yAngle + M_PI / 2.); - Debug.AddLine(wxString::Format("Mount::SetCalibration (%s) -- sets m_xAngle=%.1f m_yAngleError=%.1f", - GetMountClassName(), degrees(m_cal.xAngle), degrees(m_yAngleError))); + Debug.AddLine(wxString::Format("Mount::SetCalibration (%s) -- sets m_xAngle=%.1f m_yAngleError=%.1f", GetMountClassName(), + degrees(m_cal.xAngle), degrees(m_yAngleError))); m_calibrated = true; @@ -1608,7 +1648,7 @@ void Mount::SaveCalibrationDetails(const CalibrationDetails& calDetails) const pConfig->Profile.SetInt(prefix + "ra_step_count", calDetails.raStepCount); pConfig->Profile.SetInt(prefix + "dec_step_count", calDetails.decStepCount); - pConfig->Profile.SetInt(prefix + "last_issue", (int)calDetails.lastIssue); + pConfig->Profile.SetInt(prefix + "last_issue", (int) calDetails.lastIssue); } inline static PierSide pier_side(int val) @@ -1618,10 +1658,14 @@ inline static PierSide pier_side(int val) inline static GuideParity guide_parity(int val) { - switch (val) { - case GUIDE_PARITY_EVEN: return GUIDE_PARITY_EVEN; - case GUIDE_PARITY_ODD: return GUIDE_PARITY_ODD; - default: return GUIDE_PARITY_UNKNOWN; + switch (val) + { + case GUIDE_PARITY_EVEN: + return GUIDE_PARITY_EVEN; + case GUIDE_PARITY_ODD: + return GUIDE_PARITY_ODD; + default: + return GUIDE_PARITY_UNKNOWN; } } @@ -1777,11 +1821,11 @@ void Mount::LoadCalibrationDetails(CalibrationDetails *details) const bool err = false; while (tok.HasMoreTokens() && !err) { - wxString tk = (tok.GetNextToken()).Trim(false); // looks like {x y, left-trimmed + wxString tk = (tok.GetNextToken()).Trim(false); // looks like {x y, left-trimmed int blankLoc = tk.find(" "); double x; double y; - if (!tk.Mid(1, blankLoc-1).ToDouble(&x)) + if (!tk.Mid(1, blankLoc - 1).ToDouble(&x)) err = true; tk = tk.Mid(blankLoc + 1); if (!tk.ToDouble(&y)) @@ -1832,23 +1876,17 @@ bool Mount::Disconnect() inline static wxString OrthoErrorStr(const CalibrationDetails& det) { - return det.IsValid() ? - wxString::Format("%.1f deg", det.orthoError) : "unknown"; + return det.IsValid() ? wxString::Format("%.1f deg", det.orthoError) : "unknown"; } wxString Mount::GetSettingsSummary() const { // return a loggable summary of current mount settings - wxString s = - wxString::Format("%s = %s,%s connected, guiding %s, ", - IsStepGuider() ? "AO" : "Mount", - m_Name, - IsConnected() ? "" : " not", - m_guidingEnabled ? "enabled" : "disabled"); + wxString s = wxString::Format("%s = %s,%s connected, guiding %s, ", IsStepGuider() ? "AO" : "Mount", m_Name, + IsConnected() ? "" : " not", m_guidingEnabled ? "enabled" : "disabled"); - if (pPointingSource && pPointingSource->IsConnected() && - pPointingSource->CanReportPosition() && + if (pPointingSource && pPointingSource->IsConnected() && pPointingSource->CanReportPosition() && pPointingSource != TheScope()) { s += wxString::Format("AuxMount=%s, ", pPointingSource->Name()); @@ -1862,9 +1900,8 @@ wxString Mount::GetSettingsSummary() const s += wxString::Format("xAngle = %.1f, xRate = %.3f, " "yAngle = %.1f, yRate = %.3f, " "parity = %s/%s\n", - degrees(xAngle()), xRatePx, - degrees(yAngle()), yRatePx, - ParityStr(m_cal.raGuideParity), ParityStr(m_cal.decGuideParity)); + degrees(xAngle()), xRatePx, degrees(yAngle()), yRatePx, ParityStr(m_cal.raGuideParity), + ParityStr(m_cal.decGuideParity)); CalibrationDetails det; LoadCalibrationDetails(&det); @@ -1875,9 +1912,7 @@ wxString Mount::GetSettingsSummary() const { s += wxString::Format("Norm rates X = %.f mas/step, " "Y = %.f mas/step; ortho.err. = %s\n", - m_cal.xRate * 1000. * scale, - m_cal.yRate * 1000. * scale, - OrthoErrorStr(det)); + m_cal.xRate * 1000. * scale, m_cal.yRate * 1000. * scale, OrthoErrorStr(det)); } else { @@ -1890,25 +1925,20 @@ wxString Mount::GetSettingsSummary() const s += wxString::Format("Norm rates RA = %.1f\"/s @ dec 0, " "Dec = %.1f\"/s; ortho.err. = %s\n", - xRateAsD0, - yRateAs, - OrthoErrorStr(det)); + xRateAsD0, yRateAs, OrthoErrorStr(det)); } } else s += "not calibrated\n"; - s += wxString::Format("X guide algorithm = %s, %s", - GuideAlgorithmName(GetXGuideAlgorithmSelection()), - m_pXGuideAlgorithm->GetSettingsSummary()) + - wxString::Format("Y guide algorithm = %s, %s", - GuideAlgorithmName(GetYGuideAlgorithmSelection()), - m_pYGuideAlgorithm->GetSettingsSummary()); + s += wxString::Format("X guide algorithm = %s, %s", GuideAlgorithmName(GetXGuideAlgorithmSelection()), + m_pXGuideAlgorithm->GetSettingsSummary()) + + wxString::Format("Y guide algorithm = %s, %s", GuideAlgorithmName(GetYGuideAlgorithmSelection()), + m_pYGuideAlgorithm->GetSettingsSummary()); if (m_backlashComp) { - s += wxString::Format("Backlash comp = %s, pulse = %d ms\n", - m_backlashComp->IsEnabled() ? "enabled" : "disabled", + s += wxString::Format("Backlash comp = %s, pulse = %d ms\n", m_backlashComp->IsEnabled() ? "enabled" : "disabled", m_backlashComp->GetBacklashPulseWidth()); } @@ -1920,13 +1950,9 @@ bool Mount::CalibrationFlipRequiresDecFlip() return false; } -void Mount::StartDecDrift() -{ -} +void Mount::StartDecDrift() { } -void Mount::EndDecDrift() -{ -} +void Mount::EndDecDrift() { } bool Mount::IsDecDrifting() const { diff --git a/src/mount.h b/src/mount.h index 722f00cd0..6f9158462 100644 --- a/src/mount.h +++ b/src/mount.h @@ -45,15 +45,15 @@ struct GuiderOffset; enum GUIDE_DIRECTION { - NONE = -1, + NONE = -1, UP = 0, - NORTH = UP, // Dec + for eq mounts + NORTH = UP, // Dec + for eq mounts DOWN, - SOUTH = DOWN, // Dec- + SOUTH = DOWN, // Dec- RIGHT, - EAST = RIGHT, // RA- + EAST = RIGHT, // RA- LEFT, - WEST = LEFT // RA+ + WEST = LEFT // RA+ }; enum PierSide @@ -65,9 +65,9 @@ enum PierSide enum GuideParity { - GUIDE_PARITY_EVEN = 1, // Guide(NORTH) moves scope north - GUIDE_PARITY_ODD = -1, // Guide(NORTH) moves scope south - GUIDE_PARITY_UNKNOWN = 0, // we don't know or care + GUIDE_PARITY_EVEN = 1, // Guide(NORTH) moves scope north + GUIDE_PARITY_ODD = -1, // Guide(NORTH) moves scope south + GUIDE_PARITY_UNKNOWN = 0, // we don't know or care GUIDE_PARITY_UNCHANGED = -5, // special case for SetCalibration, leave value unchanged }; @@ -88,7 +88,10 @@ struct Calibration bool isValid; wxString timestamp; - Calibration() : isValid(false) { } + Calibration() + : isValid(false) + { + } }; enum CalibrationIssueType @@ -118,26 +121,29 @@ struct CalibrationDetails wxString origTimestamp; PierSide origPierSide; - CalibrationDetails() : raStepCount(0) { } + CalibrationDetails() + : raStepCount(0) + { + } bool IsValid() const { return raStepCount > 0; } }; enum MountMoveOptionBits { - MOVEOPT_ALGO_RESULT = (1<<0), // filter move through guide algorithm - MOVEOPT_ALGO_DEDUCE = (1<<1), // use guide algorithm to deduce the move amount (when paused or star lost) - MOVEOPT_USE_BLC = (1<<2), // use backlash comp for this move - MOVEOPT_GRAPH = (1<<3), // display the move on the graphs - MOVEOPT_MANUAL = (1<<4), // manual move - allow even when guiding disabled + MOVEOPT_ALGO_RESULT = (1 << 0), // filter move through guide algorithm + MOVEOPT_ALGO_DEDUCE = (1 << 1), // use guide algorithm to deduce the move amount (when paused or star lost) + MOVEOPT_USE_BLC = (1 << 2), // use backlash comp for this move + MOVEOPT_GRAPH = (1 << 3), // display the move on the graphs + MOVEOPT_MANUAL = (1 << 4), // manual move - allow even when guiding disabled }; enum { MOVEOPTS_CALIBRATION_MOVE = 0, - MOVEOPTS_GUIDE_STEP = MOVEOPT_ALGO_RESULT | MOVEOPT_USE_BLC | MOVEOPT_GRAPH, - MOVEOPTS_DEDUCED_MOVE = MOVEOPT_ALGO_DEDUCE | MOVEOPT_USE_BLC | MOVEOPT_GRAPH, - MOVEOPTS_RECOVERY_MOVE = MOVEOPT_USE_BLC, - MOVEOPTS_AO_BUMP = MOVEOPT_USE_BLC, + MOVEOPTS_GUIDE_STEP = MOVEOPT_ALGO_RESULT | MOVEOPT_USE_BLC | MOVEOPT_GRAPH, + MOVEOPTS_DEDUCED_MOVE = MOVEOPT_ALGO_DEDUCE | MOVEOPT_USE_BLC | MOVEOPT_GRAPH, + MOVEOPTS_RECOVERY_MOVE = MOVEOPT_USE_BLC, + MOVEOPTS_AO_BUMP = MOVEOPT_USE_BLC, }; extern wxString DumpMoveOptionBits(unsigned int moveOptions); @@ -147,17 +153,21 @@ struct MoveResultInfo int amountMoved; bool limited; - MoveResultInfo() : amountMoved(0), limited(false) { } + MoveResultInfo() + : amountMoved(0) + , limited(false) + { + } }; class MountConfigDialogCtrlSet : public ConfigDialogCtrlSet { - Mount* m_pMount; + Mount *m_pMount; wxCheckBox *m_pClearCalibration; wxCheckBox *m_pEnableGuide; public: - MountConfigDialogCtrlSet(wxWindow *pParent, Mount *pMount, AdvancedDialog* pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + MountConfigDialogCtrlSet(wxWindow *pParent, Mount *pMount, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); virtual ~MountConfigDialogCtrlSet() {}; virtual void LoadValues(); virtual void UnloadValues(); @@ -171,8 +181,8 @@ class Mount : public wxMessageBoxProxy bool m_calibrated; Calibration m_cal; - double m_xRate; // rate adjusted for declination - double m_yAngleError; // orthogonality error + double m_xRate; // rate adjusted for declination + double m_yAngleError; // orthogonality error protected: bool m_guidingEnabled; @@ -190,18 +200,18 @@ class Mount : public wxMessageBoxProxy { protected: Mount *m_pMount; - wxWindow* m_pParent; - wxChoice *m_pXGuideAlgorithmChoice; - wxChoice *m_pYGuideAlgorithmChoice; - int m_initXGuideAlgorithmSelection; - int m_initYGuideAlgorithmSelection; + wxWindow *m_pParent; + wxChoice *m_pXGuideAlgorithmChoice; + wxChoice *m_pYGuideAlgorithmChoice; + int m_initXGuideAlgorithmSelection; + int m_initYGuideAlgorithmSelection; ConfigDialogPane *m_pXGuideAlgorithmConfigDialogPane; ConfigDialogPane *m_pYGuideAlgorithmConfigDialogPane; - wxStaticBoxSizer* m_pAlgoBox; - wxStaticBoxSizer* m_pRABox; - wxStaticBoxSizer* m_pDecBox; - wxButton* m_pResetRAParams; - wxButton* m_pResetDecParams; + wxStaticBoxSizer *m_pAlgoBox; + wxStaticBoxSizer *m_pRABox; + wxStaticBoxSizer *m_pDecBox; + wxButton *m_pResetRAParams; + wxButton *m_pResetDecParams; void OnResetRAParams(wxCommandEvent& evt); void OnResetDecParams(wxCommandEvent& evt); @@ -244,11 +254,11 @@ class Mount : public wxMessageBoxProxy // functions with an implementation in Mount that cannot be over-ridden // by a subclass public: - - enum MOVE_RESULT { - MOVE_OK = 0, // move succeeded - MOVE_ERROR, // move failed for unspecified reason - MOVE_ERROR_SLEWING, // move failed due to scope slewing + enum MOVE_RESULT + { + MOVE_OK = 0, // move succeeded + MOVE_ERROR, // move failed for unspecified reason + MOVE_ERROR_SLEWING, // move failed due to scope slewing MOVE_ERROR_AO_LIMIT_REACHED, // move failed due to AO limit }; @@ -272,11 +282,11 @@ class Mount : public wxMessageBoxProxy virtual MOVE_RESULT MoveOffset(GuiderOffset *guiderOffset, unsigned int moveOptions); - bool TransformCameraCoordinatesToMountCoordinates(const PHD_Point& cameraVectorEndpoint, - PHD_Point& mountVectorEndpoint, bool logged = true); + bool TransformCameraCoordinatesToMountCoordinates( + const PHD_Point& cameraVectorEndpoint, PHD_Point& mountVectorEndpoint, bool logged = true); - bool TransformMountCoordinatesToCameraCoordinates(const PHD_Point& mountVectorEndpoint, - PHD_Point& cameraVectorEndpoint, bool logged = true); + bool TransformMountCoordinatesToCameraCoordinates( + const PHD_Point& mountVectorEndpoint, PHD_Point& cameraVectorEndpoint, bool logged = true); void LogGuideStepInfo(); @@ -305,14 +315,15 @@ class Mount : public wxMessageBoxProxy // pure virtual functions -- these MUST be overridden by a subclass public: // move the requested direction, return the actual amount of the move - virtual MOVE_RESULT MoveAxis(GUIDE_DIRECTION direction, int amount, unsigned int moveOptions, MoveResultInfo *moveResultInfo) = 0; + virtual MOVE_RESULT MoveAxis( + GUIDE_DIRECTION direction, int amount, unsigned int moveOptions, MoveResultInfo *moveResultInfo) = 0; virtual MOVE_RESULT MoveAxis(GUIDE_DIRECTION direction, int duration, unsigned int moveOptions) = 0; virtual int CalibrationMoveSize() = 0; virtual int CalibrationTotDistance() = 0; // Calibration related routines - virtual bool BeginCalibration(const PHD_Point ¤tLocation) = 0; - virtual bool UpdateCalibrationState(const PHD_Point ¤tLocation) = 0; + virtual bool BeginCalibration(const PHD_Point& currentLocation) = 0; + virtual bool UpdateCalibrationState(const PHD_Point& currentLocation) = 0; virtual void NotifyGuidingStarted(); virtual void NotifyGuidingStopped(); @@ -323,8 +334,9 @@ class Mount : public wxMessageBoxProxy virtual void NotifyDirectMove(const PHD_Point& dist); virtual MountConfigDialogPane *GetConfigDialogPane(wxWindow *pParent) = 0; - virtual MountConfigDialogCtrlSet *GetConfigDialogCtrlSet(wxWindow *pParent, Mount *pMount, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) = 0; - ConfigDialogCtrlSet* currConfigDialogCtrlSet; // instance currently in-use by AD + virtual MountConfigDialogCtrlSet *GetConfigDialogCtrlSet( + wxWindow *pParent, Mount *pMount, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) = 0; + ConfigDialogCtrlSet *currConfigDialogCtrlSet; // instance currently in-use by AD virtual wxString GetMountClassName() const = 0; @@ -338,7 +350,6 @@ class Mount : public wxMessageBoxProxy // consider whether they need to call the base class functions as part of // their operation public: - virtual bool HasNonGuiMove(); virtual bool SynchronousOnly(); virtual bool HasSetupDialog() const; diff --git a/src/myframe.cpp b/src/myframe.cpp index ec858dce4..ad05f0a77 100644 --- a/src/myframe.cpp +++ b/src/myframe.cpp @@ -211,11 +211,10 @@ struct FileDropTarget : public wxFileDropTarget // ---------------------- Main Frame ------------------------------------- // frame constructor MyFrame::MyFrame() - : - wxFrame(nullptr, wxID_ANY, wxEmptyString), - m_showBookmarksAccel(0), - m_bookmarkLockPosAccel(0), - pStatsWin(nullptr) + : wxFrame(nullptr, wxID_ANY, wxEmptyString) + , m_showBookmarksAccel(0) + , m_bookmarkLockPosAccel(0) + , pStatsWin(nullptr) { m_mgr.SetManagedWindow(this); @@ -234,13 +233,13 @@ MyFrame::MyFrame() m_sampling = 1.0; - #include "icons/phd2_128.png.h" +#include "icons/phd2_128.png.h" wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_128)); wxIcon icon; icon.CopyFromBitmap(phd2); SetIcon(icon); - //SetIcon(wxIcon(_T("progicon"))); + // SetIcon(wxIcon(_T("progicon"))); SetBackgroundColour(*wxLIGHT_GREY); // Setup menus @@ -259,14 +258,10 @@ MyFrame::MyFrame() wxSizer *sizer = new wxBoxSizer(wxVERTICAL); m_infoBar = new wxInfoBar(guiderWin); - m_infoBar->Connect(BUTTON_ALERT_ACTION, wxEVT_BUTTON, - wxCommandEventHandler(MyFrame::OnAlertButton), nullptr, this); - m_infoBar->Connect(BUTTON_ALERT_DONTSHOW, wxEVT_BUTTON, - wxCommandEventHandler(MyFrame::OnAlertButton), nullptr, this); - m_infoBar->Connect(BUTTON_ALERT_CLOSE, wxEVT_BUTTON, - wxCommandEventHandler(MyFrame::OnAlertButton), nullptr, this); - m_infoBar->Connect(BUTTON_ALERT_HELP, wxEVT_BUTTON, - wxCommandEventHandler(MyFrame::OnAlertHelp), nullptr, this); + m_infoBar->Connect(BUTTON_ALERT_ACTION, wxEVT_BUTTON, wxCommandEventHandler(MyFrame::OnAlertButton), nullptr, this); + m_infoBar->Connect(BUTTON_ALERT_DONTSHOW, wxEVT_BUTTON, wxCommandEventHandler(MyFrame::OnAlertButton), nullptr, this); + m_infoBar->Connect(BUTTON_ALERT_CLOSE, wxEVT_BUTTON, wxCommandEventHandler(MyFrame::OnAlertButton), nullptr, this); + m_infoBar->Connect(BUTTON_ALERT_HELP, wxEVT_BUTTON, wxCommandEventHandler(MyFrame::OnAlertHelp), nullptr, this); sizer->Add(m_infoBar, wxSizerFlags().Expand()); @@ -287,17 +282,10 @@ MyFrame::MyFrame() wxString geometry = pConfig->Global.GetString("/geometry", wxEmptyString); wxArrayString fields = wxSplit(geometry, ';'); long w, h, x, y; - if (fields.size() == 5 && - fields[1].ToLong(&w) && - fields[2].ToLong(&h) && - fields[3].ToLong(&x) && - fields[4].ToLong(&y)) + if (fields.size() == 5 && fields[1].ToLong(&w) && fields[2].ToLong(&h) && fields[3].ToLong(&x) && fields[4].ToLong(&y)) { wxSize screen = wxGetDisplaySize(); - if (x + w <= screen.GetWidth() && - x >= 0 && - y + h <= screen.GetHeight() && - y >= 0) + if (x + w <= screen.GetWidth() && x >= 0 && y + h <= screen.GetHeight() && y >= 0) { SetSize(w, h); SetPosition(wxPoint(x, y)); @@ -317,40 +305,27 @@ MyFrame::MyFrame() SetDropTarget(new FileDropTarget()); - m_mgr.AddPane(MainToolbar, wxAuiPaneInfo(). - Name(_T("MainToolBar")).Caption(_T("Main tool bar")). - ToolbarPane().Bottom()); + m_mgr.AddPane(MainToolbar, wxAuiPaneInfo().Name(_T("MainToolBar")).Caption(_T("Main tool bar")).ToolbarPane().Bottom()); - guiderWin->SetMinSize(wxSize(XWinSize,YWinSize)); - guiderWin->SetSize(wxSize(XWinSize,YWinSize)); - m_mgr.AddPane(guiderWin, wxAuiPaneInfo(). - Name(_T("Guider")).Caption(_T("Guider")). - CenterPane().MinSize(wxSize(XWinSize,YWinSize))); + guiderWin->SetMinSize(wxSize(XWinSize, YWinSize)); + guiderWin->SetSize(wxSize(XWinSize, YWinSize)); + m_mgr.AddPane( + guiderWin, wxAuiPaneInfo().Name(_T("Guider")).Caption(_T("Guider")).CenterPane().MinSize(wxSize(XWinSize, YWinSize))); pGraphLog = new GraphLogWindow(this); - m_mgr.AddPane(pGraphLog, wxAuiPaneInfo(). - Name(_T("GraphLog")).Caption(_("History")). - Hide()); + m_mgr.AddPane(pGraphLog, wxAuiPaneInfo().Name(_T("GraphLog")).Caption(_("History")).Hide()); pStatsWin = new StatsWindow(this); - m_mgr.AddPane(pStatsWin, wxAuiPaneInfo(). - Name(_T("Stats")).Caption(_("Guide Stats")). - Hide()); + m_mgr.AddPane(pStatsWin, wxAuiPaneInfo().Name(_T("Stats")).Caption(_("Guide Stats")).Hide()); pStepGuiderGraph = new GraphStepguiderWindow(this); - m_mgr.AddPane(pStepGuiderGraph, wxAuiPaneInfo(). - Name(_T("AOPosition")).Caption(_("AO Position")). - Hide()); + m_mgr.AddPane(pStepGuiderGraph, wxAuiPaneInfo().Name(_T("AOPosition")).Caption(_("AO Position")).Hide()); pProfile = new ProfileWindow(this); - m_mgr.AddPane(pProfile, wxAuiPaneInfo(). - Name(_T("Profile")).Caption(_("Star Profile")). - Hide()); + m_mgr.AddPane(pProfile, wxAuiPaneInfo().Name(_T("Profile")).Caption(_("Star Profile")).Hide()); pTarget = new TargetWindow(this); - m_mgr.AddPane(pTarget, wxAuiPaneInfo(). - Name(_T("Target")).Caption(_("Target")). - Hide()); + m_mgr.AddPane(pTarget, wxAuiPaneInfo().Name(_T("Target")).Caption(_("Target")).Hide()); pAdvancedDialog = new AdvancedDialog(this); @@ -379,18 +354,18 @@ MyFrame::MyFrame() if (m_serverMode) { - tools_menu->Check(MENU_SERVER,true); + tools_menu->Check(MENU_SERVER, true); StartServer(true); } - #include "xhair.xpm" +#include "xhair.xpm" wxImage Cursor = wxImage(mac_xhair); - Cursor.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X,8); - Cursor.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y,8); + Cursor.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, 8); + Cursor.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, 8); pGuider->SetCursor(wxCursor(Cursor)); m_continueCapturing = false; - CaptureActive = false; + CaptureActive = false; m_exposurePending = false; m_singleExposure.enabled = false; @@ -482,9 +457,8 @@ void MyFrame::UpdateTitle() int inst = wxGetApp().GetInstanceNumber(); wxString prof = pConfig->GetCurrentProfile(); - wxString title = inst > 1 ? - wxString::Format(_T("%s(#%d) %s - %s"), APPNAME, inst, FULLVER, prof) : - wxString::Format(_T("%s %s - %s"), APPNAME, FULLVER, prof); + wxString title = inst > 1 ? wxString::Format(_T("%s(#%d) %s - %s"), APPNAME, inst, FULLVER, prof) + : wxString::Format(_T("%s %s - %s"), APPNAME, FULLVER, prof); SetTitle(title); } @@ -511,10 +485,12 @@ void MyFrame::SetupMenuBar() tools_menu->Append(MENU_MANGUIDE, _("&Manual Guide"), _("Manual / test guide dialog")); m_autoSelectStarMenuItem = tools_menu->Append(MENU_AUTOSTAR, _("&Auto-select Star\tAlt-S"), _("Automatically select star")); tools_menu->Append(MENU_CALIBRATIONASSIST, _("Calibration Assistant..."), _("Slew to a preferred calibration position")); - tools_menu->Append(EEGG_REVIEWCAL, _("&Review Calibration Data\tAlt-C"), _("Review calibration data from last successful calibration")); + tools_menu->Append( + EEGG_REVIEWCAL, _("&Review Calibration Data\tAlt-C"), _("Review calibration data from last successful calibration")); wxMenu *calib_menu = new wxMenu; - calib_menu->Append(EEGG_RESTORECAL, _("Restore Calibration Data..."), _("Restore calibration data from last successful calibration")); + calib_menu->Append( + EEGG_RESTORECAL, _("Restore Calibration Data..."), _("Restore calibration data from last successful calibration")); calib_menu->Append(EEGG_MANUALCAL, _("Enter Calibration Data..."), _("Manually enter the calibration data")); calib_menu->Append(EEGG_FLIPCAL, _("Flip Calibration Now"), _("Flip the calibration data now")); calib_menu->Append(EEGG_CLEARCAL, _("Clear Calibration Data..."), _("Clear calibration data currently in use")); @@ -524,43 +500,53 @@ void MyFrame::SetupMenuBar() tools_menu->Append(EEGG_MANUALLOCK, _("Adjust &Lock Position"), _("Adjust the lock position")); tools_menu->Append(MENU_COMETTOOL, _("&Comet Tracking"), _("Run the Comet Tracking tool")); tools_menu->Append(MENU_STARCROSS_TEST, _("Star-Cross Test"), _("Run a star-cross test for mount diagnostics")); - tools_menu->Append(MENU_PIERFLIP_TOOL, _("Calibrate meridian flip"), _("Automatically determine the correct meridian flip settings")); + tools_menu->Append( + MENU_PIERFLIP_TOOL, _("Calibrate meridian flip"), _("Automatically determine the correct meridian flip settings")); tools_menu->Append(MENU_GUIDING_ASSISTANT, _("&Guiding Assistant"), _("Run the Guiding Assistant")); - tools_menu->Append(MENU_DRIFTTOOL, _("&Drift Align"), _("Align by analysing star drift near the celestial equator (Accurate)")); - tools_menu->Append(MENU_POLARDRIFTTOOL, _("&Polar Drift Align"), _("Align by analysing star drift near the celestial pole (Simple)")); - tools_menu->Append(MENU_STATICPATOOL, _("&Static Polar Align"), _("Align by measuring the RA axis offset from the celestial pole (Fast)")); + tools_menu->Append( + MENU_DRIFTTOOL, _("&Drift Align"), _("Align by analysing star drift near the celestial equator (Accurate)")); + tools_menu->Append( + MENU_POLARDRIFTTOOL, _("&Polar Drift Align"), _("Align by analysing star drift near the celestial pole (Simple)")); + tools_menu->Append( + MENU_STATICPATOOL, _("&Static Polar Align"), _("Align by measuring the RA axis offset from the celestial pole (Fast)")); tools_menu->AppendSeparator(); - tools_menu->AppendCheckItem(MENU_SERVER,_("Enable Server"),_("Enable PHD2 server capability")); - tools_menu->AppendCheckItem(EEGG_STICKY_LOCK,_("Sticky Lock Position"),_("Keep the same lock position when guiding starts")); + tools_menu->AppendCheckItem(MENU_SERVER, _("Enable Server"), _("Enable PHD2 server capability")); + tools_menu->AppendCheckItem( + EEGG_STICKY_LOCK, _("Sticky Lock Position"), _("Keep the same lock position when guiding starts")); view_menu = new wxMenu(); - view_menu->AppendCheckItem(MENU_TOOLBAR,_("Display Toolbar"),_("Enable / disable tool bar")); - view_menu->AppendCheckItem(MENU_GRAPH,_("Display &Graph"),_("Enable / disable graph")); + view_menu->AppendCheckItem(MENU_TOOLBAR, _("Display Toolbar"), _("Enable / disable tool bar")); + view_menu->AppendCheckItem(MENU_GRAPH, _("Display &Graph"), _("Enable / disable graph")); view_menu->AppendCheckItem(MENU_STATS, _("Display &Stats"), _("Enable / disable guide stats")); view_menu->AppendCheckItem(MENU_AO_GRAPH, _("Display &AO Graph"), _("Enable / disable AO graph")); - view_menu->AppendCheckItem(MENU_TARGET,_("Display &Target"),_("Enable / disable target")); - view_menu->AppendCheckItem(MENU_STARPROFILE,_("Display Star &Profile"),_("Enable / disable star profile view")); + view_menu->AppendCheckItem(MENU_TARGET, _("Display &Target"), _("Enable / disable target")); + view_menu->AppendCheckItem(MENU_STARPROFILE, _("Display Star &Profile"), _("Enable / disable star profile view")); view_menu->AppendSeparator(); - view_menu->AppendRadioItem(MENU_XHAIR0, _("&No Overlay"),_("No additional crosshairs")); - view_menu->AppendRadioItem(MENU_XHAIR1, _("&Bullseye"),_("Centered bullseye overlay")); - view_menu->AppendRadioItem(MENU_XHAIR2, _("&Fine Grid"),_("Grid overlay")); - view_menu->AppendRadioItem(MENU_XHAIR3, _("&Coarse Grid"),_("Grid overlay")); - view_menu->AppendRadioItem(MENU_XHAIR4, _("&RA/Dec"),_("RA and Dec overlay")); + view_menu->AppendRadioItem(MENU_XHAIR0, _("&No Overlay"), _("No additional crosshairs")); + view_menu->AppendRadioItem(MENU_XHAIR1, _("&Bullseye"), _("Centered bullseye overlay")); + view_menu->AppendRadioItem(MENU_XHAIR2, _("&Fine Grid"), _("Grid overlay")); + view_menu->AppendRadioItem(MENU_XHAIR3, _("&Coarse Grid"), _("Grid overlay")); + view_menu->AppendRadioItem(MENU_XHAIR4, _("&RA/Dec"), _("RA and Dec overlay")); view_menu->AppendRadioItem(MENU_XHAIR5, _("Spectrograph S&lit"), _("Spectrograph slit overlay")); view_menu->AppendSeparator(); view_menu->Append(MENU_SLIT_OVERLAY_COORDS, _("Slit Position...")); view_menu->AppendSeparator(); - view_menu->Append(MENU_RESTORE_WINDOWS, _("Restore Window Positions"), _("Restore all windows to their default/docked positions")); + view_menu->Append( + MENU_RESTORE_WINDOWS, _("Restore Window Positions"), _("Restore all windows to their default/docked positions")); darks_menu = new wxMenu(); m_takeDarksMenuItem = darks_menu->Append(MENU_TAKEDARKS, _("Dark &Library..."), _("Build a dark library for this profile")); - m_refineDefMapMenuItem = darks_menu->Append(MENU_REFINEDEFECTMAP, _("Bad-pixel &Map..."), _("Adjust parameters to create or modify the bad-pixel map")); - m_importCamCalMenuItem = darks_menu->Append(MENU_IMPORTCAMCAL, _("Import From Profile..."), _("Import existing dark library/bad-pixel map from a different profile")); + m_refineDefMapMenuItem = darks_menu->Append( + MENU_REFINEDEFECTMAP, _("Bad-pixel &Map..."), _("Adjust parameters to create or modify the bad-pixel map")); + m_importCamCalMenuItem = darks_menu->Append(MENU_IMPORTCAMCAL, _("Import From Profile..."), + _("Import existing dark library/bad-pixel map from a different profile")); darks_menu->AppendSeparator(); - m_useDarksMenuItem = darks_menu->AppendCheckItem(MENU_LOADDARK, _("Use &Dark Library"), _("Use the the dark library for this profile")); - m_useDefectMapMenuItem = darks_menu->AppendCheckItem(MENU_LOADDEFECTMAP, _("Use &Bad-pixel Map"), _("Use the bad-pixel map for this profile")); + m_useDarksMenuItem = + darks_menu->AppendCheckItem(MENU_LOADDARK, _("Use &Dark Library"), _("Use the the dark library for this profile")); + m_useDefectMapMenuItem = + darks_menu->AppendCheckItem(MENU_LOADDEFECTMAP, _("Use &Bad-pixel Map"), _("Use the bad-pixel map for this profile")); -#if defined (V4L_CAMERA) +#if defined(V4L_CAMERA) wxMenu *v4l_menu = new wxMenu(); v4l_menu->Append(MENU_V4LSAVESETTINGS, _("&Save settings"), _("Save current camera settings")); @@ -568,28 +554,31 @@ void MyFrame::SetupMenuBar() #endif bookmarks_menu = new wxMenu(); - m_showBookmarksMenuItem = bookmarks_menu->AppendCheckItem(MENU_BOOKMARKS_SHOW, _("Show &Bookmarks\tb"), _("Hide or show bookmarks")); + m_showBookmarksMenuItem = + bookmarks_menu->AppendCheckItem(MENU_BOOKMARKS_SHOW, _("Show &Bookmarks\tb"), _("Hide or show bookmarks")); m_showBookmarksAccel = m_showBookmarksMenuItem->GetAccel(); bookmarks_menu->Check(MENU_BOOKMARKS_SHOW, true); - m_bookmarkLockPosMenuItem = bookmarks_menu->Append(MENU_BOOKMARKS_SET_AT_LOCK, _("Bookmark &Lock Pos\tShift-B"), _("Set a bookmark at the current lock position")); + m_bookmarkLockPosMenuItem = bookmarks_menu->Append( + MENU_BOOKMARKS_SET_AT_LOCK, _("Bookmark &Lock Pos\tShift-B"), _("Set a bookmark at the current lock position")); m_bookmarkLockPosAccel = m_bookmarkLockPosMenuItem->GetAccel(); - bookmarks_menu->Append(MENU_BOOKMARKS_SET_AT_STAR, _("Bookmark &Star Pos"), _("Set a bookmark at the position of the currently selected star")); + bookmarks_menu->Append(MENU_BOOKMARKS_SET_AT_STAR, _("Bookmark &Star Pos"), + _("Set a bookmark at the position of the currently selected star")); bookmarks_menu->Append(MENU_BOOKMARKS_CLEAR_ALL, _("&Delete all\tCtrl-B"), _("Remove all bookmarks")); wxMenu *help_menu = new wxMenu; help_menu->Append(wxID_ABOUT, _("&About..."), wxString::Format(_("About %s"), APPNAME)); m_upgradeMenuItem = help_menu->Append(MENU_HELP_UPGRADE, _("&Check for updates"), _("Check for PHD2 software updates")); - help_menu->Append(MENU_HELP_ONLINE,_("Online Support"),_("Ask for help in the PHD2 Forum")); + help_menu->Append(MENU_HELP_ONLINE, _("Online Support"), _("Ask for help in the PHD2 Forum")); help_menu->Append(MENU_HELP_LOG_FOLDER, _("Open Log Folder"), _("Open the log folder")); help_menu->Append(MENU_HELP_UPLOAD_LOGS, _("Upload Log Files..."), _("Upload log files for review")); - help_menu->Append(wxID_HELP_CONTENTS,_("&Contents...\tF1"),_("Full help")); - help_menu->Append(wxID_HELP_PROCEDURES,_("&Impatient Instructions"),_("Quick instructions for the impatient")); + help_menu->Append(wxID_HELP_CONTENTS, _("&Contents...\tF1"), _("Full help")); + help_menu->Append(wxID_HELP_PROCEDURES, _("&Impatient Instructions"), _("Quick instructions for the impatient")); Menubar = new wxMenuBar(); Menubar->Append(file_menu, _("&File")); Menubar->Append(guide_menu, _("&Guide")); -#if defined (V4L_CAMERA) +#if defined(V4L_CAMERA) Menubar->Append(v4l_menu, _T("&V4L")); Menubar->Enable(MENU_V4LSAVESETTINGS, false); @@ -620,8 +609,7 @@ int MyFrame::GetExposureDelay() if (!m_varDelayConfig.enabled) rslt = m_timeLapse; - else if (pGuider->IsGuiding() && PhdController::IsIdle() && !pGuider->IsRecentering() && - pMount->GetGuidingEnabled()) + else if (pGuider->IsGuiding() && PhdController::IsIdle() && !pGuider->IsRecentering() && pMount->GetGuidingEnabled()) { rslt = m_varDelayConfig.longDelay; } @@ -641,7 +629,7 @@ int MyFrame::GetExposureDelay() void MyFrame::SetComboBoxWidth(wxComboBox *pComboBox, unsigned int extra) { unsigned int i; - int width=-1; + int width = -1; for (i = 0; i < pComboBox->GetCount(); i++) { @@ -730,10 +718,7 @@ bool MyFrame::SetAutoExposureCfg(int minExp, int maxExp, double targetSNR) pConfig->Profile.SetInt("/auto_exp/exposure_max", maxExp); pConfig->Profile.SetDouble("/auto_exp/target_snr", targetSNR); - bool changed = - m_autoExp.minExposure != minExp || - m_autoExp.maxExposure != maxExp || - m_autoExp.targetSNR != targetSNR; + bool changed = m_autoExp.minExposure != minExp || m_autoExp.maxExposure != maxExp || m_autoExp.targetSNR != targetSNR; m_autoExp.minExposure = minExp; m_autoExp.maxExposure = maxExp; @@ -746,11 +731,13 @@ wxString MyFrame::ExposureDurationSummary() const { wxString rslt; if (m_autoExp.enabled) - rslt = wxString::Format("Auto (min = %d ms, max = %d ms, SNR = %.2f)", m_autoExp.minExposure, m_autoExp.maxExposure, m_autoExp.targetSNR); + rslt = wxString::Format( + "Auto (min = %d ms, max = %d ms, SNR = %.2f)", m_autoExp.minExposure, m_autoExp.maxExposure, m_autoExp.targetSNR); else rslt = wxString::Format("%d ms", m_exposureDuration); if (m_varDelayConfig.enabled) - rslt += wxString::Format(", VarDelay (short = %d ms, long = %d ms)", m_varDelayConfig.shortDelay, m_varDelayConfig.longDelay); + rslt += wxString::Format( + ", VarDelay (short = %d ms, long = %d ms)", m_varDelayConfig.shortDelay, m_varDelayConfig.longDelay); return rslt; } @@ -850,7 +837,8 @@ static void SaveImageLoggerSettings(const ImageLoggerSettings& settings) pConfig->Profile.SetDouble("/ImageLogger/ErrorThreshPx", settings.guideErrorThreshPx); } -enum { +enum +{ GAMMA_MIN = 10, GAMMA_MAX = 300, GAMMA_DEFAULT = 100, @@ -880,7 +868,7 @@ void MyFrame::LoadProfileSettings() // Don't re-save the setting here with a call to SetAutoLoadCalibration(). An un-initialized registry key (-1) will // be populated after the 1st calibration int autoLoad = pConfig->Profile.GetInt("/AutoLoadCalibration", -1); - m_autoLoadCalibration = (autoLoad == 1); // new profile=> false + m_autoLoadCalibration = (autoLoad == 1); // new profile=> false int focalLength = pConfig->Profile.GetInt("/frame/focalLength", DefaultFocalLength); SetFocalLength(focalLength); @@ -896,7 +884,8 @@ void MyFrame::LoadProfileSettings() // set custom exposure duration vector value and drop-down list string from profile setting int customDuration = pConfig->Profile.GetInt("/CustomExposureDuration", 30000); *exposure_durations.rbegin() = customDuration; - Dur_Choice->SetString(1 + exposure_durations.size() - 1, wxString::Format(_("Custom: %g s"), (double) customDuration / 1000.)); + Dur_Choice->SetString( + 1 + exposure_durations.size() - 1, wxString::Format(_("Custom: %g s"), (double) customDuration / 1000.)); // for backward compatibity: // exposure duration used to be stored as the formatted string value appearing in the drop-down list, @@ -914,7 +903,7 @@ void MyFrame::LoadProfileSettings() wxStringCharType *end; double d = wxStrtod(start, &end); if (end != start) - exposureDuration = (int)(d * 1000.0); + exposureDuration = (int) (d * 1000.0); else if (s == _("Auto")) exposureDuration = -1; pConfig->Profile.DeleteEntry("/ExposureDuration"); @@ -923,8 +912,10 @@ void MyFrame::LoadProfileSettings() m_beepForLostStar = pConfig->Profile.GetBoolean("/BeepForLostStar", true); int val = pConfig->Profile.GetInt("/Gamma", GAMMA_DEFAULT); - if (val < GAMMA_MIN) val = GAMMA_MIN; - if (val > GAMMA_MAX) val = GAMMA_MAX; + if (val < GAMMA_MIN) + val = GAMMA_MIN; + if (val > GAMMA_MAX) + val = GAMMA_MAX; Stretch_gamma = (double) val / 100.0; Gamma_Slider->SetValue(val); @@ -936,50 +927,47 @@ void MyFrame::SetupToolBar() { MainToolbar = new wxAuiToolBar(this, -1, wxDefaultPosition, wxDefaultSize, wxAUI_TB_DEFAULT_STYLE); -# include "icons/loop.png.h" +#include "icons/loop.png.h" wxBitmap loop_bmp(wxBITMAP_PNG_FROM_DATA(loop)); -# include "icons/loop_disabled.png.h" +#include "icons/loop_disabled.png.h" wxBitmap loop_bmp_disabled(wxBITMAP_PNG_FROM_DATA(loop_disabled)); -# include "icons/guide.png.h" +#include "icons/guide.png.h" wxBitmap guide_bmp(wxBITMAP_PNG_FROM_DATA(guide)); -# include "icons/guide_disabled.png.h" +#include "icons/guide_disabled.png.h" wxBitmap guide_bmp_disabled(wxBITMAP_PNG_FROM_DATA(guide_disabled)); -# include "icons/stop.png.h" +#include "icons/stop.png.h" wxBitmap stop_bmp(wxBITMAP_PNG_FROM_DATA(stop)); -# include "icons/stop_disabled.png.h" +#include "icons/stop_disabled.png.h" wxBitmap stop_bmp_disabled(wxBITMAP_PNG_FROM_DATA(stop_disabled)); -# include "icons/auto_select.png.h" +#include "icons/auto_select.png.h" wxBitmap auto_select_bmp(wxBITMAP_PNG_FROM_DATA(auto_select)); -# include "icons/auto_select_disabled.png.h" +#include "icons/auto_select_disabled.png.h" wxBitmap auto_select_disabled_bmp(wxBITMAP_PNG_FROM_DATA(auto_select_disabled)); -# include "icons/connect.png.h" +#include "icons/connect.png.h" wxBitmap connect_bmp(wxBITMAP_PNG_FROM_DATA(connect)); -# include "icons/connect_disabled.png.h" +#include "icons/connect_disabled.png.h" wxBitmap connect_bmp_disabled(wxBITMAP_PNG_FROM_DATA(connect_disabled)); -# include "icons/brain.png.h" +#include "icons/brain.png.h" wxBitmap brain_bmp(wxBITMAP_PNG_FROM_DATA(brain)); -# include "icons/cam_setup.png.h" +#include "icons/cam_setup.png.h" wxBitmap cam_setup_bmp(wxBITMAP_PNG_FROM_DATA(cam_setup)); -# include "icons/cam_setup_disabled.png.h" +#include "icons/cam_setup_disabled.png.h" wxBitmap cam_setup_bmp_disabled(wxBITMAP_PNG_FROM_DATA(cam_setup_disabled)); int dur_values[] = { - 10, 20, 50, - 100, 200, 500, 1000, 1500, - 2000, 2500, 3000, 3500, 4000, 4500, 5000, - 6000, 7000, 8000, 9000, 10000, 15000, + 10, 20, 50, 100, 200, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 6000, 7000, 8000, 9000, 10000, 15000, 30000, // final entry is custom value }; for (unsigned int i = 0; i < WXSIZEOF(dur_values); i++) @@ -992,19 +980,22 @@ void MyFrame::SetupToolBar() durs.Add(wxString::Format(_("Custom: %g s"), 9999.0)); durs.Add(_("Edit Custom...")); - Dur_Choice = new wxComboBox(MainToolbar, BUTTON_DURATION, wxEmptyString, wxDefaultPosition, wxDefaultSize, - durs, wxCB_READONLY); + Dur_Choice = + new wxComboBox(MainToolbar, BUTTON_DURATION, wxEmptyString, wxDefaultPosition, wxDefaultSize, durs, wxCB_READONLY); Dur_Choice->SetToolTip(_("Camera exposure duration")); SetComboBoxWidth(Dur_Choice, 10); - Gamma_Slider = new wxSlider(MainToolbar, CTRL_GAMMA, GAMMA_DEFAULT, GAMMA_MIN, GAMMA_MAX, wxPoint(-1,-1), wxSize(160,-1)); - Gamma_Slider->SetBackgroundColour(wxColor(60, 60, 60)); // Slightly darker than toolbar background + Gamma_Slider = new wxSlider(MainToolbar, CTRL_GAMMA, GAMMA_DEFAULT, GAMMA_MIN, GAMMA_MAX, wxPoint(-1, -1), wxSize(160, -1)); + Gamma_Slider->SetBackgroundColour(wxColor(60, 60, 60)); // Slightly darker than toolbar background Gamma_Slider->SetToolTip(_("Screen gamma (brightness)")); - MainToolbar->AddTool(BUTTON_GEAR, connect_bmp, connect_bmp_disabled, false, 0, _("Connect to equipment. Shift-click to reconnect the same equipment last connected.")); + MainToolbar->AddTool(BUTTON_GEAR, connect_bmp, connect_bmp_disabled, false, 0, + _("Connect to equipment. Shift-click to reconnect the same equipment last connected.")); MainToolbar->AddTool(BUTTON_LOOP, loop_bmp, loop_bmp_disabled, false, 0, _("Begin looping exposures for frame and focus")); - MainToolbar->AddTool(BUTTON_AUTOSTAR, auto_select_bmp, auto_select_disabled_bmp, false, 0, _("Auto-select Star. Shift-click to de-select star.")); - MainToolbar->AddTool(BUTTON_GUIDE, guide_bmp, guide_bmp_disabled, false, 0, _("Begin guiding (PHD). Shift-click to force calibration.")); + MainToolbar->AddTool(BUTTON_AUTOSTAR, auto_select_bmp, auto_select_disabled_bmp, false, 0, + _("Auto-select Star. Shift-click to de-select star.")); + MainToolbar->AddTool( + BUTTON_GUIDE, guide_bmp, guide_bmp_disabled, false, 0, _("Begin guiding (PHD). Shift-click to force calibration.")); MainToolbar->AddTool(BUTTON_STOP, stop_bmp, stop_bmp_disabled, false, 0, _("Stop looping and guiding")); MainToolbar->AddSeparator(); MainToolbar->AddControl(Dur_Choice, _("Exposure duration")); @@ -1019,7 +1010,7 @@ void MyFrame::SetupToolBar() MainToolbar->EnableTool(BUTTON_STOP, false); MainToolbar->Realize(); - MainToolbar->SetArtProvider(new PHDToolBarArt); // Get the custom background we want + MainToolbar->SetArtProvider(new PHDToolBarArt); // Get the custom background we want } void MyFrame::SetupStatusBar() @@ -1033,15 +1024,15 @@ void MyFrame::SetupStatusBar() void MyFrame::SetupKeyboardShortcuts() { wxAcceleratorEntry entries[] = { - wxAcceleratorEntry(wxACCEL_CTRL, (int) '0', EEGG_CLEARCAL), - wxAcceleratorEntry(wxACCEL_CTRL, (int) 'A', MENU_BRAIN), - wxAcceleratorEntry(wxACCEL_CTRL, (int) 'C', MENU_CONNECT), - wxAcceleratorEntry(wxACCEL_CTRL|wxACCEL_SHIFT, (int) 'C', MENU_CONNECT), - wxAcceleratorEntry(wxACCEL_CTRL, (int) 'G', MENU_GUIDE), - wxAcceleratorEntry(wxACCEL_CTRL, (int) 'L', MENU_LOOP), - wxAcceleratorEntry(wxACCEL_CTRL|wxACCEL_SHIFT, (int) 'M', EEGG_MANUALCAL), - wxAcceleratorEntry(wxACCEL_CTRL, (int) 'S', MENU_STOP), - wxAcceleratorEntry(wxACCEL_CTRL, (int) 'D', BUTTON_ALERT_CLOSE), + wxAcceleratorEntry(wxACCEL_CTRL, (int) '0', EEGG_CLEARCAL), + wxAcceleratorEntry(wxACCEL_CTRL, (int) 'A', MENU_BRAIN), + wxAcceleratorEntry(wxACCEL_CTRL, (int) 'C', MENU_CONNECT), + wxAcceleratorEntry(wxACCEL_CTRL | wxACCEL_SHIFT, (int) 'C', MENU_CONNECT), + wxAcceleratorEntry(wxACCEL_CTRL, (int) 'G', MENU_GUIDE), + wxAcceleratorEntry(wxACCEL_CTRL, (int) 'L', MENU_LOOP), + wxAcceleratorEntry(wxACCEL_CTRL | wxACCEL_SHIFT, (int) 'M', EEGG_MANUALCAL), + wxAcceleratorEntry(wxACCEL_CTRL, (int) 'S', MENU_STOP), + wxAcceleratorEntry(wxACCEL_CTRL, (int) 'D', BUTTON_ALERT_CLOSE), }; wxAcceleratorTable accel(WXSIZEOF(entries), entries); SetAcceleratorTable(accel); @@ -1049,10 +1040,7 @@ void MyFrame::SetupKeyboardShortcuts() struct PHDHelpController : public wxHtmlHelpController { - PHDHelpController() - { - UseConfig(pConfig->Global.GetWxConfig(), "/help"); - } + PHDHelpController() { UseConfig(pConfig->Global.GetWxConfig(), "/help"); } }; void MyFrame::SetupHelpFile() @@ -1062,16 +1050,14 @@ void MyFrame::SetupHelpFile() int langid = wxGetApp().GetLocale().GetLanguage(); // first try to find locale-specific help file - wxString filename = wxGetApp().GetLocalesDir() + wxFILE_SEP_PATH - + wxLocale::GetLanguageCanonicalName(langid) + wxFILE_SEP_PATH - + _T("PHD2GuideHelp.zip"); + wxString filename = wxGetApp().GetLocalesDir() + wxFILE_SEP_PATH + wxLocale::GetLanguageCanonicalName(langid) + + wxFILE_SEP_PATH + _T("PHD2GuideHelp.zip"); Debug.Write(wxString::Format("SetupHelpFile: langid=%d, locale-specific help = %s\n", langid, filename)); if (!wxFileExists(filename)) { - filename = wxGetApp().GetPHDResourcesDir() + wxFILE_SEP_PATH - + _T("PHD2GuideHelp.zip"); + filename = wxGetApp().GetPHDResourcesDir() + wxFILE_SEP_PATH + _T("PHD2GuideHelp.zip"); Debug.Write(wxString::Format("SetupHelpFile: using default help %s\n", filename)); } @@ -1102,9 +1088,7 @@ void MyFrame::UpdateButtonsStatus() bool need_update = false; - bool const loop_enabled = - (!CaptureActive || pGuider->IsCalibratingOrGuiding()) && - pCamera && pCamera->Connected; + bool const loop_enabled = (!CaptureActive || pGuider->IsCalibratingOrGuiding()) && pCamera && pCamera->Connected; if (cond_update_tool(MainToolbar, BUTTON_LOOP, m_loopMenuItem, loop_enabled)) need_update = true; @@ -1125,7 +1109,7 @@ void MyFrame::UpdateButtonsStatus() need_update = true; } - bool guiding_active = pGuider && pGuider->IsCalibratingOrGuiding(); // Not the same as 'bGuideable below + bool guiding_active = pGuider && pGuider->IsCalibratingOrGuiding(); // Not the same as 'bGuideable below if (!guiding_active ^ m_autoSelectStarMenuItem->IsEnabled()) { @@ -1147,14 +1131,12 @@ void MyFrame::UpdateButtonsStatus() need_update = true; } - bool bGuideable = pGuider->GetState() == STATE_SELECTED && - pMount && pMount->IsConnected(); + bool bGuideable = pGuider->GetState() == STATE_SELECTED && pMount && pMount->IsConnected(); if (cond_update_tool(MainToolbar, BUTTON_GUIDE, m_guideMenuItem, bGuideable)) need_update = true; - bool cam_props = pCamera && - (pCamera->PropertyDialogType & PROPDLG_WHEN_CONNECTED) != 0 && pCamera->Connected; + bool cam_props = pCamera && (pCamera->PropertyDialogType & PROPDLG_WHEN_CONNECTED) != 0 && pCamera->Connected; if (cond_update_tool(MainToolbar, BUTTON_CAM_PROPERTIES, m_cameraMenuItem, cam_props)) need_update = true; @@ -1206,9 +1188,7 @@ static wxString WrapText(wxWindow *win, const wxString& text, int width) struct Wrapper : public wxTextWrapper { wxString m_str; - Wrapper(wxWindow *win, const wxString& text, int width) { - Wrap(win, text, width); - } + Wrapper(wxWindow *win, const wxString& text, int width) { Wrap(win, text, width); } const wxString& Str() const { return m_str; } void OnOutputLine(const wxString& line) { m_str += line; } void OnNewLine() { m_str += '\n'; } @@ -1252,8 +1232,8 @@ void MyFrame::OnAlertHelp(wxCommandEvent& evt) help->Display(_("Trouble-shooting and Analysis")); } -// Alerts may have a combination of 'Don't show', help, close, and 'Custom' buttons. The 'close' button is added automatically if any of -// the other buttons are present. +// Alerts may have a combination of 'Don't show', help, close, and 'Custom' buttons. The 'close' button is added automatically +// if any of the other buttons are present. void MyFrame::DoAlert(const alert_params& params) { Debug.Write(wxString::Format("Alert: %s\n", params.msg)); @@ -1305,11 +1285,12 @@ void MyFrame::DoAlert(const alert_params& params) showMessageFlags = wxICON_NONE; #endif m_infoBar->ShowMessage(wrappedText, showMessageFlags); - m_statusbar->UpdateStates(); // might have disconnected a device + m_statusbar->UpdateStates(); // might have disconnected a device EvtServer.NotifyAlert(params.msg, params.flags); } -void MyFrame::Alert(const wxString& msg, alert_fn *DontShowFn, const wxString& buttonLabel, alert_fn *SpecialFn, long arg, bool showHelpButton, int flags) +void MyFrame::Alert(const wxString& msg, alert_fn *DontShowFn, const wxString& buttonLabel, alert_fn *SpecialFn, long arg, + bool showHelpButton, int flags) { if (wxThread::IsMain()) { @@ -1339,13 +1320,14 @@ void MyFrame::Alert(const wxString& msg, alert_fn *DontShowFn, const wxString& b } } -// Standardized version for building an alert that has the "don't show again" option button. Insures that debug log entry is made if -// the user has blocked the alert for this type of problem -void MyFrame::SuppressableAlert(const wxString& configPropKey, const wxString& msg, alert_fn *dontShowFn, long arg, bool showHelpButton, int flags) +// Standardized version for building an alert that has the "don't show again" option button. Insures that debug log entry is +// made if the user has blocked the alert for this type of problem +void MyFrame::SuppressableAlert( + const wxString& configPropKey, const wxString& msg, alert_fn *dontShowFn, long arg, bool showHelpButton, int flags) { if (pConfig->Global.GetBoolean(configPropKey, true)) { - Alert(msg, dontShowFn, wxEmptyString, 0, arg, showHelpButton); + Alert(msg, dontShowFn, wxEmptyString, 0, arg, showHelpButton); } else Debug.Write(wxString::Format("Suppressed alert: %s\n", msg)); @@ -1383,7 +1365,11 @@ void MyFrame::TryReconnect() void MyFrame::DoTryReconnect() { // do not reconnect more than 3 times in 1 minute - enum { TIME_WINDOW = 60, MAX_ATTEMPTS = 3 }; + enum + { + TIME_WINDOW = 60, + MAX_ATTEMPTS = 3 + }; time_t now = wxDateTime::GetTimeNow(); Debug.Write(wxString::Format("Try camera reconnect, now = %lu\n", (unsigned long) now)); while (m_cameraReconnectAttempts.size() > 0 && now - m_cameraReconnectAttempts[0] > TIME_WINDOW) @@ -1391,7 +1377,8 @@ void MyFrame::DoTryReconnect() if (m_cameraReconnectAttempts.size() + 1 > MAX_ATTEMPTS) { Debug.Write(wxString::Format("More than %d camera reconnect attempts in less than %d seconds, " - "return without reconnect.\n", MAX_ATTEMPTS, TIME_WINDOW)); + "return without reconnect.\n", + MAX_ATTEMPTS, TIME_WINDOW)); OnExposeComplete(0, true); return; } @@ -1481,8 +1468,10 @@ void MyFrame::StatusMsgNoTimeout(const wxString& text) void MyFrame::OnStatusMsg(wxThreadEvent& event) { - switch (event.GetExtraLong()) { - case THR_SB_MSG_TEXT: { + switch (event.GetExtraLong()) + { + case THR_SB_MSG_TEXT: + { wxString msg(event.GetString()); bool withTimeout = event.GetInt() ? true : false; @@ -1533,7 +1522,7 @@ void MyFrame::UpdateStatusBarCalibrationStatus() void MyFrame::UpdateStatsWindowScopePointing() { - if(pStatsWin) + if (pStatsWin) { pStatsWin->UpdateScopePointing(); } @@ -1553,9 +1542,9 @@ void MyFrame::NotifyUpdateButtonsStatus() void MyFrame::UpdateStatusBarGuiderInfo(const GuideStepInfo& info) { - Debug.Write(wxString::Format("GuideStep: %.1f px %d ms %s, %.1f px %d ms %s\n", - info.mountOffset.X, info.durationRA, info.directionRA == EAST ? "EAST" : "WEST", - info.mountOffset.Y, info.durationDec, info.directionDec == NORTH ? "NORTH" : "SOUTH")); + Debug.Write(wxString::Format("GuideStep: %.1f px %d ms %s, %.1f px %d ms %s\n", info.mountOffset.X, info.durationRA, + info.directionRA == EAST ? "EAST" : "WEST", info.mountOffset.Y, info.durationDec, + info.directionDec == NORTH ? "NORTH" : "SOUTH")); assert(wxThread::IsMain()); m_statusbar->UpdateGuiderInfo(info); @@ -1583,7 +1572,7 @@ void MyFrame::OnUpdaterStateChanged(wxThreadEvent& event) PHD2Updater::OnUpdaterStateChanged(); } -bool MyFrame::StartWorkerThread(WorkerThread*& pWorkerThread) +bool MyFrame::StartWorkerThread(WorkerThread *& pWorkerThread) { bool bError = false; wxCriticalSectionLocker lock(m_CSpWorkerThread); @@ -1621,7 +1610,7 @@ bool MyFrame::StartWorkerThread(WorkerThread*& pWorkerThread) return bError; } -bool MyFrame::StopWorkerThread(WorkerThread*& pWorkerThread) +bool MyFrame::StopWorkerThread(WorkerThread *& pWorkerThread) { bool killed = false; @@ -1633,7 +1622,10 @@ bool MyFrame::StopWorkerThread(WorkerThread*& pWorkerThread) { pWorkerThread->EnqueueWorkerThreadTerminateRequest(); - enum { TIMEOUT_MS = 1000 }; + enum + { + TIMEOUT_MS = 1000 + }; wxStopWatch swatch; while (pWorkerThread->IsAlive() && swatch.Time() < TIMEOUT_MS) wxGetApp().Yield(); @@ -1710,11 +1702,10 @@ void MyFrame::ScheduleExposure() { int exposureDuration = RequestedExposureDuration(); int exposureOptions = GetRawImageMode() ? CAPTURE_BPM_REVIEW : CAPTURE_LIGHT; - const wxRect& subframe = - m_singleExposure.enabled ? m_singleExposure.subframe : pGuider->GetBoundingBox(); + const wxRect& subframe = m_singleExposure.enabled ? m_singleExposure.subframe : pGuider->GetBoundingBox(); - Debug.Write(wxString::Format("ScheduleExposure(%d,%x,%d) exposurePending=%d\n", - exposureDuration, exposureOptions, !subframe.IsEmpty(), m_exposurePending)); + Debug.Write(wxString::Format("ScheduleExposure(%d,%x,%d) exposurePending=%d\n", exposureDuration, exposureOptions, + !subframe.IsEmpty(), m_exposurePending)); assert(wxThread::IsMain()); // m_exposurePending only updated in main thread assert(!m_exposurePending); @@ -1731,7 +1722,8 @@ void MyFrame::ScheduleExposure() void MyFrame::SchedulePrimaryMove(Mount *mount, const GuiderOffset& ofs, unsigned int moveOptions) { - Debug.Write(wxString::Format("SchedulePrimaryMove(%p, x=%.2f, y=%.2f, opts=%u)\n", mount, ofs.cameraOfs.X, ofs.cameraOfs.Y, moveOptions)); + Debug.Write(wxString::Format( + "SchedulePrimaryMove(%p, x=%.2f, y=%.2f, opts=%u)\n", mount, ofs.cameraOfs.X, ofs.cameraOfs.Y, moveOptions)); wxCriticalSectionLocker lock(m_CSpWorkerThread); @@ -1747,7 +1739,8 @@ void MyFrame::SchedulePrimaryMove(Mount *mount, const GuiderOffset& ofs, unsigne void MyFrame::ScheduleSecondaryMove(Mount *mount, const GuiderOffset& ofs, unsigned int moveOptions) { - Debug.Write(wxString::Format("ScheduleSecondaryMove(%p, x=%.2f, y=%.2f, opts=%u)\n", mount, ofs.cameraOfs.X, ofs.cameraOfs.Y, moveOptions)); + Debug.Write(wxString::Format( + "ScheduleSecondaryMove(%p, x=%.2f, y=%.2f, opts=%u)\n", mount, ofs.cameraOfs.X, ofs.cameraOfs.Y, moveOptions)); wxCriticalSectionLocker lock(m_CSpWorkerThread); @@ -1846,7 +1839,8 @@ bool MyFrame::AutoSelectStar(const wxRect& roi) void MyFrame::StartCapturing() { - Debug.Write(wxString::Format("StartCapturing CaptureActive=%d continueCapturing=%d exposurePending=%d\n", CaptureActive, m_continueCapturing, m_exposurePending)); + Debug.Write(wxString::Format("StartCapturing CaptureActive=%d continueCapturing=%d exposurePending=%d\n", CaptureActive, + m_continueCapturing, m_exposurePending)); if (!CaptureActive) { @@ -1872,7 +1866,8 @@ void MyFrame::StartCapturing() bool MyFrame::StopCapturing() { - Debug.Write(wxString::Format("StopCapturing CaptureActive=%d continueCapturing=%d exposurePending=%d\n", CaptureActive, m_continueCapturing, m_exposurePending)); + Debug.Write(wxString::Format("StopCapturing CaptureActive=%d continueCapturing=%d exposurePending=%d\n", CaptureActive, + m_continueCapturing, m_exposurePending)); bool finished = true; bool continueCapturing = m_continueCapturing; @@ -1989,9 +1984,7 @@ bool MyFrame::StartGuiding() wxGetApp().CheckLogRollover(); - if (pMount && pMount->IsConnected() && - pCamera && pCamera->Connected && - pGuider->GetState() >= STATE_SELECTED) + if (pMount && pMount->IsConnected() && pCamera && pCamera->Connected && pGuider->GetState() >= STATE_SELECTED) { pGuider->StartGuiding(); StartCapturing(); @@ -2039,7 +2032,7 @@ void DitherSpiral::GetDither(double amount, bool raOnly, double *dRa, double *dD else x += dy; - *dRa = (double)(x - x0) * amount; + *dRa = (double) (x - x0) * amount; *dDec = 0.0; } else @@ -2050,7 +2043,7 @@ void DitherSpiral::GetDither(double amount, bool raOnly, double *dRa, double *dD x += dx; y += dy; - *dRa = (double) dx * amount; + *dRa = (double) dx * amount; *dDec = (double) dy * amount; } } @@ -2085,8 +2078,8 @@ bool MyFrame::Dither(double amount, bool raOnly) else { // DITHER_RANDOM - dRa = amount * ((rand() / (double)RAND_MAX) * 2.0 - 1.0); - dDec = raOnly ? 0.0 : amount * ((rand() / (double)RAND_MAX) * 2.0 - 1.0); + dRa = amount * ((rand() / (double) RAND_MAX) * 2.0 - 1.0); + dDec = raOnly ? 0.0 : amount * ((rand() / (double) RAND_MAX) * 2.0 - 1.0); } Debug.Write(wxString::Format("dither: size=%.2f, dRA=%.2f dDec=%.2f\n", amount, dRa, dDec)); @@ -2145,8 +2138,8 @@ void MyFrame::OnClose(wxCloseEvent& event) { if (CaptureActive && event.CanVeto()) { - bool confirmed = ConfirmDialog::Confirm(_("Are you sure you want to exit while capturing is active?"), - "/quit_when_looping_ok", _("Confirm Exit")); + bool confirmed = ConfirmDialog::Confirm( + _("Are you sure you want to exit while capturing is active?"), "/quit_when_looping_ok", _("Confirm Exit")); if (!confirmed) { event.Veto(); @@ -2173,10 +2166,8 @@ void MyFrame::OnClose(wxCloseEvent& event) GuideLog.CloseGuideLog(); pConfig->Global.SetString("/perspective", m_mgr.SavePerspective()); - wxString geometry = wxString::Format("%c;%d;%d;%d;%d", - this->IsMaximized() ? '1' : '0', - this->GetSize().x, this->GetSize().y, - this->GetScreenPosition().x, this->GetScreenPosition().y); + wxString geometry = wxString::Format("%c;%d;%d;%d;%d", this->IsMaximized() ? '1' : '0', this->GetSize().x, + this->GetSize().y, this->GetScreenPosition().x, this->GetScreenPosition().y); pConfig->Global.SetString("/geometry", geometry); if (help->GetFrame()) @@ -2195,21 +2186,21 @@ bool MyFrame::SetNoiseReductionMethod(int noiseReductionMethod) { switch (noiseReductionMethod) { - case NR_NONE: - case NR_2x2MEAN: - case NR_3x3MEDIAN: - break; - default: - throw ERROR_INFO("invalid noiseReductionMethod"); + case NR_NONE: + case NR_2x2MEAN: + case NR_3x3MEDIAN: + break; + default: + throw ERROR_INFO("invalid noiseReductionMethod"); } - m_noiseReductionMethod = (NOISE_REDUCTION_METHOD)noiseReductionMethod; + m_noiseReductionMethod = (NOISE_REDUCTION_METHOD) noiseReductionMethod; } catch (const wxString& Msg) { POSSIBLY_UNUSED(Msg); bError = true; - m_noiseReductionMethod = (NOISE_REDUCTION_METHOD)DefaultNoiseReductionMethod; + m_noiseReductionMethod = (NOISE_REDUCTION_METHOD) DefaultNoiseReductionMethod; } pConfig->Profile.SetInt("/NoiseReductionMethod", m_noiseReductionMethod); @@ -2295,10 +2286,14 @@ void MyFrame::SetAutoLoadCalibration(bool val) inline static GuideParity guide_parity(int p) { - switch (p) { - case GUIDE_PARITY_EVEN: return GUIDE_PARITY_EVEN; - case GUIDE_PARITY_ODD: return GUIDE_PARITY_ODD; - default: return GUIDE_PARITY_UNKNOWN; + switch (p) + { + case GUIDE_PARITY_EVEN: + return GUIDE_PARITY_EVEN; + case GUIDE_PARITY_ODD: + return GUIDE_PARITY_ODD; + default: + return GUIDE_PARITY_UNKNOWN; } } @@ -2316,8 +2311,7 @@ static void load_calibration(Mount *mnt) cal.yAngle = pConfig->Profile.GetDouble(prefix + "yAngle", M_PI / 2.0); cal.declination = pConfig->Profile.GetDouble(prefix + "declination", 0.0); int t = pConfig->Profile.GetInt(prefix + "pierSide", PIER_SIDE_UNKNOWN); - cal.pierSide = t == PIER_SIDE_EAST ? PIER_SIDE_EAST : - t == PIER_SIDE_WEST ? PIER_SIDE_WEST : PIER_SIDE_UNKNOWN; + cal.pierSide = t == PIER_SIDE_EAST ? PIER_SIDE_EAST : t == PIER_SIDE_WEST ? PIER_SIDE_WEST : PIER_SIDE_UNKNOWN; cal.raGuideParity = guide_parity(pConfig->Profile.GetInt(prefix + "raGuideParity", GUIDE_PARITY_UNKNOWN)); cal.decGuideParity = guide_parity(pConfig->Profile.GetInt(prefix + "decGuideParity", GUIDE_PARITY_UNKNOWN)); cal.rotatorAngle = pConfig->Profile.GetDouble(prefix + "rotatorAngle", Rotator::POSITION_UNKNOWN); @@ -2344,8 +2338,8 @@ static bool save_multi_darks(const ExposureImgMap& darks, const wxString& fname, try { - fitsfile *fptr; // FITS file pointer - int status = 0; // CFITSIO status value MUST be initialized to zero! + fitsfile *fptr; // FITS file pointer + int status = 0; // CFITSIO status value MUST be initialized to zero! PHD_fits_create_file(&fptr, fname, true, &status); if (status) @@ -2355,8 +2349,8 @@ static bool save_multi_darks(const ExposureImgMap& darks, const wxString& fname, { const usImage *const img = it->second; long fsize[] = { - (long)img->Size.GetWidth(), - (long)img->Size.GetHeight(), + (long) img->Size.GetWidth(), + (long) img->Size.GetHeight(), }; if (!status) fits_create_img(fptr, USHORT_IMG, 2, fsize, &status); @@ -2364,12 +2358,14 @@ static bool save_multi_darks(const ExposureImgMap& darks, const wxString& fname, float exposure = (float) img->ImgExpDur / 1000.0f; char *keyname = const_cast("EXPOSURE"); char *comment = const_cast("Exposure time in seconds"); - if (!status) fits_write_key(fptr, TFLOAT, keyname, &exposure, comment, &status); + if (!status) + fits_write_key(fptr, TFLOAT, keyname, &exposure, comment, &status); if (!note.IsEmpty()) { char *USERNOTE = const_cast("USERNOTE"); - if (!status) fits_write_key(fptr, TSTRING, USERNOTE, note.char_str(), nullptr, &status); + if (!status) + fits_write_key(fptr, TSTRING, USERNOTE, note.char_str(), nullptr, &status); } if (!status) @@ -2397,8 +2393,8 @@ static bool load_multi_darks(GuideCamera *camera, const wxString& fname) { bool bError = false; fitsfile *fptr = 0; - int status = 0; // CFITSIO status value MUST be initialized to zero! - long last_frame_size [] = { -1L, -1L }; + int status = 0; // CFITSIO status value MUST be initialized to zero! + long last_frame_size[] = { -1L, -1L }; try { @@ -2436,7 +2432,8 @@ static bool load_multi_darks(GuideCamera *camera, const wxString& fname) { if (last_frame_size[0] != fsize[0] || last_frame_size[1] != fsize[1]) { - pFrame->Alert(_("Existing dark library has frames with incompatible formats - please rebuild the dark library from scratch.")); + pFrame->Alert(_("Existing dark library has frames with incompatible formats - please rebuild the dark " + "library from scratch.")); throw ERROR_INFO("Incompatible frame sizes in dark library"); } } @@ -2445,7 +2442,7 @@ static bool load_multi_darks(GuideCamera *camera, const wxString& fname) std::unique_ptr img(new usImage()); - if (img->Init((int)fsize[0], (int)fsize[1])) + if (img->Init((int) fsize[0], (int) fsize[1])) { pFrame->Alert(wxString::Format(_("Memory allocation error reading FITS file %s"), fname)); throw ERROR_INFO("Memory Allocation failure"); @@ -2462,7 +2459,7 @@ static bool load_multi_darks(GuideCamera *camera, const wxString& fname) float exposure; if (fits_read_key(fptr, TFLOAT, keyname, &exposure, nullptr, &status)) { - exposure = (float)pFrame->RequestedExposureDuration() / 1000.0; + exposure = (float) pFrame->RequestedExposureDuration() / 1000.0; Debug.Write(wxString::Format("missing EXPOSURE value, assume %.3f\n", exposure)); status = 0; } @@ -2470,8 +2467,7 @@ static bool load_multi_darks(GuideCamera *camera, const wxString& fname) img->CalcStats(); - Debug.Write(wxString::Format("loaded dark frame exposure = %d, med = %u\n", - img->ImgExpDur, img->MedianADU)); + Debug.Write(wxString::Format("loaded dark frame exposure = %d, med = %u\n", img->ImgExpDur, img->MedianADU)); camera->AddDark(img.release()); @@ -2510,7 +2506,7 @@ wxString MyFrame::GetDarksDir() wxString dirpath = GetDefaultFileDir() + PATHSEPSTR + "darks_defects"; if (!wxDirExists(dirpath)) if (!wxFileName::Mkdir(dirpath, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) - dirpath = GetDefaultFileDir(); // should never happen + dirpath = GetDefaultFileDir(); // should never happen return dirpath; } @@ -2537,7 +2533,7 @@ bool MyFrame::DarkLibExists(int profileId, bool showAlert) else { fitsfile *fptr; - int status = 0; // CFITSIO status value MUST be initialized to zero! + int status = 0; // CFITSIO status value MUST be initialized to zero! if (PHD_fits_open_diskfile(&fptr, fileName, READONLY, &status) == 0) { @@ -2547,12 +2543,14 @@ bool MyFrame::DarkLibExists(int profileId, bool showAlert) bOk = true; else { - Debug.Write(wxString::Format("DarkLib check: failed geometry check - fits status = %d, cam dimensions = {%d,%d}, " - " dark dimensions = {%d,%d}\n", status, sensorSize.x, sensorSize.y, fsize[0], fsize[1])); + Debug.Write( + wxString::Format("DarkLib check: failed geometry check - fits status = %d, cam dimensions = {%d,%d}, " + " dark dimensions = {%d,%d}\n", + status, sensorSize.x, sensorSize.y, fsize[0], fsize[1])); if (showAlert) Alert(_("Dark library does not match the camera in this profile. Check that you are " - "connected to the camera you want to use for guiding.")); + "connected to the camera you want to use for guiding.")); } PHD_fits_close_file(fptr); @@ -2599,7 +2597,7 @@ void MyFrame::CheckDarkFrameGeometry() Debug.Write("CheckDarkFrameGeometry: Dark lib incompatibility found\n"); if (!defectMapOk) pFrame->Alert(_("Dark library and bad-pixel maps don't match the current camera. " - "Check that you are connected to the camera you want to use for guiding.")); + "Check that you are connected to the camera you want to use for guiding.")); } } else if (haveDarkLib) @@ -2740,7 +2738,8 @@ bool MyFrame::SetFocalLength(int focalLength) void MyFrame::SetVariableDelayConfig(bool varDelayEnabled, int ShortDelayMS, int LongDelayMS) { - Debug.Write(wxString::Format("Variable delay: %s, Short = %d ms, Long = %d ms\n", (varDelayEnabled ? "Enabled" : "Disabled"), ShortDelayMS, LongDelayMS)); + Debug.Write(wxString::Format("Variable delay: %s, Short = %d ms, Long = %d ms\n", + (varDelayEnabled ? "Enabled" : "Disabled"), ShortDelayMS, LongDelayMS)); m_varDelayConfig.enabled = varDelayEnabled; m_varDelayConfig.shortDelay = ShortDelayMS; @@ -2754,11 +2753,11 @@ void MyFrame::SetVariableDelayConfig(bool varDelayEnabled, int ShortDelayMS, int wxString MyFrame::GetDefaultFileDir() { wxStandardPathsBase& stdpath = wxStandardPaths::Get(); - wxString rslt = stdpath.GetUserLocalDataDir(); // Automatically includes app name + wxString rslt = stdpath.GetUserLocalDataDir(); // Automatically includes app name if (!wxDirExists(rslt)) if (!wxFileName::Mkdir(rslt, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL)) - rslt = stdpath.GetUserLocalDataDir(); // should never happen + rslt = stdpath.GetUserLocalDataDir(); // should never happen return rslt; } @@ -2786,8 +2785,7 @@ wxString MyFrame::PixelScaleSummary() const else focalLengthStr = wxString::Format("%d mm", m_focalLength); - return wxString::Format("Pixel scale = %s, Binning = %hu, Focal length = %s", - scaleStr, pCamera->Binning, focalLengthStr); + return wxString::Format("Pixel scale = %s, Binning = %hu, Focal length = %s", scaleStr, pCamera->Binning, focalLengthStr); } bool MyFrame::GetBeepForLostStar() @@ -2805,15 +2803,14 @@ void MyFrame::SetBeepForLostStar(bool beep) wxString MyFrame::GetSettingsSummary() const { // return a loggable summary of current global configs managed by MyFrame - return wxString::Format("Dither = %s, Dither scale = %.3f, Image noise reduction = %s, Guide-frame time lapse = %d, Server %s\n" + return wxString::Format( + "Dither = %s, Dither scale = %.3f, Image noise reduction = %s, Guide-frame time lapse = %d, Server %s\n" "%s\n", - m_ditherRaOnly ? "RA only" : "both axes", - m_ditherScaleFactor, - m_noiseReductionMethod == NR_NONE ? "none" : m_noiseReductionMethod == NR_2x2MEAN ? "2x2 mean" : "3x3 median", - m_timeLapse, - m_serverMode ? "enabled" : "disabled", - PixelScaleSummary() - ); + m_ditherRaOnly ? "RA only" : "both axes", m_ditherScaleFactor, + m_noiseReductionMethod == NR_NONE ? "none" + : m_noiseReductionMethod == NR_2x2MEAN ? "2x2 mean" + : "3x3 median", + m_timeLapse, m_serverMode ? "enabled" : "disabled", PixelScaleSummary()); } void MyFrame::RegisterTextCtrl(wxTextCtrl *ctrl) @@ -2823,8 +2820,8 @@ void MyFrame::RegisterTextCtrl(wxTextCtrl *ctrl) ctrl->Bind(wxEVT_KILL_FOCUS, &MyFrame::OnTextControlKillFocus, this); } -// Reset the guiding parameters and the various graphical displays when image scale is changed outside the AD UI. Goal is to restore basic guiding behavior -// until a fresh calibration is done. +// Reset the guiding parameters and the various graphical displays when image scale is changed outside the AD UI. Goal is to +// restore basic guiding behavior until a fresh calibration is done. void MyFrame::HandleImageScaleChange() { Scope *scope = TheScope(); @@ -2852,7 +2849,7 @@ void MyFrame::HandleImageScaleChange() } Alert(_("Binning or camera pixel size changed unexpectedly. " - "You should use separate profiles for different image scales.")); + "You should use separate profiles for different image scales.")); } MyFrameConfigDialogPane *MyFrame::GetConfigDialogPane(wxWindow *pParent) @@ -2883,7 +2880,8 @@ void MyFrameConfigDialogPane::LayoutControls(BrainCtrlIdMap& CtrlMap) Layout(); } -MyFrameConfigDialogCtrlSet *MyFrame::GetConfigDlgCtrlSet(MyFrame *pFrame, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +MyFrameConfigDialogCtrlSet *MyFrame::GetConfigDlgCtrlSet( + MyFrame *pFrame, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) { return new MyFrameConfigDialogCtrlSet(pFrame, pAdvancedDialog, CtrlMap); } @@ -2892,11 +2890,14 @@ struct FocalLengthValidator : public wxIntegerValidator { typedef wxIntegerValidator Super; AdvancedDialog *m_dlg; - FocalLengthValidator(AdvancedDialog *dlg) : Super(nullptr, 0), m_dlg(dlg) { } - wxObject *Clone() const override { - return new FocalLengthValidator(*this); + FocalLengthValidator(AdvancedDialog *dlg) + : Super(nullptr, 0) + , m_dlg(dlg) + { } - bool Validate(wxWindow *parent) override { + wxObject *Clone() const override { return new FocalLengthValidator(*this); } + bool Validate(wxWindow *parent) override + { bool ok = false; if (Super::Validate(parent)) { @@ -2909,7 +2910,7 @@ struct FocalLengthValidator : public wxIntegerValidator { m_dlg->ShowInvalid(GetWindow(), wxString::Format(_("Enter a focal length in millimeters, between %.f and %.f"), - AdvancedDialog::MIN_FOCAL_LENGTH, AdvancedDialog::MAX_FOCAL_LENGTH)); + AdvancedDialog::MIN_FOCAL_LENGTH, AdvancedDialog::MAX_FOCAL_LENGTH)); } return ok; } @@ -2954,8 +2955,7 @@ class AvailableLanguages void Init() { - wxArrayString availableTranslations = - wxTranslations::Get()->GetAvailableTranslations(PHD_MESSAGES_CATALOG); + wxArrayString availableTranslations = wxTranslations::Get()->GetAvailableTranslations(PHD_MESSAGES_CATALOG); availableTranslations.Sort(); @@ -2981,29 +2981,31 @@ class AvailableLanguages } public: - - const wxArrayString& Names() { + const wxArrayString& Names() + { if (m_names.empty()) Init(); return m_names; } - int Index(int langid) { + int Index(int langid) + { if (m_names.empty()) Init(); return m_ids.Index(langid); } - int LangId(int index) { + int LangId(int index) + { if (m_names.empty()) Init(); - return index >= 0 && index < m_names.size() ? - m_ids[index] : wxLANGUAGE_DEFAULT; + return index >= 0 && index < m_names.size() ? m_ids[index] : wxLANGUAGE_DEFAULT; } }; static AvailableLanguages PhdLanguages; -MyFrameConfigDialogCtrlSet::MyFrameConfigDialogCtrlSet(MyFrame *pFrame, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +MyFrameConfigDialogCtrlSet::MyFrameConfigDialogCtrlSet( + MyFrame *pFrame, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) : ConfigDialogCtrlSet(pFrame, pAdvancedDialog, CtrlMap) { int width; @@ -3011,41 +3013,40 @@ MyFrameConfigDialogCtrlSet::MyFrameConfigDialogCtrlSet(MyFrame *pFrame, Advanced m_pFrame = pFrame; m_pResetConfiguration = new wxCheckBox(GetParentWindow(AD_cbResetConfig), wxID_ANY, _("Reset Configuration")); - AddCtrl(CtrlMap, AD_cbResetConfig, m_pResetConfiguration, _("Reset all configuration and program settings to fresh install status. This will require restarting PHD2")); + AddCtrl(CtrlMap, AD_cbResetConfig, m_pResetConfiguration, + _("Reset all configuration and program settings to fresh install status. This will require restarting PHD2")); m_pResetDontAskAgain = new wxCheckBox(GetParentWindow(AD_cbDontAsk), wxID_ANY, _("Reset \"Don't Show Again\" messages")); - AddCtrl(CtrlMap, AD_cbDontAsk, m_pResetDontAskAgain, _("Restore any messages that were hidden when you checked \"Don't show this again\".")); + AddCtrl(CtrlMap, AD_cbDontAsk, m_pResetDontAskAgain, + _("Restore any messages that were hidden when you checked \"Don't show this again\".")); - wxString nralgo_choices[] = - { - _("None"), _("2x2 mean"), _("3x3 median") - }; + wxString nralgo_choices[] = { _("None"), _("2x2 mean"), _("3x3 median") }; width = StringArrayWidth(nralgo_choices, WXSIZEOF(nralgo_choices)); parent = GetParentWindow(AD_szNoiseReduction); - m_pNoiseReduction = new wxChoice(parent, wxID_ANY, wxPoint(-1, -1), - wxSize(width + 35, -1), WXSIZEOF(nralgo_choices), nralgo_choices); - AddLabeledCtrl(CtrlMap, AD_szNoiseReduction, _("Noise Reduction"), m_pNoiseReduction, - _("Technique to reduce noise in images")); + m_pNoiseReduction = + new wxChoice(parent, wxID_ANY, wxPoint(-1, -1), wxSize(width + 35, -1), WXSIZEOF(nralgo_choices), nralgo_choices); + AddLabeledCtrl( + CtrlMap, AD_szNoiseReduction, _("Noise Reduction"), m_pNoiseReduction, _("Technique to reduce noise in images")); width = StringWidth(_T("00000")); parent = GetParentWindow(AD_szTimeLapse); - m_pTimeLapse = pFrame->MakeSpinCtrl(parent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0, 10000, 0, _T("TimeLapse")); + m_pTimeLapse = pFrame->MakeSpinCtrl( + parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 10000, 0, _T("TimeLapse")); AddLabeledCtrl(CtrlMap, AD_szTimeLapse, _("Time Lapse (ms)"), m_pTimeLapse, - _("How long should PHD wait between guide frames? Default = 0ms, useful when using very short exposures (e.g., using a video camera) but wanting to send guide commands less frequently")); + _("How long should PHD wait between guide frames? Default = 0ms, useful when using very short exposures (e.g., using a " + "video camera) but wanting to send guide commands less frequently")); parent = GetParentWindow(AD_szFocalLength); // Put a validator on this field to be sure that only digits are entered - avoids problem where // user face-plant on keyboard results in a focal length of zero - m_pFocalLength = new wxTextCtrl(parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width + 30, -1), 0, - FocalLengthValidator(pAdvancedDialog)); + m_pFocalLength = new wxTextCtrl( + parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width + 30, -1), 0, FocalLengthValidator(pAdvancedDialog)); AddLabeledCtrl(CtrlMap, AD_szFocalLength, _("Focal length (mm)"), m_pFocalLength, _("Guider telescope focal length, used with the camera pixel size to display guiding error in arc-sec.")); width = StringWidth(_("System default")); parent = GetParentWindow(AD_szLanguage); - m_pLanguage = new wxChoice(parent, wxID_ANY, wxPoint(-1, -1), - wxSize(width + 35, -1), PhdLanguages.Names()); + m_pLanguage = new wxChoice(parent, wxID_ANY, wxPoint(-1, -1), wxSize(width + 35, -1), PhdLanguages.Names()); AddLabeledCtrl(CtrlMap, AD_szLanguage, _("Language"), m_pLanguage, wxString::Format(_("%s Language. You'll have to restart PHD to take effect."), APPNAME)); @@ -3092,24 +3093,29 @@ MyFrameConfigDialogCtrlSet::MyFrameConfigDialogCtrlSet(MyFrame *pFrame, Advanced m_LogDroppedFrames->SetToolTip(_("Save guider image whenever a lost-star event occurs")); m_LogAutoSelectFrames = new wxCheckBox(parent, wxID_ANY, _("For all Auto-select Star frames")); - m_LogAutoSelectFrames->SetToolTip(_("Save guider image when a star auto-selection is made. Note: the image is always saved when star auto-selection fails, regardless of this setting.")); + m_LogAutoSelectFrames->SetToolTip(_("Save guider image when a star auto-selection is made. Note: the image is always saved " + "when star auto-selection fails, regardless of this setting.")); wxBoxSizer *pHzRel = new wxBoxSizer(wxHORIZONTAL); m_LogRelErrors = new wxCheckBox(parent, wxID_ANY, _("When relative error exceeds")); - m_LogRelErrors->SetToolTip(_("Save guider images when the error for the current frame exceeds the average error by this factor. " - "For example, if the average (RMS) error is 0.5 pixels, and the current frame's error is 1.5 pixels, the relative error is 3")); - m_LogRelErrorThresh = pFrame->MakeSpinCtrlDouble(parent, wxID_ANY, _(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 10.0, 4.0, 1.0); - m_LogRelErrorThresh->SetToolTip(_("Relative error threshold. Relative error is the ratio between the current frame's error and the average error")); + m_LogRelErrors->SetToolTip( + _("Save guider images when the error for the current frame exceeds the average error by this factor. " + "For example, if the average (RMS) error is 0.5 pixels, and the current frame's error is 1.5 pixels, the relative " + "error is 3")); + m_LogRelErrorThresh = pFrame->MakeSpinCtrlDouble( + parent, wxID_ANY, _(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 10.0, 4.0, 1.0); + m_LogRelErrorThresh->SetToolTip( + _("Relative error threshold. Relative error is the ratio between the current frame's error and the average error")); pHzRel->Add(m_LogRelErrors, wxSizerFlags().Border(wxALL, PAD).Align(wxALIGN_CENTER_VERTICAL)); pHzRel->Add(m_LogRelErrorThresh, wxSizerFlags().Border(wxALL, PAD).Align(wxALIGN_CENTER_VERTICAL)); wxBoxSizer *pHzAbs = new wxBoxSizer(wxHORIZONTAL); m_LogAbsErrors = new wxCheckBox(parent, wxID_ANY, _("When absolute error exceeds (pixels)")); - m_LogAbsErrors->SetToolTip(_("Save guider images when the distance between the guide star and the lock position exceeds this many pixels")); + m_LogAbsErrors->SetToolTip( + _("Save guider images when the distance between the guide star and the lock position exceeds this many pixels")); width = StringWidth(_T("00.0")); - m_LogAbsErrorThresh = pFrame->MakeSpinCtrlDouble(parent, wxID_ANY, _(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 10.0, 4.0, 1.0); + m_LogAbsErrorThresh = pFrame->MakeSpinCtrlDouble( + parent, wxID_ANY, _(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 10.0, 4.0, 1.0); m_LogAbsErrorThresh->SetToolTip(_("Absolute error threshold in pixels")); pHzAbs->Add(m_LogAbsErrors, wxSizerFlags().Border(wxALL, PAD).Align(wxALIGN_CENTER_VERTICAL)); pHzAbs->Add(m_LogAbsErrorThresh, wxSizerFlags().Border(wxALL, PAD).Align(wxALIGN_CENTER_VERTICAL)); @@ -3117,7 +3123,8 @@ MyFrameConfigDialogCtrlSet::MyFrameConfigDialogCtrlSet(MyFrame *pFrame, Advanced wxBoxSizer *pHzN = new wxBoxSizer(wxHORIZONTAL); m_LogNextNFrames = new wxCheckBox(parent, wxID_ANY, _("Until this count is reached")); m_LogNextNFrames->SetToolTip(_("Save each guider image until the specified number of images have been saved")); - m_LogNextNFramesCount = pFrame->MakeSpinCtrl(parent, wxID_ANY, "1", wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1, 100, 1); + m_LogNextNFramesCount = + pFrame->MakeSpinCtrl(parent, wxID_ANY, "1", wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1, 100, 1); m_LogNextNFramesCount->SetToolTip(_("Number of images to save")); pHzN->Add(m_LogNextNFrames, wxSizerFlags().Border(wxALL, PAD).Align(wxALIGN_CENTER_VERTICAL)); pHzN->Add(m_LogNextNFramesCount, wxSizerFlags().Border(wxALL, PAD).Align(wxALIGN_CENTER_VERTICAL)); @@ -3148,14 +3155,15 @@ MyFrameConfigDialogCtrlSet::MyFrameConfigDialogCtrlSet(MyFrame *pFrame, Advanced m_ditherRaOnly->SetToolTip(_("Constrain dither to RA only")); width = StringWidth(_T("000.00")); - m_ditherScaleFactor = pFrame->MakeSpinCtrlDouble(parent, wxID_ANY, _T(" "), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0.1, 100.0, 0.0, 1.0); + m_ditherScaleFactor = pFrame->MakeSpinCtrlDouble( + parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.1, 100.0, 0.0, 1.0); m_ditherScaleFactor->SetDigits(1); m_ditherScaleFactor->SetToolTip(_("Scaling for dither commands. Default = 1.0 (0.1-100.0)")); sz = new wxBoxSizer(wxHORIZONTAL); sz->Add(m_ditherRaOnly, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Border(wxLEFT, 8)); - sz->Add(new wxStaticText(parent, wxID_ANY, _("Scale") + _(": ")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Border(wxLEFT, 40)); + sz->Add(new wxStaticText(parent, wxID_ANY, _("Scale") + _(": ")), + wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Border(wxLEFT, 40)); sz->Add(m_ditherScaleFactor, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Border(wxLEFT, 10)); ditherGroupBox->Add(sz); @@ -3163,26 +3171,29 @@ MyFrameConfigDialogCtrlSet::MyFrameConfigDialogCtrlSet(MyFrame *pFrame, Advanced parent = GetParentWindow(AD_cbAutoRestoreCal); m_pAutoLoadCalibration = new wxCheckBox(parent, wxID_ANY, _("Auto restore calibration"), wxDefaultPosition, wxDefaultSize); - AddCtrl(CtrlMap, AD_cbAutoRestoreCal, m_pAutoLoadCalibration, _("For this equipment profile, automatically restore data from last successful calibration after gear is connected.")); + AddCtrl(CtrlMap, AD_cbAutoRestoreCal, m_pAutoLoadCalibration, + _("For this equipment profile, automatically restore data from last successful calibration after gear is connected.")); parent = GetParentWindow(AD_szAutoExposure); - m_autoExpDurationMin = new wxComboBox(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, - wxArrayString(), wxCB_READONLY); - m_autoExpDurationMax = new wxComboBox(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, - wxArrayString(), wxCB_READONLY); + m_autoExpDurationMin = + new wxComboBox(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxArrayString(), wxCB_READONLY); + m_autoExpDurationMax = + new wxComboBox(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxArrayString(), wxCB_READONLY); wxSize minsz(StringWidth(pFrame->ExposureDurationLabel(999990)) + 30, -1); m_autoExpDurationMin->SetMinSize(minsz); m_autoExpDurationMax->SetMinSize(minsz); width = StringWidth(_T("00.0")); - m_autoExpSNR = pFrame->MakeSpinCtrlDouble(parent, wxID_ANY, _T(""), wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 3.5, 99.9, 0.0, 1.0); + m_autoExpSNR = pFrame->MakeSpinCtrlDouble( + parent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 3.5, 99.9, 0.0, 1.0); wxFlexGridSizer *sz1 = new wxFlexGridSizer(1, 3, 10, 10); sz1->Add(MakeLabeledControl(AD_szAutoExposure, _("Min"), m_autoExpDurationMin, _("Auto exposure minimum duration"))); - sz1->Add(MakeLabeledControl(AD_szAutoExposure, _("Max"), m_autoExpDurationMax, _("Auto exposure maximum duration")), wxSizerFlags(0).Border(wxLEFT, 70)); - sz1->Add(MakeLabeledControl(AD_szAutoExposure, _("Target SNR"), m_autoExpSNR, _("Auto exposure target SNR value")), wxSizerFlags(0).Border(wxLEFT, 80)); + sz1->Add(MakeLabeledControl(AD_szAutoExposure, _("Max"), m_autoExpDurationMax, _("Auto exposure maximum duration")), + wxSizerFlags(0).Border(wxLEFT, 70)); + sz1->Add(MakeLabeledControl(AD_szAutoExposure, _("Target SNR"), m_autoExpSNR, _("Auto exposure target SNR value")), + wxSizerFlags(0).Border(wxLEFT, 80)); wxStaticBoxSizer *autoExp = new wxStaticBoxSizer(wxHORIZONTAL, parent, _("Auto Exposure")); autoExp->Add(sz1, wxSizerFlags(0).Expand()); AddGroup(CtrlMap, AD_szAutoExposure, autoExp); @@ -3190,15 +3201,22 @@ MyFrameConfigDialogCtrlSet::MyFrameConfigDialogCtrlSet(MyFrame *pFrame, Advanced wxFlexGridSizer *sz2 = new wxFlexGridSizer(1, 3, 10, 10); width = StringWidth(_T("600")); parent = GetParentWindow(AD_szVariableExposureDelay); - m_varExposureDelayEnabled = new wxCheckBox(parent, wxID_ANY, _("Use Variable Exposure Delays"), wxDefaultPosition, wxDefaultSize); - m_varExposureDelayEnabled->SetToolTip(_("Use \"short\" delay for calibration, looping, dithering, GA, \"long\" delay for normal guiding")); + m_varExposureDelayEnabled = + new wxCheckBox(parent, wxID_ANY, _("Use Variable Exposure Delays"), wxDefaultPosition, wxDefaultSize); + m_varExposureDelayEnabled->SetToolTip( + _("Use \"short\" delay for calibration, looping, dithering, GA, \"long\" delay for normal guiding")); m_varExposureDelayEnabled->Bind(wxEVT_COMMAND_CHECKBOX_CLICKED, &MyFrameConfigDialogCtrlSet::OnVariableDelayChecked, this); sz2->Add(m_varExposureDelayEnabled, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Border(wxLEFT, 8)); - m_varExpDelayShort = pFrame->MakeSpinCtrl(parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 10, 0, _T("ExpDelayShort")); - m_varExpDelayLong = pFrame->MakeSpinCtrl(parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 120, 0, _T("ExpDelayLong")); - sz2->Add(MakeLabeledControl(AD_szVariableExposureDelay, _("Short delay (sec)"), m_varExpDelayShort, _("Short delay for calibration, looping, dithering, GA"))); - sz2->Add(MakeLabeledControl(AD_szVariableExposureDelay, _("Long delay (sec)"), m_varExpDelayLong, _("Long delay for normal guiding"))); - wxStaticBoxSizer* varDelayGrp = new wxStaticBoxSizer(wxHORIZONTAL, parent, _("Variable Exposure Delay (High-precision encoder mounts)")); + m_varExpDelayShort = pFrame->MakeSpinCtrl( + parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 10, 0, _T("ExpDelayShort")); + m_varExpDelayLong = pFrame->MakeSpinCtrl( + parent, wxID_ANY, _T(" "), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 120, 0, _T("ExpDelayLong")); + sz2->Add(MakeLabeledControl(AD_szVariableExposureDelay, _("Short delay (sec)"), m_varExpDelayShort, + _("Short delay for calibration, looping, dithering, GA"))); + sz2->Add(MakeLabeledControl( + AD_szVariableExposureDelay, _("Long delay (sec)"), m_varExpDelayLong, _("Long delay for normal guiding"))); + wxStaticBoxSizer *varDelayGrp = + new wxStaticBoxSizer(wxHORIZONTAL, parent, _("Variable Exposure Delay (High-precision encoder mounts)")); varDelayGrp->Add(sz2, wxSizerFlags(0).Expand()); AddGroup(CtrlMap, AD_szVariableExposureDelay, varDelayGrp); } @@ -3218,8 +3236,8 @@ void MyFrameConfigDialogCtrlSet::LoadValues() m_pTimeLapse->SetValue(m_pFrame->GetTimeLapse()); VarDelayCfg delayCfg = m_pFrame->GetVariableDelayConfig(); m_varExposureDelayEnabled->SetValue(delayCfg.enabled); - m_varExpDelayShort->SetValue((int)delayCfg.shortDelay / 1000.); - m_varExpDelayLong->SetValue((int)delayCfg.longDelay / 1000.); + m_varExpDelayShort->SetValue((int) delayCfg.shortDelay / 1000.); + m_varExpDelayLong->SetValue((int) delayCfg.longDelay / 1000.); m_pTimeLapse->Enable(!delayCfg.enabled); m_varExpDelayShort->Enable(delayCfg.enabled); m_varExpDelayLong->Enable(delayCfg.enabled); @@ -3289,7 +3307,9 @@ void MyFrameConfigDialogCtrlSet::UnloadValues() { if (m_pResetConfiguration->GetValue()) { - int choice = wxMessageBox(_("This will reset all PHD2 configuration values and restart the program. Are you sure?"), _("Confirmation"), wxYES_NO); + int choice = + wxMessageBox(_("This will reset all PHD2 configuration values and restart the program. Are you sure?"), + _("Confirmation"), wxYES_NO); if (choice == wxYES) { @@ -3308,10 +3328,11 @@ void MyFrameConfigDialogCtrlSet::UnloadValues() m_pFrame->SetDitherRaOnly(m_ditherRaOnly->GetValue()); m_pFrame->SetDitherScaleFactor(m_ditherScaleFactor->GetValue()); m_pFrame->SetTimeLapse(m_pTimeLapse->GetValue()); - pFrame->SetVariableDelayConfig(m_varExposureDelayEnabled->GetValue(), m_varExpDelayShort->GetValue() * 1000, m_varExpDelayLong->GetValue() * 1000); + pFrame->SetVariableDelayConfig( + m_varExposureDelayEnabled->GetValue(), m_varExpDelayShort->GetValue() * 1000, m_varExpDelayLong->GetValue() * 1000); int oldFL = m_pFrame->GetFocalLength(); - int newFL = GetFocalLength(); // From UI control - if (oldFL != newFL) // Validator insures fl is generally reasonable and non-zero + int newFL = GetFocalLength(); // From UI control + if (oldFL != newFL) // Validator insures fl is generally reasonable and non-zero m_pFrame->pAdvancedDialog->FlagImageScaleChange(); m_pFrame->SetFocalLength(GetFocalLength()); @@ -3322,7 +3343,8 @@ void MyFrameConfigDialogCtrlSet::UnloadValues() { wxString title = TranslateStrToLang(wxTRANSLATE("Restart PHD2"), langid); wxString msg = TranslateStrToLang(wxTRANSLATE("You must restart PHD2 for the language change to take effect.\n" - "Would you like to restart PHD2 now?"), langid); + "Would you like to restart PHD2 now?"), + langid); int val = wxMessageBox(msg, title, wxYES_NO | wxCENTRE); if (val == wxYES) wxGetApp().RestartApp(); @@ -3382,7 +3404,7 @@ int MyFrameConfigDialogCtrlSet::GetFocalLength() const { long val = 0; m_pFocalLength->GetValue().ToLong(&val); - return (int)val; + return (int) val; } void MyFrameConfigDialogCtrlSet::SetFocalLength(int val) @@ -3421,8 +3443,8 @@ void MyFrameConfigDialogCtrlSet::OnVariableDelayChecked(wxCommandEvent& evt) void MyFrame::PlaceWindowOnScreen(wxWindow *win, int x, int y) { - if (x < 0 || x > wxSystemSettings::GetMetric(wxSYS_SCREEN_X) - 20 || - y < 0 || y > wxSystemSettings::GetMetric(wxSYS_SCREEN_Y) - 20) + if (x < 0 || x > wxSystemSettings::GetMetric(wxSYS_SCREEN_X) - 20 || y < 0 || + y > wxSystemSettings::GetMetric(wxSYS_SCREEN_Y) - 20) { win->Centre(wxBOTH); } @@ -3434,16 +3456,18 @@ inline static void AdjustSpinnerWidth(wxSize *sz) { #ifdef __APPLE__ // GetSizeFromTextSize() not working on OSX, so we need to add more padding - enum { SPINNER_WIDTH_PAD = 20 }; + enum + { + SPINNER_WIDTH_PAD = 20 + }; sz->SetWidth(sz->GetWidth() + SPINNER_WIDTH_PAD); #endif } // The spin control factories allow clients to specify a width based on the max width of the numeric values without having // to make guesses about the additional space required by the other parts of the control -wxSpinCtrl* MyFrame::MakeSpinCtrl(wxWindow *parent, wxWindowID id, const wxString& value, - const wxPoint& pos, const wxSize& size, long style, - int min, int max, int initial, const wxString& name) +wxSpinCtrl *MyFrame::MakeSpinCtrl(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, + const wxSize& size, long style, int min, int max, int initial, const wxString& name) { wxSpinCtrl *ctrl = new wxSpinCtrl(parent, id, value, pos, size, style, min, max, initial, name); wxSize initsize(ctrl->GetSizeFromTextSize(size)); @@ -3452,9 +3476,8 @@ wxSpinCtrl* MyFrame::MakeSpinCtrl(wxWindow *parent, wxWindowID id, const wxStrin return ctrl; } -wxSpinCtrlDouble* MyFrame::MakeSpinCtrlDouble(wxWindow *parent, wxWindowID id, const wxString& value, - const wxPoint& pos, const wxSize& size, long style, double min, double max, double initial, - double inc, const wxString& name) +wxSpinCtrlDouble *MyFrame::MakeSpinCtrlDouble(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, + const wxSize& size, long style, double min, double max, double initial, double inc, const wxString& name) { wxSpinCtrlDouble *ctrl = new wxSpinCtrlDouble(parent, id, value, pos, size, style, min, max, initial, inc, name); wxSize initsize(ctrl->GetSizeFromTextSize(size)); diff --git a/src/myframe.h b/src/myframe.h index 362f9702a..33afaa9ab 100644 --- a/src/myframe.h +++ b/src/myframe.h @@ -45,7 +45,7 @@ class PHDStatusBar; enum E_MYFRAME_WORKER_THREAD_MESSAGES { - MYFRAME_WORKER_THREAD_EXPOSE_COMPLETE = wxID_HIGHEST+1, + MYFRAME_WORKER_THREAD_EXPOSE_COMPLETE = wxID_HIGHEST + 1, MYFRAME_WORKER_THREAD_MOVE_COMPLETE, }; @@ -75,7 +75,7 @@ struct AutoExposureCfg struct VarDelayCfg { bool enabled; - int shortDelay; // times in milliseconds + int shortDelay; // times in milliseconds int longDelay; }; @@ -156,7 +156,7 @@ class MyFrameConfigDialogCtrlSet : public ConfigDialogCtrlSet void OnVariableDelayChecked(wxCommandEvent& evt); public: - MyFrameConfigDialogCtrlSet(MyFrame *pFrame, AdvancedDialog* pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + MyFrameConfigDialogCtrlSet(MyFrame *pFrame, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); virtual ~MyFrameConfigDialogCtrlSet() {}; virtual void LoadValues(); @@ -185,16 +185,15 @@ class MyFrame : public wxFrame friend class WorkerThread; private: - NOISE_REDUCTION_METHOD m_noiseReductionMethod; DitherMode m_ditherMode; double m_ditherScaleFactor; bool m_ditherRaOnly; DitherSpiral m_ditherSpiral; bool m_serverMode; - int m_timeLapse; // Delay between frames (useful for vid cameras) + int m_timeLapse; // Delay between frames (useful for vid cameras) VarDelayCfg m_varDelayConfig; - int m_focalLength; + int m_focalLength; bool m_beepForLostStar; double m_sampling; bool m_autoLoadCalibration; @@ -232,7 +231,7 @@ class MyFrame : public wxFrame wxMenuItem *m_upgradeMenuItem; wxAuiToolBar *MainToolbar; wxInfoBar *m_infoBar; - wxComboBox *Dur_Choice; + wxComboBox *Dur_Choice; wxCheckBox *HotPixel_Checkbox; wxHtmlHelpController *help; wxSlider *Gamma_Slider; @@ -317,12 +316,12 @@ class MyFrame : public wxFrame void OnCharHook(wxKeyEvent& evt); void OnTextControlSetFocus(wxFocusEvent& evt); void OnTextControlKillFocus(wxFocusEvent& evt); -#if defined (GUIDE_INDI) || defined (INDI_CAMERA) +#if defined(GUIDE_INDI) || defined(INDI_CAMERA) void OnINDIConfig(wxCommandEvent& evt); void OnINDIDialog(wxCommandEvent& evt); #endif void OnPanelClose(wxAuiManagerEvent& evt); -#if defined (V4L_CAMERA) +#if defined(V4L_CAMERA) void OnSaveSettings(wxCommandEvent& evt); void OnRestoreSettings(wxCommandEvent& evt); #endif @@ -384,7 +383,7 @@ class MyFrame : public wxFrame static void DeleteDarkLibraryFiles(int profileID); static wxString DarkLibFileName(int profileId); void SetDarkMenuState(); - bool LoadDarkHandler(bool checkIt); // Use to also set menu item states + bool LoadDarkHandler(bool checkIt); // Use to also set menu item states void LoadDefectMapHandler(bool checkIt); void CheckDarkFrameGeometry(); void UpdateStatusBarCalibrationStatus(); @@ -435,8 +434,10 @@ class MyFrame : public wxFrame double GetCameraPixelScale() const; void Alert(const wxString& msg, int flags = wxICON_EXCLAMATION); - void Alert(const wxString& msg, alert_fn *DontShowFn, const wxString& buttonLabel, alert_fn *SpecialFn, long arg, bool showHelpButton = false, int flags = wxICON_EXCLAMATION); - void SuppressableAlert(const wxString& configPropKey, const wxString& msg, alert_fn *dontShowFn, long arg, bool showHelpButton = false, int flags = wxICON_EXCLAMATION); + void Alert(const wxString& msg, alert_fn *DontShowFn, const wxString& buttonLabel, alert_fn *SpecialFn, long arg, + bool showHelpButton = false, int flags = wxICON_EXCLAMATION); + void SuppressableAlert(const wxString& configPropKey, const wxString& msg, alert_fn *dontShowFn, long arg, + bool showHelpButton = false, int flags = wxICON_EXCLAMATION); void ClearAlert(); void StatusMsg(const wxString& text); void StatusMsgNoTimeout(const wxString& text); @@ -467,12 +468,12 @@ class MyFrame : public wxFrame // Following 2 functions are used by clients that need to size the spin control based on the max text width wxSpinCtrl *MakeSpinCtrl(wxWindow *parent, wxWindowID id = -1, const wxString& value = wxEmptyString, - const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxSP_ARROW_KEYS, - int min = 0, int max = 100, int initial = 0, const wxString& name = wxT("wxSpinCtrl")); + const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxSP_ARROW_KEYS, int min = 0, + int max = 100, int initial = 0, const wxString& name = wxT("wxSpinCtrl")); wxSpinCtrlDouble *MakeSpinCtrlDouble(wxWindow *parent, wxWindowID id = wxID_ANY, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, - long style = wxSP_ARROW_KEYS | wxALIGN_RIGHT, double min = 0, double max = 100, double initial = 0, - double inc = 1, const wxString& name = wxT("wxSpinCtrlDouble")); + long style = wxSP_ARROW_KEYS | wxALIGN_RIGHT, double min = 0, double max = 100, double initial = 0, double inc = 1, + const wxString& name = wxT("wxSpinCtrlDouble")); private: wxCriticalSection m_CSpWorkerThread; @@ -491,8 +492,8 @@ class MyFrame : public wxFrame std::vector m_cameraReconnectAttempts; // for rate-limiting camera reconnect attempts - bool StartWorkerThread(WorkerThread*& pWorkerThread); - bool StopWorkerThread(WorkerThread*& pWorkerThread); + bool StartWorkerThread(WorkerThread *& pWorkerThread); + bool StopWorkerThread(WorkerThread *& pWorkerThread); void OnStatusMsg(wxThreadEvent& event); void DoAlert(const alert_params& params); void OnAlertButton(wxCommandEvent& evt); @@ -518,25 +519,26 @@ class MyFrame : public wxFrame extern MyFrame *pFrame; -enum { +enum +{ MENU_SHOWHELP = 101, BEGIN_SCOPES, - SCOPE_ASCOM, - SCOPE_CAMERA, - SCOPE_GPUSB, - SCOPE_GPINT3BC, - SCOPE_GPINT378, - SCOPE_GPINT278, - SCOPE_VOYAGER, - SCOPE_EQUINOX, - SCOPE_EQMAC, - SCOPE_GCUSBST4, - SCOPE_INDI, + SCOPE_ASCOM, + SCOPE_CAMERA, + SCOPE_GPUSB, + SCOPE_GPINT3BC, + SCOPE_GPINT378, + SCOPE_GPINT278, + SCOPE_VOYAGER, + SCOPE_EQUINOX, + SCOPE_EQMAC, + SCOPE_GCUSBST4, + SCOPE_INDI, END_SCOPES, BEGIN_STEPGUIDERS, - AO_NONE, - AO_SXAO, - AO_SIMULATOR, + AO_NONE, + AO_SXAO, + AO_SIMULATOR, END_STEPGUIDERS, BUTTON_GEAR, BUTTON_CAL, @@ -552,50 +554,50 @@ enum { BUTTON_ALERT_HELP, BUTTON_ALERT_DONTSHOW, GEAR_DIALOG_IDS_BEGIN, - GEAR_PROFILES, - GEAR_PROFILE_MANAGE, - GEAR_PROFILE_NEW, - GEAR_PROFILE_DELETE, - GEAR_PROFILE_RENAME, - GEAR_PROFILE_LOAD, - GEAR_PROFILE_SAVE, - GEAR_PROFILE_WIZARD, - - GEAR_CHOICE_CAMERA, - GEAR_BUTTON_SELECT_CAMERA, - MENU_SELECT_CAMERA_BEGIN, // a range of ids camera selection popup menu - MENU_SELECT_CAMERA_END = MENU_SELECT_CAMERA_BEGIN + 10, - GEAR_BUTTON_SETUP_CAMERA, - GEAR_BUTTON_CONNECT_CAMERA, - GEAR_BUTTON_DISCONNECT_CAMERA, - - GEAR_CHOICE_SCOPE, - GEAR_BUTTON_SETUP_SCOPE, - GEAR_BUTTON_CONNECT_SCOPE, - GEAR_BUTTON_DISCONNECT_SCOPE, - - GEAR_CHOICE_AUXSCOPE, - GEAR_BUTTON_SETUP_AUXSCOPE, - GEAR_BUTTON_CONNECT_AUXSCOPE, - GEAR_BUTTON_DISCONNECT_AUXSCOPE, - - GEAR_BUTTON_MORE, - - GEAR_CHOICE_STEPGUIDER, - GEAR_BUTTON_SETUP_STEPGUIDER, - GEAR_BUTTON_CONNECT_STEPGUIDER, - GEAR_BUTTON_DISCONNECT_STEPGUIDER, - - GEAR_CHOICE_ROTATOR, - GEAR_BUTTON_SETUP_ROTATOR, - GEAR_BUTTON_CONNECT_ROTATOR, - GEAR_BUTTON_DISCONNECT_ROTATOR, - - GEAR_BUTTON_CONNECT_ALL, - GEAR_BUTTON_DISCONNECT_ALL, + GEAR_PROFILES, + GEAR_PROFILE_MANAGE, + GEAR_PROFILE_NEW, + GEAR_PROFILE_DELETE, + GEAR_PROFILE_RENAME, + GEAR_PROFILE_LOAD, + GEAR_PROFILE_SAVE, + GEAR_PROFILE_WIZARD, + + GEAR_CHOICE_CAMERA, + GEAR_BUTTON_SELECT_CAMERA, + MENU_SELECT_CAMERA_BEGIN, // a range of ids camera selection popup menu + MENU_SELECT_CAMERA_END = MENU_SELECT_CAMERA_BEGIN + 10, + GEAR_BUTTON_SETUP_CAMERA, + GEAR_BUTTON_CONNECT_CAMERA, + GEAR_BUTTON_DISCONNECT_CAMERA, + + GEAR_CHOICE_SCOPE, + GEAR_BUTTON_SETUP_SCOPE, + GEAR_BUTTON_CONNECT_SCOPE, + GEAR_BUTTON_DISCONNECT_SCOPE, + + GEAR_CHOICE_AUXSCOPE, + GEAR_BUTTON_SETUP_AUXSCOPE, + GEAR_BUTTON_CONNECT_AUXSCOPE, + GEAR_BUTTON_DISCONNECT_AUXSCOPE, + + GEAR_BUTTON_MORE, + + GEAR_CHOICE_STEPGUIDER, + GEAR_BUTTON_SETUP_STEPGUIDER, + GEAR_BUTTON_CONNECT_STEPGUIDER, + GEAR_BUTTON_DISCONNECT_STEPGUIDER, + + GEAR_CHOICE_ROTATOR, + GEAR_BUTTON_SETUP_ROTATOR, + GEAR_BUTTON_CONNECT_ROTATOR, + GEAR_BUTTON_DISCONNECT_ROTATOR, + + GEAR_BUTTON_CONNECT_ALL, + GEAR_BUTTON_DISCONNECT_ALL, GEAR_DIALOG_IDS_END, CTRL_GAMMA, - WIN_VFW, // Dummy event to capture VFW streams + WIN_VFW, // Dummy event to capture VFW streams MGUIDE1_UP, MGUIDE1_DOWN, MGUIDE1_RIGHT, @@ -646,15 +648,15 @@ enum { BUTTON_GRAPH_LENGTH, BUTTON_GRAPH_HEIGHT, BUTTON_GRAPH_SETTINGS, - GRAPH_RADEC, - GRAPH_DXDY, - GRAPH_ARCSECS, - GRAPH_PIXELS, - GRAPH_STAR_MASS, - GRAPH_STAR_SNR, - GRAPH_RADX_COLOR, - GRAPH_DECDY_COLOR, - GRAPH_SCALE_CORR, + GRAPH_RADEC, + GRAPH_DXDY, + GRAPH_ARCSECS, + GRAPH_PIXELS, + GRAPH_STAR_MASS, + GRAPH_STAR_SNR, + GRAPH_RADX_COLOR, + GRAPH_DECDY_COLOR, + GRAPH_SCALE_CORR, BUTTON_GRAPH_CLEAR, TARGET_ENABLE_REF_CIRCLE, TARGET_REF_CIRCLE_RADIUS, @@ -693,7 +695,8 @@ enum { GA_REVIEW_ITEMS_LIMIT = GA_REVIEW_ITEMS_BASE + 4, }; -enum { +enum +{ SOCK_SERVER_ID = 100, SOCK_SERVER_CLIENT_ID, EVENT_SERVER_ID, diff --git a/src/myframe_events.cpp b/src/myframe_events.cpp index 342320348..c1775cb99 100644 --- a/src/myframe_events.cpp +++ b/src/myframe_events.cpp @@ -84,7 +84,7 @@ void MyFrame::OnExposureDurationSelected(wxCommandEvent& evt) double val; if (dlg.GetValue().ToDouble(&val) && val > 0.0 && val < 3600.) { - int ms = (int)(val * 1000.0); + int ms = (int) (val * 1000.0); SetCustomExposureDuration(ms); } } @@ -186,8 +186,8 @@ PHD2 will then calibrate itself and begin guiding. That's it!\n\n \ To stop guiding, simply press the 'Loop' or 'Stop' buttons. If you need to \n \ tweak any options, click on the 'Brain' button to bring up the 'Advanced' \n \ panel. Use the 'View' menu to watch your guiding performance. If you have\n \ -problems, read the 'Best Practices' document and the help files! ")),_("Instructions")); - +problems, read the 'Best Practices' document and the help files! ")), + _("Instructions")); } void MyFrame::OnHelp(wxCommandEvent& WXUNUSED(event)) @@ -244,7 +244,8 @@ struct SlitPropertiesDlg : public wxDialog const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(390, 181), long style = wxDEFAULT_DIALOG_STYLE); }; -SlitPropertiesDlg::SlitPropertiesDlg(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) +SlitPropertiesDlg::SlitPropertiesDlg( + wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) { wxSize textSz = pFrame->GetTextExtent("888888"); @@ -261,7 +262,7 @@ SlitPropertiesDlg::SlitPropertiesDlg(wxWindow *parent, wxWindowID id, const wxSt szPosition->Add(hXSizer, 0, wxEXPAND, 5); wxBoxSizer *hYSizer = new wxBoxSizer(wxHORIZONTAL); - wxStaticText* yLabel = new wxStaticText(this, wxID_ANY, _("Y"), wxDefaultPosition, wxDefaultSize, 0); + wxStaticText *yLabel = new wxStaticText(this, wxID_ANY, _("Y"), wxDefaultPosition, wxDefaultSize, 0); hYSizer->Add(yLabel, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_y = pFrame->MakeSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, textSz, wxSP_ARROW_KEYS, 0, 8000, 0); hYSizer->Add(m_y, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); @@ -292,9 +293,9 @@ SlitPropertiesDlg::SlitPropertiesDlg(wxWindow *parent, wxWindowID id, const wxSt vSizer->Add(hSizer, 0, wxEXPAND, 5); // Angle controls - wxBoxSizer* hAngleSizer = new wxBoxSizer(wxHORIZONTAL); - wxStaticText* staticText1 = new wxStaticText(this, wxID_ANY, _("Angle (degrees)"), wxDefaultPosition, wxDefaultSize, 0); - //staticText1->Wrap(-1); + wxBoxSizer *hAngleSizer = new wxBoxSizer(wxHORIZONTAL); + wxStaticText *staticText1 = new wxStaticText(this, wxID_ANY, _("Angle (degrees)"), wxDefaultPosition, wxDefaultSize, 0); + // staticText1->Wrap(-1); hAngleSizer->Add(staticText1, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_angle = pFrame->MakeSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, textSz, wxSP_ARROW_KEYS, -90, 90, 0); hAngleSizer->Add(m_angle, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); @@ -302,9 +303,7 @@ SlitPropertiesDlg::SlitPropertiesDlg(wxWindow *parent, wxWindowID id, const wxSt vSizer->Add(hAngleSizer, 0, wxEXPAND, 5); // ok/cancel buttons - vSizer->Add( - CreateButtonSizer(wxOK | wxCANCEL), - wxSizerFlags(0).Expand().Border(wxALL, 10)); + vSizer->Add(CreateButtonSizer(wxOK | wxCANCEL), wxSizerFlags(0).Expand().Border(wxALL, 10)); SetSizerAndFit(vSizer); } @@ -313,7 +312,11 @@ struct SlitPosCtx : public wxObject { SlitPropertiesDlg *dlg; Guider *guider; - SlitPosCtx(SlitPropertiesDlg *d, Guider *g) : dlg(d), guider(g) { } + SlitPosCtx(SlitPropertiesDlg *d, Guider *g) + : dlg(d) + , guider(g) + { + } }; static void UpdateSlitPos(wxSpinEvent& event) @@ -354,13 +357,11 @@ void MyFrame::OnSave(wxCommandEvent& WXUNUSED(event)) if (!pGuider->CurrentImage()->ImageData) return; - wxString fname = wxFileSelector( _("Save FITS Image"), (const wxChar *)NULL, - (const wxChar *)NULL, - wxT("fit"), wxT("FITS files (*.fit)|*.fit"),wxFD_SAVE | wxFD_OVERWRITE_PROMPT, - this); + wxString fname = wxFileSelector(_("Save FITS Image"), (const wxChar *) NULL, (const wxChar *) NULL, wxT("fit"), + wxT("FITS files (*.fit)|*.fit"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT, this); if (fname.IsEmpty()) - return; // Check for canceled dialog + return; // Check for canceled dialog if (pGuider->SaveCurrentImage(fname)) { @@ -372,9 +373,7 @@ void MyFrame::OnSave(wxCommandEvent& WXUNUSED(event)) } } -void MyFrame::OnIdle(wxIdleEvent& WXUNUSED(event)) -{ -} +void MyFrame::OnIdle(wxIdleEvent& WXUNUSED(event)) { } void MyFrame::StartLoopingInteractive(const wxString& context) { @@ -429,7 +428,9 @@ static void WarnRawImageMode(void) { if (pCamera->FullSize != pCamera->DarkFrameSize()) { - pFrame->SuppressableAlert(RawModeWarningKey(), _("For refining the Bad-pixel Map PHD2 is now displaying raw camera data frames, which are a different size from ordinary guide frames for this camera."), + pFrame->SuppressableAlert(RawModeWarningKey(), + _("For refining the Bad-pixel Map PHD2 is now displaying raw camera data frames, which are a different size from " + "ordinary guide frames for this camera."), SuppressRawModeWarning, 0); } } @@ -508,8 +509,8 @@ void MyFrame::OnExposeComplete(usImage *pNewFrame, bool err) PhdController::UpdateControllerState(); - Debug.Write(wxString::Format("OnExposeComplete: CaptureActive=%d m_continueCapturing=%d\n", - CaptureActive, m_continueCapturing)); + Debug.Write(wxString::Format( + "OnExposeComplete: CaptureActive=%d m_continueCapturing=%d\n", CaptureActive, m_continueCapturing)); CaptureActive = m_continueCapturing; @@ -559,8 +560,7 @@ void MyFrame::OnMoveComplete(wxThreadEvent& event_) // deliver the outstanding GuidingStopped notification if this is a late-arriving // move completion event - if (!pGuider->IsCalibratingOrGuiding() && - (!pMount || !pMount->IsBusy()) && + if (!pGuider->IsCalibratingOrGuiding() && (!pMount || !pMount->IsBusy()) && (!pSecondaryMount || !pSecondaryMount->IsBusy())) { pFrame->NotifyGuidingStopped(); @@ -583,8 +583,8 @@ void MyFrame::OnMoveComplete(wxThreadEvent& event_) if (pGuider->IsCalibrating()) { pFrame->Alert(wxString::Format(_("The AO exceeded its travel limit stepping" - " from (%d, %d) to (%d, %d) and calibration cannot proceed. Try reducing" - " the AO Travel setting to %d or lower and try again."), + " from (%d, %d) to (%d, %d) and calibration cannot proceed. Try reducing" + " the AO Travel setting to %d or lower and try again."), step.x, step.y, step.x + step.dx, step.y + step.dy, newval)); pGuider->StopGuiding(); @@ -592,8 +592,8 @@ void MyFrame::OnMoveComplete(wxThreadEvent& event_) else // Guiding { pFrame->Alert(wxString::Format(_("The AO exceeded its travel limit stepping" - " from (%d, %d) to (%d, %d) and has been re-centered. Try reducing the AO" - " Travel setting to %d or lower."), + " from (%d, %d) to (%d, %d) and has been re-centered. Try reducing the AO" + " Travel setting to %d or lower."), step.x, step.y, step.x + step.dx, step.y + step.dy, newval)); // Attempt to restart guiding after centering, otherwise the AO will @@ -648,7 +648,7 @@ void MyFrame::OnDark(wxCommandEvent& WXUNUSED(event)) DarksDialog dlg(this, true); dlg.ShowModal(); - pCamera->SelectDark(RequestedExposureDuration()); // Might be req'd if user cancelled in midstream + pCamera->SelectDark(RequestedExposureDuration()); // Might be req'd if user cancelled in midstream } // Outside event handler because loading a dark library will automatically unload a defect map @@ -661,7 +661,7 @@ bool MyFrame::LoadDarkHandler(bool checkIt) return false; } pConfig->Profile.SetBoolean("/camera/AutoLoadDarks", checkIt); - if (checkIt) // enable it + if (checkIt) // enable it { m_useDarksMenuItem->Check(true); if (pCamera->CurrentDefectMap) @@ -678,7 +678,7 @@ bool MyFrame::LoadDarkHandler(bool checkIt) { if (!pCamera->CurrentDarkFrame) { - m_useDarksMenuItem->Check(false); // shouldn't have gotten here + m_useDarksMenuItem->Check(false); // shouldn't have gotten here return false; } pCamera->ClearDarks(); @@ -725,7 +725,7 @@ void MyFrame::LoadDefectMapHandler(bool checkIt) { if (!pCamera->CurrentDefectMap) { - m_useDefectMapMenuItem->Check(false); // Shouldn't have gotten here + m_useDefectMapMenuItem->Check(false); // Shouldn't have gotten here return; } pCamera->ClearDefectMap(); @@ -751,17 +751,17 @@ void MyFrame::OnRefineDefMap(wxCommandEvent& evt) if (!pRefineDefMap) pRefineDefMap = new RefineDefMap(this); - if (pRefineDefMap->InitUI()) // Required data present, UI built and ready to go + if (pRefineDefMap->InitUI()) // Required data present, UI built and ready to go { pRefineDefMap->Show(); // Don't let the user build a new defect map while we're trying to refine one; and it almost certainly makes sense // to have a defect map loaded if the user wants to refine it - m_takeDarksMenuItem->Enable(false); // Dialog restores it when its window is closed + m_takeDarksMenuItem->Enable(false); // Dialog restores it when its window is closed LoadDefectMapHandler(true); } else - pRefineDefMap->Destroy(); // user cancelled out before starting the process + pRefineDefMap->Destroy(); // user cancelled out before starting the process } void MyFrame::OnImportCamCal(wxCommandEvent& evt) @@ -781,8 +781,8 @@ void MyFrame::OnToolBar(wxCommandEvent& evt) { if (evt.IsChecked()) { - //wxSize toolBarSize = MainToolbar->GetSize(); - m_mgr.GetPane(_T("MainToolBar")).Show().Bottom()/*.MinSize(toolBarSize)*/; + // wxSize toolBarSize = MainToolbar->GetSize(); + m_mgr.GetPane(_T("MainToolBar")).Show().Bottom() /*.MinSize(toolBarSize)*/; } else { @@ -823,7 +823,7 @@ void MyFrame::OnAoGraph(wxCommandEvent& evt) { if (pStepGuiderGraph->SetState(evt.IsChecked())) { - m_mgr.GetPane(_T("AOPosition")).Show().Right().Position(1).MinSize(293,208); + m_mgr.GetPane(_T("AOPosition")).Show().Right().Position(1).MinSize(293, 208); } else { @@ -836,11 +836,11 @@ void MyFrame::OnStarProfile(wxCommandEvent& evt) { if (evt.IsChecked()) { -#if defined (__APPLE__) - m_mgr.GetPane(_T("Profile")).Show().Float().MinSize(110,72); +#if defined(__APPLE__) + m_mgr.GetPane(_T("Profile")).Show().Float().MinSize(110, 72); #else - m_mgr.GetPane(_T("Profile")).Show().Right().Position(0).MinSize(115,85); - //m_mgr.GetPane(_T("Profile")).Show().Bottom().Layer(1).Position(2).MinSize(115,85); + m_mgr.GetPane(_T("Profile")).Show().Right().Position(0).MinSize(115, 85); + // m_mgr.GetPane(_T("Profile")).Show().Bottom().Layer(1).Position(2).MinSize(115,85); #endif } else @@ -855,7 +855,7 @@ void MyFrame::OnTarget(wxCommandEvent& evt) { if (evt.IsChecked()) { - m_mgr.GetPane(_T("Target")).Show().Right().Position(2).MinSize(293,208); + m_mgr.GetPane(_T("Target")).Show().Right().Position(2).MinSize(293, 208); } else { @@ -872,12 +872,12 @@ void MyFrame::OnRestoreWindows(wxCommandEvent& evt) // Start by restoring the main window although it doesn't seem like this could be much of a problem pFrame->SetSize(wxSize(800, 600)); - pFrame->SetPosition(wxPoint(20, 20)); // Should work on any screen size + pFrame->SetPosition(wxPoint(20, 20)); // Should work on any screen size // Now re-dock all the windows that are being managed by wxAuiManager int lim = panes.GetCount(); for (int i = 0; i < lim; i++) { - panes.Item(i).Dock(); // Already docked, shown or not, doesn't matter + panes.Item(i).Dock(); // Already docked, shown or not, doesn't matter if (panes.Item(i).name == _("Guider")) panes.Item(i).Show(true); } @@ -922,7 +922,7 @@ void MyFrame::OnSetupCamera(wxCommandEvent& WXUNUSED(event)) { if (pCamera && (((pCamera->PropertyDialogType & PROPDLG_WHEN_CONNECTED) != 0 && pCamera->Connected) || - ((pCamera->PropertyDialogType & PROPDLG_WHEN_DISCONNECTED) != 0 && !pCamera->Connected))) + ((pCamera->PropertyDialogType & PROPDLG_WHEN_DISCONNECTED) != 0 && !pCamera->Connected))) { pCamera->ShowPropertyDialog(); } @@ -950,7 +950,8 @@ void MyFrame::OnAdvanced(wxCommandEvent& WXUNUSED(event)) static wxString DarksWarningEnabledKey() { - // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting to be per-profile + // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting + // to be per-profile return wxString::Format("/Confirm/%d/DarksWarningEnabled", pConfig->GetCurrentProfileId()); } @@ -965,8 +966,9 @@ static void ValidateDarksLoaded(void) { pFrame->SuppressableAlert(DarksWarningEnabledKey(), _("For best results, use a Dark Library or a Bad-pixel Map " - "while guiding. This will help prevent PHD from locking on to a hot pixel. " - "Use the Darks menu to build a Dark Library or Bad-pixel Map."), SuppressDarksAlert, 0); + "while guiding. This will help prevent PHD from locking on to a hot pixel. " + "Use the Darks menu to build a Dark Library or Bad-pixel Map."), + SuppressDarksAlert, 0); } } @@ -980,17 +982,16 @@ static bool UseCalibrationAssistant() { double ha = norm(lst - ra, -12.0, 12.0); if ((fabs(dec) > 20 && dec < degrees(Scope::DEC_COMP_LIMIT)) || fabs(ha) > 3) - dontUse = ConfirmDialog::Confirm( - _("Scope isn't pointing in recommended sky area for calibration - run the Calibration Assistant to improve results."), - "/v2_highdec_calibration_ok", _("Calibrate here"), _("Calibration Assistant...") - ); + dontUse = ConfirmDialog::Confirm(_("Scope isn't pointing in recommended sky area for calibration - run the " + "Calibration Assistant to improve results."), + "/v2_highdec_calibration_ok", _("Calibrate here"), _("Calibration Assistant...")); else if (fabs(dec) > degrees(Scope::DEC_COMP_LIMIT)) dontUse = ConfirmDialog::Confirm( - _("With the scope pointing this close to the pole, calibration can be degraded and may ") + "\n" + - _("fail altogether. Run the Calibration Assistant and follow the instructions to eliminate these risks, ") + "\n" + - _("including slewing the scope as close as practical to the recommended position."), - "/v2_very_highdec_calibration_ok", _("Calibrate here"), _("Calibration Assistant...") - ); + _("With the scope pointing this close to the pole, calibration can be degraded and may ") + "\n" + + _("fail altogether. Run the Calibration Assistant and follow the instructions to eliminate these " + "risks, ") + + "\n" + _("including slewing the scope as close as practical to the recommended position."), + "/v2_very_highdec_calibration_ok", _("Calibrate here"), _("Calibration Assistant...")); } else { @@ -1037,8 +1038,8 @@ void MyFrame::GuideButtonClick(bool interactive, const wxString& context) bool recalibrate = true; if (pMount->IsCalibrated() || (pSecondaryMount && pSecondaryMount->IsCalibrated())) { - recalibrate = ConfirmDialog::Confirm(_("Are you sure you want to force recalibration?"), - "/force_recalibration_ok", _("Force Recalibration")); + recalibrate = ConfirmDialog::Confirm( + _("Are you sure you want to force recalibration?"), "/force_recalibration_ok", _("Force Recalibration")); } if (recalibrate) { @@ -1050,13 +1051,13 @@ void MyFrame::GuideButtonClick(bool interactive, const wxString& context) return; } - if (interactive && pPointingSource && pPointingSource->IsConnected() && - pPointingSource->CanReportPosition()) + if (interactive && pPointingSource && pPointingSource->IsConnected() && pPointingSource->CanReportPosition()) { - // If it's being used, the ask-for-coordinates dialog will populate scope position info needed for UseCalibrationAssistant() and StartGuiding() - if (pPointingSource->PreparePositionInteractive()) // Returns true only if user cancels ask-for-coordinates dialog + // If it's being used, the ask-for-coordinates dialog will populate scope position info needed for + // UseCalibrationAssistant() and StartGuiding() + if (pPointingSource->PreparePositionInteractive()) // Returns true only if user cancels ask-for-coordinates dialog return; - if (!TheScope()->IsCalibrated()) // Either cleared above or not calibrated for other reasons + if (!TheScope()->IsCalibrated()) // Either cleared above or not calibrated for other reasons { if (UseCalibrationAssistant()) { @@ -1186,10 +1187,9 @@ static void CheckDecGuideModeAlert() wxString msg = _("With your current setting for Dec guide mode, this version of PHD2 will " "dither in Declination. To restore the old behavior you can set the RA-only " "option in the Dither Settings of the Advanced Dialog."); - pFrame->Alert(msg, 0, - _("Set RA-only now"), AlertSetRAOnly, 0); + pFrame->Alert(msg, 0, _("Set RA-only now"), AlertSetRAOnly, 0); - pConfig->Profile.SetBoolean("/ShowDecModeWarning", false); + pConfig->Profile.SetBoolean("/ShowDecModeWarning", false); } } } @@ -1207,10 +1207,10 @@ void MyFrame::OnSelectGear(wxCommandEvent& evt) if (pConfig->NumProfiles() == 1 && pGearDialog->IsEmptyProfile()) { if (ConfirmDialog::Confirm( - _("It looks like this is a first-time connection to your camera and mount. The Setup Wizard can help\n" - "you with that and will also establish baseline guiding parameters for your new configuration.\n" - "Would you like to use the Setup Wizard now?"), - "/use_new_profile_wizard", _("Yes"), _("No"), _("Setup Wizard Recommendation"))) + _("It looks like this is a first-time connection to your camera and mount. The Setup Wizard can help\n" + "you with that and will also establish baseline guiding parameters for your new configuration.\n" + "Would you like to use the Setup Wizard now?"), + "/use_new_profile_wizard", _("Yes"), _("No"), _("Setup Wizard Recommendation"))) { pGearDialog->ShowProfileWizard(evt); return; diff --git a/src/nudge_lock.cpp b/src/nudge_lock.cpp index f52f008ca..b04397e3e 100644 --- a/src/nudge_lock.cpp +++ b/src/nudge_lock.cpp @@ -103,7 +103,15 @@ wxBEGIN_EVENT_TABLE(NudgeLockDialog, wxDialog) wxEND_EVENT_TABLE(); // clang-format on -static double NudgeIncrements[] = { 0.01, 0.03, 0.1, 0.3, 1, 3, 10, }; +static double NudgeIncrements[] = { + 0.01, + 0.03, + 0.1, + 0.3, + 1, + 3, + 10, +}; static int IncrIdx(double incr) { @@ -116,7 +124,7 @@ static int IncrIdx(double incr) } NudgeLockDialog::NudgeLockDialog() - : wxDialog(pFrame, wxID_ANY, _("Adjust Lock Position"), wxPoint(-1,-1), wxSize(300,300)) + : wxDialog(pFrame, wxID_ANY, _("Adjust Lock Position"), wxPoint(-1, -1), wxSize(300, 300)) { stayOnTop = new wxCheckBox(this, ID_STAY_ON_TOP, _("Always on top")); stayOnTop->SetToolTip(_("Keep this window on top of all others")); @@ -129,15 +137,15 @@ NudgeLockDialog::NudgeLockDialog() wxGridSizer *sz1 = new wxGridSizer(3, 3, 0, 0); sz1->AddStretchSpacer(); - sz1->Add(upButton, wxSizerFlags().Expand().Border(wxALL,1)); + sz1->Add(upButton, wxSizerFlags().Expand().Border(wxALL, 1)); sz1->AddStretchSpacer(); - sz1->Add(leftButton, wxSizerFlags().Expand().Border(wxALL,1)); + sz1->Add(leftButton, wxSizerFlags().Expand().Border(wxALL, 1)); sz1->AddStretchSpacer(); - sz1->Add(rightButton, wxSizerFlags().Expand().Border(wxALL,1)); + sz1->Add(rightButton, wxSizerFlags().Expand().Border(wxALL, 1)); sz1->AddStretchSpacer(); - sz1->Add(downButton, wxSizerFlags().Expand().Border(wxALL,1)); + sz1->Add(downButton, wxSizerFlags().Expand().Border(wxALL, 1)); wxBoxSizer *sz0 = new wxBoxSizer(wxHORIZONTAL); sz0->AddStretchSpacer(); @@ -146,11 +154,13 @@ NudgeLockDialog::NudgeLockDialog() wxSizer *sz2 = new wxBoxSizer(wxHORIZONTAL); - sz2->Add(new wxStaticText(this, wxID_ANY, _("Step")), wxSizerFlags().Right().Border(wxALL, 5).Align(wxALIGN_CENTER_VERTICAL)); + sz2->Add( + new wxStaticText(this, wxID_ANY, _("Step")), wxSizerFlags().Right().Border(wxALL, 5).Align(wxALIGN_CENTER_VERTICAL)); double incr = pConfig->Global.GetDouble("/NudgeLock/Amount", NudgeIncrements[2]); int idx = IncrIdx(incr); - nudgeAmountSlider = new wxSlider(this, ID_NUDGE_AMOUNT, idx, 0, WXSIZEOF(NudgeIncrements) - 1, wxDefaultPosition, wxSize(100, -1)); + nudgeAmountSlider = + new wxSlider(this, ID_NUDGE_AMOUNT, idx, 0, WXSIZEOF(NudgeIncrements) - 1, wxDefaultPosition, wxSize(100, -1)); nudgeAmountSlider->SetToolTip(_("Adjust how far the lock position moves when you click the Up/Down/Left/Right buttons")); sz2->Add(nudgeAmountSlider, wxSizerFlags().Expand().Border(wxALL, 0)); @@ -158,22 +168,26 @@ NudgeLockDialog::NudgeLockDialog() sz2->Add(nudgeAmountText, wxSizerFlags().Border(wxLEFT, 5).Align(wxALIGN_CENTER_VERTICAL)); stickyLockPos = new wxCheckBox(this, ID_STICKY, _("Sticky Lock Position")); - stickyLockPos->SetToolTip(_("Sticky lock position will not follow the star when guiding is stopped and restarted, or after calibration completes")); + stickyLockPos->SetToolTip(_( + "Sticky lock position will not follow the star when guiding is stopped and restarted, or after calibration completes")); sz2->Add(0, 0, 1, wxEXPAND, 5); sz2->Add(stickyLockPos, wxSizerFlags().Border(wxALL, 5).Align(wxALIGN_CENTER_VERTICAL)); wxSizer *sz3 = new wxBoxSizer(wxHORIZONTAL); - sz3->Add(new wxStaticText(this, wxID_ANY, _("Lock Pos:")), wxSizerFlags().Right().Border(wxALL, 5).Align(wxALIGN_CENTER_VERTICAL)); + sz3->Add(new wxStaticText(this, wxID_ANY, _("Lock Pos:")), + wxSizerFlags().Right().Border(wxALL, 5).Align(wxALIGN_CENTER_VERTICAL)); wxFloatingPointValidator valX(2, &lockPosX, wxNUM_VAL_ZERO_AS_BLANK); valX.SetMin(0.0); - lockPosCtrlX = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, StringSize(this, _T("12345.67"), 10), 0, valX); + lockPosCtrlX = + new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, StringSize(this, _T("12345.67"), 10), 0, valX); lockPosCtrlX->SetToolTip(_("Lock position X coordinate")); sz3->Add(lockPosCtrlX, wxSizerFlags().Border(wxALL, 0).Align(wxALIGN_CENTER_VERTICAL)); wxFloatingPointValidator valY(2, &lockPosY, wxNUM_VAL_ZERO_AS_BLANK); valY.SetMin(0.0); - lockPosCtrlY = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, StringSize(this, _T("12345.67"), 10), 0, valY); + lockPosCtrlY = + new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, StringSize(this, _T("12345.67"), 10), 0, valY); lockPosCtrlY->SetToolTip(_("Lock position Y coordinate")); sz3->Add(lockPosCtrlY, wxSizerFlags().Border(wxLEFT, 5).Align(wxALIGN_CENTER_VERTICAL)); @@ -197,9 +211,9 @@ NudgeLockDialog::NudgeLockDialog() wxBoxSizer *outerSizer = new wxBoxSizer(wxVERTICAL); outerSizer->Add(stayOnTop, wxSizerFlags().Border(wxALL, 5)); outerSizer->AddSpacer(5); - outerSizer->Add(sz0, wxSizerFlags().Border(wxALL,3).Expand()); - outerSizer->Add(sz2, wxSizerFlags().Border(wxALL,3).Expand()); - outerSizer->Add(sz3, wxSizerFlags().Border(wxALL,3)); + outerSizer->Add(sz0, wxSizerFlags().Border(wxALL, 3).Expand()); + outerSizer->Add(sz2, wxSizerFlags().Border(wxALL, 3).Expand()); + outerSizer->Add(sz3, wxSizerFlags().Border(wxALL, 3)); UpdateSliderLabel(); UpdateLockPosCtrls(); @@ -276,7 +290,7 @@ void NudgeLockDialog::OnStayOnTopClicked(wxCommandEvent& evt) SetWindowStyle(style & ~wxSTAY_ON_TOP); } -void NudgeLockDialog::OnButton(wxCommandEvent &evt) +void NudgeLockDialog::OnButton(wxCommandEvent& evt) { if (!lockPosIsValid) return; @@ -286,18 +300,18 @@ void NudgeLockDialog::OnButton(wxCommandEvent &evt) switch (evt.GetId()) { - case ID_UP_BTN: - DoMove(0.0, -incr); - break; - case ID_DOWN_BTN: - DoMove(0.0, +incr); - break; - case ID_RIGHT_BTN: - DoMove(+incr, 0.0); - break; - case ID_LEFT_BTN: - DoMove(-incr, 0.0); - break; + case ID_UP_BTN: + DoMove(0.0, -incr); + break; + case ID_DOWN_BTN: + DoMove(0.0, +incr); + break; + case ID_RIGHT_BTN: + DoMove(+incr, 0.0); + break; + case ID_LEFT_BTN: + DoMove(-incr, 0.0); + break; } } @@ -346,7 +360,7 @@ void NudgeLockDialog::OnRestoreLockPosClicked(wxCommandEvent& evt) return; if (ConfirmDialog::Confirm(wxString::Format(_("Set lock position to saved value (%.2f,%.2f)?"), x, y), - "/RestoreSavedLockPosOK", _("Restore saved Lock Pos"))) + "/RestoreSavedLockPosOK", _("Restore saved Lock Pos"))) { UpdateLockPos(PHD_Point(x, y)); } diff --git a/src/onboard_st4.h b/src/onboard_st4.h index 7613f815b..a1c3ad8d5 100644 --- a/src/onboard_st4.h +++ b/src/onboard_st4.h @@ -39,11 +39,11 @@ class OnboardST4 { public: - virtual bool ST4HasGuideOutput(); - virtual bool ST4HostConnected(); - virtual bool ST4HasNonGuiMove(); - virtual bool ST4SynchronousOnly(); - virtual bool ST4PulseGuideScope(int direction, int duration); + virtual bool ST4HasGuideOutput(); + virtual bool ST4HostConnected(); + virtual bool ST4HasNonGuiMove(); + virtual bool ST4SynchronousOnly(); + virtual bool ST4PulseGuideScope(int direction, int duration); }; -#endif //ONBOARD_ST4_H_INCLUDED +#endif // ONBOARD_ST4_H_INCLUDED diff --git a/src/optionsbutton.cpp b/src/optionsbutton.cpp index 9e6891039..5584487ca 100644 --- a/src/optionsbutton.cpp +++ b/src/optionsbutton.cpp @@ -54,12 +54,11 @@ enum PADY = 5, }; -OptionsButton::OptionsButton(wxWindow *parent, wxWindowID id, const wxString& label, - const wxPoint& pos, const wxSize& size, long style, const wxString& name) - : - wxPanel(parent, id, pos, size, style, name), - m_highlighted(false), - m_label(label) +OptionsButton::OptionsButton(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos, const wxSize& size, + long style, const wxString& name) + : wxPanel(parent, id, pos, size, style, name) + , m_highlighted(false) + , m_label(label) { m_bmp = new wxBitmap(down_arrow); m_bmp_bold = new wxBitmap(down_arrow_bold); @@ -76,8 +75,7 @@ OptionsButton::~OptionsButton() wxSize OptionsButton::GetMinSize() const { wxSize txtsz = GetTextExtent(m_label); - return wxSize(PADX + txtsz.x + PADX + m_bmp->GetWidth() + PADX, - PADY + txtsz.y + PADY); + return wxSize(PADX + txtsz.x + PADX + m_bmp->GetWidth() + PADX, PADY + txtsz.y + PADY); } void OptionsButton::SetLabel(const wxString& label) @@ -86,7 +84,7 @@ void OptionsButton::SetLabel(const wxString& label) Refresh(); } -void OptionsButton::OnPaint(wxPaintEvent & evt) +void OptionsButton::OnPaint(wxPaintEvent& evt) { wxBufferedPaintDC dc(this); @@ -152,7 +150,7 @@ void OptionsButton::OnMouseLeave(wxMouseEvent& event) void OptionsButton::OnClick(wxMouseEvent& event) { wxCommandEvent cmd(wxEVT_COMMAND_BUTTON_CLICKED, GetId()); -#ifdef __WXGTK__ // Process the event as in wxgtk_button_clicked_callback() +#ifdef __WXGTK__ // Process the event as in wxgtk_button_clicked_callback() HandleWindowEvent(cmd); #else ::wxPostEvent(GetParent(), cmd); diff --git a/src/optionsbutton.h b/src/optionsbutton.h index e4c36b058..1504adfd8 100644 --- a/src/optionsbutton.h +++ b/src/optionsbutton.h @@ -43,16 +43,13 @@ class OptionsButton : public wxPanel wxBitmap *m_bmp_bold; public: - - OptionsButton(wxWindow *parent, wxWindowID id, const wxString& label, - const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, - long style = wxTAB_TRAVERSAL, const wxString& name = "OptionsButton"); + OptionsButton(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL, const wxString& name = "OptionsButton"); ~OptionsButton(); void SetLabel(const wxString& label); private: - wxSize GetMinSize() const; void OnPaint(wxPaintEvent& evt); diff --git a/src/parallelport.cpp b/src/parallelport.cpp index 0963296b5..62d263ea8 100644 --- a/src/parallelport.cpp +++ b/src/parallelport.cpp @@ -35,13 +35,9 @@ #include "phd.h" -ParallelPort::ParallelPort(void) -{ -} +ParallelPort::ParallelPort(void) { } -ParallelPort::~ParallelPort(void) -{ -} +ParallelPort::~ParallelPort(void) { } bool ParallelPort::ManipulateByte(BYTE clearBits, BYTE setBits) { @@ -62,7 +58,7 @@ bool ParallelPort::ManipulateByte(BYTE clearBits, BYTE setBits) data |= setBits; Debug.Write(wxString::Format("ParallelPort::ManipulateByte: orig=0x%x clearBits=0x%x setBits=0x%x data=0x%x\n", - origData, clearBits, setBits, data)); + origData, clearBits, setBits, data)); if (WriteByte(data)) { diff --git a/src/parallelport_win32.cpp b/src/parallelport_win32.cpp index 97c836726..800f6e2b6 100644 --- a/src/parallelport_win32.cpp +++ b/src/parallelport_win32.cpp @@ -46,9 +46,7 @@ ParallelPortWin32::ParallelPortWin32(void) m_portAddr = 0; } -ParallelPortWin32::~ParallelPortWin32(void) -{ -} +ParallelPortWin32::~ParallelPortWin32(void) { } struct ParallelPortChooser : public wxDialog { @@ -74,7 +72,7 @@ wxString ParallelPortWin32::ChooseParallelPort(const wxString& dflt) sz1->Add(portlb); wxWindow *label = new wxStaticText(&dlg, wxID_ANY, _("Custom Port Address:")); - wxTextCtrl *customtxt = new wxTextCtrl(&dlg ,wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(70, -1)); + wxTextCtrl *customtxt = new wxTextCtrl(&dlg, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(70, -1)); wxSizer *sz2 = new wxBoxSizer(wxHORIZONTAL); sz2->Add(label, wxSizerFlags(0).Border(wxALL, 10)); @@ -82,8 +80,7 @@ wxString ParallelPortWin32::ChooseParallelPort(const wxString& dflt) sz1->Add(sz2); - sz1->Add(dlg.CreateButtonSizer(wxOK | wxCANCEL), - wxSizerFlags(0).Right().Border(wxALL, 10)); + sz1->Add(dlg.CreateButtonSizer(wxOK | wxCANCEL), wxSizerFlags(0).Right().Border(wxALL, 10)); dlg.SetSizerAndFit(sz1); diff --git a/src/parallelport_win32.h b/src/parallelport_win32.h index 0b65c4eba..9e92dab7e 100644 --- a/src/parallelport_win32.h +++ b/src/parallelport_win32.h @@ -33,15 +33,14 @@ * */ -#if !defined(PARALLELPORT_WIN32_H_INCLUDED) && defined (__WINDOWS__) -#define PARALLELPORT_WIN32_H_INCLUDED +#if !defined(PARALLELPORT_WIN32_H_INCLUDED) && defined(__WINDOWS__) +# define PARALLELPORT_WIN32_H_INCLUDED -class ParallelPortWin32:public ParallelPort +class ParallelPortWin32 : public ParallelPort { short m_portAddr; public: - ParallelPortWin32(void); virtual ~ParallelPortWin32(void); diff --git a/src/phd.cpp b/src/phd.cpp index 003992459..c7e198cf5 100644 --- a/src/phd.cpp +++ b/src/phd.cpp @@ -42,11 +42,11 @@ #include #include -#ifdef __linux__ +#ifdef __linux__ # include #endif // __linux__ -//#define DEVBUILD +// #define DEVBUILD // Globals @@ -63,16 +63,13 @@ GuidingLog GuideLog; int XWinSize = 640; int YWinSize = 512; -static const wxCmdLineEntryDesc cmdLineDesc[] = -{ - { wxCMD_LINE_SWITCH, "?", "help", "display this help and exit" }, - { wxCMD_LINE_OPTION, "i", "instanceNumber", "sets the PHD2 instance number (default = 1)", wxCMD_LINE_VAL_NUMBER, wxCMD_LINE_PARAM_OPTIONAL}, +static const wxCmdLineEntryDesc cmdLineDesc[] = { { wxCMD_LINE_SWITCH, "?", "help", "display this help and exit" }, + { wxCMD_LINE_OPTION, "i", "instanceNumber", "sets the PHD2 instance number (default = 1)", wxCMD_LINE_VAL_NUMBER, + wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_OPTION, "l", "load", "load settings from file and exit", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, { wxCMD_LINE_SWITCH, "R", "Reset", "Reset all PHD2 settings to default values" }, { wxCMD_LINE_OPTION, "s", "save", "save settings to file and exit", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, - { wxCMD_LINE_SWITCH, "v", "version", "print the program version and exit" }, - { wxCMD_LINE_NONE } -}; + { wxCMD_LINE_SWITCH, "v", "version", "print the program version and exit" }, { wxCMD_LINE_NONE } }; enum ConfigOp { @@ -91,17 +88,18 @@ static void DisableOSXAppNap() // this is obsolete (2020-02-04) now that we disable AppNap in a // launcher script (run_phd2_macos), but it is harmless so we can // leave it in for a release or two -# define APPKEY "org.openphdguiding.phd2" +# define APPKEY "org.openphdguiding.phd2" int major = wxPlatformInfo::Get().GetOSMajorVersion(); int minor = wxPlatformInfo::Get().GetOSMinorVersion(); - if (major > 10 || (major == 10 && minor >= 9)) // Mavericks or later -- deal with App Nap + if (major > 10 || (major == 10 && minor >= 9)) // Mavericks or later -- deal with App Nap { wxArrayString out, err; wxExecute("defaults read " APPKEY " NSAppSleepDisabled", out, err); if (err.GetCount() > 0 || (out.GetCount() > 0 && out[0].Contains("0"))) // it's not there or disabled { wxExecute("defaults write " APPKEY " NSAppSleepDisabled -bool YES"); - wxMessageBox("OSX 10.9's App Nap feature causes problems. Please quit and relaunch PHD to finish disabling App Nap."); + wxMessageBox( + "OSX 10.9's App Nap feature causes problems. Please quit and relaunch PHD to finish disabling App Nap."); } } # undef APPKEY @@ -117,15 +115,17 @@ struct ExecFuncThreadEvent : public wxThreadEvent { std::function func; ExecFuncThreadEvent(std::function func_) - : wxThreadEvent(EXEC_IN_MAIN_THREAD_EVENT), func(func_) - { } + : wxThreadEvent(EXEC_IN_MAIN_THREAD_EVENT) + , func(func_) + { + } }; PhdApp::PhdApp() { m_resetConfig = false; m_instanceNumber = 1; -#ifdef __linux__ +#ifdef __linux__ XInitThreads(); #endif // __linux__ @@ -137,14 +137,15 @@ void PhdApp::HandleRestart() // wait until prev instance (parent) terminates while (true) { - std::unique_ptr si(new wxSingleInstanceChecker(wxString::Format("%s.%ld", GetAppName(), m_instanceNumber))); + std::unique_ptr si( + new wxSingleInstanceChecker(wxString::Format("%s.%ld", GetAppName(), m_instanceNumber))); if (!si->IsAnotherRunning()) break; wxMilliSleep(200); } // copy command-line args skipping "restart" - wchar_t **targv = new wchar_t*[argc * sizeof(*targv)]; + wchar_t **targv = new wchar_t *[argc * sizeof(*targv)]; targv[0] = wxStrdup(argv[0].wc_str()); int src = 2, dst = 1; while (src < argc) @@ -161,7 +162,7 @@ void PhdApp::HandleRestart() void PhdApp::RestartApp() { // copy command-line args inserting "restart" as the first arg - wchar_t **targv = new wchar_t*[(argc + 2) * sizeof(*targv)]; + wchar_t **targv = new wchar_t *[(argc + 2) * sizeof(*targv)]; targv[0] = wxStrdup(argv[0].wc_str()); targv[1] = wxStrdup(_T("restart")); int src = 1, dst = 2; @@ -210,9 +211,9 @@ void PhdApp::TerminateApp() #ifdef __WINDOWS__ # if wxCHECK_VERSION(3, 1, 0) -# pragma message ("FIXME: obsolete code -- remove and use wxGetOsDescription()") +# pragma message("FIXME: obsolete code -- remove and use wxGetOsDescription()") # endif -#include +# include static OSVERSIONINFOEXW wx_3_1_wxGetWindowsVersionInfo() { OSVERSIONINFOEXW info; @@ -221,52 +222,51 @@ static OSVERSIONINFOEXW wx_3_1_wxGetWindowsVersionInfo() // The simplest way to get the version is to call the kernel // RtlGetVersion() directly, if it is available. -#if wxUSE_DYNLIB_CLASS +# if wxUSE_DYNLIB_CLASS wxDynamicLibrary dllNtDll; - if ( dllNtDll.Load(wxS("ntdll.dll"), wxDL_VERBATIM | wxDL_QUIET) ) + if (dllNtDll.Load(wxS("ntdll.dll"), wxDL_VERBATIM | wxDL_QUIET)) { - typedef LONG /* NTSTATUS */ (WINAPI *RtlGetVersion_t)(OSVERSIONINFOEXW*); + typedef LONG /* NTSTATUS */ (WINAPI * RtlGetVersion_t)(OSVERSIONINFOEXW *); RtlGetVersion_t wxDL_INIT_FUNC(pfn, RtlGetVersion, dllNtDll); - if ( pfnRtlGetVersion && - (pfnRtlGetVersion(&info) == 0 /* STATUS_SUCCESS */) ) + if (pfnRtlGetVersion && (pfnRtlGetVersion(&info) == 0 /* STATUS_SUCCESS */)) { return info; } } -#endif // wxUSE_DYNLIB_CLASS +# endif // wxUSE_DYNLIB_CLASS -#ifdef __VISUALC__ -#pragma warning(push) -#pragma warning(disable:4996) // 'xxx': was declared deprecated -#endif +# ifdef __VISUALC__ +# pragma warning(push) +# pragma warning(disable : 4996) // 'xxx': was declared deprecated +# endif - if ( !::GetVersionExW(reinterpret_cast(&info)) ) + if (!::GetVersionExW(reinterpret_cast(&info))) { // This really shouldn't ever happen. - wxFAIL_MSG( "GetVersionEx() unexpectedly failed" ); + wxFAIL_MSG("GetVersionEx() unexpectedly failed"); } -#ifdef __VISUALC__ -#pragma warning(pop) -#endif +# ifdef __VISUALC__ +# pragma warning(pop) +# endif return info; } static int wxIsWindowsServer() { -#ifdef VER_NT_WORKSTATION - switch ( wx_3_1_wxGetWindowsVersionInfo().wProductType ) +# ifdef VER_NT_WORKSTATION + switch (wx_3_1_wxGetWindowsVersionInfo().wProductType) { - case VER_NT_WORKSTATION: - return false; + case VER_NT_WORKSTATION: + return false; - case VER_NT_SERVER: - case VER_NT_DOMAIN_CONTROLLER: - return true; + case VER_NT_SERVER: + case VER_NT_DOMAIN_CONTROLLER: + return true; } -#endif // VER_NT_WORKSTATION +# endif // VER_NT_WORKSTATION return -1; } @@ -286,8 +286,7 @@ static wxString wx_3_1_wxGetOsDescription() switch (info.dwMinorVersion) { case 0: - if (info.szCSDVersion[1] == 'B' || - info.szCSDVersion[1] == 'C') + if (info.szCSDVersion[1] == 'B' || info.szCSDVersion[1] == 'C') { str = _("Windows 95 OSR2"); } @@ -297,8 +296,7 @@ static wxString wx_3_1_wxGetOsDescription() } break; case 10: - if (info.szCSDVersion[1] == 'B' || - info.szCSDVersion[1] == 'C') + if (info.szCSDVersion[1] == 'B' || info.szCSDVersion[1] == 'C') { str = _("Windows 98 SE"); } @@ -311,9 +309,7 @@ static wxString wx_3_1_wxGetOsDescription() str = _("Windows ME"); break; default: - str.Printf(_("Windows 9x (%d.%d)"), - info.dwMajorVersion, - info.dwMinorVersion); + str.Printf(_("Windows 9x (%d.%d)"), info.dwMajorVersion, info.dwMinorVersion); break; } if (!wxIsEmpty(info.szCSDVersion)) @@ -341,7 +337,7 @@ static wxString wx_3_1_wxGetOsDescription() str = _("Windows Server 2003"); break; } - //else: must be XP, fall through + // else: must be XP, fall through case 1: str = _("Windows XP"); @@ -353,47 +349,34 @@ static wxString wx_3_1_wxGetOsDescription() switch (info.dwMinorVersion) { case 0: - str = wxIsWindowsServer() == 1 - ? _("Windows Server 2008") - : _("Windows Vista"); + str = wxIsWindowsServer() == 1 ? _("Windows Server 2008") : _("Windows Vista"); break; case 1: - str = wxIsWindowsServer() == 1 - ? _("Windows Server 2008 R2") - : _("Windows 7"); + str = wxIsWindowsServer() == 1 ? _("Windows Server 2008 R2") : _("Windows 7"); break; case 2: - str = wxIsWindowsServer() == 1 - ? _("Windows Server 2012") - : _("Windows 8"); + str = wxIsWindowsServer() == 1 ? _("Windows Server 2012") : _("Windows 8"); break; case 3: - str = wxIsWindowsServer() == 1 - ? _("Windows Server 2012 R2") - : _("Windows 8.1"); + str = wxIsWindowsServer() == 1 ? _("Windows Server 2012 R2") : _("Windows 8.1"); break; } break; case 10: - str = wxIsWindowsServer() == 1 - ? _("Windows Server 2016") - : _("Windows 10"); + str = wxIsWindowsServer() == 1 ? _("Windows Server 2016") : _("Windows 10"); break; } if (str.empty()) { - str.Printf(_("Windows NT %lu.%lu"), - info.dwMajorVersion, - info.dwMinorVersion); + str.Printf(_("Windows NT %lu.%lu"), info.dwMajorVersion, info.dwMinorVersion); } - str << wxT(" (") - << wxString::Format(_("build %lu"), info.dwBuildNumber); + str << wxT(" (") << wxString::Format(_("build %lu"), info.dwBuildNumber); if (!wxIsEmpty(info.szCSDVersion)) { str << wxT(", ") << info.szCSDVersion; @@ -426,8 +409,7 @@ static void OpenLogs(bool rollover) bool forceDebugOpen = rollover ? true : false; Debug.InitDebugLog(debugEnabled, forceDebugOpen); - Debug.Write(wxString::Format("PHD2 version %s %s execution with:\n", FULLVER, - rollover ? "continues" : "begins")); + Debug.Write(wxString::Format("PHD2 version %s %s execution with:\n", FULLVER, rollover ? "continues" : "begins")); Debug.Write(wxString::Format(" %s\n", GetOsDescription())); #if defined(__linux__) Debug.Write(wxString::Format(" %s\n", wxGetLinuxDistributionInfo().Description)); @@ -452,14 +434,8 @@ static void OpenLogs(bool rollover) struct LogToStderr { wxLog *m_prev; - LogToStderr() - { - m_prev = wxLog::SetActiveTarget(new wxLogStderr()); - } - ~LogToStderr() - { - delete wxLog::SetActiveTarget(m_prev); - } + LogToStderr() { m_prev = wxLog::SetActiveTarget(new wxLogStderr()); } + ~LogToStderr() { delete wxLog::SetActiveTarget(m_prev); } }; // A log class for duplicating wxWidgets error messages to the debug log @@ -476,10 +452,7 @@ struct EarlyLogger : public wxLog m_prev = wxLog::SetActiveTarget(this); DisableTimestamp(); } - ~EarlyLogger() - { - Close(); - } + ~EarlyLogger() { Close(); } void Close() { if (m_closed) @@ -538,7 +511,8 @@ bool PhdApp::OnInit() if (m_instanceChecker->IsAnotherRunning()) { wxLogError(wxString::Format(_("PHD2 instance %ld is already running. Use the " - "-i INSTANCE_NUM command-line option to start a different instance."), m_instanceNumber)); + "-i INSTANCE_NUM command-line option to start a different instance."), + m_instanceNumber)); delete m_instanceChecker; // OnExit() won't be called if we return false m_instanceChecker = 0; return false; @@ -580,7 +554,8 @@ bool PhdApp::OnInit() return false; } - m_logFileTime = DebugLog::GetLogFileTime(); // GetLogFileTime implements grouping by imaging-day, the 24-hour period starting at 09:00 am local time + m_logFileTime = DebugLog::GetLogFileTime(); // GetLogFileTime implements grouping by imaging-day, the 24-hour period + // starting at 09:00 am local time OpenLogs(false /* not for rollover */); logger.Close(); // writes any deferrred error messages to the debug log @@ -626,7 +601,7 @@ bool PhdApp::OnInit() } wxSetlocale(LC_NUMERIC, "C"); - wxTranslations::Get()->SetLanguage((wxLanguage)langid); + wxTranslations::Get()->SetLanguage((wxLanguage) langid); Debug.Write(wxString::Format("locale: wxTranslations language set to %d\n", langid)); Debug.RemoveOldFiles(); @@ -647,7 +622,7 @@ bool PhdApp::OnInit() if (pConfig->IsNewInstance() || (pConfig->NumProfiles() == 1 && pFrame->pGearDialog->IsEmptyProfile())) { - pFrame->pGearDialog->ShowProfileWizard(); // First-light version of profile wizard + pFrame->pGearDialog->ShowProfileWizard(); // First-light version of profile wizard } PHD2Updater::InitUpdater(); diff --git a/src/phd.h b/src/phd.h index 74ac268fd..c86f96e68 100644 --- a/src/phd.h +++ b/src/phd.h @@ -82,12 +82,12 @@ #define PHDSUBVER _T("dev4") #define FULLVER PHDVERSION PHDSUBVER -#if defined (__WINDOWS__) -# pragma warning(disable:4189) -# pragma warning(disable:4018) -# pragma warning(disable:4305) -# pragma warning(disable:4100) -# pragma warning(disable:4996) +#if defined(__WINDOWS__) +# pragma warning(disable : 4189) +# pragma warning(disable : 4018) +# pragma warning(disable : 4305) +# pragma warning(disable : 4100) +# pragma warning(disable : 4996) # if HAVE_VLD # include # endif @@ -96,36 +96,36 @@ WX_DEFINE_ARRAY_INT(int, ArrayOfInts); WX_DEFINE_ARRAY_DOUBLE(double, ArrayOfDbl); -#if defined (__WINDOWS__) -#define PHD_OSNAME _T("Windows") -#define PATHSEPCH '\\' -#define PATHSEPSTR "\\" +#if defined(__WINDOWS__) +# define PHD_OSNAME _T("Windows") +# define PATHSEPCH '\\' +# define PATHSEPSTR "\\" #endif -#if defined (__APPLE__) -#define PHD_OSNAME _T("OSX") -#define PATHSEPCH '/' -#define PATHSEPSTR "/" +#if defined(__APPLE__) +# define PHD_OSNAME _T("OSX") +# define PATHSEPCH '/' +# define PATHSEPSTR "/" #endif -#if defined (__WXGTK__) -#define PHD_OSNAME _T("Linux") -#define PATHSEPCH '/' -#define PATHSEPSTR _T("/") +#if defined(__WXGTK__) +# define PHD_OSNAME _T("Linux") +# define PATHSEPCH '/' +# define PATHSEPSTR _T("/") #endif #define DEGREES_SYMBOL "\u00B0" #define MICRONS_SYMBOL "\u00B5m" -//#define TEST_TRANSFORMS +// #define TEST_TRANSFORMS #define ROUND(x) (int) floor((x) + 0.5) #define ROUNDF(x) (int) floorf((x) + 0.5) #define DIV_ROUND_UP(x, y) (((x) + (y) - 1) / (y)) /* eliminate warnings for unused variables */ -#define POSSIBLY_UNUSED(x) (void)(x) -//#define POSSIBLY_UNUSED(x) printf(x) +#define POSSIBLY_UNUSED(x) (void) (x) +// #define POSSIBLY_UNUSED(x) printf(x) // these macros are used for building messages for thrown exceptions // It is surprisingly hard to get the line number into a string... @@ -137,18 +137,18 @@ WX_DEFINE_ARRAY_DOUBLE(double, ArrayOfDbl); #define THROW_INFO(s) (Debug.AddLine(wxString(THROW_INFO_BASE("Throw from", __FILE__, __LINE__) "->" s))) #define ERROR_INFO(s) (Debug.AddLine(wxString(THROW_INFO_BASE("Error thrown from", __FILE__, __LINE__) "->" s))) -#if defined (__WINDOWS__) -#define PHD_MESSAGES_CATALOG "messages" +#if defined(__WINDOWS__) +# define PHD_MESSAGES_CATALOG "messages" #endif -#if defined (__APPLE__) -#define PHD_MESSAGES_CATALOG "messages" +#if defined(__APPLE__) +# define PHD_MESSAGES_CATALOG "messages" #endif -#if defined (__linux__) || defined (__FreeBSD__) +#if defined(__linux__) || defined(__FreeBSD__) // On Linux the messages catalogs for all the applications are in the same directory // in /usr/share/locale, so the catalog name must be the application name. -#define PHD_MESSAGES_CATALOG "phd2" +# define PHD_MESSAGES_CATALOG "phd2" #endif #include "phdconfig.h" @@ -194,7 +194,7 @@ class wxSingleInstanceChecker; extern Mount *pMount; extern Mount *pSecondaryMount; -extern Scope *pPointingSource; // For using an 'aux' mount connection to get pointing info if the user has specified one +extern Scope *pPointingSource; // For using an 'aux' mount connection to get pointing info if the user has specified one extern GuideCamera *pCamera; inline static Scope *TheScope() @@ -220,16 +220,14 @@ class PhdApp : public wxApp wxDateTime m_logFileTime; protected: - wxLocale m_locale; public: - PhdApp(); bool OnInit(); int OnExit(); void OnInitCmdLine(wxCmdLineParser& parser); - bool OnCmdLineParsed(wxCmdLineParser & parser); + bool OnCmdLineParsed(wxCmdLineParser& parser); void TerminateApp(); void RestartApp(); void HandleRestart(); diff --git a/src/phdconfig.cpp b/src/phdconfig.cpp index 796cb313e..c63039b9a 100644 --- a/src/phdconfig.cpp +++ b/src/phdconfig.cpp @@ -51,9 +51,7 @@ ConfigSection::ConfigSection() { } -ConfigSection::~ConfigSection() -{ -} +ConfigSection::~ConfigSection() { } void ConfigSection::SelectProfile(int profileId) { @@ -130,9 +128,9 @@ int ConfigSection::GetInt(const wxString& name, int defaultValue) m_pConfig->Read(path, &lReturn, defaultValue); } - Debug.Write(wxString::Format("GetInt(\"%s\", %d) returns %d\n", path, defaultValue, (int)lReturn)); + Debug.Write(wxString::Format("GetInt(\"%s\", %d) returns %d\n", path, defaultValue, (int) lReturn)); - return (int)lReturn; + return (int) lReturn; } void ConfigSection::SetBoolean(const wxString& name, bool value) @@ -260,10 +258,7 @@ struct AutoConfigPath m_savePath = cfg->GetPath(); cfg->SetPath(path); } - ~AutoConfigPath() - { - m_cfg->SetPath(m_savePath); - } + ~AutoConfigPath() { m_cfg->SetPath(m_savePath); } }; int PhdConfig::FirstProfile() @@ -410,26 +405,31 @@ bool PhdConfig::CreateProfile(const wxString& name) static void CopyVal(wxConfigBase *cfg, const wxString& src, const wxString& dst) { wxConfigBase::EntryType type = cfg->GetEntryType(src); - switch (type) { - case wxConfigBase::Type_String: { + switch (type) + { + case wxConfigBase::Type_String: + { wxString val; cfg->Read(src, &val); cfg->Write(dst, val); break; } - case wxConfigBase::Type_Boolean: { + case wxConfigBase::Type_Boolean: + { bool val; cfg->Read(src, &val); cfg->Write(dst, val); break; } - case wxConfigBase::Type_Integer: { + case wxConfigBase::Type_Integer: + { long val; cfg->Read(src, &val); cfg->Write(dst, val); break; } - case wxConfigBase::Type_Float: { + case wxConfigBase::Type_Float: + { double val; cfg->Read(src, &val); cfg->Write(dst, val); @@ -474,7 +474,8 @@ bool PhdConfig::CloneProfile(const wxString& dest, const wxString& source) int dstId = GetProfileId(dest); if (dstId > 0) { - Debug.Write(wxString::Format("Clone profile could not clone %s: destination profile %s already exists\n", source, dest)); + Debug.Write( + wxString::Format("Clone profile could not clone %s: destination profile %s already exists\n", source, dest)); return true; } @@ -571,11 +572,25 @@ static wxString unescape_string(const wxString& s) { switch (s[i + 1].GetValue()) { - case '\\': d.Append('\\'); ++i; break; - case 't': d.Append('\t'); ++i; break; - case 'r': d.Append('\r'); ++i; break; - case 'n': d.Append('\n'); ++i; break; - default: d.Append(ch); break; + case '\\': + d.Append('\\'); + ++i; + break; + case 't': + d.Append('\t'); + ++i; + break; + case 'r': + d.Append('\r'); + ++i; + break; + case 'n': + d.Append('\n'); + ++i; + break; + default: + d.Append(ch); + break; } } else @@ -596,8 +611,8 @@ static bool ParseLine(const wxString& s, wxString *name, wxString *typestr, wxSt return true; } -static void LoadVal(ConfigSection& section, const wxString& s, const wxString& name, - const wxString& typestr, const wxString& val) +static void LoadVal( + ConfigSection& section, const wxString& s, const wxString& name, const wxString& typestr, const wxString& val) { long type; if (!typestr.ToLong(&type)) @@ -610,7 +625,8 @@ static void LoadVal(ConfigSection& section, const wxString& s, const wxString& n case wxConfigBase::Type_String: section.SetString(name, unescape_string(val)); break; - case wxConfigBase::Type_Boolean: { + case wxConfigBase::Type_Boolean: + { long lval; if (!val.ToLong(&lval)) { @@ -622,7 +638,8 @@ static void LoadVal(ConfigSection& section, const wxString& s, const wxString& n } break; } - case wxConfigBase::Type_Integer: { + case wxConfigBase::Type_Integer: + { long lval; if (!val.ToLong(&lval)) { @@ -634,7 +651,8 @@ static void LoadVal(ConfigSection& section, const wxString& s, const wxString& n } break; } - case wxConfigBase::Type_Float: { + case wxConfigBase::Type_Float: + { double dval; if (!val.ToDouble(&dval)) { @@ -703,26 +721,31 @@ static void WriteVal(wxTextOutputStream& os, wxConfigBase *cfg, const wxString& { wxString sval; wxConfigBase::EntryType type = cfg->GetEntryType(key); - switch (type) { - case wxConfigBase::Type_String: { + switch (type) + { + case wxConfigBase::Type_String: + { wxString val; cfg->Read(key, &val); sval = escape_string(val); break; } - case wxConfigBase::Type_Boolean: { + case wxConfigBase::Type_Boolean: + { bool val; cfg->Read(key, &val); sval = wxString(val ? "1" : "0"); break; } - case wxConfigBase::Type_Integer: { + case wxConfigBase::Type_Integer: + { long val; cfg->Read(key, &val); sval = wxString::Format("%lu", val); break; } - case wxConfigBase::Type_Float: { + case wxConfigBase::Type_Float: + { double val; cfg->Read(key, &val); sval = wxString::Format("%g", val); diff --git a/src/phdconfig.h b/src/phdconfig.h index d6c5f4e8d..d319fb9f3 100644 --- a/src/phdconfig.h +++ b/src/phdconfig.h @@ -80,11 +80,11 @@ class ConfigSection void SelectProfile(int profileId); - bool GetBoolean(const wxString& name, bool defaultValue); + bool GetBoolean(const wxString& name, bool defaultValue); wxString GetString(const wxString& name, const wxString& defaultValue); - double GetDouble(const wxString& name, double defaultValue); - long GetLong(const wxString& name, long defaultValue); - int GetInt(const wxString& name, int defaultValue); + double GetDouble(const wxString& name, double defaultValue); + long GetLong(const wxString& name, long defaultValue); + int GetInt(const wxString& name, int defaultValue); void SetBoolean(const wxString& name, bool value); void SetString(const wxString& name, const wxString& value); @@ -111,7 +111,6 @@ class PhdConfig int m_currentProfileId; public: - PhdConfig(int instance); ~PhdConfig(); diff --git a/src/phdcontrol.cpp b/src/phdcontrol.cpp index 82c7064cf..71ca0183a 100644 --- a/src/phdcontrol.cpp +++ b/src/phdcontrol.cpp @@ -55,7 +55,10 @@ enum SettleOp OP_GUIDE, }; -enum { SETTLING_TIME_DISABLED = 9999 }; +enum +{ + SETTLING_TIME_DISABLED = 9999 +}; struct ControllerState { @@ -107,10 +110,12 @@ bool PhdController::IsIdle() return ctrl.state == STATE_IDLE; } -#define SETSTATE(newstate) do { \ - Debug.AddLine("PhdController: newstate " #newstate); \ - ctrl.state = newstate; \ -} while (false) +#define SETSTATE(newstate) \ + do \ + { \ + Debug.AddLine("PhdController: newstate " #newstate); \ + ctrl.state = newstate; \ + } while (false) static wxString ReentrancyError(const char *op) { @@ -226,7 +231,10 @@ bool PhdController::DitherCompat(double pixels, wxString *errMsg) { AbortController("manual or phd1-style dither"); - enum { SETTLE_FRAMES = 10 }; + enum + { + SETTLE_FRAMES = 10 + }; return Dither(pixels, SETTLE_FRAMES, errMsg); } @@ -242,8 +250,7 @@ void PhdController::AbortController(const wxString& reason) static bool all_gear_connected(void) { - return pCamera && pCamera->Connected && - (!pMount || pMount->IsConnected()) && + return pCamera && pCamera->Connected && (!pMount || pMount->IsConnected()) && (!pSecondaryMount || pSecondaryMount->IsConnected()); } @@ -308,7 +315,8 @@ void PhdController::UpdateControllerState(void) while (!done) { - switch (ctrl.state) { + switch (ctrl.state) + { case STATE_IDLE: done = true; break; @@ -317,11 +325,12 @@ void PhdController::UpdateControllerState(void) Debug.AddLine("PhdController: setup"); ctrl.haveSaveSticky = false; ctrl.autoFindAttemptsRemaining = 3; - ctrl.overrideDecGuideMode = false; // guide stop/start with no dithering + ctrl.overrideDecGuideMode = false; // guide stop/start with no dithering SETSTATE(STATE_ATTEMPT_START); break; - case STATE_ATTEMPT_START: { + case STATE_ATTEMPT_START: + { wxString err; @@ -382,11 +391,13 @@ void PhdController::UpdateControllerState(void) break; } - case STATE_SELECT_STAR: { + case STATE_SELECT_STAR: + { bool error = pFrame->AutoSelectStar(ctrl.roi); if (error) { - Debug.Write(wxString::Format("auto find star failed, attempts remaining = %d\n", ctrl.autoFindAttemptsRemaining)); + Debug.Write( + wxString::Format("auto find star failed, attempts remaining = %d\n", ctrl.autoFindAttemptsRemaining)); if (--ctrl.autoFindAttemptsRemaining == 0) { do_fail(_T("failed to find a suitable guide star")); @@ -414,7 +425,8 @@ void PhdController::UpdateControllerState(void) } else { - Debug.Write(wxString::Format("waiting for star selected, attempts remaining = %d\n", ctrl.waitSelectedRemaining)); + Debug.Write( + wxString::Format("waiting for star selected, attempts remaining = %d\n", ctrl.waitSelectedRemaining)); if (--ctrl.waitSelectedRemaining == 0) { SETSTATE(STATE_ATTEMPT_START); @@ -433,8 +445,7 @@ void PhdController::UpdateControllerState(void) pSecondaryMount->ClearCalibration(); } - if ((pMount && !pMount->IsCalibrated()) || - (pSecondaryMount && !pSecondaryMount->IsCalibrated())) + if ((pMount && !pMount->IsCalibrated()) || (pSecondaryMount && !pSecondaryMount->IsCalibrated())) { Debug.AddLine("PhdController: start calibration"); @@ -463,8 +474,7 @@ void PhdController::UpdateControllerState(void) break; case STATE_CALIBRATION_WAIT: - if ((!pMount || pMount->IsCalibrated()) && - (!pSecondaryMount || pSecondaryMount->IsCalibrated())) + if ((!pMount || pMount->IsCalibrated()) && (!pSecondaryMount || pSecondaryMount->IsCalibrated())) { if (ctrl.useStickyLock && ctrl.haveSaveSticky) pFrame->pGuider->SetLockPosIsSticky(ctrl.saveSticky); @@ -490,8 +500,8 @@ void PhdController::UpdateControllerState(void) GuideLog.NotifySettlingStateChange("Settling started"); if (ctrl.overrideDecGuideMode) { - Debug.Write(wxString::Format("PhdController: setting Dec guide mode to %s for dither settle\n", - Scope::DecGuideModeStr(DEC_AUTO))); + Debug.Write(wxString::Format( + "PhdController: setting Dec guide mode to %s for dither settle\n", Scope::DecGuideModeStr(DEC_AUTO))); TheScope()->SetDecGuideMode(DEC_AUTO); } ctrl.settlePriorFrameInRange = false; @@ -501,7 +511,8 @@ void PhdController::UpdateControllerState(void) done = true; break; - case STATE_SETTLE_WAIT: { + case STATE_SETTLE_WAIT: + { bool lockedOnStar = pFrame->pGuider->IsLocked(); double currentError = pFrame->CurrentGuideError(); bool inRange = lockedOnStar && currentError <= ctrl.settle.tolerancePx; @@ -513,9 +524,9 @@ void PhdController::UpdateControllerState(void) if (!lockedOnStar) ++ctrl.droppedFrameCount; - Debug.Write(wxString::Format("PhdController: settling, locked = %d, distance = %.2f (%.2f) aobump = %d frame = %d / %d\n", - lockedOnStar, currentError, ctrl.settle.tolerancePx, aoBumpInProgress, ctrl.settleFrameCount, - ctrl.settle.frames)); + Debug.Write(wxString::Format( + "PhdController: settling, locked = %d, distance = %.2f (%.2f) aobump = %d frame = %d / %d\n", lockedOnStar, + currentError, ctrl.settle.tolerancePx, aoBumpInProgress, ctrl.settleFrameCount, ctrl.settle.frames)); if (ctrl.settleFrameCount >= ctrl.settle.frames) { @@ -549,7 +560,7 @@ void PhdController::UpdateControllerState(void) do_fail(_T("timed-out waiting for guider to settle")); break; } - EvtServer.NotifySettling(currentError, (double)timeInRange / 1000., ctrl.settle.settleTimeSec, lockedOnStar); + EvtServer.NotifySettling(currentError, (double) timeInRange / 1000., ctrl.settle.settleTimeSec, lockedOnStar); ctrl.settlePriorFrameInRange = inRange; done = true; break; @@ -559,7 +570,7 @@ void PhdController::UpdateControllerState(void) if (ctrl.overrideDecGuideMode) { Debug.Write(wxString::Format("PhdController: restore Dec guide mode to %s after dither\n", - Scope::DecGuideModeStr(ctrl.saveDecGuideMode))); + Scope::DecGuideModeStr(ctrl.saveDecGuideMode))); TheScope()->SetDecGuideMode(ctrl.saveDecGuideMode); ctrl.overrideDecGuideMode = false; } diff --git a/src/phdcontrol.h b/src/phdcontrol.h index e13b60200..c4e998bdd 100644 --- a/src/phdcontrol.h +++ b/src/phdcontrol.h @@ -37,16 +37,16 @@ struct SettleParams { - double tolerancePx; // settle threshold, pixels - int settleTimeSec; // time to be within tolerance - int timeoutSec; // timeout value - int frames; // number of frames + double tolerancePx; // settle threshold, pixels + int settleTimeSec; // time to be within tolerance + int timeoutSec; // timeout value + int frames; // number of frames }; enum ControlGuideOptions { - GUIDEOPT_FORCE_RECAL = (1U << 0), // Always recalibrate - GUIDEOPT_USE_STICKY_LOCK = (1U << 1), // Insure that recalibration returns star to initial position + GUIDEOPT_FORCE_RECAL = (1U << 0), // Always recalibrate + GUIDEOPT_USE_STICKY_LOCK = (1U << 1), // Insure that recalibration returns star to initial position }; class PhdController @@ -64,7 +64,7 @@ class PhdController static void OnAppExit(); static bool IsSettling(); - static bool IsIdle(); // Not currently working through various transitions in guiding state + static bool IsIdle(); // Not currently working through various transitions in guiding state }; #endif diff --git a/src/phdupdate.cpp b/src/phdupdate.cpp index b0f7a8f2b..a3c41cb08 100644 --- a/src/phdupdate.cpp +++ b/src/phdupdate.cpp @@ -60,11 +60,13 @@ struct Updater; struct UpdaterDialog : public wxDialog { - enum Mode { - MODE_NOTIFY, // notification that a new version is available (Linux/OSX) + enum Mode + { + MODE_NOTIFY, // notification that a new version is available (Linux/OSX) MODE_INSTALL, // ready to install a new version (Windows) }; - enum Interactive { + enum Interactive + { NONINTERACTIVE, INTERACTIVE, }; @@ -107,14 +109,20 @@ class UpdaterThread : public wxThread { Updater *m_upd; ExitCode Entry() override; + public: - UpdaterThread(Updater *upd) : wxThread(wxTHREAD_DETACHED), m_upd(upd) { } + UpdaterThread(Updater *upd) + : wxThread(wxTHREAD_DETACHED) + , m_upd(upd) + { + } ~UpdaterThread(); }; class UpdateNow : public RunInBg { Updater *m_upd; + public: UpdateNow(Updater *upd); ~UpdateNow() override; @@ -152,7 +160,8 @@ struct Version ++p; } r[l] += adj; - if (!*p) return; + if (!*p) + return; if (strncmp(p, "alpha", 5) == 0) adj = -60; else if (strncmp(p, "beta", 4) == 0) @@ -170,23 +179,27 @@ struct Version bool operator==(const Version& rhs) const { - return r[0] == rhs.r[0] && - r[1] == rhs.r[1] && - r[2] == rhs.r[2] && - r[3] == rhs.r[3] && - r[4] == rhs.r[4]; + return r[0] == rhs.r[0] && r[1] == rhs.r[1] && r[2] == rhs.r[2] && r[3] == rhs.r[3] && r[4] == rhs.r[4]; } bool operator<(const Version& rhs) const { - if (r[0] < rhs.r[0]) return true; - if (r[0] > rhs.r[0]) return false; - if (r[1] < rhs.r[1]) return true; - if (r[1] > rhs.r[1]) return false; - if (r[2] < rhs.r[2]) return true; - if (r[2] > rhs.r[2]) return false; - if (r[3] < rhs.r[3]) return true; - if (r[3] > rhs.r[3]) return false; + if (r[0] < rhs.r[0]) + return true; + if (r[0] > rhs.r[0]) + return false; + if (r[1] < rhs.r[1]) + return true; + if (r[1] > rhs.r[1]) + return false; + if (r[2] < rhs.r[2]) + return true; + if (r[2] > rhs.r[2]) + return false; + if (r[3] < rhs.r[3]) + return true; + if (r[3] > rhs.r[3]) + return false; return r[4] < rhs.r[4]; } @@ -236,7 +249,8 @@ struct Updater m_settings.enabled = pConfig->Global.GetBoolean("/Update/enabled", DefaultEnableUpdate); int DefaultSeries = Version::ThisVersion().IsDevBuild() ? UPD_SERIES_DEV : UPD_SERIES_MAIN; int series = pConfig->Global.GetInt("/Update/series", DefaultSeries); - switch (series) { + switch (series) + { case UPD_SERIES_MAIN: case UPD_SERIES_DEV: break; @@ -282,12 +296,11 @@ struct Updater } Updater() - : - m_status(UPD_NOT_STARTED), - m_thread(nullptr), - m_curl(nullptr), - m_updatenow(nullptr), - abort(false) + : m_status(UPD_NOT_STARTED) + , m_thread(nullptr) + , m_curl(nullptr) + , m_updatenow(nullptr) + , abort(false) { LoadSettings(); } @@ -300,9 +313,13 @@ struct Updater wxString SeriesName() { - switch (m_settings.series) { - case UPD_SERIES_MAIN: return _T("main"); - case UPD_SERIES_DEV: default: return _T("dev"); + switch (m_settings.series) + { + case UPD_SERIES_MAIN: + return _T("main"); + case UPD_SERIES_DEV: + default: + return _T("dev"); } } @@ -311,10 +328,7 @@ struct Updater return wxString::Format(_T("https://openphdguiding.org/release-%s-") OSNAME _T(".txt"), SeriesName()); } - wxString ChangeLogURL() - { - return wxString::Format(_T("https://openphdguiding.org/changelog-%s/"), SeriesName()); - } + wxString ChangeLogURL() { return wxString::Format(_T("https://openphdguiding.org/changelog-%s/"), SeriesName()); } bool FetchURL(wxString *buf, const wxString& url) { @@ -331,7 +345,7 @@ struct Updater if (res != CURLE_OK) { - Debug.Write(wxString::Format("UPD: fetch error: %s\n", curl_easy_strerror(res))); + Debug.Write(wxString::Format("UPD: fetch error: %s\n", curl_easy_strerror(res))); return false; } @@ -443,17 +457,13 @@ struct Updater unsigned char res[SHA1_BLOCK_SIZE]; sha1_final(&ctx, res); - wxString val = wxString::Format( - _T("%02hhx%02hhx%02hhx%02hhx") - _T("%02hhx%02hhx%02hhx%02hhx") - _T("%02hhx%02hhx%02hhx%02hhx") - _T("%02hhx%02hhx%02hhx%02hhx") - _T("%02hhx%02hhx%02hhx%02hhx"), - res[0], res[1], res[2], res[3], - res[4], res[5], res[6], res[7], - res[8], res[9], res[10], res[11], - res[12], res[13], res[14], res[15], - res[16], res[17], res[18], res[19]); + wxString val = wxString::Format(_T("%02hhx%02hhx%02hhx%02hhx") + _T("%02hhx%02hhx%02hhx%02hhx") + _T("%02hhx%02hhx%02hhx%02hhx") + _T("%02hhx%02hhx%02hhx%02hhx") + _T("%02hhx%02hhx%02hhx%02hhx"), + res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7], res[8], res[9], res[10], res[11], res[12], res[13], + res[14], res[15], res[16], res[17], res[18], res[19]); bool matches = wxStricmp(val, expected) == 0; @@ -465,10 +475,7 @@ struct Updater return matches; } - static wxString installer_filename() - { - return MyFrame::GetDefaultFileDir() + PATHSEPSTR + "phd2_installer.exe"; - } + static wxString installer_filename() { return MyFrame::GetDefaultFileDir() + PATHSEPSTR + "phd2_installer.exe"; } bool DownloadNeeded() { @@ -510,19 +517,18 @@ struct Updater if (!m_interactive) { // limit download speed for background download - curl_easy_setopt(m_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)DownloadBgMaxBPS); + curl_easy_setopt(m_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) DownloadBgMaxBPS); } Debug.Write(wxString::Format("UPD: begin download %s to %s\n", installer_url, filename)); CURLcode res = curl_easy_perform(m_curl); - curl_easy_setopt(m_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)0); // restore unlimited rate + curl_easy_setopt(m_curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t) 0); // restore unlimited rate if (res != CURLE_OK) { - Debug.Write(wxString::Format("UPD: could not download installer: %s\n", - curl_easy_strerror(res))); + Debug.Write(wxString::Format("UPD: could not download installer: %s\n", curl_easy_strerror(res))); file.Close(); wxRemoveFile(filename); return false; @@ -557,8 +563,12 @@ struct Updater struct AutoCleanupCurl { CURL **m_pp; - AutoCleanupCurl(CURL **pp) : m_pp(pp) { } - ~AutoCleanupCurl() { + AutoCleanupCurl(CURL **pp) + : m_pp(pp) + { + } + ~AutoCleanupCurl() + { if (*m_pp) { curl_easy_cleanup(*m_pp); @@ -669,8 +679,8 @@ struct Updater wxString GetDownloadPageURL() { - return m_settings.series == UPD_SERIES_DEV ? - wxT("http://openphdguiding.org/development-snapshots") : wxT("http://openphdguiding.org/downloads"); + return m_settings.series == UPD_SERIES_DEV ? wxT("http://openphdguiding.org/development-snapshots") + : wxT("http://openphdguiding.org/downloads"); } void ShowUpdate(UpdaterDialog::Mode mode, UpdaterDialog::Interactive interactive) @@ -679,13 +689,11 @@ struct Updater if (mode == UpdaterDialog::MODE_NOTIFY) { - msg = wxString::Format( - _("PHD2 version %s is available at %s"), newver, GetDownloadPageURL()); + msg = wxString::Format(_("PHD2 version %s is available at %s"), newver, GetDownloadPageURL()); } else { - msg = wxString::Format( - _("PHD2 version %s is ready to install. Update and restart PHD2 now?"), newver); + msg = wxString::Format(_("PHD2 version %s is ready to install. Update and restart PHD2 now?"), newver); } UpdaterDialog *dlg = new UpdaterDialog(this, mode, interactive, msg, changelog); @@ -700,7 +708,8 @@ struct Updater void HandleStateNonInteractive() { - switch (m_status) { + switch (m_status) + { case UPD_ABORTED: case UPD_UPDATE_NEEDED: case UPD_DOWNLOAD_DONE: @@ -713,7 +722,7 @@ struct Updater } if (m_status == UPD_UPDATE_NEEDED) - ShowUpdate(UpdaterDialog::MODE_NOTIFY, UpdaterDialog::NONINTERACTIVE); // Mac and Linux + ShowUpdate(UpdaterDialog::MODE_NOTIFY, UpdaterDialog::NONINTERACTIVE); // Mac and Linux else if (m_status == UPD_READY_FOR_INSTALL) ShowUpdate(UpdaterDialog::MODE_INSTALL, UpdaterDialog::NONINTERACTIVE); else if (m_status == UPD_UP_TO_DATE) @@ -744,9 +753,8 @@ wxThread::ExitCode UpdaterThread::Entry() } UpdateNow::UpdateNow(Updater *upd) - : - RunInBg(pFrame, _("PHD2 Update"), _("Checking for updates")), - m_upd(upd) + : RunInBg(pFrame, _("PHD2 Update"), _("Checking for updates")) + , m_upd(upd) { m_upd->m_updatenow = this; SetPopupDelay(500); @@ -770,18 +778,17 @@ void UpdateNow::OnCancel() m_upd->abort = true; } -UpdaterDialog::UpdaterDialog(Updater *updater, Mode mode, Interactive interactive, const wxString& text, const wxString& changelog) - : - wxDialog(pFrame, wxID_ANY, _("PHD2 Update Available"), wxDefaultPosition, wxDefaultSize, - wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER), - m_updater(updater), - m_mode(mode), - m_keepOpen(nullptr) +UpdaterDialog::UpdaterDialog( + Updater *updater, Mode mode, Interactive interactive, const wxString& text, const wxString& changelog) + : wxDialog(pFrame, wxID_ANY, _("PHD2 Update Available"), wxDefaultPosition, wxDefaultSize, + wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) + , m_updater(updater) + , m_mode(mode) + , m_keepOpen(nullptr) { wxBoxSizer *sz1 = new wxBoxSizer(wxVERTICAL); - m_text = new wxTextCtrl(this, wxID_ANY, text, wxDefaultPosition, wxDefaultSize, - wxTE_READONLY | wxTE_CENTRE | wxNO_BORDER); + m_text = new wxTextCtrl(this, wxID_ANY, text, wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxTE_CENTRE | wxNO_BORDER); wxFont fnt = m_text->GetFont(); fnt.SetWeight(wxFONTWEIGHT_BOLD); m_text->SetFont(fnt); @@ -821,7 +828,8 @@ UpdaterDialog::UpdaterDialog(Updater *updater, Mode mode, Interactive interactiv { wxBoxSizer *sz3 = new wxBoxSizer(wxHORIZONTAL); - m_closingMessage = new wxStaticText(this, wxID_ANY, wxString::Format(_("Closing in %d seconds"), 9999), wxDefaultPosition, wxDefaultSize, wxST_NO_AUTORESIZE); + m_closingMessage = new wxStaticText(this, wxID_ANY, wxString::Format(_("Closing in %d seconds"), 9999), + wxDefaultPosition, wxDefaultSize, wxST_NO_AUTORESIZE); m_closingMessage->Wrap(-1); sz3->Add(m_closingMessage, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); @@ -836,7 +844,8 @@ UpdaterDialog::UpdaterDialog(Updater *updater, Mode mode, Interactive interactiv m_timer.Start(1000); - m_keepOpen->Connect(wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(UpdaterDialog::OnKeepOpenChecked), NULL, this); + m_keepOpen->Connect( + wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(UpdaterDialog::OnKeepOpenChecked), NULL, this); } SetSizerAndFit(sz1); @@ -854,7 +863,8 @@ UpdaterDialog::~UpdaterDialog() // Disconnect Events m_goButton->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(UpdaterDialog::OnGoClicked), NULL, this); if (m_keepOpen) - m_keepOpen->Disconnect(wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(UpdaterDialog::OnKeepOpenChecked), NULL, this); + m_keepOpen->Disconnect( + wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(UpdaterDialog::OnKeepOpenChecked), NULL, this); Disconnect(wxID_ANY, wxEVT_TIMER, wxTimerEventHandler(UpdaterDialog::OnTimer)); } @@ -914,7 +924,7 @@ void PHD2Updater::InitUpdater() if (updater->m_settings.enabled) { pFrame->m_upgradeMenuItem->Enable(false); - updater->Run(); // starts check in background + updater->Run(); // starts check in background } else { diff --git a/src/phdupdate.h b/src/phdupdate.h index c1174bba3..9524606ff 100644 --- a/src/phdupdate.h +++ b/src/phdupdate.h @@ -50,7 +50,6 @@ struct UpdaterSettings class PHD2Updater { public: - // start the updater process at app init static void InitUpdater(); diff --git a/src/pierflip_tool.cpp b/src/pierflip_tool.cpp index a1335aa85..b93388706 100644 --- a/src/pierflip_tool.cpp +++ b/src/pierflip_tool.cpp @@ -75,9 +75,8 @@ struct PierFlipCalToolWin : public wxFrame }; PierFlipCalToolWin::PierFlipCalToolWin() - : - wxFrame(pFrame, wxID_ANY, _("Meridian Flip Calibration Tool"), wxDefaultPosition, wxSize(334, 350), - wxCAPTION|wxCLOSE_BOX|wxFRAME_NO_TASKBAR|wxTAB_TRAVERSAL) + : wxFrame(pFrame, wxID_ANY, _("Meridian Flip Calibration Tool"), wxDefaultPosition, wxSize(334, 350), + wxCAPTION | wxCLOSE_BOX | wxFRAME_NO_TASKBAR | wxTAB_TRAVERSAL) { SetSizeHints(wxDefaultSize, wxDefaultSize); @@ -86,35 +85,34 @@ PierFlipCalToolWin::PierFlipCalToolWin() wxSize sz = GetTextExtent(_T("M")); m_instructions = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(31 * sz.GetWidth(), 19 * sz.GetHeight() / 2), - wxTE_MULTILINE | wxTE_NO_VSCROLL | wxTE_READONLY | wxTE_WORDWRAP); - sz1->Add(m_instructions, 0, wxALL|wxEXPAND, 5); + wxSize(31 * sz.GetWidth(), 19 * sz.GetHeight() / 2), wxTE_MULTILINE | wxTE_NO_VSCROLL | wxTE_READONLY | wxTE_WORDWRAP); + sz1->Add(m_instructions, 0, wxALL | wxEXPAND, 5); wxFlexGridSizer *sz2 = new wxFlexGridSizer(3, 2, 0, 0); sz2->SetFlexibleDirection(wxBOTH); sz2->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); wxStaticText *label1 = new wxStaticText(this, wxID_ANY, _("Declination")); - sz2->Add(label1, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); + sz2->Add(label1, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_dec = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); - sz2->Add(m_dec, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); + sz2->Add(m_dec, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); wxStaticText *label2 = new wxStaticText(this, wxID_ANY, _("Hour Angle")); - sz2->Add(label2, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); + sz2->Add(label2, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_ha = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); - sz2->Add(m_ha, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); + sz2->Add(m_ha, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); wxStaticText *label3 = new wxStaticText(this, wxID_ANY, _("Pier Side")); - sz2->Add(label3, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); + sz2->Add(label3, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_pierSide = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); - sz2->Add(m_pierSide, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); + sz2->Add(m_pierSide, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_scopePosCtrls = sz2; - sz1->Add(sz2, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); + sz1->Add(sz2, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 5); wxBoxSizer *sz3 = new wxBoxSizer(wxHORIZONTAL); @@ -149,7 +147,8 @@ PierFlipCalToolWin::~PierFlipCalToolWin() Debug.Write("PFT: closed\n"); // Disconnect Events - m_restart->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(PierFlipCalToolWin::OnRestartClick), nullptr, this); + m_restart->Disconnect( + wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(PierFlipCalToolWin::OnRestartClick), nullptr, this); m_next->Disconnect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(PierFlipCalToolWin::OnNextClick), nullptr, this); Disconnect(wxID_ANY, wxEVT_TIMER, wxTimerEventHandler(PierFlipCalToolWin::OnTimer)); @@ -216,8 +215,7 @@ static void SetBg(wxTextCtrl *ctrl, Color c) static wxColor Y(237, 237, 88); static wxColor G(88, 237, 88); - const wxColor& cl = c == GREY ? wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW) : - c == RED ? R : c == YELLOW ? Y : G; + const wxColor& cl = c == GREY ? wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW) : c == RED ? R : c == YELLOW ? Y : G; if (ctrl->SetBackgroundColour(cl)) ctrl->Refresh(); @@ -236,18 +234,18 @@ void PierFlipCalToolWin::SetState(State state) { case ST_INTRO: s = _("This tool will automatically determine the correct value for the setting " - "'Reverse Dec output after meridian flip'.\n\n" - "The procedure requires two calibrations -- one with the telescope on the East " - "side of the pier, and one on the West. You will be instructed to slew the " - "telescope when needed.\n\n" - "Click Next to begin"); + "'Reverse Dec output after meridian flip'.\n\n" + "The procedure requires two calibrations -- one with the telescope on the East " + "side of the pier, and one on the West. You will be instructed to slew the " + "telescope when needed.\n\n" + "Click Next to begin"); m_next->SetLabel(_("Next")); m_scopePosCtrls->ShowItems(false); Fit(); break; case ST_SLEW_1: s = _("Point the telescope in the direction of the intersection of the meridian and the celestial " - "equator, near Hour Angle = 0 and Declination = 0.\n\nClick Calibrate when ready."); + "equator, near Hour Angle = 0 and Declination = 0.\n\nClick Calibrate when ready."); m_next->SetLabel(_("Calibrate")); m_status->SetStatusText(wxEmptyString); if (!m_scopePosCtrls->AreAnyItemsShown()) @@ -258,37 +256,35 @@ void PierFlipCalToolWin::SetState(State state) break; case ST_CALIBRATE_1: s = _("Wait for the first calibration to complete."); - m_status->SetStatusText(wxString::Format(_("Calibrating on the %s side of pier"), - Scope::PierSideStrTr(pPointingSource->SideOfPier()))); + m_status->SetStatusText( + wxString::Format(_("Calibrating on the %s side of pier"), Scope::PierSideStrTr(pPointingSource->SideOfPier()))); break; case ST_SLEW_2: - s = wxString::Format(_("Slew the telescope to force a meridian flip - the scope should move to the %s side of the pier, still pointing near Dec = 0."), - Scope::PierSideStrTr(m_firstCal.pierSide == PIER_SIDE_EAST ? PIER_SIDE_WEST : PIER_SIDE_EAST)) + + s = wxString::Format(_("Slew the telescope to force a meridian flip - the scope should move to the %s side of the " + "pier, still pointing near Dec = 0."), + Scope::PierSideStrTr(m_firstCal.pierSide == PIER_SIDE_EAST ? PIER_SIDE_WEST : PIER_SIDE_EAST)) + _T("\n\n") + _("Point the telescope in the direction of the intersection of the meridian and the celestial " - "equator, near Hour Angle = 0 and Declination = 0.\n\nClick Calibrate when ready."); + "equator, near Hour Angle = 0 and Declination = 0.\n\nClick Calibrate when ready."); m_status->SetStatusText(wxEmptyString); break; case ST_CALIBRATE_2: s = _("Wait for the second calibration to complete."); - m_status->SetStatusText(wxString::Format(_("Calibrating on the %s side of pier"), - Scope::PierSideStrTr(pPointingSource->SideOfPier()))); + m_status->SetStatusText( + wxString::Format(_("Calibrating on the %s side of pier"), Scope::PierSideStrTr(pPointingSource->SideOfPier()))); break; case ST_DONE: if (m_resultError.empty()) { - s = _("Meridian flip calibration completed sucessfully.") + - _T("\n\n") + + s = _("Meridian flip calibration completed sucessfully.") + _T("\n\n") + wxString::Format(_("The correct setting for 'Reverse Dec output after meridian flip' " - "for this mount is: %s"), - m_result ? _("enabled") : _("disabled")) + - _T("\n\n") + - _("Click Apply to accept the setting"); + "for this mount is: %s"), + m_result ? _("enabled") : _("disabled")) + + _T("\n\n") + _("Click Apply to accept the setting"); } else { - s = _("Meridian flip calibration failed.") + _T("\n\n") + - m_resultError + _T("\n\n") + + s = _("Meridian flip calibration failed.") + _T("\n\n") + m_resultError + _T("\n\n") + _("Resolve any calibration issues and try again"); } m_next->SetLabel(_("Apply")); @@ -415,7 +411,7 @@ void PierFlipCalToolWin::DoOnTimer() void PierFlipCalToolWin::OnTimer(wxTimerEvent&) { - DoOnTimer(); + DoOnTimer(); } void PierFlipCalToolWin::OnGuidingStateUpdated() @@ -500,14 +496,14 @@ bool PierFlipTool::CanRunTool(wxString *error) { Debug.Write("PFT: called when no mount present\n"); *error = _("The meridian flip calibration tool requires a mount. " - "Click the Connect Equipment button to select your mount."); + "Click the Connect Equipment button to select your mount."); return false; } if (TheScope()->GetDecGuideMode() == DEC_GUIDE_MODE::DEC_NONE) { Debug.Write("PFT: called when dec guiding disabled\n"); *error = _("The meridian flip calibration tool cannnot be run with Declination guiding disabled. " - "If your mount can guide in Declination, set your Dec guide mode to Auto and try again."); + "If your mount can guide in Declination, set your Dec guide mode to Auto and try again."); return false; } return true; diff --git a/src/point.h b/src/point.h index 5bd385a96..052d35e5f 100644 --- a/src/point.h +++ b/src/point.h @@ -41,34 +41,23 @@ class PHD_Point bool m_valid; public: - double X; double Y; - PHD_Point(double x, double y) - { - SetXY(x, y); - } + PHD_Point(double x, double y) { SetXY(x, y); } PHD_Point(const PHD_Point& p) - : m_valid(p.m_valid), X(p.X), Y(p.Y) + : m_valid(p.m_valid) + , X(p.X) + , Y(p.Y) { } - PHD_Point() - { - Invalidate(); - } + PHD_Point() { Invalidate(); } - bool IsValid() const - { - return m_valid; - } + bool IsValid() const { return m_valid; } - void Invalidate() - { - m_valid = false; - } + void Invalidate() { m_valid = false; } void SetXY(double x, double y) { @@ -85,23 +74,17 @@ class PHD_Point return dRet; } - double dX(const PHD_Point *pPoint) const - { - return this->dX(*pPoint); - } + double dX(const PHD_Point *pPoint) const { return this->dX(*pPoint); } double dY(const PHD_Point& p) const { assert(m_valid && p.m_valid); - double dRet = Y-p.Y; + double dRet = Y - p.Y; return dRet; } - double dY(const PHD_Point *pPoint) const - { - return this->dY(*pPoint); - } + double dY(const PHD_Point *pPoint) const { return this->dY(*pPoint); } double Distance(const PHD_Point& p) const { @@ -111,15 +94,9 @@ class PHD_Point return dRet; } - double Distance(const PHD_Point *pPoint) const - { - return Distance(*pPoint); - } + double Distance(const PHD_Point *pPoint) const { return Distance(*pPoint); } - double Distance() const - { - return hypot(X, Y); - } + double Distance() const { return hypot(X, Y); } double Angle(const PHD_Point& p) const { @@ -139,15 +116,12 @@ class PHD_Point double Angle() const { - PHD_Point origin(0,0); + PHD_Point origin(0, 0); return Angle(origin); } - double Angle(const PHD_Point *pPoint) const - { - return Angle(*pPoint); - } + double Angle(const PHD_Point *pPoint) const { return Angle(*pPoint); } PHD_Point operator+(const PHD_Point& addend) const { @@ -182,7 +156,7 @@ class PHD_Point PHD_Point operator/(double divisor) const { assert(m_valid); - return PHD_Point(this->X/divisor, this->Y/divisor); + return PHD_Point(this->X / divisor, this->Y / divisor); } PHD_Point& operator/=(double divisor) @@ -215,12 +189,11 @@ class ShiftPoint : public PHD_Point typedef PHD_Point super; PHD_Point m_rate; // rate of change (per second) - double m_x0; // initial x position - double m_y0; // initial y position - wxLongLong_t m_t0; // initial time (seconds) + double m_x0; // initial x position + double m_y0; // initial y position + wxLongLong_t m_t0; // initial time (seconds) public: - ShiftPoint() { } void SetShiftRate(double xrate, double yrate) @@ -239,16 +212,13 @@ class ShiftPoint : public PHD_Point } } - void DisableShift() - { - m_rate.Invalidate(); - } + void DisableShift() { m_rate.Invalidate(); } void UpdateShift() { if (IsValid() && m_rate.IsValid()) { - double dt = (double)(::wxGetUTCTimeMillis().GetValue() - m_t0) / 1000.; + double dt = (double) (::wxGetUTCTimeMillis().GetValue() - m_t0) / 1000.; X = m_x0 + m_rate.X * dt; Y = m_y0 + m_rate.Y * dt; } diff --git a/src/polardrift_tool.h b/src/polardrift_tool.h index b4df4eeb7..2b01dbff3 100644 --- a/src/polardrift_tool.h +++ b/src/polardrift_tool.h @@ -37,6 +37,7 @@ class PolarDriftTool { PolarDriftTool() = delete; + public: static wxWindow *CreatePolarDriftToolWindow(); static bool UpdateState(); diff --git a/src/polardrift_toolwin.cpp b/src/polardrift_toolwin.cpp index c1f79c701..07430c3c6 100644 --- a/src/polardrift_toolwin.cpp +++ b/src/polardrift_toolwin.cpp @@ -63,14 +63,13 @@ wxWindow *PolarDriftTool::CreatePolarDriftToolWindow() if (pFrame->GetCameraPixelScale() == 1.0) { - bool confirmed = ConfirmDialog::Confirm(_( - "The Polar Drift Align tool is most effective when PHD2 knows your guide\n" - "scope focal length and camera pixel size.\n" - "\n" - "Enter your guide scope focal length on the Global tab in the Brain.\n" - "Enter your camera pixel size on the Camera tab in the Brain.\n" - "\n" - "Would you like to run the tool anyway?"), + bool confirmed = ConfirmDialog::Confirm(_("The Polar Drift Align tool is most effective when PHD2 knows your guide\n" + "scope focal length and camera pixel size.\n" + "\n" + "Enter your guide scope focal length on the Global tab in the Brain.\n" + "Enter your camera pixel size on the Camera tab in the Brain.\n" + "\n" + "Would you like to run the tool anyway?"), "/rotate_tool_without_pixscale"); if (!confirmed) @@ -109,8 +108,9 @@ bool PolarDriftTool::UpdateState() } PolarDriftToolWin::PolarDriftToolWin() -: wxFrame(pFrame, wxID_ANY, _("Polar Drift Alignment"), wxDefaultPosition, wxDefaultSize, -wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxFRAME_FLOAT_ON_PARENT | wxFRAME_NO_TASKBAR | wxRESIZE_BORDER ) + : wxFrame(pFrame, wxID_ANY, _("Polar Drift Alignment"), wxDefaultPosition, wxDefaultSize, + wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxFRAME_FLOAT_ON_PARENT | + wxFRAME_NO_TASKBAR | wxRESIZE_BORDER) { m_t0 = 0; m_sumt = m_sumt2 = m_sumx = m_sumx2 = m_sumy = m_sumy2 = m_sumtx = m_sumty = m_sumxy = 0.0; @@ -119,15 +119,15 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF m_drifting = false; m_pxScale = pFrame->GetCameraPixelScale(); -// Fullsize is easier but the camera simulator does not set this. -// wxSize camsize = pCamera->FullSize; -// g_camWidth = pCamera->FullSize.GetWidth() == 0 ? xpx: pCamera->FullSize.GetWidth(); + // Fullsize is easier but the camera simulator does not set this. + // wxSize camsize = pCamera->FullSize; + // g_camWidth = pCamera->FullSize.GetWidth() == 0 ? xpx: pCamera->FullSize.GetWidth(); -// g_camAngle = 0.0; -// if (pMount && pMount->IsConnected() && pMount->IsCalibrated()) -// { -// g_camAngle = degrees(pMount->xAngle()); -// } + // g_camAngle = 0.0; + // if (pMount && pMount->IsConnected() && pMount->IsCalibrated()) + // { + // g_camAngle = degrees(pMount->xAngle()); + // } m_hemi = pConfig->Profile.GetInt("/PolarDriftTool/Hemisphere", 1); if (pPointingSource) @@ -152,16 +152,14 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF // a horizontal box sizer for the bitmap and the instructions wxBoxSizer *instrSizer = new wxBoxSizer(wxHORIZONTAL); - c_instr = _( - "Slew to near the Celestial Pole.\n" - "Make sure tracking is ON.\n" - "Select a guide star on the main display.\n" - "Click Start.\n" - "Wait for the display to stabilise.\n" - "Click Stop.\n" - "Adjust your mount's altitude and azimuth to place " - "the guide star in its target circle.\n" - ); + c_instr = _("Slew to near the Celestial Pole.\n" + "Make sure tracking is ON.\n" + "Select a guide star on the main display.\n" + "Click Start.\n" + "Wait for the display to stabilise.\n" + "Click Stop.\n" + "Adjust your mount's altitude and azimuth to place " + "the guide star in its target circle.\n"); m_instructionsText = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(280, 240), wxALIGN_LEFT); #ifdef __WXOSX__ @@ -182,7 +180,7 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF wxStaticText *txt; -// First row of grid + // First row of grid int gridRow = 0; txt = new wxStaticText(this, wxID_ANY, _("Hemisphere"), wxDefaultPosition, wxDefaultSize, 0); txt->Wrap(-1); @@ -199,7 +197,7 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF gridRow++; m_mirrorCheck = new wxCheckBox(this, ID_MIRROR, _("Mirror image")); gbSizer->Add(m_mirrorCheck, wxGBPosition(gridRow, 0), wxGBSpan(1, 1), wxALL | wxALIGN_BOTTOM, 5); - m_mirrorCheck->SetValue(m_mirror==-1?true:false); + m_mirrorCheck->SetValue(m_mirror == -1 ? true : false); m_mirrorCheck->SetToolTip(_("The image is mirrored e.g. from OAG")); m_startButton = new wxButton(this, ID_START, _("Start"), wxDefaultPosition, wxDefaultSize, 0); @@ -264,22 +262,24 @@ void PolarDriftToolWin::OnHemi(wxCommandEvent& evt) void PolarDriftToolWin::OnMirror(wxCommandEvent& evt) { - int i_mirror = m_mirrorCheck->IsChecked()? -1: 1; + int i_mirror = m_mirrorCheck->IsChecked() ? -1 : 1; pConfig->Profile.SetInt("/PolarDriftTool/Mirror", i_mirror); if (i_mirror != m_mirror) { - m_mirror = i_mirror; + m_mirror = i_mirror; } FillPanel(); } void PolarDriftToolWin::OnStart(wxCommandEvent& evt) { - if (m_drifting){ // STOP drifting + if (m_drifting) + { // STOP drifting m_drifting = false; SetStatusText(_("Polar Drift alignment stopped")); Debug.AddLine(wxString::Format("Polar Drift alignment stopped")); - SetStatusText(wxString::Format(_("PA err(arcmin): %.1f Angle (deg): %.1f"), m_offset*m_pxScale / 60, norm(-m_alpha, -180, 180))); + SetStatusText(wxString::Format( + _("PA err(arcmin): %.1f Angle (deg): %.1f"), m_offset * m_pxScale / 60, norm(-m_alpha, -180, 180))); FillPanel(); if (pMount) { @@ -353,7 +353,8 @@ void PolarDriftToolWin::FillPanel() m_instructionsText->SetLabel(c_instr); m_startButton->SetLabel(_("Start")); - if (m_drifting) { + if (m_drifting) + { m_startButton->SetLabel(_("Stop")); } m_hemiChoice->Enable(true); @@ -367,8 +368,8 @@ void PolarDriftToolWin::FillPanel() } } m_hemiChoice->SetSelection(m_hemi > 0 ? 0 : 1); -// w_camScale->SetValue(wxString::Format("%+.3f", m_pxScale)); -// w_camRot->SetValue(wxString::Format("%+.3f", g_camAngle)); + // w_camScale->SetValue(wxString::Format("%+.3f", m_pxScale)); + // w_camRot->SetValue(wxString::Format("%+.3f", g_camAngle)); Layout(); } @@ -382,8 +383,8 @@ void PolarDriftToolWin::PaintHelper(wxAutoBufferedPaintDCBase& dc, double scale) // Draw adjustment lines for placing the guide star in its correct position relative to the CoR // Blue (azimuth) and Red (altitude) dc.SetPen(wxPen(wxColor(255, 0, 0), 1, wxPENSTYLE_SOLID)); - dc.DrawLine(m_current.X*scale, m_current.Y*scale, m_target.X*scale, m_target.Y*scale); - dc.DrawCircle(m_target.X*scale, m_target.Y*scale, 10*scale); + dc.DrawLine(m_current.X * scale, m_current.Y * scale, m_target.X * scale, m_target.Y * scale); + dc.DrawCircle(m_target.X * scale, m_target.Y * scale, 10 * scale); } bool PolarDriftToolWin::WatchDrift() @@ -392,7 +393,7 @@ bool PolarDriftToolWin::WatchDrift() // Calculate a least squares fit of the drift agains time along each sensor axis // Calculate the tangential ditance of that movement // Mark the starting position then rotate the mount - double tnow = ::wxGetUTCTimeMillis().GetValue()/1000.0; + double tnow = ::wxGetUTCTimeMillis().GetValue() / 1000.0; m_current = pFrame->pGuider->CurrentPosition(); m_num++; if (m_num <= 1) @@ -403,36 +404,38 @@ bool PolarDriftToolWin::WatchDrift() } tnow -= m_t0; m_sumt += tnow; - m_sumt2 += tnow*tnow; + m_sumt2 += tnow * tnow; m_sumx += m_current.X; m_sumx2 += m_current.X * m_current.X; m_sumy += m_current.Y; - m_sumy2 += m_current.Y*m_current.Y; + m_sumy2 += m_current.Y * m_current.Y; m_sumtx += tnow * m_current.X; m_sumty += tnow * m_current.Y; m_sumxy += m_current.X * m_current.Y; - if (m_num <= 1) return true; + if (m_num <= 1) + return true; const double factor = 24 * 3600 / 2 / M_PI; // approx 13751: seconds per radian - double xslope = (m_num*m_sumtx - m_sumt*m_sumx) / (m_num*m_sumt2 - m_sumt*m_sumt); - double yslope = (m_num*m_sumty - m_sumt*m_sumy) / (m_num*m_sumt2 - m_sumt*m_sumt); + double xslope = (m_num * m_sumtx - m_sumt * m_sumx) / (m_num * m_sumt2 - m_sumt * m_sumt); + double yslope = (m_num * m_sumty - m_sumt * m_sumy) / (m_num * m_sumt2 - m_sumt * m_sumt); double theta = degrees(atan2(yslope, xslope)); // In the northern hemisphere the star rotates clockwise, in the southern hemisphere anti-clockwise - // In NH the pole is to the right of the drift vector (-90 degrees) however in pixel terms (Y +ve down) it is to the left (+90 degrees) - // So we multiply by m_hemi to get the correct direction + // In NH the pole is to the right of the drift vector (-90 degrees) however in pixel terms (Y +ve down) it is to the left + // (+90 degrees) So we multiply by m_hemi to get the correct direction m_alpha = theta + m_hemi * 90 * m_mirror; // direction to the pole - m_offset = hypot(xslope, yslope)*factor; //polar alignment error in pixels - m_target = PHD_Point(m_current.X + m_offset*cos(radians(m_alpha)), m_current.Y + m_offset*(sin(radians(m_alpha)))); + m_offset = hypot(xslope, yslope) * factor; // polar alignment error in pixels + m_target = PHD_Point(m_current.X + m_offset * cos(radians(m_alpha)), m_current.Y + m_offset * (sin(radians(m_alpha)))); Debug.AddLine(wxString::Format("Polar Drift: m_hemi %d m_mirror %d m_pxScale %.1f", m_hemi, m_mirror, m_pxScale)); - Debug.AddLine(wxString::Format("Polar Drift: m_num %d m_t0 %.1f tnow %.1f m_current(X,Y): %.1f,%.1f", m_num, m_t0, tnow, - m_current.X, m_current.Y)); - Debug.AddLine(wxString::Format("Polar Drift: slope(X,Y) %.4f,%.4f m_offset %.1f theta %.1f m_alpha %.1f", xslope, yslope, m_offset, theta, m_alpha)); + Debug.AddLine(wxString::Format( + "Polar Drift: m_num %d m_t0 %.1f tnow %.1f m_current(X,Y): %.1f,%.1f", m_num, m_t0, tnow, m_current.X, m_current.Y)); + Debug.AddLine(wxString::Format( + "Polar Drift: slope(X,Y) %.4f,%.4f m_offset %.1f theta %.1f m_alpha %.1f", xslope, yslope, m_offset, theta, m_alpha)); Debug.AddLine(wxString::Format("Polar Drift: m_target(X,Y) %.1f,%.1f", m_target.X, m_target.Y)); SetStatusText(wxString::Format(_("Time %.fs"), tnow), 0); - SetStatusText(wxString::Format(_("PA Err: %.f min"), m_offset*m_pxScale / 60), 1); + SetStatusText(wxString::Format(_("PA Err: %.f min"), m_offset * m_pxScale / 60), 1); SetStatusText(wxString::Format(_("Angle: %.f deg"), norm(-m_alpha, -180, 180)), 2); return true; diff --git a/src/polardrift_toolwin.h b/src/polardrift_toolwin.h index 9162837ae..fc51ff4d4 100644 --- a/src/polardrift_toolwin.h +++ b/src/polardrift_toolwin.h @@ -49,13 +49,13 @@ struct PolarDriftToolWin : public wxFrame Tool window controls */ wxStaticText *m_instructionsText; - wxButton *m_startButton; // Button to start or stop drift + wxButton *m_startButton; // Button to start or stop drift wxStaticText *m_notesLabel; wxTextCtrl *w_notesText; - wxButton *m_closeButton; // Close button + wxButton *m_closeButton; // Close button wxStatusBar *m_statusBar; - wxChoice *m_hemiChoice; // Listbox for manual hemisphere choice - wxCheckBox *m_mirrorCheck; // Checkbox for mirrored camera + wxChoice *m_hemiChoice; // Listbox for manual hemisphere choice + wxCheckBox *m_mirrorCheck; // Checkbox for mirrored camera bool m_savePrimaryMountEnabled; bool m_saveSecondaryMountEnabled; bool m_guideOutputDisabled; @@ -73,12 +73,12 @@ struct PolarDriftToolWin : public wxFrame ID_CLOSE, }; - double m_pxScale; // Camera pixel scale + double m_pxScale; // Camera pixel scale - int m_hemi; // Hemisphere of the observer - int m_mirror; // -1 if the image is mirrored e.g. due to OAG + int m_hemi; // Hemisphere of the observer + int m_mirror; // -1 if the image is mirrored e.g. due to OAG - bool m_drifting; // Indicates that alignment points are being collected + bool m_drifting; // Indicates that alignment points are being collected double m_t0; double m_sumt, m_sumt2, m_sumx, m_sumx2, m_sumy, m_sumy2, m_sumtx, m_sumty, m_sumxy; long m_num; @@ -93,7 +93,7 @@ struct PolarDriftToolWin : public wxFrame void OnCloseBtn(wxCommandEvent& evt); void OnClose(wxCloseEvent& evt); - bool IsDrifting(){ return m_drifting; }; + bool IsDrifting() { return m_drifting; }; bool WatchDrift(); void PaintHelper(wxAutoBufferedPaintDCBase& dc, double scale); @@ -101,4 +101,3 @@ struct PolarDriftToolWin : public wxFrame }; #endif - diff --git a/src/profile_wizard.cpp b/src/profile_wizard.cpp index ffcfec880..08b18602d 100644 --- a/src/profile_wizard.cpp +++ b/src/profile_wizard.cpp @@ -52,7 +52,8 @@ class ProfileWizard : public wxDialog STATE_AO, STATE_ROTATOR, STATE_WRAPUP, - STATE_DONE, NUM_PAGES = STATE_DONE + STATE_DONE, + NUM_PAGES = STATE_DONE }; enum CtrlIds @@ -98,7 +99,7 @@ class ProfileWizard : public wxDialog wxCheckBox *m_pLaunchDarks; wxCheckBox *m_pAutoRestore; wxStatusBar *m_pStatusBar; - wxHyperlinkCtrl* m_EqLink; + wxHyperlinkCtrl *m_EqLink; wxString m_SelectedCamera; wxString m_SelectedMount; @@ -136,7 +137,6 @@ class ProfileWizard : public wxDialog bool m_autoRestore; public: - bool m_launchDarks; ProfileWizard(wxWindow *parent, bool showGreeting); @@ -190,25 +190,29 @@ static void AddCellPair(wxWindow *parent, wxGridBagSizer *gbs, int row, const wx gbs->Add(ctrl, wxGBPosition(row, 2), wxDefaultSpan, wxALL, 5); } -ProfileWizard::ProfileWizard(wxWindow *parent, bool showGreeting) : - wxDialog(parent, wxID_ANY, _("New Profile Wizard"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX), - m_useCamera(false), m_useMount(false), m_useAuxMount(false), m_autoRestore(false), m_launchDarks(true) +ProfileWizard::ProfileWizard(wxWindow *parent, bool showGreeting) + : wxDialog(parent, wxID_ANY, _("New Profile Wizard"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) + , m_useCamera(false) + , m_useMount(false) + , m_useAuxMount(false) + , m_autoRestore(false) + , m_launchDarks(true) { TitlePrefix = _("New Profile Wizard - "); // Create overall vertical sizer m_pvSizer = new wxBoxSizer(wxVERTICAL); -# include "icons/phd2_48.png.h" +#include "icons/phd2_48.png.h" wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_48)); m_bitmaps[STATE_GREETINGS] = new wxBitmap(phd2); m_bitmaps[STATE_WRAPUP] = new wxBitmap(phd2); -# include "icons/cam2.xpm" +#include "icons/cam2.xpm" m_bitmaps[STATE_CAMERA] = new wxBitmap(cam_icon); -# include "icons/scope1.xpm" +#include "icons/scope1.xpm" m_bitmaps[STATE_MOUNT] = new wxBitmap(scope_icon); m_bitmaps[STATE_AUXMOUNT] = new wxBitmap(scope_icon); -# include "icons/ao.xpm" +#include "icons/ao.xpm" m_bitmaps[STATE_AO] = new wxBitmap(ao_xpm); m_bitmaps[STATE_ROTATOR] = new wxBitmap(phd2); @@ -218,7 +222,8 @@ ProfileWizard::ProfileWizard(wxWindow *parent, bool showGreeting) : m_bitmap = new wxStaticBitmap(this, wxID_ANY, *m_bitmaps[STATE_GREETINGS], wxDefaultPosition, wxSize(55, 55)); instrSizer->Add(m_bitmap, 0, wxALIGN_CENTER_VERTICAL | wxFIXED_MINSIZE, 5); - m_pInstructions = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(DialogWidth, 75), wxALIGN_LEFT | wxST_NO_AUTORESIZE); + m_pInstructions = new wxStaticText( + this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(DialogWidth, 75), wxALIGN_LEFT | wxST_NO_AUTORESIZE); wxFont font = m_pInstructions->GetFont(); font.SetWeight(wxFONTWEIGHT_BOLD); m_pInstructions->SetFont(font); @@ -239,35 +244,38 @@ ProfileWizard::ProfileWizard(wxWindow *parent, bool showGreeting) : // Gear label and combo box m_pGearGrid = new wxFlexGridSizer(1, 2, 5, 15); m_pGearLabel = new wxStaticText(this, wxID_ANY, "Temp:", wxDefaultPosition, wxDefaultSize); - m_pGearChoice = new wxChoice(this, ID_COMBO, wxDefaultPosition, wxDefaultSize, - GuideCamera::GuideCameraList(), 0, wxDefaultValidator, _("Gear")); + m_pGearChoice = new wxChoice( + this, ID_COMBO, wxDefaultPosition, wxDefaultSize, GuideCamera::GuideCameraList(), 0, wxDefaultValidator, _("Gear")); m_pGearGrid->Add(m_pGearLabel, 1, wxALL, 5); m_pGearGrid->Add(m_pGearChoice, 1, wxLEFT, 10); m_pvSizer->Add(m_pGearGrid, wxSizerFlags().Center().Border(wxALL, 5)); - m_pUserProperties = new wxGridBagSizer(6,5); + m_pUserProperties = new wxGridBagSizer(6, 5); // Pixel-size m_pPixelSize = pFrame->MakeSpinCtrlDouble(this, ID_PIXELSIZE, wxEmptyString, wxDefaultPosition, wxSize(StringWidth(this, _T("888.88")), -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.1); m_pPixelSize->SetDigits(2); m_PixelSize = m_pPixelSize->GetValue(); - m_pPixelSize->SetToolTip(_("Get this value from your camera documentation or from an online source. You can use the up/down control " - "or type in a value directly. If the pixels aren't square, just enter the larger of the X/Y dimensions.")); - AddCellPair(this, m_pUserProperties, 0, wxString::Format(_("Guide camera un-binned pixel size (%s)"), MICRONS_SYMBOL), m_pPixelSize); + m_pPixelSize->SetToolTip( + _("Get this value from your camera documentation or from an online source. You can use the up/down control " + "or type in a value directly. If the pixels aren't square, just enter the larger of the X/Y dimensions.")); + AddCellPair(this, m_pUserProperties, 0, wxString::Format(_("Guide camera un-binned pixel size (%s)"), MICRONS_SYMBOL), + m_pPixelSize); // Binning wxArrayString opts; GuideCamera::GetBinningOpts(4, &opts); m_pBinningLevel = new wxChoice(this, ID_BINNING, wxDefaultPosition, wxDefaultSize, opts); m_pBinningLevel->SetToolTip(_("If your camera supports binning (many do not), you can choose a binning value > 1. " - "With long focal length guide scopes and OAGs, binning can allow use of fainter guide " - "stars. For more common setups, it's better to leave binning at 1.")); + "With long focal length guide scopes and OAGs, binning can allow use of fainter guide " + "stars. For more common setups, it's better to leave binning at 1.")); m_pBinningLevel->SetSelection(0); m_pBits8 = new wxRadioButton(this, wxID_ANY, _("8-bit")); m_pBits8->SetToolTip(_("Choose this if your guide camera driver downloads 8-bit data")); m_pBits16 = new wxRadioButton(this, wxID_ANY, _("16-bit")); - m_pBits16->SetToolTip(_("Choose this if your guide camera driver downoads 16-bit data. Requires a camera with 10, 12, 14 or 16-bit ADC electronics")); + m_pBits16->SetToolTip(_("Choose this if your guide camera driver downoads 16-bit data. Requires a camera with 10, 12, 14 " + "or 16-bit ADC electronics")); wxBoxSizer *sz = new wxBoxSizer(wxHORIZONTAL); sz->Add(Label(this, _("Binning level")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); sz->Add(m_pBinningLevel, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); @@ -280,17 +288,18 @@ ProfileWizard::ProfileWizard(wxWindow *parent, bool showGreeting) : m_pUserProperties->Add(sz2, wxGBPosition(2, 1), wxDefaultSpan, 0, 0); // Focal length m_pFocalLength = pFrame->MakeSpinCtrlDouble(this, ID_FOCALLENGTH, wxEmptyString, wxDefaultPosition, - wxSize(StringWidth(this, _T("888888")), -1), wxSP_ARROW_KEYS, - 0, AdvancedDialog::MAX_FOCAL_LENGTH, 0.0, 50.0); + wxSize(StringWidth(this, _T("888888")), -1), wxSP_ARROW_KEYS, 0, AdvancedDialog::MAX_FOCAL_LENGTH, 0.0, 50.0); m_pFocalLength->SetValue(0); m_pFocalLength->SetDigits(0); - m_pFocalLength->SetToolTip(_("This is the focal length of the guide scope - or the imaging scope if you are using an off-axis-guider or " - "adaptive optics device (Focal length = aperture x f-ratio). Typical finder scopes have a focal length of about 165mm.")); - m_FocalLength = (int)m_pFocalLength->GetValue(); + m_pFocalLength->SetToolTip( + _("This is the focal length of the guide scope - or the imaging scope if you are using an off-axis-guider or " + "adaptive optics device (Focal length = aperture x f-ratio). Typical finder scopes have a focal length of about " + "165mm.")); + m_FocalLength = (int) m_pFocalLength->GetValue(); AddCellPair(this, m_pUserProperties, 3, _("Guide scope focal length (mm)"), m_pFocalLength); // pixel scale -# include "icons/transparent24.png.h" +#include "icons/transparent24.png.h" wxBitmap transparent(wxBITMAP_PNG_FROM_DATA(transparent24)); m_scaleIcon = new wxStaticBitmap(this, wxID_ANY, transparent); m_pUserProperties->Add(m_scaleIcon, wxGBPosition(3, 0)); @@ -304,18 +313,22 @@ ProfileWizard::ProfileWizard(wxWindow *parent, bool showGreeting) : // controls for the mount pane wxBoxSizer *mtSizer = new wxBoxSizer(wxHORIZONTAL); m_pMountProperties = new wxFlexGridSizer(1, 2, 5, 15); - m_pGuideSpeed = new wxSpinCtrlDouble(this, ID_GUIDESPEED, wxEmptyString, wxDefaultPosition, - wxDefaultSize, wxSP_ARROW_KEYS, 0.2, 1.0, 0.5, 0.1); + m_pGuideSpeed = new wxSpinCtrlDouble( + this, ID_GUIDESPEED, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 0.2, 1.0, 0.5, 0.1); m_GuideSpeed = Scope::DEFAULT_MOUNT_GUIDE_SPEED; m_pGuideSpeed->SetValue(m_GuideSpeed); m_pGuideSpeed->SetDigits(2); - m_pGuideSpeed->SetToolTip(wxString::Format(_("The mount guide speed you will use for calibration and guiding, expressed as a multiple of the sidereal rate. If you " - "don't know, leave the setting at the default value (%0.1fX), which should produce a successful calibration in most cases"), Scope::DEFAULT_MOUNT_GUIDE_SPEED)); + m_pGuideSpeed->SetToolTip(wxString::Format(_("The mount guide speed you will use for calibration and guiding, expressed as " + "a multiple of the sidereal rate. If you " + "don't know, leave the setting at the default value (%0.1fX), which should " + "produce a successful calibration in most cases"), + Scope::DEFAULT_MOUNT_GUIDE_SPEED)); mtSizer->Add(m_pGuideSpeed, 1); AddTableEntryPair(this, m_pMountProperties, _("Mount guide speed (n.n x sidereal)"), mtSizer); m_pHPEncoders = new wxCheckBox(this, wxID_ANY, _("Mount has high-precision encoders")); - m_pHPEncoders->SetToolTip(_("Mount has high-precision encoders on both axes with little or no Dec backlash (e.g. 10Micron, Astro-Physics AE, Planewave, iOptron EC2 or other high-end mounts")); + m_pHPEncoders->SetToolTip(_("Mount has high-precision encoders on both axes with little or no Dec backlash (e.g. 10Micron, " + "Astro-Physics AE, Planewave, iOptron EC2 or other high-end mounts")); m_pHPEncoders->SetValue(false); m_pMountProperties->Add(m_pHPEncoders); @@ -325,14 +338,15 @@ ProfileWizard::ProfileWizard(wxWindow *parent, bool showGreeting) : // Wrapup panel m_pWrapUp = new wxFlexGridSizer(2, 2, 5, 15); - m_pProfileName = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(250,-1)); + m_pProfileName = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(250, -1)); m_pLaunchDarks = new wxCheckBox(this, wxID_ANY, _("Build dark library")); m_pLaunchDarks->SetValue(m_launchDarks); m_pLaunchDarks->SetToolTip(_("Check this to automatically start the process of building a dark library for this profile.")); m_pAutoRestore = new wxCheckBox(this, wxID_ANY, _("Auto restore calibration")); m_pAutoRestore->SetValue(m_autoRestore); m_pAutoRestore->SetToolTip(_("Check this to automatically re-use the last calibration when the profile is loaded. " - "For this to work, the rotational orientation of the guide camera and all other optical properties of the guiding setup must remain the same between imaging sessions.")); + "For this to work, the rotational orientation of the guide camera and all other optical " + "properties of the guiding setup must remain the same between imaging sessions.")); AddTableEntryPair(this, m_pWrapUp, _("Profile Name"), m_pProfileName); m_pWrapUp->Add(m_pLaunchDarks, wxSizerFlags().Border(wxTOP, 5).Border(wxLEFT, 10)); m_pWrapUp->Add(m_pAutoRestore, wxSizerFlags().Align(wxALIGN_RIGHT)); @@ -343,21 +357,15 @@ ProfileWizard::ProfileWizard(wxWindow *parent, bool showGreeting) : m_pPrevBtn = new wxButton(this, ID_PREV, _("< Back")); m_pPrevBtn->SetToolTip(_("Back up to the previous screen")); - wxButton* helpBtn = new wxButton(this, ID_HELP, _("Help")); + wxButton *helpBtn = new wxButton(this, ID_HELP, _("Help")); m_pNextBtn = new wxButton(this, ID_NEXT, _("Next >")); m_pNextBtn->SetToolTip(_("Move forward to next screen")); pButtonSizer->AddStretchSpacer(); - pButtonSizer->Add( - m_pPrevBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 5)); - pButtonSizer->Add( - helpBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 5)); - pButtonSizer->Add( - m_pNextBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 5)); + pButtonSizer->Add(m_pPrevBtn, wxSizerFlags(0).Align(0).Border(wxALL, 5)); + pButtonSizer->Add(helpBtn, wxSizerFlags(0).Align(0).Border(wxALL, 5)); + pButtonSizer->Add(m_pNextBtn, wxSizerFlags(0).Align(0).Border(wxALL, 5)); m_pvSizer->Add(pButtonSizer, wxSizerFlags().Expand().Border(wxALL, 10)); m_pvSizer->Add(m_pStatusBar, 0, wxGROW); @@ -395,52 +403,75 @@ void ProfileWizard::ShowHelp(DialogState state) switch (m_State) { case STATE_GREETINGS: - hText = _("This short sequence of steps will help you identify the equipment you want to use for guiding and will associate it with a profile name of your choice. " - "This profile will then be available any time you run PHD2. At a minimum, you will need to choose both the guide camera and the mount interface that PHD2 will use for guiding. " - "You will also enter some information about the optical characteristics of your setup. " - "PHD2 will use this to create a good 'starter set' of guiding and calibration " - "parameters. If you are a new user, please review the 'Basic Use' section of the 'Help' guide after the wizard dialog has finished."); + hText = _("This short sequence of steps will help you identify the equipment you want to use for guiding and will " + "associate it with a profile name of your choice. " + "This profile will then be available any time you run PHD2. At a minimum, you will need to choose both the " + "guide camera and the mount interface that PHD2 will use for guiding. " + "You will also enter some information about the optical characteristics of your setup. " + "PHD2 will use this to create a good 'starter set' of guiding and calibration " + "parameters. If you are a new user, please review the 'Basic Use' section of the 'Help' guide after the " + "wizard dialog has finished."); break; case STATE_CAMERA: - hText = _("Select your guide camera from the list. All cameras supported by PHD2 and all installed ASCOM cameras are shown. If your camera is not shown, " - "it is either not supported by PHD2 or its camera driver is not installed. " - " PHD2 needs to know the camera pixel size and guide scope focal length in order to compute reasonable guiding parameters. " - " When you choose a camera, you'll be given the option to connect to it immediately to get the pixel-size automatically. " - " You can also choose a binning-level if your camera supports binning." ); + hText = _("Select your guide camera from the list. All cameras supported by PHD2 and all installed ASCOM cameras are " + "shown. If your camera is not shown, " + "it is either not supported by PHD2 or its camera driver is not installed. " + " PHD2 needs to know the camera pixel size and guide scope focal length in order to compute reasonable " + "guiding parameters. " + " When you choose a camera, you'll be given the option to connect to it immediately to get the pixel-size " + "automatically. " + " You can also choose a binning-level if your camera supports binning."); break; case STATE_MOUNT: - hText = wxString::Format(_("Select your mount interface from the list. This determines how PHD2 will send guide commands to the mount. For most modern " - "mounts, the ASCOM interface is a good choice if you are running MS Windows. The other interfaces are available for " - "cases where ASCOM isn't available or isn't well supported by mount firmware. If you know the mount guide speed, you can specify it " - " so PHD2 can calibrate more efficiently. If you don't know the mount guide speed, you can just use the default value of %0.1fx. When you choose a " - " mount, you'll usually be given the option to connect to it immediately so PHD2 can read the guide speed for you."), Scope::DEFAULT_MOUNT_GUIDE_SPEED ); + hText = wxString::Format(_("Select your mount interface from the list. This determines how PHD2 will send guide " + "commands to the mount. For most modern " + "mounts, the ASCOM interface is a good choice if you are running MS Windows. The other " + "interfaces are available for " + "cases where ASCOM isn't available or isn't well supported by mount firmware. If you know " + "the mount guide speed, you can specify it " + " so PHD2 can calibrate more efficiently. If you don't know the mount guide speed, you can " + "just use the default value of %0.1fx. When you choose a " + " mount, you'll usually be given the option to connect to it immediately so PHD2 can read " + "the guide speed for you."), + Scope::DEFAULT_MOUNT_GUIDE_SPEED); break; case STATE_AUXMOUNT: if (m_SelectedCamera == _("Simulator")) { - hText = _("The 'simulator' camera/mount interface doesn't provide pointing information, so PHD2 will not be able to automatically adjust " - "guiding for side-of-pier and declination. You can enable these features by choosing an 'Aux Mount' connection that does provide pointing " - "information."); + hText = _("The 'simulator' camera/mount interface doesn't provide pointing information, so PHD2 will not be able " + "to automatically adjust " + "guiding for side-of-pier and declination. You can enable these features by choosing an 'Aux Mount' " + "connection that does provide pointing " + "information."); } else { - hText = _("The mount interface you chose in the previous step doesn't provide pointing information, so PHD2 will not be able to automatically adjust " - "guiding for side-of-pier and declination. You can enable these features by choosing an 'Aux Mount' connection that does provide pointing " + hText = _( + "The mount interface you chose in the previous step doesn't provide pointing information, so PHD2 will not be " + "able to automatically adjust " + "guiding for side-of-pier and declination. You can enable these features by choosing an 'Aux Mount' connection " + "that does provide pointing " "information. The Aux Mount interface will be used only for that purpose and not for sending guide commands."); } break; case STATE_AO: - hText = _("If you have an adaptive optics (AO) device, you can select it here. The AO device will be used for high speed, small guiding corrections, " - "while the mount interface you chose earlier will be used for larger ('bump') corrections. Calibration of both interfaces will be handled automatically."); + hText = _("If you have an adaptive optics (AO) device, you can select it here. The AO device will be used for high " + "speed, small guiding corrections, " + "while the mount interface you chose earlier will be used for larger ('bump') corrections. Calibration of " + "both interfaces will be handled automatically."); break; case STATE_ROTATOR: - hText = _("If you have an ASCOM or INDI-compatible rotator device, you can select it here. This will allow PHD2 to automatically adjust calibration when the rotator " + hText = _("If you have an ASCOM or INDI-compatible rotator device, you can select it here. This will allow PHD2 to " + "automatically adjust calibration when the rotator " "is moved. Otherwise, any change in rotator position will require a re-calibration in PHD2"); break; case STATE_WRAPUP: - hText = _("Your profile is complete and ready to save. Give it a name and, optionally, build a dark-frame library for it. This is strongly " + hText = _( + "Your profile is complete and ready to save. Give it a name and, optionally, build a dark-frame library for it. " + "This is strongly " "recommended for best results. If your setup is stable from one night to the next, you can choose to automatically " - "re-use the last calibration when you load this profile. If you are new to PHD2 or encounter problems, please use the 'Help' function for assistance."); + "re-use the last calibration when you load this profile. If you are new to PHD2 or encounter problems, please use " + "the 'Help' function for assistance."); case STATE_DONE: break; } @@ -476,7 +507,7 @@ enum ConfigWarningTypes // Dialog for warning user about poor config choices struct ConfigSuggestionDlg : public wxDialog { - ConfigSuggestionDlg(ConfigWarningTypes Type, wxHyperlinkCtrl* m_EqLink); + ConfigSuggestionDlg(ConfigWarningTypes Type, wxHyperlinkCtrl *m_EqLink); ConfigSuggestionResults UserChoice; void OnBack(wxCommandEvent& evt); void OnProceed(wxCommandEvent& evt); @@ -484,35 +515,40 @@ struct ConfigSuggestionDlg : public wxDialog void OnURLClicked(wxHyperlinkEvent& event); }; -ConfigSuggestionDlg::ConfigSuggestionDlg(ConfigWarningTypes Type, wxHyperlinkCtrl* m_EqLink) : wxDialog(pFrame, wxID_ANY, _("Configuration Suggestion")) +ConfigSuggestionDlg::ConfigSuggestionDlg(ConfigWarningTypes Type, wxHyperlinkCtrl *m_EqLink) + : wxDialog(pFrame, wxID_ANY, _("Configuration Suggestion")) { - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); - wxStaticText* explanation = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT); - wxStaticText* wikiLoc; + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); + wxStaticText *explanation = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT); + wxStaticText *wikiLoc; wxString msg; if (Type == eNoPointingInfo) - msg = _("This configuration doesn't provide PHD2 with any information about the scope's pointing position. This means you will need to recalibrate\n" - "whenever the scope is slewed, and some PHD2 features will be disabled. You should choose an ASCOM or INDI mount connection\n" - "for either 'mount' or 'aux-mount' unless there are no drivers available for your mount.\n" - "Please review the Help guide on 'Equipment Connections' for more details."); + msg = _("This configuration doesn't provide PHD2 with any information about the scope's pointing position. This means " + "you will need to recalibrate\n" + "whenever the scope is slewed, and some PHD2 features will be disabled. You should choose an ASCOM or INDI " + "mount connection\n" + "for either 'mount' or 'aux-mount' unless there are no drivers available for your mount.\n" + "Please review the Help guide on 'Equipment Connections' for more details."); else if (Type == eEQModMount) { - msg = wxString::Format(_("Please make sure the EQMOD ASCOM settings are configured for PHD2 according to this document: \n"), ""); - wikiLoc = new wxStaticText (this, wxID_ANY, "https://github.com/OpenPHDGuiding/phd2/wiki/EQASCOM-Settings"); - m_EqLink = new wxHyperlinkCtrl(this, wxID_ANY, _("Open EQMOD document..."), "https://github.com/OpenPHDGuiding/phd2/wiki/EQASCOM-Settings"); + msg = wxString::Format( + _("Please make sure the EQMOD ASCOM settings are configured for PHD2 according to this document: \n"), ""); + wikiLoc = new wxStaticText(this, wxID_ANY, "https://github.com/OpenPHDGuiding/phd2/wiki/EQASCOM-Settings"); + m_EqLink = new wxHyperlinkCtrl( + this, wxID_ANY, _("Open EQMOD document..."), "https://github.com/OpenPHDGuiding/phd2/wiki/EQASCOM-Settings"); m_EqLink->Connect(wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler(ConfigSuggestionDlg::OnURLClicked), nullptr, this); } explanation->SetLabelText(msg); - wxButton* backBtn = new wxButton(this, wxID_ANY, _("Go Back")); + wxButton *backBtn = new wxButton(this, wxID_ANY, _("Go Back")); backBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ConfigSuggestionDlg::OnBack), NULL, this); - wxButton* proceedBtn = new wxButton(this, wxID_ANY, _("Proceed")); + wxButton *proceedBtn = new wxButton(this, wxID_ANY, _("Proceed")); proceedBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ConfigSuggestionDlg::OnProceed), NULL, this); - wxButton* dontAskBtn = new wxButton(this, wxID_ANY, _("Don't Ask")); + wxButton *dontAskBtn = new wxButton(this, wxID_ANY, _("Don't Ask")); dontAskBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ConfigSuggestionDlg::OnDontAsk), NULL, this); - wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); + wxBoxSizer *btnSizer = new wxBoxSizer(wxHORIZONTAL); btnSizer->Add(backBtn, wxSizerFlags(0).Border(wxALL, 8)); btnSizer->Add(proceedBtn, wxSizerFlags(0).Border(wxALL, 8)); if (Type != eEQModMount) @@ -575,7 +611,7 @@ static void BlockWarning(ConfigWarningTypes Type) // Do semantic checks for 'next' commands bool ProfileWizard::SemanticCheck(DialogState state, int change) { - bool bOk = true; // Only 'next' commands could have problems + bool bOk = true; // Only 'next' commands could have problems if (change > 0) { switch (state) @@ -583,7 +619,8 @@ bool ProfileWizard::SemanticCheck(DialogState state, int change) case STATE_GREETINGS: break; case STATE_CAMERA: - bOk = (m_SelectedCamera.length() > 0 && m_PixelSize > 0 && m_FocalLength > 0 && (m_pBits8->GetValue() || m_pBits16->GetValue()) && m_SelectedCamera != _("None")); + bOk = (m_SelectedCamera.length() > 0 && m_PixelSize > 0 && m_FocalLength > 0 && + (m_pBits8->GetValue() || m_pBits16->GetValue()) && m_SelectedCamera != _("None")); if (!bOk) ShowStatus(_("Please specify camera type, guider focal length, camera bit-depth, and guide camera pixel size")); break; @@ -592,7 +629,7 @@ bool ProfileWizard::SemanticCheck(DialogState state, int change) if (bOk) { // Check for absence of pointing info - if ((m_SelectedMount.Upper().Contains("EQMOD"))) // && !m_PositionAware && WarningAllowed(eNoPointingInfo)) + if ((m_SelectedMount.Upper().Contains("EQMOD"))) // && !m_PositionAware && WarningAllowed(eNoPointingInfo)) { ConfigSuggestionDlg userAlert(eEQModMount, m_EqLink); int userRspns = userAlert.ShowModal(); @@ -614,26 +651,26 @@ bool ProfileWizard::SemanticCheck(DialogState state, int change) ShowStatus(_("Please select a mount type to handle guider commands")); break; case STATE_AUXMOUNT: - { + { // Check for absence of pointing info if (m_SelectedAuxMount == _("None") && !m_PositionAware && WarningAllowed(eNoPointingInfo)) + { + ConfigSuggestionDlg userAlert(eNoPointingInfo, m_EqLink); + int userRspns = userAlert.ShowModal(); + if (userRspns == wxOK) { - ConfigSuggestionDlg userAlert(eNoPointingInfo, m_EqLink); - int userRspns = userAlert.ShowModal(); - if (userRspns == wxOK) + // Could be either 'proceed' or 'dontAsk' + if (userAlert.UserChoice == eDontAsk) { - // Could be either 'proceed' or 'dontAsk' - if (userAlert.UserChoice == eDontAsk) - { - BlockWarning(eNoPointingInfo); - } - bOk = true; + BlockWarning(eNoPointingInfo); } - else - bOk = false; + bOk = true; } + else + bOk = false; } - break; + } + break; case STATE_AO: break; case STATE_ROTATOR: @@ -668,7 +705,7 @@ void ProfileWizard::UpdateState(const int change) ShowStatus(wxEmptyString); if (SemanticCheck(m_State, change)) { - m_State = (DialogState) RangeCheck(((int)m_State + change)); + m_State = (DialogState) RangeCheck(((int) m_State + change)); if (m_State >= 0 && m_State < NUM_PAGES) { @@ -729,12 +766,13 @@ void ProfileWizard::UpdateState(const int change) m_pGearChoice->SetStringSelection(m_SelectedMount); m_pUserProperties->Show(false); m_pMountProperties->Show(true); - m_pInstructions->SetLabel(_("Select your mount connection - this will determine how guide signals are transmitted")); + m_pInstructions->SetLabel( + _("Select your mount connection - this will determine how guide signals are transmitted")); } break; case STATE_AUXMOUNT: m_pMountProperties->Show(false); - if (m_PositionAware) // Skip this state if the selected mount is already position aware + if (m_PositionAware) // Skip this state if the selected mount is already position aware { UpdateState(change); } @@ -744,8 +782,9 @@ void ProfileWizard::UpdateState(const int change) m_pGearLabel->SetLabel(_("Aux Mount:")); m_pGearChoice->Clear(); m_pGearChoice->Append(Scope::AuxMountList()); - m_pGearChoice->SetStringSelection(m_SelectedAuxMount); // SelectedAuxMount is never null - m_pInstructions->SetLabel(_("Since your primary mount connection does not report pointing position, you may want to choose an 'Aux Mount' connection")); + m_pGearChoice->SetStringSelection(m_SelectedAuxMount); // SelectedAuxMount is never null + m_pInstructions->SetLabel(_("Since your primary mount connection does not report pointing position, you may " + "want to choose an 'Aux Mount' connection")); } break; case STATE_AO: @@ -753,9 +792,9 @@ void ProfileWizard::UpdateState(const int change) m_pGearLabel->SetLabel(_("AO:")); m_pGearChoice->Clear(); m_pGearChoice->Append(StepGuider::AOList()); - m_pGearChoice->SetStringSelection(m_SelectedAO); // SelectedAO is never null + m_pGearChoice->SetStringSelection(m_SelectedAO); // SelectedAO is never null m_pInstructions->SetLabel(_("Specify your adaptive optics device if desired")); - if (change == -1) // User is backing up in wizard dialog + if (change == -1) // User is backing up in wizard dialog { // Assert UI state for gear selection m_pGearGrid->Show(true); @@ -769,9 +808,9 @@ void ProfileWizard::UpdateState(const int change) m_pGearLabel->SetLabel(_("Rotator:")); m_pGearChoice->Clear(); m_pGearChoice->Append(Rotator::RotatorList()); - m_pGearChoice->SetStringSelection(m_SelectedRotator); // SelectedRotator is never null + m_pGearChoice->SetStringSelection(m_SelectedRotator); // SelectedRotator is never null m_pInstructions->SetLabel(_("Specify your rotator device if desired")); - if (change == -1) // User is backing up in wizard dialog + if (change == -1) // User is backing up in wizard dialog { // Assert UI state for gear selection m_pGearGrid->Show(true); @@ -787,7 +826,8 @@ void ProfileWizard::UpdateState(const int change) m_pNextBtn->SetLabel(_("Finish")); m_pNextBtn->SetToolTip(_("Finish creating the equipment profile")); m_pLaunchDarks->SetValue(m_useCamera || m_pLaunchDarks); - m_pInstructions->SetLabel(_("Enter a name for your profile and optionally launch the process to build a dark library")); + m_pInstructions->SetLabel( + _("Enter a name for your profile and optionally launch the process to build a dark library")); m_pAutoRestore->Show((m_PositionAware || m_SelectedAuxMount != _("None"))); m_pAutoRestore->SetValue(m_autoRestore); SetSizerAndFit(m_pvSizer); @@ -805,8 +845,8 @@ static int GetCalibrationStepSize(int focalLength, double pixelSize, double guid { int calibrationStep; double const declination = 0.0; - CalstepDialog::GetCalibrationStepSize(focalLength, pixelSize, binning, guideSpeed, - CalstepDialog::DEFAULT_STEPS, declination, distance, 0, &calibrationStep); + CalstepDialog::GetCalibrationStepSize( + focalLength, pixelSize, binning, guideSpeed, CalstepDialog::DEFAULT_STEPS, declination, distance, 0, &calibrationStep); return calibrationStep; } @@ -848,14 +888,14 @@ struct AutoConnectCamera if (!m_camera || !m_camera->Connected) { wxMessageBox(_("PHD2 could not connect to the camera so you may want to deal with that later. " - "In the meantime, you can just enter the pixel-size manually along with the " - "focal length and binning levels.")); + "In the meantime, you can just enter the pixel-size manually along with the " + "focal length and binning levels.")); delete m_camera; m_camera = nullptr; } - parent->SetFocus(); // In case driver messages might have caused us to lose it + parent->SetFocus(); // In case driver messages might have caused us to lose it } ~AutoConnectCamera() @@ -868,7 +908,7 @@ struct AutoConnectCamera } } - operator GuideCamera*() const { return m_camera; } + operator GuideCamera *() const { return m_camera; } GuideCamera *operator->() const { return m_camera; } }; @@ -893,9 +933,9 @@ void ProfileWizard::WrapUp() int calibrationStepSize = GetCalibrationStepSize(m_FocalLength, m_PixelSize, m_GuideSpeed, binning, calibrationDistance); Debug.Write(wxString::Format("Profile Wiz: Name=%s, Camera=%s, Mount=%s, High-res encoders=%s, AuxMount=%s, " - "AO=%s, PixelSize=%0.1f, FocalLength=%d, CalStep=%d, CalDist=%d, LaunchDarks=%d\n", - m_ProfileName, m_SelectedCamera, m_SelectedMount, m_pHPEncoders->GetValue() ? "True" : "False", m_SelectedAuxMount, m_SelectedAO, - m_PixelSize, m_FocalLength, calibrationStepSize, calibrationDistance, m_launchDarks)); + "AO=%s, PixelSize=%0.1f, FocalLength=%d, CalStep=%d, CalDist=%d, LaunchDarks=%d\n", + m_ProfileName, m_SelectedCamera, m_SelectedMount, m_pHPEncoders->GetValue() ? "True" : "False", m_SelectedAuxMount, + m_SelectedAO, m_PixelSize, m_FocalLength, calibrationStepSize, calibrationDistance, m_launchDarks)); // create the new profile if (!m_profile.Commit(m_ProfileName)) @@ -933,7 +973,7 @@ void ProfileWizard::WrapUp() else pConfig->Profile.SetInt("/camera/SaturationADU", 65535); - GuideLog.EnableLogging(true); // Especially for newbies + GuideLog.EnableLogging(true); // Especially for newbies // Construct a good baseline set of guiding parameters based on image scale SetGuideAlgoParams(m_PixelSize, m_FocalLength, binning, m_pHPEncoders->GetValue()); @@ -944,7 +984,7 @@ void ProfileWizard::WrapUp() class ConnectDialog : public wxDialog { wxStaticText *m_Instructions; - ProfileWizard* m_Parent; + ProfileWizard *m_Parent; public: ConnectDialog(ProfileWizard *parent, ProfileWizard::DialogState currState); @@ -959,7 +999,8 @@ void ProfileWizard::OnGearChoice(wxCommandEvent& evt) { switch (m_State) { - case STATE_CAMERA: { + case STATE_CAMERA: + { wxString prevSelection = m_SelectedCamera; m_SelectedCamera = m_pGearChoice->GetStringSelection(); bool camNone = (m_SelectedCamera == _("None")); @@ -987,7 +1028,8 @@ void ProfileWizard::OnGearChoice(wxCommandEvent& evt) break; } - case STATE_MOUNT: { + case STATE_MOUNT: + { wxString prevSelection = m_SelectedMount; m_SelectedMount = m_pGearChoice->GetStringSelection(); std::unique_ptr scope(Scope::Factory(m_SelectedMount)); @@ -1030,7 +1072,8 @@ void ProfileWizard::OnGearChoice(wxCommandEvent& evt) break; } - case STATE_AUXMOUNT: { + case STATE_AUXMOUNT: + { ShowStatus(wxEmptyString); wxString prevSelection = m_SelectedAuxMount; m_SelectedAuxMount = m_pGearChoice->GetStringSelection(); @@ -1068,7 +1111,8 @@ void ProfileWizard::OnGearChoice(wxCommandEvent& evt) double oldGuideSpeed = m_pGuideSpeed->GetValue(); InitMountProps(scope.get()); if (oldGuideSpeed != m_pGuideSpeed->GetValue()) - ShowStatus(wxString::Format(_("Guide speed setting adjusted from %0.1f to %0.1fx"), oldGuideSpeed, m_pGuideSpeed->GetValue())); + ShowStatus(wxString::Format( + _("Guide speed setting adjusted from %0.1f to %0.1fx"), oldGuideSpeed, m_pGuideSpeed->GetValue())); } else InitMountProps(nullptr); @@ -1111,7 +1155,7 @@ void ProfileWizard::InitCameraProps(bool tryConnect) AutoConnectCamera cam(this, m_SelectedCamera); if (cam) pxSz = GetPixelSize(cam); - m_pPixelSize->SetValue(pxSz); // Might be zero if driver doesn't report it + m_pPixelSize->SetValue(pxSz); // Might be zero if driver doesn't report it m_pPixelSize->Enable(pxSz == 0); wxSpinDoubleEvent dummy; OnPixelSizeChange(dummy); @@ -1127,7 +1171,7 @@ void ProfileWizard::InitCameraProps(bool tryConnect) wxByte bitDepth = 0; if (cam) bitDepth = cam->BitsPerPixel(); - if (bitDepth == 0) // Cam doesn't report it, force the user to choose + if (bitDepth == 0) // Cam doesn't report it, force the user to choose { m_pBits8->SetValue(false); m_pBits16->SetValue(false); @@ -1152,12 +1196,12 @@ void ProfileWizard::InitCameraProps(bool tryConnect) m_pPixelSize->Enable(true); wxSpinDoubleEvent dummy; OnPixelSizeChange(dummy); - m_pBits8->SetValue(false); // force a user selection + m_pBits8->SetValue(false); // force a user selection m_pBits16->SetValue(false); } } -void ProfileWizard::InitMountProps(Scope* theScope) +void ProfileWizard::InitMountProps(Scope *theScope) { double raSpeed; double decSpeed; @@ -1174,20 +1218,22 @@ void ProfileWizard::InitMountProps(Scope* theScope) { wxMessageBox( wxString::Format(_("PHD2 could not connect to the mount, so you'll probably want to deal with that later. " - "In the meantime, if you know the mount guide speed setting, you can enter it manually. " - " Otherwise, you can just leave it at the default value of %0.1fx"), Scope::DEFAULT_MOUNT_GUIDE_SPEED)); + "In the meantime, if you know the mount guide speed setting, you can enter it manually. " + " Otherwise, you can just leave it at the default value of %0.1fx"), + Scope::DEFAULT_MOUNT_GUIDE_SPEED)); speedVal = Scope::DEFAULT_MOUNT_GUIDE_SPEED; } else { // GetGuideRates handles exceptions thrown from driver, just returns a bool error if (!theScope->GetGuideRates(&raSpeed, &decSpeed)) - speedVal = wxMax(raSpeed, decSpeed) * 3600.0 / (15.0 * siderealSecondPerSec); // deg/sec -> sidereal multiple + speedVal = wxMax(raSpeed, decSpeed) * 3600.0 / (15.0 * siderealSecondPerSec); // deg/sec -> sidereal multiple else { - wxMessageBox( - wxString::Format(_("Apparently, this mount driver doesn't report guide speeds. If you know the mount guide speed setting, you can enter it manually. " - "Otherwise, you can just leave it at the default value of %0.1fx"), Scope::DEFAULT_MOUNT_GUIDE_SPEED)); + wxMessageBox(wxString::Format(_("Apparently, this mount driver doesn't report guide speeds. If you know the " + "mount guide speed setting, you can enter it manually. " + "Otherwise, you can just leave it at the default value of %0.1fx"), + Scope::DEFAULT_MOUNT_GUIDE_SPEED)); speedVal = Scope::DEFAULT_MOUNT_GUIDE_SPEED; } } @@ -1209,16 +1255,14 @@ void ProfileWizard::OnPixelSizeChange(wxSpinDoubleEvent& evt) void ProfileWizard::OnFocalLengthChange(wxSpinDoubleEvent& evt) { m_FocalLength = (int) m_pFocalLength->GetValue(); - m_pFocalLength->SetValue(m_FocalLength); // Rounding + m_pFocalLength->SetValue(m_FocalLength); // Rounding UpdatePixelScale(); } void ProfileWizard::OnFocalLengthText(wxCommandEvent& evt) { unsigned long val; - if (evt.GetString().ToULong(&val) && - val >= AdvancedDialog::MIN_FOCAL_LENGTH && - val <= AdvancedDialog::MAX_FOCAL_LENGTH) + if (evt.GetString().ToULong(&val) && val >= AdvancedDialog::MIN_FOCAL_LENGTH && val <= AdvancedDialog::MAX_FOCAL_LENGTH) { m_FocalLength = val; UpdatePixelScale(); @@ -1254,12 +1298,12 @@ void ProfileWizard::UpdatePixelScale() { if (!m_scaleIcon->GetClientData()) { - m_scaleIcon->SetClientData((void *)-1); // so we only do this once -# include "icons/alert24.png.h" + m_scaleIcon->SetClientData((void *) -1); // so we only do this once +#include "icons/alert24.png.h" wxBitmap alert(wxBITMAP_PNG_FROM_DATA(alert24)); m_scaleIcon->SetBitmap(alert); m_scaleIcon->SetToolTip(_("Guide star identification works best when the pixel scale is above 0.5\"/px. " - "Select binning level 2 to increase the pixel scale.")); + "Select binning level 2 to increase the pixel scale.")); m_scaleIcon->Hide(); } if (!m_scaleIcon->IsShown()) @@ -1295,7 +1339,7 @@ void ProfileWizard::OnContextHelp(wxCommandEvent& evt) void ProfileWizard::OnPrev(wxCommandEvent& evt) { - if (m_State == ProfileWizard::STATE_WRAPUP) // Special handling for basic controls with no event-handlers + if (m_State == ProfileWizard::STATE_WRAPUP) // Special handling for basic controls with no event-handlers { m_autoRestore = m_pAutoRestore->GetValue(); m_launchDarks = m_pLaunchDarks->GetValue(); @@ -1304,38 +1348,42 @@ void ProfileWizard::OnPrev(wxCommandEvent& evt) } // Supporting dialog classes -ConnectDialog::ConnectDialog(ProfileWizard* parent, ProfileWizard::DialogState currState) : -wxDialog(parent, wxID_ANY, _("Ask About Connection"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) +ConnectDialog::ConnectDialog(ProfileWizard *parent, ProfileWizard::DialogState currState) + : wxDialog(parent, wxID_ANY, _("Ask About Connection"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) { static const int DialogWidth = 425; static const int TextWrapPoint = 400; m_Parent = parent; - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); // Expanded explanations - m_Instructions = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(DialogWidth, 95), wxALIGN_LEFT | wxST_NO_AUTORESIZE); + m_Instructions = new wxStaticText( + this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(DialogWidth, 95), wxALIGN_LEFT | wxST_NO_AUTORESIZE); switch (currState) { case ProfileWizard::STATE_CAMERA: - m_Instructions->SetLabelText( - _("Is the camera already connected to the PC? If so, PHD2 can usually determine the camera pixel-size automatically. " - " If the camera isn't connected or its driver doesn't report the pixel-size, you can enter the value yourself using information in the camera manual or online. ") - ); + m_Instructions->SetLabelText(_("Is the camera already connected to the PC? If so, PHD2 can usually determine the " + "camera pixel-size automatically. " + " If the camera isn't connected or its driver doesn't report the pixel-size, you can " + "enter the value yourself using information in the camera manual or online. ")); this->SetTitle(_("Camera Already Connected?")); break; case ProfileWizard::STATE_MOUNT: - m_Instructions->SetLabelText( - wxString::Format(_("Is the mount already connected and set up to communicate with PHD2? If so, PHD2 can determine the mount guide speed automatically. " - " If not, you can enter the guide-speed manually. If you don't know what it is, just leave the setting at the default value of %0.1fx."), Scope::DEFAULT_MOUNT_GUIDE_SPEED) - ); + m_Instructions->SetLabelText(wxString::Format(_("Is the mount already connected and set up to communicate with PHD2? " + "If so, PHD2 can determine the mount guide speed automatically. " + " If not, you can enter the guide-speed manually. If you don't know " + "what it is, just leave the setting at the default value of %0.1fx."), + Scope::DEFAULT_MOUNT_GUIDE_SPEED)); this->SetTitle(_("Mount Already Connected?")); break; case ProfileWizard::STATE_AUXMOUNT: - m_Instructions->SetLabelText( - wxString::Format(_("Is the aux-mount already connected and set up to communicate with PHD2? If so, PHD2 can determine the mount guide speed automatically. " - " If not, you can enter it manually. If you don't know what it is, just leave the setting at the default value of %0.1fx. " - " If the guide speed on the previous page doesn't match what is read from the mount, the mount value will be used."), Scope::DEFAULT_MOUNT_GUIDE_SPEED) - ); + m_Instructions->SetLabelText(wxString::Format(_("Is the aux-mount already connected and set up to communicate with " + "PHD2? If so, PHD2 can determine the mount guide speed automatically. " + " If not, you can enter it manually. If you don't know what it is, " + "just leave the setting at the default value of %0.1fx. " + " If the guide speed on the previous page doesn't match what is read " + "from the mount, the mount value will be used."), + Scope::DEFAULT_MOUNT_GUIDE_SPEED)); this->SetTitle(_("Aux-mount Already Connected?")); break; default: @@ -1348,23 +1396,17 @@ wxDialog(parent, wxID_ANY, _("Ask About Connection"), wxDefaultPosition, wxDefau // Buttons for yes, no, cancel wxBoxSizer *pButtonSizer = new wxBoxSizer(wxHORIZONTAL); - wxButton* yesBtn = new wxButton(this, wxID_ANY, _("Yes")); + wxButton *yesBtn = new wxButton(this, wxID_ANY, _("Yes")); yesBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ConnectDialog::OnYesButton), NULL, this); - wxButton* noBtn = new wxButton(this, wxID_ANY, _("No")); + wxButton *noBtn = new wxButton(this, wxID_ANY, _("No")); noBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ConnectDialog::OnNoButton), NULL, this); - wxButton* cancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); + wxButton *cancelBtn = new wxButton(this, wxID_ANY, _("Cancel")); cancelBtn->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ConnectDialog::OnCancelButton), NULL, this); pButtonSizer->AddStretchSpacer(); - pButtonSizer->Add( - yesBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 5)); - pButtonSizer->Add( - noBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 5)); - pButtonSizer->Add( - cancelBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 5)); + pButtonSizer->Add(yesBtn, wxSizerFlags(0).Align(0).Border(wxALL, 5)); + pButtonSizer->Add(noBtn, wxSizerFlags(0).Align(0).Border(wxALL, 5)); + pButtonSizer->Add(cancelBtn, wxSizerFlags(0).Align(0).Border(wxALL, 5)); vSizer->Add(pButtonSizer, wxSizerFlags().Expand().Border(wxALL, 10)); SetAutoLayout(true); diff --git a/src/rotator.cpp b/src/rotator.cpp index 3896b47d5..6e9c741a0 100644 --- a/src/rotator.cpp +++ b/src/rotator.cpp @@ -1,36 +1,36 @@ /* -* rotator.cpp -* PHD Guiding -* -* Created by Andy Galasso -* Copyright (c) 2015 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * rotator.cpp + * PHD Guiding + * + * Created by Andy Galasso + * Copyright (c) 2015 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" @@ -43,7 +43,8 @@ const float Rotator::POSITION_UNKNOWN = -888.f; Rotator *pRotator; -static wxString INDIRotatorName() { +static wxString INDIRotatorName() +{ wxString indirotator = pConfig->Profile.GetString("/indi/INDIrotator", wxEmptyString); return indirotator.empty() ? _T("INDI Rotator") : wxString::Format("INDI Rotator [%s]", indirotator); } @@ -86,23 +87,28 @@ Rotator *Rotator::Factory(const wxString& choice) } #ifdef ROTATOR_ASCOM // do ascom first since it includes many choices, some of which match other choices below (like Simulator) - else if (choice.Find(_T("ASCOM")) != wxNOT_FOUND) { + else if (choice.Find(_T("ASCOM")) != wxNOT_FOUND) + { rotator = new RotatorAscom(choice); } #endif #ifdef ROTATOR_INDI - else if (choice.Contains(_T("INDI"))) { + else if (choice.Contains(_T("INDI"))) + { rotator = INDIRotatorFactory::MakeINDIRotator(); } #endif - else if (choice.Find(_("None")) != wxNOT_FOUND) { + else if (choice.Find(_("None")) != wxNOT_FOUND) + { } #ifdef ROTATOR_SIMULATOR - else if (choice.Find(_T("Simulator")) != wxNOT_FOUND) { + else if (choice.Find(_T("Simulator")) != wxNOT_FOUND) + { rotator = GearSimulator::MakeRotatorSimulator(); } #endif - else { + else + { throw ERROR_INFO("RotatorFactory: Unknown rotator choice"); } } @@ -126,9 +132,7 @@ Rotator::Rotator() Debug.Write(wxString::Format("Rotator:ctor: isReversed = %d\n", m_isReversed)); } -Rotator::~Rotator() -{ -} +Rotator::~Rotator() { } bool Rotator::Connect() { @@ -147,9 +151,7 @@ bool Rotator::IsConnected() const return m_connected; } -void Rotator::ShowPropertyDialog() -{ -} +void Rotator::ShowPropertyDialog() { } void Rotator::SetReversed(bool val) { @@ -161,7 +163,6 @@ void Rotator::SetReversed(bool val) RotatorConfigDialogPane::RotatorConfigDialogPane(wxWindow *parent) : ConfigDialogPane(_("Rotator Settings"), parent) { - } void RotatorConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdMap& CtrlMap) @@ -176,12 +177,14 @@ ConfigDialogPane *Rotator::GetConfigDialogPane(wxWindow *parent) return new RotatorConfigDialogPane(parent); } -RotatorConfigDialogCtrlSet *Rotator::GetConfigDlgCtrlSet(wxWindow *pParent, Rotator *pRotator, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +RotatorConfigDialogCtrlSet *Rotator::GetConfigDlgCtrlSet( + wxWindow *pParent, Rotator *pRotator, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) { return new RotatorConfigDialogCtrlSet(pParent, pRotator, pAdvancedDialog, CtrlMap); } -RotatorConfigDialogCtrlSet::RotatorConfigDialogCtrlSet(wxWindow *pParent, Rotator *pRotator, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +RotatorConfigDialogCtrlSet::RotatorConfigDialogCtrlSet( + wxWindow *pParent, Rotator *pRotator, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) : ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) { m_rotator = pRotator; diff --git a/src/rotator.h b/src/rotator.h index 760ae0a36..e6bf7b7f8 100644 --- a/src/rotator.h +++ b/src/rotator.h @@ -1,36 +1,36 @@ /* -* rotator.h -* PHD Guiding -* -* Created by Andy Galasso -* Copyright (c) 2015 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * rotator.h + * PHD Guiding + * + * Created by Andy Galasso + * Copyright (c) 2015 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef ROTATOR_INCLUDED #define ROTATOR_INCLUDED @@ -66,7 +66,6 @@ class Rotator bool m_isReversed; public: - static const float POSITION_UNKNOWN; static const float POSITION_ERROR; @@ -83,7 +82,8 @@ class Rotator virtual bool IsConnected() const; virtual ConfigDialogPane *GetConfigDialogPane(wxWindow *pParent); - RotatorConfigDialogCtrlSet *GetConfigDlgCtrlSet(wxWindow *pParent, Rotator *pRotator, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + RotatorConfigDialogCtrlSet *GetConfigDlgCtrlSet( + wxWindow *pParent, Rotator *pRotator, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); virtual void ShowPropertyDialog(); // get the display name of the rotator device diff --git a/src/rotator_ascom.cpp b/src/rotator_ascom.cpp index 00ce18266..967f9fce6 100644 --- a/src/rotator_ascom.cpp +++ b/src/rotator_ascom.cpp @@ -1,42 +1,42 @@ /* -* rotator_ascom.cpp -* PHD Guiding -* -* Created by Andy Galasso -* Copyright (c) 2015 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * rotator_ascom.cpp + * PHD Guiding + * + * Created by Andy Galasso + * Copyright (c) 2015 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #ifdef ROTATOR_ASCOM -#include +# include struct AscomRotatorImpl { @@ -76,7 +76,8 @@ wxArrayString RotatorAscom::EnumAscomRotators(void) { DispatchObj profile; if (!profile.Create(L"ASCOM.Utilities.Profile")) - throw ERROR_INFO("ASCOM Rotator: could not instantiate ASCOM profile class ASCOM.Utilities.Profile. Is ASCOM installed?"); + throw ERROR_INFO( + "ASCOM Rotator: could not instantiate ASCOM profile class ASCOM.Utilities.Profile. Is ASCOM installed?"); Variant res; if (!profile.InvokeMethod(&res, L"RegisteredDevices", L"Rotator")) @@ -156,7 +157,10 @@ bool RotatorAscom::Connect(void) struct ConnectInBg : public ConnectRotatorInBg { AscomRotatorImpl *rotator; - ConnectInBg(AscomRotatorImpl *rotator_) : rotator(rotator_) { } + ConnectInBg(AscomRotatorImpl *rotator_) + : rotator(rotator_) + { + } bool Entry() { GITObjRef dobj(rotator->m_gitEntry); diff --git a/src/rotator_ascom.h b/src/rotator_ascom.h index 83898a33c..9fd3c8c56 100644 --- a/src/rotator_ascom.h +++ b/src/rotator_ascom.h @@ -1,36 +1,36 @@ /* -* rotator_ascom.h -* PHD Guiding -* -* Created by Andy Galasso -* Copyright (c) 2015 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * rotator_ascom.h + * PHD Guiding + * + * Created by Andy Galasso + * Copyright (c) 2015 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef ROTATOR_ASCOM_INCLUDED #define ROTATOR_ASCOM_INCLUDED @@ -44,7 +44,6 @@ class RotatorAscom : public Rotator AscomRotatorImpl *m_impl; public: - RotatorAscom(const wxString& name); virtual ~RotatorAscom(); diff --git a/src/rotator_indi.cpp b/src/rotator_indi.cpp index c04f5d857..1cbdea9e0 100644 --- a/src/rotator_indi.cpp +++ b/src/rotator_indi.cpp @@ -1,119 +1,128 @@ /* -* rotator_indi.cpp -* PHD Guiding -* -* Created by Philipp Weber and Kirill M. Skorobogatov -* Copyright (c) 2024 openphdguiding.org -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * rotator_indi.cpp + * PHD Guiding + * + * Created by Philipp Weber and Kirill M. Skorobogatov + * Copyright (c) 2024 openphdguiding.org + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #ifdef ROTATOR_INDI -#include "rotator_indi.h" -#include "rotator.h" -#include "config_indi.h" -#include "indi_gui.h" -#include "libindi/baseclient.h" - -#include -#include - -class RotatorINDI : public Rotator, public INDI::BaseClient { - public: - RotatorINDI(); - ~RotatorINDI(); - bool Connect() override; - bool Disconnect() override; - wxString Name() const override; - float Position() const override; - - private: - long INDIport; - wxString INDIhost; - volatile bool modal; - bool m_ready = false; - float m_angle = POSITION_UNKNOWN; - - INumberVectorProperty *angle_prop; - ISwitchVectorProperty *connection_prop; - - IndiGui *m_gui; - - wxString INDIRotatorName; - wxString m_Name; - - void ClearStatus(); - void CheckState(); - void RotatorDialog(); - void RotatorSetup(); - void updateAngle(); - - protected: - void serverConnected() override; - void serverDisconnected(int exit_code) override; - void newDevice(INDI::BaseDevice dp) override; - void removeDevice(INDI::BaseDevice dp) override; - void newProperty(INDI::Property property) override; - void updateProperty(INDI::Property property) override; - void newMessage(INDI::BaseDevice dp, int messageID) override; - - private: - void ShowPropertyDialog() override; +# include "rotator_indi.h" +# include "rotator.h" +# include "config_indi.h" +# include "indi_gui.h" +# include "libindi/baseclient.h" + +# include +# include + +class RotatorINDI : public Rotator, public INDI::BaseClient +{ +public: + RotatorINDI(); + ~RotatorINDI(); + bool Connect() override; + bool Disconnect() override; + wxString Name() const override; + float Position() const override; + +private: + long INDIport; + wxString INDIhost; + volatile bool modal; + bool m_ready = false; + float m_angle = POSITION_UNKNOWN; + + INumberVectorProperty *angle_prop; + ISwitchVectorProperty *connection_prop; + + IndiGui *m_gui; + + wxString INDIRotatorName; + wxString m_Name; + + void ClearStatus(); + void CheckState(); + void RotatorDialog(); + void RotatorSetup(); + void updateAngle(); + +protected: + void serverConnected() override; + void serverDisconnected(int exit_code) override; + void newDevice(INDI::BaseDevice dp) override; + void removeDevice(INDI::BaseDevice dp) override; + void newProperty(INDI::Property property) override; + void updateProperty(INDI::Property property) override; + void newMessage(INDI::BaseDevice dp, int messageID) override; + +private: + void ShowPropertyDialog() override; }; -void RotatorINDI::ClearStatus() { +void RotatorINDI::ClearStatus() +{ angle_prop = nullptr; connection_prop = nullptr; m_ready = false; m_angle = POSITION_UNKNOWN; } -void RotatorINDI::CheckState() { - if ( ! IsConnected() ) { +void RotatorINDI::CheckState() +{ + if (!IsConnected()) + { return; } - if ( m_ready ) { + if (m_ready) + { return; } - if ( ! angle_prop ) { + if (!angle_prop) + { return; } Debug.Write(wxString(_("INDI Rotator is ready\n"))); m_ready = true; - if ( modal ) { + if (modal) + { modal = false; } } -RotatorINDI::RotatorINDI() : m_gui(nullptr) { +RotatorINDI::RotatorINDI() + : m_gui(nullptr) +{ ClearStatus(); INDIhost = pConfig->Profile.GetString("/indi/INDIhost", _T("localhost")); INDIport = pConfig->Profile.GetLong("/indi/INDIport", 7624); @@ -121,19 +130,24 @@ RotatorINDI::RotatorINDI() : m_gui(nullptr) { m_Name = wxString::Format("INDI Rotator [%s]", INDIRotatorName); } -RotatorINDI::~RotatorINDI() { - if ( m_gui ) { +RotatorINDI::~RotatorINDI() +{ + if (m_gui) + { IndiGui::DestroyIndiGui(&m_gui); } disconnectServer(); } -bool RotatorINDI::Connect() { - if ( INDIRotatorName == wxT("INDI Rotator") ) { +bool RotatorINDI::Connect() +{ + if (INDIRotatorName == wxT("INDI Rotator")) + { RotatorSetup(); } - if(isServerConnected()) { + if (isServerConnected()) + { return false; } @@ -143,16 +157,24 @@ bool RotatorINDI::Connect() { Debug.Write(wxString::Format("Waiting for 30s for [%s] to connect...\n", INDIRotatorName)); /* Wait in background for driver to establish a device connection */ - struct ConnectInBg : public ConnectRotatorInBg { - RotatorINDI* rotator {nullptr}; - ConnectInBg(RotatorINDI* rotator_) : rotator(rotator_) {} + struct ConnectInBg : public ConnectRotatorInBg + { + RotatorINDI *rotator { nullptr }; + ConnectInBg(RotatorINDI *rotator_) + : rotator(rotator_) + { + } - bool Entry() { + bool Entry() + { // Wait for driver to establish a device connection - if(rotator->connectServer()) { + if (rotator->connectServer()) + { int i = 0; - while(!rotator->IsConnected() && i++ < 300) { - if(IsCanceled()) { + while (!rotator->IsConnected() && i++ < 300) + { + if (IsCanceled()) + { break; } wxMilliSleep(100); @@ -167,61 +189,78 @@ bool RotatorINDI::Connect() { return ConnectInBg(this).Run(); } -void RotatorINDI::serverConnected() { +void RotatorINDI::serverConnected() +{ Debug.Write("INDI Rotator connection succeeded\n"); Rotator::Connect(); } -bool RotatorINDI::Disconnect() { +bool RotatorINDI::Disconnect() +{ disconnectServer(); return false; } -void RotatorINDI::serverDisconnected(int exit_code) { +void RotatorINDI::serverDisconnected(int exit_code) +{ Rotator::Disconnect(); ClearStatus(); - if(pFrame) { + if (pFrame) + { pFrame->UpdateStatsWindowScopePointing(); } - if ( exit_code == -1 ) { - if(pFrame) { + if (exit_code == -1) + { + if (pFrame) + { pFrame->Alert(wxString(_("INDI server disconnected"))); } Disconnect(); } } -void RotatorINDI::removeDevice(INDI::BaseDevice dp) { +void RotatorINDI::removeDevice(INDI::BaseDevice dp) +{ ClearStatus(); Disconnect(); } -void RotatorINDI::ShowPropertyDialog() { - if ( IsConnected() ) { +void RotatorINDI::ShowPropertyDialog() +{ + if (IsConnected()) + { RotatorDialog(); - } else { + } + else + { RotatorSetup(); } } -void RotatorINDI::RotatorDialog() { - if ( m_gui ) { +void RotatorINDI::RotatorDialog() +{ + if (m_gui) + { m_gui->Show(); - } else { + } + else + { IndiGui::ShowIndiGui(&m_gui, INDIhost, INDIport, false, false); } } -void RotatorINDI::RotatorSetup() { +void RotatorINDI::RotatorSetup() +{ INDIConfig indiDlg(wxGetApp().GetTopWindow(), _("INDI Rotator Selection"), INDI_TYPE_ROTATOR); indiDlg.INDIhost = INDIhost; indiDlg.INDIport = INDIport; indiDlg.INDIDevName = INDIRotatorName; indiDlg.SetSettings(); indiDlg.Connect(); - if ( indiDlg.ShowModal() == wxID_OK ) { + if (indiDlg.ShowModal() == wxID_OK) + { indiDlg.SaveSettings(); INDIhost = indiDlg.INDIhost; INDIport = indiDlg.INDIport; @@ -234,116 +273,145 @@ void RotatorINDI::RotatorSetup() { indiDlg.Disconnect(); } -wxString RotatorINDI::Name() const { +wxString RotatorINDI::Name() const +{ return m_Name; } -float RotatorINDI::Position() const { +float RotatorINDI::Position() const +{ return m_angle; } -void RotatorINDI::updateAngle() { - if (!IsConnected()) { +void RotatorINDI::updateAngle() +{ + if (!IsConnected()) + { m_angle = POSITION_UNKNOWN; return; } - if(!angle_prop) { + if (!angle_prop) + { return; } m_angle = IUFindNumber(angle_prop, "ANGLE")->value; } -void RotatorINDI::newProperty(INDI::Property property) { +void RotatorINDI::newProperty(INDI::Property property) +{ wxString PropName(property.getName()); INDI_PROPERTY_TYPE Proptype = property.getType(); Debug.Write(wxString::Format("INDI Rotator: Received property: %s\n", PropName)); - if ( Proptype == INDI_NUMBER && PropName == "ABS_ROTATOR_ANGLE" ) { - if ( INDIConfig::Verbose() ) { - Debug.Write(wxString::Format(_("INDI Rotator found ABS_ROTATOR_ANGLE for %s %s\n"), - property.getDeviceName(), PropName)); + if (Proptype == INDI_NUMBER && PropName == "ABS_ROTATOR_ANGLE") + { + if (INDIConfig::Verbose()) + { + Debug.Write( + wxString::Format(_("INDI Rotator found ABS_ROTATOR_ANGLE for %s %s\n"), property.getDeviceName(), PropName)); } angle_prop = property.getNumber(); updateAngle(); - if(pFrame) { + if (pFrame) + { pFrame->UpdateStatsWindowScopePointing(); } } - if ( Proptype == INDI_SWITCH && PropName == "CONNECTION" ) { - if ( INDIConfig::Verbose() ) { - Debug.Write(wxString::Format(_("INDI Rotator found CONNECTION for %s %s\n"), - property.getDeviceName(), PropName)); + if (Proptype == INDI_SWITCH && PropName == "CONNECTION") + { + if (INDIConfig::Verbose()) + { + Debug.Write(wxString::Format(_("INDI Rotator found CONNECTION for %s %s\n"), property.getDeviceName(), PropName)); } connection_prop = property.getSwitch(); ISwitch *connectswitch = IUFindSwitch(connection_prop, "CONNECT"); - if ( connectswitch->s == ISS_ON ) { + if (connectswitch->s == ISS_ON) + { Rotator::Connect(); } } CheckState(); } -void RotatorINDI::newMessage(INDI::BaseDevice dp, int messageID) { - if ( INDIConfig::Verbose() ) { +void RotatorINDI::newMessage(INDI::BaseDevice dp, int messageID) +{ + if (INDIConfig::Verbose()) + { Debug.Write(wxString::Format(_("INDI Rotator received message: %s\n"), dp.messageQueue(messageID))); } } -void RotatorINDI::newDevice(INDI::BaseDevice dp) { - if ( INDIConfig::Verbose() ) { +void RotatorINDI::newDevice(INDI::BaseDevice dp) +{ + if (INDIConfig::Verbose()) + { Debug.Write(wxString::Format("INDI Rotator new device %s\n", dp.getDeviceName())); } } -void RotatorINDI::updateProperty(INDI::Property property) { - switch(property.getType()) { - case INDI_SWITCH: +void RotatorINDI::updateProperty(INDI::Property property) +{ + switch (property.getType()) + { + case INDI_SWITCH: + { + auto *svp = property.getSwitch(); + if (INDIConfig::Verbose()) { - auto* svp = property.getSwitch(); - if ( INDIConfig::Verbose() ) { - Debug.Write(wxString::Format("INDI Rotator: Receiving Switch: %s = %i\n", - svp->name, svp->sp->s)); + Debug.Write(wxString::Format("INDI Rotator: Receiving Switch: %s = %i\n", svp->name, svp->sp->s)); + } + if (strcmp(svp->name, "CONNECTION") == 0) + { + ISwitch *connectswitch = IUFindSwitch(svp, "CONNECT"); + if (connectswitch->s == ISS_ON) + { + Rotator::Connect(); + CheckState(); } - if ( strcmp(svp->name, "CONNECTION") == 0 ) { - ISwitch *connectswitch = IUFindSwitch(svp, "CONNECT"); - if ( connectswitch->s == ISS_ON ) { - Rotator::Connect(); - CheckState(); - } else { - if ( m_ready ) { - ClearStatus(); - PhdApp::ExecInMainThread( - [this]() { - pFrame->Alert(_("INDI rotator was disconnected")); - Disconnect(); - }); - } + else + { + if (m_ready) + { + ClearStatus(); + PhdApp::ExecInMainThread( + [this]() + { + pFrame->Alert(_("INDI rotator was disconnected")); + Disconnect(); + }); } } - } break; - case INDI_NUMBER: + } + } + break; + case INDI_NUMBER: + { + auto *nvp = property.getNumber(); + if (INDIConfig::Verbose()) { - auto* nvp = property.getNumber(); - if ( INDIConfig::Verbose() ) { - Debug.Write(wxString::Format(_("INDI Rotator: New number: %s\n"), nvp->name)); - } - if ( strcmp(nvp->name, "ABS_ROTATOR_ANGLE") == 0 ) { - updateAngle(); + Debug.Write(wxString::Format(_("INDI Rotator: New number: %s\n"), nvp->name)); + } + if (strcmp(nvp->name, "ABS_ROTATOR_ANGLE") == 0) + { + updateAngle(); - if(pFrame) { - pFrame->UpdateStatsWindowScopePointing(); - } + if (pFrame) + { + pFrame->UpdateStatsWindowScopePointing(); } - } break; - default: - break; + } + } + break; + default: + break; } } -Rotator *INDIRotatorFactory::MakeINDIRotator() { +Rotator *INDIRotatorFactory::MakeINDIRotator() +{ return new RotatorINDI(); } diff --git a/src/rotator_indi.h b/src/rotator_indi.h index 4c7ad7e46..547b96cc6 100644 --- a/src/rotator_indi.h +++ b/src/rotator_indi.h @@ -1,45 +1,46 @@ /* -* rotator_indi.h -* PHD Guiding -* -* Created by Philipp Weber and Kirill M. Skorobogatov -* Copyright (c) 2024 openphdguiding.org -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * rotator_indi.h + * PHD Guiding + * + * Created by Philipp Weber and Kirill M. Skorobogatov + * Copyright (c) 2024 openphdguiding.org + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef ROTATOR_INDI_INCLUDED #define ROTATOR_INDI_INCLUDED class Rotator; -class INDIRotatorFactory { - public: - static Rotator *MakeINDIRotator(); +class INDIRotatorFactory +{ +public: + static Rotator *MakeINDIRotator(); }; #endif diff --git a/src/rotators.h b/src/rotators.h index 1a412dfbe..312a810a2 100644 --- a/src/rotators.h +++ b/src/rotators.h @@ -36,7 +36,7 @@ #define ROTATORS_INCLUDED #if defined(__WINDOWS__) -#define ROTATOR_ASCOM +# define ROTATOR_ASCOM #endif #define ROTATOR_INDI diff --git a/src/runinbg.cpp b/src/runinbg.cpp index f8557704c..8c854ecf5 100644 --- a/src/runinbg.cpp +++ b/src/runinbg.cpp @@ -61,16 +61,16 @@ struct RunInBgImpl : public wxTimer, public wxThreadHelper unsigned int m_popupDelayMillis; RunInBgImpl(RunInBg *bg, wxWindow *parent, const wxString& title, const wxString& message) - : m_bg(bg), - m_parent(parent), - m_title(title), - m_message(message), - m_updateMsg(nullptr), - m_win(0), - m_shown(false), - m_done(false), - m_canceled(false), - m_popupDelayMillis(2500) + : m_bg(bg) + , m_parent(parent) + , m_title(title) + , m_message(message) + , m_updateMsg(nullptr) + , m_win(0) + , m_shown(false) + , m_done(false) + , m_canceled(false) + , m_popupDelayMillis(2500) { } @@ -226,10 +226,6 @@ bool RunInBg::IsCanceled(void) return m_impl->m_canceled; } -void RunInBg::OnCancel() -{ -} +void RunInBg::OnCancel() { } -void RunInBg::OnKill() -{ -} +void RunInBg::OnKill() { } diff --git a/src/runinbg.h b/src/runinbg.h index 4b9138a2d..7b938ee17 100644 --- a/src/runinbg.h +++ b/src/runinbg.h @@ -42,10 +42,9 @@ class RunInBg RunInBgImpl *m_impl; RunInBg(const RunInBg&); // not implemented - RunInBg& operator= (const RunInBg&); // not implemented + RunInBg& operator=(const RunInBg&); // not implemented public: - RunInBg(wxWindow *parent, const wxString& title, const wxString& message); virtual ~RunInBg(void); void SetPopupDelay(unsigned int millis); @@ -82,25 +81,37 @@ inline static wxWindow *GetConnectGearParentWindow(void) class ConnectMountInBg : public RunInBg { public: - ConnectMountInBg(wxWindow *parent = GetConnectGearParentWindow()) : RunInBg(parent, _("Connect"), _("Connecting to Mount...")) { } + ConnectMountInBg(wxWindow *parent = GetConnectGearParentWindow()) + : RunInBg(parent, _("Connect"), _("Connecting to Mount...")) + { + } }; class ConnectAoInBg : public RunInBg { public: - ConnectAoInBg(wxWindow *parent = GetConnectGearParentWindow()) : RunInBg(parent, _("Connect"), _("Connecting to AO...")) { } + ConnectAoInBg(wxWindow *parent = GetConnectGearParentWindow()) + : RunInBg(parent, _("Connect"), _("Connecting to AO...")) + { + } }; class ConnectCameraInBg : public RunInBg { public: - ConnectCameraInBg(wxWindow *parent = GetConnectGearParentWindow()) : RunInBg(parent, _("Connect"), _("Connecting to Camera...")) { } + ConnectCameraInBg(wxWindow *parent = GetConnectGearParentWindow()) + : RunInBg(parent, _("Connect"), _("Connecting to Camera...")) + { + } }; class ConnectRotatorInBg : public RunInBg { public: - ConnectRotatorInBg(wxWindow *parent = GetConnectGearParentWindow()) : RunInBg(parent, _("Connect"), _("Connecting to Rotator...")) { } + ConnectRotatorInBg(wxWindow *parent = GetConnectGearParentWindow()) + : RunInBg(parent, _("Connect"), _("Connecting to Rotator...")) + { + } }; #endif // RUNINBG_INLCUDED diff --git a/src/scope.cpp b/src/scope.cpp index 0374c503e..cb47dd8b0 100644 --- a/src/scope.cpp +++ b/src/scope.cpp @@ -44,36 +44,39 @@ static const int DefaultCalibrationDuration = 750; static const int DefaultMaxDecDuration = 2500; static const int DefaultMaxRaDuration = 2500; -enum { MAX_DURATION_MIN = 50, MAX_DURATION_MAX = 8000, }; +enum +{ + MAX_DURATION_MIN = 50, + MAX_DURATION_MAX = 8000, +}; static const DEC_GUIDE_MODE DefaultDecGuideMode = DEC_AUTO; static const GUIDE_ALGORITHM DefaultRaGuideAlgorithm = GUIDE_ALGORITHM_HYSTERESIS; static const GUIDE_ALGORITHM DefaultDecGuideAlgorithm = GUIDE_ALGORITHM_RESIST_SWITCH; static const int MAX_CALIBRATION_STEPS = 60; static const int CAL_ALERT_MINSTEPS = 4; -static const double CAL_ALERT_ORTHOGONALITY_TOLERANCE = 12.5; // Degrees -static const double CAL_ALERT_DECRATE_DIFFERENCE = 0.20; // Ratio tolerance -static const double CAL_ALERT_AXISRATES_TOLERANCE = 0.20; // Ratio tolerance -static const bool SANITY_CHECKING_ACTIVE = true; // Control calibration sanity checking +static const double CAL_ALERT_ORTHOGONALITY_TOLERANCE = 12.5; // Degrees +static const double CAL_ALERT_DECRATE_DIFFERENCE = 0.20; // Ratio tolerance +static const double CAL_ALERT_AXISRATES_TOLERANCE = 0.20; // Ratio tolerance +static const bool SANITY_CHECKING_ACTIVE = true; // Control calibration sanity checking static int LIMIT_REACHED_WARN_COUNT = 5; static int MAX_NUDGES = 3; static double NUDGE_TOLERANCE = 2.0; // enable dec compensation when calibration declination is less than this -const double Scope::DEC_COMP_LIMIT = M_PI / 2.0 * 2.0 / 3.0; // 60 degrees +const double Scope::DEC_COMP_LIMIT = M_PI / 2.0 * 2.0 / 3.0; // 60 degrees const double Scope::DEFAULT_MOUNT_GUIDE_SPEED = 0.5; Scope::Scope() - : - m_maxDecDuration(0), - m_maxRaDuration(0), - m_decGuideMode(DEC_NONE), - m_raLimitReachedDirection(NONE), - m_raLimitReachedCount(0), - m_decLimitReachedDirection(NONE), - m_decLimitReachedCount(0), - m_bogusGuideRatesFlagged(0) + : m_maxDecDuration(0) + , m_maxRaDuration(0) + , m_decGuideMode(DEC_NONE) + , m_raLimitReachedDirection(NONE) + , m_raLimitReachedCount(0) + , m_decLimitReachedDirection(NONE) + , m_decLimitReachedCount(0) + , m_bogusGuideRatesFlagged(0) { m_calibrationSteps = 0; m_limitReachedDeferralTime = wxDateTime::GetTimeNow(); @@ -87,7 +90,7 @@ Scope::Scope() int calibrationDistance = pConfig->Profile.GetInt(prefix + "/CalibrationDistance", CalstepDialog::DEFAULT_DISTANCE); SetCalibrationDistance(calibrationDistance); - int maxRaDuration = pConfig->Profile.GetInt(prefix + "/MaxRaDuration", DefaultMaxRaDuration); + int maxRaDuration = pConfig->Profile.GetInt(prefix + "/MaxRaDuration", DefaultMaxRaDuration); SetMaxRaDuration(maxRaDuration); int maxDecDuration = pConfig->Profile.GetInt(prefix + "/MaxDecDuration", DefaultMaxDecDuration); @@ -245,11 +248,16 @@ wxString Scope::DecGuideModeStr(DEC_GUIDE_MODE m) { switch (m) { - case DEC_NONE: return "Off"; - case DEC_AUTO: return "Auto"; - case DEC_NORTH: return "North"; - case DEC_SOUTH: return "South"; - default: return "Invalid"; + case DEC_NONE: + return "Off"; + case DEC_AUTO: + return "Auto"; + case DEC_NORTH: + return "North"; + case DEC_SOUTH: + return "South"; + default: + return "Invalid"; } } @@ -257,11 +265,16 @@ wxString Scope::DecGuideModeLocaleStr(DEC_GUIDE_MODE m) { switch (m) { - case DEC_NONE: return _("Off"); - case DEC_AUTO: return _("Auto"); - case DEC_NORTH: return _("North"); - case DEC_SOUTH: return _("South"); - default: return _("Invalid"); + case DEC_NONE: + return _("Off"); + case DEC_AUTO: + return _("Auto"); + case DEC_NORTH: + return _("North"); + case DEC_SOUTH: + return _("South"); + default: + return _("Invalid"); } } @@ -273,14 +286,14 @@ bool Scope::SetDecGuideMode(int decGuideMode) { switch (decGuideMode) { - case DEC_NONE: - case DEC_AUTO: - case DEC_NORTH: - case DEC_SOUTH: - break; - default: - throw ERROR_INFO("invalid decGuideMode"); - break; + case DEC_NONE: + case DEC_AUTO: + case DEC_NORTH: + case DEC_SOUTH: + break; + default: + throw ERROR_INFO("invalid decGuideMode"); + break; } if (m_decGuideMode != decGuideMode) @@ -296,7 +309,8 @@ bool Scope::SetDecGuideMode(int decGuideMode) if (blc) { if (decGuideMode != DEC_AUTO) - blc->EnableBacklashComp(false); // Can't do blc in uni-direction mode because there's no recovery from over-shoots + blc->EnableBacklashComp( + false); // Can't do blc in uni-direction mode because there's no recovery from over-shoots else blc->ResetBLCState(); } @@ -371,7 +385,7 @@ wxArrayString Scope::MountList() wxArrayString Scope::AuxMountList() { wxArrayString scopeList; - scopeList.Add(_("None")); // Keep this at the top of the list + scopeList.Add(_("None")); // Keep this at the top of the list #ifdef GUIDE_ASCOM wxArrayString positionAwareScopes = ScopeASCOM::EnumAscomScopes(); @@ -439,9 +453,8 @@ Scope *Scope::Factory(const wxString& choice) #ifdef GUIDE_VOYAGER else if (choice.Contains(_T("Voyager"))) { - This needs work. We have to move the setting of the IP address - into the connect routine - ScopeVoyager *pVoyager = new ScopeVoyager(); + This needs work.We have to move the setting of the IP address into the connect routine ScopeVoyager *pVoyager = + new ScopeVoyager(); } #endif #ifdef GUIDE_EQUINOX @@ -466,8 +479,8 @@ Scope *Scope::Factory(const wxString& choice) if (pReturn) { // virtual function call means we cannot do this in the Scope constructor - pReturn->EnableStopGuidingWhenSlewing(pConfig->Profile.GetBoolean("/scope/StopGuidingWhenSlewing", - pReturn->CanCheckSlewing())); + pReturn->EnableStopGuidingWhenSlewing( + pConfig->Profile.GetBoolean("/scope/StopGuidingWhenSlewing", pReturn->CanCheckSlewing())); } } catch (const wxString& Msg) @@ -532,8 +545,8 @@ void Scope::StartDecDrift() m_saveDecGuideMode = m_decGuideMode; m_decGuideMode = DEC_NONE; - Debug.Write(wxString::Format("StartDecDrift: DecGuideMode set to %s (%d)\n", - DecGuideModeStr(m_decGuideMode), m_decGuideMode)); + Debug.Write( + wxString::Format("StartDecDrift: DecGuideMode set to %s (%d)\n", DecGuideModeStr(m_decGuideMode), m_decGuideMode)); if (m_graphControlPane) { @@ -546,8 +559,8 @@ void Scope::EndDecDrift() { m_decGuideMode = m_saveDecGuideMode; - Debug.Write(wxString::Format("EndDecDrift: DecGuideMode set to %s (%d)\n", - DecGuideModeStr(m_decGuideMode), m_decGuideMode)); + Debug.Write( + wxString::Format("EndDecDrift: DecGuideMode set to %s (%d)\n", DecGuideModeStr(m_decGuideMode), m_decGuideMode)); if (m_graphControlPane) { @@ -592,8 +605,10 @@ int Scope::CalibrationMoveSize() static wxString LimitReachedWarningKey(long axis) { - // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting to be per-profile - return wxString::Format("/Confirm/%d/Max%sLimitWarningEnabled", pConfig->GetCurrentProfileId(), axis == GUIDE_RA ? "RA" : "Dec"); + // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting + // to be per-profile + return wxString::Format( + "/Confirm/%d/Max%sLimitWarningEnabled", pConfig->GetCurrentProfileId(), axis == GUIDE_RA ? "RA" : "Dec"); } static void SuppressLimitReachedWarning(long axis) @@ -603,10 +618,12 @@ static void SuppressLimitReachedWarning(long axis) void Scope::DeferPulseLimitAlertCheck() { - enum { LIMIT_REACHED_GRACE_PERIOD_SECONDS = 120 }; + enum + { + LIMIT_REACHED_GRACE_PERIOD_SECONDS = 120 + }; - m_limitReachedDeferralTime = - wxDateTime::GetTimeNow() + LIMIT_REACHED_GRACE_PERIOD_SECONDS; + m_limitReachedDeferralTime = wxDateTime::GetTimeNow() + LIMIT_REACHED_GRACE_PERIOD_SECONDS; } void Scope::AlertLimitReached(int duration, GuideAxis axis) @@ -625,65 +642,76 @@ void Scope::AlertLimitReached(int duration, GuideAxis axis) if (duration < MAX_DURATION_MAX) { int defaultVal = axis == GUIDE_RA ? DefaultMaxRaDuration : DefaultMaxDecDuration; - if (duration >= defaultVal) // Max duration is probably ok, some other kind of problem + if (duration >= defaultVal) // Max duration is probably ok, some other kind of problem { wxString msg; if (axis == GUIDE_RA) { if (CanPulseGuide()) { - msg = _("PHD2 is not able to make sufficient corrections in RA. Check for cable snags, try re-doing your calibration, and " + msg = _("PHD2 is not able to make sufficient corrections in RA. Check for cable snags, try re-doing your " + "calibration, and " "check for problems with the mount mechanics."); } else { - msg = _("PHD2 is not able to make sufficient corrections in RA. Check for cable snags, try re-doing your calibration, and " + msg = _("PHD2 is not able to make sufficient corrections in RA. Check for cable snags, try re-doing your " + "calibration, and " "confirm the ST-4 cable is working properly."); } } - else // Dec axis problems + else // Dec axis problems { if (CanPulseGuide()) { msg = _("PHD2 is not able to make sufficient corrections in Dec. If you have just done a meridian flip, " - "check to see if the 'Reverse Dec output option' on the Advanced Dialog guiding tab is wrong. Otherwise, " - "check for cable snags, try re-doing your calibration, and check for problems with the mount mechanics."); + "check to see if the 'Reverse Dec output option' on the Advanced Dialog guiding tab is wrong. " + "Otherwise, " + "check for cable snags, try re-doing your calibration, and check for problems with the mount " + "mechanics."); } else { - msg = _("PHD2 is not able to make sufficient corrections in Dec. Check for cable snags, try re-doing your calibration and " + msg = _("PHD2 is not able to make sufficient corrections in Dec. Check for cable snags, try re-doing your " + "calibration and " "confirm the ST-4 cable is working properly."); } } - pFrame->SuppressableAlert(LimitReachedWarningKey(axis), msg, SuppressLimitReachedWarning, axis, false, wxICON_INFORMATION); + pFrame->SuppressableAlert( + LimitReachedWarningKey(axis), msg, SuppressLimitReachedWarning, axis, false, wxICON_INFORMATION); } - else // Max duration has been decreased by user, start by recommending use of default value + else // Max duration has been decreased by user, start by recommending use of default value { wxString s = axis == GUIDE_RA ? _("Max RA Duration setting") : _("Max Dec Duration setting"); pFrame->SuppressableAlert(LimitReachedWarningKey(axis), wxString::Format(_("Your %s is preventing PHD from making adequate corrections to keep the guide star locked. " - "Try restoring %s to its default value to allow PHD2 to make larger corrections."), s, s), - SuppressLimitReachedWarning, axis, false, wxICON_INFORMATION); + "Try restoring %s to its default value to allow PHD2 to make larger corrections."), + s, s), + SuppressLimitReachedWarning, axis, false, wxICON_INFORMATION); } } - else // Already at maximum allowed value + else // Already at maximum allowed value { wxString which_axis = axis == GUIDE_RA ? _("RA") : _("Dec"); pFrame->SuppressableAlert(LimitReachedWarningKey(axis), - wxString::Format(_("Even using the maximum moves, PHD2 can't properly correct for the large guide star movements in %s. " - "Guiding will be impaired until you can eliminate the source of these problems."), which_axis), + wxString::Format( + _("Even using the maximum moves, PHD2 can't properly correct for the large guide star movements in %s. " + "Guiding will be impaired until you can eliminate the source of these problems."), + which_axis), SuppressLimitReachedWarning, axis, false, wxICON_INFORMATION); } } -Mount::MOVE_RESULT Scope::MoveAxis(GUIDE_DIRECTION direction, int duration, unsigned int moveOptions, MoveResultInfo *moveResult) +Mount::MOVE_RESULT Scope::MoveAxis( + GUIDE_DIRECTION direction, int duration, unsigned int moveOptions, MoveResultInfo *moveResult) { MOVE_RESULT result = MOVE_OK; bool limitReached = false; try { - Debug.Write(wxString::Format("MoveAxis(%s, %d, %s)\n", DirectionChar(direction), duration, DumpMoveOptionBits(moveOptions))); + Debug.Write( + wxString::Format("MoveAxis(%s, %d, %s)\n", DirectionChar(direction), duration, DumpMoveOptionBits(moveOptions))); if (!m_guidingEnabled && (moveOptions & MOVEOPT_MANUAL) == 0) { @@ -694,71 +722,70 @@ Mount::MOVE_RESULT Scope::MoveAxis(GUIDE_DIRECTION direction, int duration, unsi switch (direction) { - case NORTH: - case SOUTH: + case NORTH: + case SOUTH: - // Enforce dec guide mode and max duration for guide step (or deduced step) moves - if (moveOptions & (MOVEOPT_ALGO_RESULT | MOVEOPT_ALGO_DEDUCE)) + // Enforce dec guide mode and max duration for guide step (or deduced step) moves + if (moveOptions & (MOVEOPT_ALGO_RESULT | MOVEOPT_ALGO_DEDUCE)) + { + if ((m_decGuideMode == DEC_NONE) || (direction == SOUTH && m_decGuideMode == DEC_NORTH) || + (direction == NORTH && m_decGuideMode == DEC_SOUTH)) { - if ((m_decGuideMode == DEC_NONE) || - (direction == SOUTH && m_decGuideMode == DEC_NORTH) || - (direction == NORTH && m_decGuideMode == DEC_SOUTH)) - { - duration = 0; - Debug.Write("duration set to 0 by GuideMode\n"); - } - - if (duration > m_maxDecDuration) - { - duration = m_maxDecDuration; - Debug.Write(wxString::Format("duration set to %d by maxDecDuration\n", duration)); - limitReached = true; - } - - if (limitReached && direction == m_decLimitReachedDirection) - { - if (++m_decLimitReachedCount >= LIMIT_REACHED_WARN_COUNT) - AlertLimitReached(duration, GUIDE_DEC); - } - else - m_decLimitReachedCount = 0; + duration = 0; + Debug.Write("duration set to 0 by GuideMode\n"); + } - if (limitReached) - m_decLimitReachedDirection = direction; - else - m_decLimitReachedDirection = NONE; + if (duration > m_maxDecDuration) + { + duration = m_maxDecDuration; + Debug.Write(wxString::Format("duration set to %d by maxDecDuration\n", duration)); + limitReached = true; } - break; - case EAST: - case WEST: - // Enforce max duration for guide step (or deduced step) moves - if (moveOptions & (MOVEOPT_ALGO_RESULT | MOVEOPT_ALGO_DEDUCE)) + if (limitReached && direction == m_decLimitReachedDirection) { - if (duration > m_maxRaDuration) - { - duration = m_maxRaDuration; - Debug.Write(wxString::Format("duration set to %d by maxRaDuration\n", duration)); - limitReached = true; - } + if (++m_decLimitReachedCount >= LIMIT_REACHED_WARN_COUNT) + AlertLimitReached(duration, GUIDE_DEC); + } + else + m_decLimitReachedCount = 0; - if (limitReached && direction == m_raLimitReachedDirection) - { - if (++m_raLimitReachedCount >= LIMIT_REACHED_WARN_COUNT) - AlertLimitReached(duration, GUIDE_RA); - } - else - m_raLimitReachedCount = 0; + if (limitReached) + m_decLimitReachedDirection = direction; + else + m_decLimitReachedDirection = NONE; + } + break; + case EAST: + case WEST: - if (limitReached) - m_raLimitReachedDirection = direction; - else - m_raLimitReachedDirection = NONE; + // Enforce max duration for guide step (or deduced step) moves + if (moveOptions & (MOVEOPT_ALGO_RESULT | MOVEOPT_ALGO_DEDUCE)) + { + if (duration > m_maxRaDuration) + { + duration = m_maxRaDuration; + Debug.Write(wxString::Format("duration set to %d by maxRaDuration\n", duration)); + limitReached = true; } - break; - case NONE: - break; + if (limitReached && direction == m_raLimitReachedDirection) + { + if (++m_raLimitReachedCount >= LIMIT_REACHED_WARN_COUNT) + AlertLimitReached(duration, GUIDE_RA); + } + else + m_raLimitReachedCount = 0; + + if (limitReached) + m_raLimitReachedDirection = direction; + else + m_raLimitReachedDirection = NONE; + } + break; + + case NONE: + break; } // Actually do the guide @@ -810,7 +837,6 @@ static wxString CalibrationWarningKey(CalibrationIssueType etype) case CI_None: qual = "Bogus"; break; - } wxString rtn = wxString::Format("/Confirm/%d/CalWarning_%s", pConfig->GetCurrentProfileId(), qual); return rtn; @@ -834,12 +860,13 @@ void Scope::HandleSanityCheckDialog() if (pFrame->pCalSanityCheckDlg) pFrame->pCalSanityCheckDlg->Destroy(); - pFrame->pCalSanityCheckDlg = new CalSanityDialog(pFrame, m_prevCalibration, m_prevCalibrationDetails, m_lastCalibrationIssue); + pFrame->pCalSanityCheckDlg = + new CalSanityDialog(pFrame, m_prevCalibration, m_prevCalibrationDetails, m_lastCalibrationIssue); pFrame->pCalSanityCheckDlg->Show(); } -// Do some basic sanity checking on the just-completed calibration, looking for things that are fishy. Do the checking in the order of -// importance/confidence, since we only alert about a single condition +// Do some basic sanity checking on the just-completed calibration, looking for things that are fishy. Do the checking in the +// order of importance/confidence, since we only alert about a single condition void Scope::SanityCheckCalibration(const Calibration& oldCal, const CalibrationDetails& oldDetails) { Calibration newCal; @@ -855,7 +882,7 @@ void Scope::SanityCheckCalibration(const Calibration& oldCal, const CalibrationD wxString detailInfo; // Too few steps - if (xSteps < CAL_ALERT_MINSTEPS || (ySteps < CAL_ALERT_MINSTEPS && ySteps > 0)) // Dec guiding might be disabled + if (xSteps < CAL_ALERT_MINSTEPS || (ySteps < CAL_ALERT_MINSTEPS && ySteps > 0)) // Dec guiding might be disabled { m_lastCalibrationIssue = CI_Steps; detailInfo = wxString::Format("Actual RA calibration steps = %d, Dec calibration steps = %d", xSteps, ySteps); @@ -863,22 +890,23 @@ void Scope::SanityCheckCalibration(const Calibration& oldCal, const CalibrationD else { // Non-orthogonal RA/Dec axes - double nonOrtho = degrees(fabs(fabs(norm_angle(newCal.xAngle - newCal.yAngle)) - M_PI / 2.)); // Delta from the nearest multiple of 90 degrees - if (nonOrtho > CAL_ALERT_ORTHOGONALITY_TOLERANCE) + double nonOrtho = degrees( + fabs(fabs(norm_angle(newCal.xAngle - newCal.yAngle)) - M_PI / 2.)); // Delta from the nearest multiple of 90 degrees + if (nonOrtho > CAL_ALERT_ORTHOGONALITY_TOLERANCE) { m_lastCalibrationIssue = CI_Angle; detailInfo = wxString::Format("Non-orthogonality = %0.3f", nonOrtho); } else { - // RA/Dec rates should be related by cos(dec) but don't check if Dec is too high or Dec guiding is disabled. Also don't check if DecComp - // is disabled because a Sitech controller might be monkeying around with the apparent rates + // RA/Dec rates should be related by cos(dec) but don't check if Dec is too high or Dec guiding is disabled. Also + // don't check if DecComp is disabled because a Sitech controller might be monkeying around with the apparent rates if (newCal.declination != UNKNOWN_DECLINATION && newCal.yRate != CALIBRATION_RATE_UNCALIBRATED && fabs(newCal.declination) <= Scope::DEC_COMP_LIMIT && DecCompensationEnabled()) { double expectedRatio = cos(newCal.declination); double speedRatio; - if (newDetails.raGuideSpeed > 0.) // for mounts that may have different guide speeds on RA and Dec axes + if (newDetails.raGuideSpeed > 0.) // for mounts that may have different guide speeds on RA and Dec axes speedRatio = newDetails.decGuideSpeed / newDetails.raGuideSpeed; else speedRatio = 1.0; @@ -886,15 +914,17 @@ void Scope::SanityCheckCalibration(const Calibration& oldCal, const CalibrationD if (fabs(expectedRatio - actualRatio) > CAL_ALERT_AXISRATES_TOLERANCE) { m_lastCalibrationIssue = CI_Rates; - detailInfo = wxString::Format("Expected ratio at dec=%0.1f is %0.3f, actual is %0.3f", degrees(newCal.declination), expectedRatio, actualRatio); + detailInfo = wxString::Format("Expected ratio at dec=%0.1f is %0.3f, actual is %0.3f", + degrees(newCal.declination), expectedRatio, actualRatio); } } } - // Finally check for a significantly different result but don't be stupid - ignore differences if the configuration looks quite different - // Can't do straight equality checks because of rounding - the "old" values have passed through the registry get/set routines - if (m_lastCalibrationIssue == CI_None && oldCal.isValid && - fabs(oldDetails.imageScale - newDetails.imageScale) < 0.1 && (fabs(degrees(oldCal.xAngle - newCal.xAngle)) < 5.0)) + // Finally check for a significantly different result but don't be stupid - ignore differences if the configuration + // looks quite different Can't do straight equality checks because of rounding - the "old" values have passed through + // the registry get/set routines + if (m_lastCalibrationIssue == CI_None && oldCal.isValid && fabs(oldDetails.imageScale - newDetails.imageScale) < 0.1 && + (fabs(degrees(oldCal.xAngle - newCal.xAngle)) < 5.0)) { if (newCal.yRate != CALIBRATION_RATE_UNCALIBRATED && oldCal.yRate != CALIBRATION_RATE_UNCALIBRATED) { @@ -925,24 +955,27 @@ void Scope::SanityCheckCalibration(const Calibration& oldCal, const CalibrationD alertMsg = _("Advisory: Calibration completed but RA/Dec axis angles are questionable and guiding may be impaired"); break; case CI_Different: - alertMsg = _("Advisory: This calibration is substantially different from the previous one - have you changed configurations?"); + alertMsg = _("Advisory: This calibration is substantially different from the previous one - have you changed " + "configurations?"); break; case CI_Rates: - alertMsg = _("Advisory: Calibration completed but RA and Dec rates vary by an unexpected amount (often caused by large Dec backlash)"); + alertMsg = _("Advisory: Calibration completed but RA and Dec rates vary by an unexpected amount (often caused by " + "large Dec backlash)"); default: break; } // Suppression of calibration alerts is handled in the 'Details' dialog - a special case - if (pConfig->Global.GetBoolean(CalibrationWarningKey(m_lastCalibrationIssue), true)) // User hasn't disabled this type of alert + if (pConfig->Global.GetBoolean( + CalibrationWarningKey(m_lastCalibrationIssue), true)) // User hasn't disabled this type of alert { // Generate alert with 'Help' button that will lead to trouble-shooting section - pFrame->Alert(alertMsg, 0, - _("Details..."), ShowCalibrationIssues, (long)this, true); + pFrame->Alert(alertMsg, 0, _("Details..."), ShowCalibrationIssues, (long) this, true); } else { - Debug.Write(wxString::Format("Alert detected in scope calibration but not shown to user - suppressed message was: %s\n", alertMsg)); + Debug.Write(wxString::Format( + "Alert detected in scope calibration but not shown to user - suppressed message was: %s\n", alertMsg)); } Debug.Write(wxString::Format("Calibration alert details: %s\n", detailInfo)); @@ -972,13 +1005,14 @@ void Scope::CheckCalibrationDuration(int currDuration) if (binningChange) { int prevDistance = GetCalibrationDistance(); - int newDistance = CalstepDialog::GetCalibrationDistance(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), - pCamera->Binning); + int newDistance = + CalstepDialog::GetCalibrationDistance(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning); if (newDistance != prevDistance) { - Debug.Write(wxString::Format("CalDistance adjusted at start of calibration from %d to %d because of binning change\n", - prevDistance, newDistance)); + Debug.Write( + wxString::Format("CalDistance adjusted at start of calibration from %d to %d because of binning change\n", + prevDistance, newDistance)); SetCalibrationDistance(newDistance); } @@ -987,25 +1021,26 @@ void Scope::CheckCalibrationDuration(int currDuration) double raSpd; double decSpd; double const siderealSecsPerSec = 0.9973; - bool haveRates = !pPointingSource->GetGuideRates(&raSpd, &decSpd); // units of degrees/sec as in ASCOM + bool haveRates = !pPointingSource->GetGuideRates(&raSpd, &decSpd); // units of degrees/sec as in ASCOM - double currSpdX = raSpd * 3600.0 / (15.0 * siderealSecsPerSec); // multiple of sidereal + double currSpdX = raSpd * 3600.0 / (15.0 * siderealSecsPerSec); // multiple of sidereal // Don't check the step size on very first calibration and don't adjust if the reported mount guide speeds are bogus if (!haveRates || calDetails.raGuideSpeed <= 0) return; - bool refineStepSize = binningChange || (fabs(1.0 - raSpd / calDetails.raGuideSpeed) > 0.05); // binning change or speed change of > 5% + bool refineStepSize = + binningChange || (fabs(1.0 - raSpd / calDetails.raGuideSpeed) > 0.05); // binning change or speed change of > 5% if (!refineStepSize) return; int rslt; - CalstepDialog::GetCalibrationStepSize(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), - pCamera->Binning, currSpdX, CalstepDialog::DEFAULT_STEPS, 0.0, GetCalibrationDistance(), 0, &rslt); + CalstepDialog::GetCalibrationStepSize(pFrame->GetFocalLength(), pCamera->GetCameraPixelSize(), pCamera->Binning, currSpdX, + CalstepDialog::DEFAULT_STEPS, 0.0, GetCalibrationDistance(), 0, &rslt); wxString why = binningChange ? " binning " : " mount guide speed "; - Debug.Write(wxString::Format("CalDuration adjusted at start of calibration from %d to %d because of %s change\n", - currDuration, rslt, why)); + Debug.Write(wxString::Format( + "CalDuration adjusted at start of calibration from %d to %d because of %s change\n", currDuration, rslt, why)); SetCalibrationDuration(rslt); } @@ -1026,7 +1061,7 @@ bool Scope::BeginCalibration(const PHD_Point& currentLocation) throw ERROR_INFO("Must have a valid lock position"); } - CheckCalibrationDuration(m_calibrationDuration); // Make sure guide speeds or binning haven't changed underneath us + CheckCalibrationDuration(m_calibrationDuration); // Make sure guide speeds or binning haven't changed underneath us ClearCalibration(); m_calibrationSteps = 0; m_calibrationInitialLocation = currentLocation; @@ -1061,7 +1096,7 @@ void Scope::SetCalibrationDetails(const CalibrationDetails& calDetails, double x double ra_rate; double dec_rate; - if (pPointingSource->GetGuideRates(&ra_rate, &dec_rate)) // true means error + if (pPointingSource->GetGuideRates(&ra_rate, &dec_rate)) // true means error { ra_rate = -1.0; dec_rate = -1.0; @@ -1071,7 +1106,8 @@ void Scope::SetCalibrationDetails(const CalibrationDetails& calDetails, double x m_calibrationDetails.decGuideSpeed = dec_rate; m_calibrationDetails.focalLength = pFrame->GetFocalLength(); m_calibrationDetails.imageScale = pFrame->GetCameraPixelScale(); - m_calibrationDetails.orthoError = degrees(fabs(fabs(norm_angle(xAngle - yAngle)) - M_PI / 2.)); // Delta from the nearest multiple of 90 degrees + m_calibrationDetails.orthoError = + degrees(fabs(fabs(norm_angle(xAngle - yAngle)) - M_PI / 2.)); // Delta from the nearest multiple of 90 degrees m_calibrationDetails.origBinning = binning; m_calibrationDetails.origTimestamp = wxDateTime::Now().Format(); m_calibrationDetails.origPierSide = pPointingSource->SideOfPier(); @@ -1099,10 +1135,10 @@ bool Scope::IsCalibrated() const case DEC_AUTO: case DEC_NORTH: case DEC_SOUTH: - { - bool have_ns_calibration = m_calibration.yRate != CALIBRATION_RATE_UNCALIBRATED; - return have_ns_calibration; - } + { + bool have_ns_calibration = m_calibration.yRate != CALIBRATION_RATE_UNCALIBRATED; + return have_ns_calibration; + } default: assert(false); return true; @@ -1144,7 +1180,8 @@ static void GetRADecCoordinates(PHD_Point *coords) static wxString DecBacklashAlertKey() { - // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting to be per-profile + // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting + // to be per-profile return wxString::Format("/Confirm/%d/DecBacklashWarningEnabled", pConfig->GetCurrentProfileId()); } @@ -1173,8 +1210,9 @@ bool Scope::UpdateCalibrationState(const PHD_Point& currentLocation) Debug.Write(wxString::Format("Scope::UpdateCalibrationstate: starting location = %.2f,%.2f coords = %s\n", currentLocation.X, currentLocation.Y, - m_calibrationStartingCoords.IsValid() ? - wxString::Format("%.2f,%.1f", m_calibrationStartingCoords.X, m_calibrationStartingCoords.Y) : wxString("N/A"))); + m_calibrationStartingCoords.IsValid() + ? wxString::Format("%.2f,%.1f", m_calibrationStartingCoords.X, m_calibrationStartingCoords.Y) + : wxString("N/A"))); } double dX = m_calibrationStartingLocation.dX(currentLocation); @@ -1194,503 +1232,537 @@ bool Scope::UpdateCalibrationState(const PHD_Point& currentLocation) switch (m_calibrationState) { - case CALIBRATION_STATE_CLEARED: - assert(false); - break; + case CALIBRATION_STATE_CLEARED: + assert(false); + break; - case CALIBRATION_STATE_GO_WEST: { + case CALIBRATION_STATE_GO_WEST: + { - // step number in the log is the step that just finished - CalibrationStepInfo info(this, _T("West"), m_calibrationSteps, dX, dY, currentLocation, dist); - GuideLog.CalibrationStep(info); - m_calibrationDetails.raSteps.push_back(wxRealPoint(dX, dY)); + // step number in the log is the step that just finished + CalibrationStepInfo info(this, _T("West"), m_calibrationSteps, dX, dY, currentLocation, dist); + GuideLog.CalibrationStep(info); + m_calibrationDetails.raSteps.push_back(wxRealPoint(dX, dY)); - if (dist < dist_crit) + if (dist < dist_crit) + { + if (m_calibrationSteps++ > MAX_CALIBRATION_STEPS) { - if (m_calibrationSteps++ > MAX_CALIBRATION_STEPS) - { - wxString msg(wxTRANSLATE("RA Calibration Failed: star did not move enough")); - const wxString& translated(wxGetTranslation(msg)); - pFrame->Alert(translated); - GuideLog.CalibrationFailed(this, msg); - EvtServer.NotifyCalibrationFailed(this, msg); - throw ERROR_INFO("RA calibration failed"); - } - CalibrationStatus(info, wxString::Format(_("West step %3d, dist=%4.1f"), m_calibrationSteps, dist)); - pFrame->ScheduleAxisMove(this, WEST, m_calibrationDuration, MOVEOPTS_CALIBRATION_MOVE); - break; + wxString msg(wxTRANSLATE("RA Calibration Failed: star did not move enough")); + const wxString& translated(wxGetTranslation(msg)); + pFrame->Alert(translated); + GuideLog.CalibrationFailed(this, msg); + EvtServer.NotifyCalibrationFailed(this, msg); + throw ERROR_INFO("RA calibration failed"); } + CalibrationStatus(info, wxString::Format(_("West step %3d, dist=%4.1f"), m_calibrationSteps, dist)); + pFrame->ScheduleAxisMove(this, WEST, m_calibrationDuration, MOVEOPTS_CALIBRATION_MOVE); + break; + } - // West calibration complete + // West calibration complete - m_calibration.xAngle = m_calibrationStartingLocation.Angle(currentLocation); - m_calibration.xRate = dist / (m_calibrationSteps * m_calibrationDuration); + m_calibration.xAngle = m_calibrationStartingLocation.Angle(currentLocation); + m_calibration.xRate = dist / (m_calibrationSteps * m_calibrationDuration); - m_calibration.raGuideParity = GUIDE_PARITY_UNKNOWN; - if (m_calibrationStartingCoords.IsValid()) + m_calibration.raGuideParity = GUIDE_PARITY_UNKNOWN; + if (m_calibrationStartingCoords.IsValid()) + { + PHD_Point endingCoords; + GetRADecCoordinates(&endingCoords); + if (endingCoords.IsValid()) { - PHD_Point endingCoords; - GetRADecCoordinates(&endingCoords); - if (endingCoords.IsValid()) - { - // true westward motion decreases RA - double ONE_ARCSEC = 24.0 / (360. * 60. * 60.); // hours - double dra = endingCoords.X - m_calibrationStartingCoords.X; - if (dra < -ONE_ARCSEC) - m_calibration.raGuideParity = GUIDE_PARITY_EVEN; - else if (dra > ONE_ARCSEC) - m_calibration.raGuideParity = GUIDE_PARITY_ODD; - } + // true westward motion decreases RA + double ONE_ARCSEC = 24.0 / (360. * 60. * 60.); // hours + double dra = endingCoords.X - m_calibrationStartingCoords.X; + if (dra < -ONE_ARCSEC) + m_calibration.raGuideParity = GUIDE_PARITY_EVEN; + else if (dra > ONE_ARCSEC) + m_calibration.raGuideParity = GUIDE_PARITY_ODD; } + } - Debug.Write(wxString::Format("WEST calibration completes with steps=%d angle=%.1f rate=%.3f parity=%d\n", - m_calibrationSteps, degrees(m_calibration.xAngle), m_calibration.xRate * 1000.0, m_calibration.raGuideParity)); + Debug.Write(wxString::Format("WEST calibration completes with steps=%d angle=%.1f rate=%.3f parity=%d\n", + m_calibrationSteps, degrees(m_calibration.xAngle), m_calibration.xRate * 1000.0, m_calibration.raGuideParity)); - m_raSteps = m_calibrationSteps; - GuideLog.CalibrationDirectComplete(this, "West", m_calibration.xAngle, m_calibration.xRate, m_calibration.raGuideParity); + m_raSteps = m_calibrationSteps; + GuideLog.CalibrationDirectComplete( + this, "West", m_calibration.xAngle, m_calibration.xRate, m_calibration.raGuideParity); - // for GO_EAST m_recenterRemaining contains the total remaining duration. - // Choose the largest pulse size that will not lose the guide star or exceed - // the user-specified max pulse + // for GO_EAST m_recenterRemaining contains the total remaining duration. + // Choose the largest pulse size that will not lose the guide star or exceed + // the user-specified max pulse - m_recenterRemaining = m_calibrationSteps * m_calibrationDuration; + m_recenterRemaining = m_calibrationSteps * m_calibrationDuration; - if (pFrame->pGuider->IsFastRecenterEnabled()) - { - m_recenterDuration = (int)floor((double)pFrame->pGuider->GetMaxMovePixels() / m_calibration.xRate); - if (m_recenterDuration > m_maxRaDuration) - m_recenterDuration = m_maxRaDuration; - if (m_recenterDuration < m_calibrationDuration) - m_recenterDuration = m_calibrationDuration; - } - else + if (pFrame->pGuider->IsFastRecenterEnabled()) + { + m_recenterDuration = (int) floor((double) pFrame->pGuider->GetMaxMovePixels() / m_calibration.xRate); + if (m_recenterDuration > m_maxRaDuration) + m_recenterDuration = m_maxRaDuration; + if (m_recenterDuration < m_calibrationDuration) m_recenterDuration = m_calibrationDuration; - - m_calibrationSteps = DIV_ROUND_UP(m_recenterRemaining, m_recenterDuration); - m_calibrationState = CALIBRATION_STATE_GO_EAST; - m_eastStartingLocation = currentLocation; - - // fall through - Debug.Write("Falling Through to state GO_EAST\n"); } + else + m_recenterDuration = m_calibrationDuration; - case CALIBRATION_STATE_GO_EAST: { + m_calibrationSteps = DIV_ROUND_UP(m_recenterRemaining, m_recenterDuration); + m_calibrationState = CALIBRATION_STATE_GO_EAST; + m_eastStartingLocation = currentLocation; - CalibrationStepInfo info(this, _T("East"), m_calibrationSteps, dX, dY, currentLocation, dist); - GuideLog.CalibrationStep(info); - m_calibrationDetails.raSteps.push_back(wxRealPoint(dX, dY)); + // fall through + Debug.Write("Falling Through to state GO_EAST\n"); + } - if (m_recenterRemaining > 0) - { - int duration = m_recenterDuration; - if (duration > m_recenterRemaining) - duration = m_recenterRemaining; + case CALIBRATION_STATE_GO_EAST: + { - CalibrationStatus(info, wxString::Format(_("East step %3d, dist=%4.1f"), m_calibrationSteps, dist)); + CalibrationStepInfo info(this, _T("East"), m_calibrationSteps, dX, dY, currentLocation, dist); + GuideLog.CalibrationStep(info); + m_calibrationDetails.raSteps.push_back(wxRealPoint(dX, dY)); - m_recenterRemaining -= duration; - --m_calibrationSteps; - m_lastLocation = currentLocation; + if (m_recenterRemaining > 0) + { + int duration = m_recenterDuration; + if (duration > m_recenterRemaining) + duration = m_recenterRemaining; - pFrame->ScheduleAxisMove(this, EAST, duration, MOVEOPTS_CALIBRATION_MOVE); - break; - } + CalibrationStatus(info, wxString::Format(_("East step %3d, dist=%4.1f"), m_calibrationSteps, dist)); - // If not pulse-guiding check for obvious guide cable problem and no useful east moves - if (!CanPulseGuide()) - { - double eastDistMoved = m_eastStartingLocation.Distance(currentLocation); - double westDistMoved = m_calibrationStartingLocation.Distance(m_eastStartingLocation); - double eastAngle = m_eastStartingLocation.Angle(currentLocation); - // Want a significant east movement that re-traces the west vector to within 30 degrees - if (fabs(eastDistMoved) < 0.25 * westDistMoved || fabs(norm_angle(eastAngle - (m_calibration.xAngle + M_PI))) > radians(30)) - { - wxString msg(wxTRANSLATE("Advisory: Little or no east movement was measured, so guiding will probably be impaired. " - "Check the guide cable and use the Manual Guide tool to confirm basic operation of the mount.")); - const wxString& translated(wxGetTranslation(msg)); - pFrame->Alert(translated, 0, wxEmptyString, 0, 0, true); - Debug.Write("Calibration alert: " + msg + "\n"); - m_eastAlertShown = true; - } - } - // setup for clear backlash + m_recenterRemaining -= duration; + --m_calibrationSteps; + m_lastLocation = currentLocation; - m_calibrationSteps = 0; - dist = dX = dY = 0.0; - m_calibrationStartingLocation = currentLocation; + pFrame->ScheduleAxisMove(this, EAST, duration, MOVEOPTS_CALIBRATION_MOVE); + break; + } - if (m_decGuideMode == DEC_NONE) + // If not pulse-guiding check for obvious guide cable problem and no useful east moves + if (!CanPulseGuide()) + { + double eastDistMoved = m_eastStartingLocation.Distance(currentLocation); + double westDistMoved = m_calibrationStartingLocation.Distance(m_eastStartingLocation); + double eastAngle = m_eastStartingLocation.Angle(currentLocation); + // Want a significant east movement that re-traces the west vector to within 30 degrees + if (fabs(eastDistMoved) < 0.25 * westDistMoved || + fabs(norm_angle(eastAngle - (m_calibration.xAngle + M_PI))) > radians(30)) { - Debug.Write("Skipping Dec calibration as DecGuideMode == NONE\n"); - m_calibrationState = CALIBRATION_STATE_COMPLETE; - m_calibration.yAngle = norm_angle(m_calibration.xAngle + M_PI / 2.); // choose an arbitrary angle perpendicular to xAngle - // indicate lack of Dec calibration data, see Scope::IsCalibrated. - m_calibration.yRate = CALIBRATION_RATE_UNCALIBRATED; - m_calibration.decGuideParity = GUIDE_PARITY_UNKNOWN; - break; + wxString msg(wxTRANSLATE( + "Advisory: Little or no east movement was measured, so guiding will probably be impaired. " + "Check the guide cable and use the Manual Guide tool to confirm basic operation of the mount.")); + const wxString& translated(wxGetTranslation(msg)); + pFrame->Alert(translated, 0, wxEmptyString, 0, 0, true); + Debug.Write("Calibration alert: " + msg + "\n"); + m_eastAlertShown = true; } + } + // setup for clear backlash - m_calibrationState = CALIBRATION_STATE_CLEAR_BACKLASH; - m_blMarkerPoint = currentLocation; - GetRADecCoordinates(&m_calibrationStartingCoords); - m_blExpectedBacklashStep = m_calibration.xRate * m_calibrationDuration * 0.6; + m_calibrationSteps = 0; + dist = dX = dY = 0.0; + m_calibrationStartingLocation = currentLocation; - double RASpeed; - double DecSpeed; - if (!pPointingSource->GetGuideRates(&RASpeed, &DecSpeed) && - RASpeed != 0.0 && RASpeed != DecSpeed) - { - m_blExpectedBacklashStep *= DecSpeed / RASpeed; - } + if (m_decGuideMode == DEC_NONE) + { + Debug.Write("Skipping Dec calibration as DecGuideMode == NONE\n"); + m_calibrationState = CALIBRATION_STATE_COMPLETE; + m_calibration.yAngle = + norm_angle(m_calibration.xAngle + M_PI / 2.); // choose an arbitrary angle perpendicular to xAngle + // indicate lack of Dec calibration data, see Scope::IsCalibrated. + m_calibration.yRate = CALIBRATION_RATE_UNCALIBRATED; + m_calibration.decGuideParity = GUIDE_PARITY_UNKNOWN; + break; + } - m_blMaxClearingPulses = wxMax(8, BL_MAX_CLEARING_TIME / m_calibrationDuration); - m_blLastCumDistance = 0; - m_blAcceptedMoves = 0; - Debug.Write(wxString::Format("Backlash: Looking for 3 moves of %0.1f px, max attempts = %d\n", m_blExpectedBacklashStep, m_blMaxClearingPulses)); - // fall through - Debug.Write("Falling Through to state CLEAR_BACKLASH\n"); + m_calibrationState = CALIBRATION_STATE_CLEAR_BACKLASH; + m_blMarkerPoint = currentLocation; + GetRADecCoordinates(&m_calibrationStartingCoords); + m_blExpectedBacklashStep = m_calibration.xRate * m_calibrationDuration * 0.6; + + double RASpeed; + double DecSpeed; + if (!pPointingSource->GetGuideRates(&RASpeed, &DecSpeed) && RASpeed != 0.0 && RASpeed != DecSpeed) + { + m_blExpectedBacklashStep *= DecSpeed / RASpeed; } - case CALIBRATION_STATE_CLEAR_BACKLASH: { + m_blMaxClearingPulses = wxMax(8, BL_MAX_CLEARING_TIME / m_calibrationDuration); + m_blLastCumDistance = 0; + m_blAcceptedMoves = 0; + Debug.Write(wxString::Format("Backlash: Looking for 3 moves of %0.1f px, max attempts = %d\n", + m_blExpectedBacklashStep, m_blMaxClearingPulses)); + // fall through + Debug.Write("Falling Through to state CLEAR_BACKLASH\n"); + } - CalibrationStepInfo info(this, _T("Backlash"), m_calibrationSteps, dX, dY, currentLocation, dist); - GuideLog.CalibrationStep(info); - blDelta = m_blMarkerPoint.Distance(currentLocation); - blCumDelta = dist; + case CALIBRATION_STATE_CLEAR_BACKLASH: + { - // Want to see the mount moving north for 3 moves of >= expected distance pixels without any direction reversals - if (m_calibrationSteps == 0) - { - // Get things moving with the first clearing pulse - Debug.Write(wxString::Format("Backlash: Starting north clearing using pulse width of %d\n", - m_calibrationDuration)); - pFrame->ScheduleAxisMove(this, NORTH, m_calibrationDuration, MOVEOPTS_CALIBRATION_MOVE); - m_calibrationSteps = 1; - CalibrationStatus(info, _("Clearing backlash step 1")); - break; - } + CalibrationStepInfo info(this, _T("Backlash"), m_calibrationSteps, dX, dY, currentLocation, dist); + GuideLog.CalibrationStep(info); + blDelta = m_blMarkerPoint.Distance(currentLocation); + blCumDelta = dist; - if (blDelta >= m_blExpectedBacklashStep) + // Want to see the mount moving north for 3 moves of >= expected distance pixels without any direction reversals + if (m_calibrationSteps == 0) + { + // Get things moving with the first clearing pulse + Debug.Write( + wxString::Format("Backlash: Starting north clearing using pulse width of %d\n", m_calibrationDuration)); + pFrame->ScheduleAxisMove(this, NORTH, m_calibrationDuration, MOVEOPTS_CALIBRATION_MOVE); + m_calibrationSteps = 1; + CalibrationStatus(info, _("Clearing backlash step 1")); + break; + } + + if (blDelta >= m_blExpectedBacklashStep) + { + if (m_blAcceptedMoves == 0 || + (blCumDelta > m_blLastCumDistance)) // Just starting or still moving in same direction { - if (m_blAcceptedMoves == 0 || (blCumDelta > m_blLastCumDistance)) // Just starting or still moving in same direction - { - m_blAcceptedMoves++; - Debug.Write(wxString::Format("Backlash: Accepted clearing move of %0.1f\n", blDelta)); - } - else - { - m_blAcceptedMoves = 0; // Reset on a direction reversal - Debug.Write(wxString::Format("Backlash: Rejected clearing move of %0.1f, direction reversal\n", blDelta)); - } + m_blAcceptedMoves++; + Debug.Write(wxString::Format("Backlash: Accepted clearing move of %0.1f\n", blDelta)); } else { - if (blCumDelta < m_blLastCumDistance) - { - m_blAcceptedMoves = 0; - Debug.Write(wxString::Format("Backlash: Rejected small direction reversal of %0.1f px\n", blDelta)); - } - else - Debug.Write(wxString::Format("Backlash: Rejected small move of %0.1f px\n", blDelta)); + m_blAcceptedMoves = 0; // Reset on a direction reversal + Debug.Write(wxString::Format("Backlash: Rejected clearing move of %0.1f, direction reversal\n", blDelta)); + } + } + else + { + if (blCumDelta < m_blLastCumDistance) + { + m_blAcceptedMoves = 0; + Debug.Write(wxString::Format("Backlash: Rejected small direction reversal of %0.1f px\n", blDelta)); } + else + Debug.Write(wxString::Format("Backlash: Rejected small move of %0.1f px\n", blDelta)); + } - if (m_blAcceptedMoves < BL_BACKLASH_MIN_COUNT) // More work to do + if (m_blAcceptedMoves < BL_BACKLASH_MIN_COUNT) // More work to do + { + if (m_calibrationSteps < m_blMaxClearingPulses && blCumDelta < dist_crit) + { + // Still have attempts left, haven't moved the star by 25 px yet + pFrame->ScheduleAxisMove(this, NORTH, m_calibrationDuration, MOVEOPTS_CALIBRATION_MOVE); + m_calibrationSteps++; + m_blMarkerPoint = currentLocation; + GetRADecCoordinates(&m_calibrationStartingCoords); + m_blLastCumDistance = blCumDelta; + CalibrationStatus(info, wxString::Format(_("Clearing backlash step %3d"), m_calibrationSteps)); + Debug.Write(wxString::Format( + "Backlash: %s, Last Delta = %0.2f px, CumDistance = %0.2f px\n", info.msg, blDelta, blCumDelta)); + break; + } + else { - if (m_calibrationSteps < m_blMaxClearingPulses && blCumDelta < dist_crit) + // Used up all our attempts - might be ok or not + if (blCumDelta >= BL_MIN_CLEARING_DISTANCE) { - // Still have attempts left, haven't moved the star by 25 px yet - pFrame->ScheduleAxisMove(this, NORTH, m_calibrationDuration, MOVEOPTS_CALIBRATION_MOVE); - m_calibrationSteps++; - m_blMarkerPoint = currentLocation; - GetRADecCoordinates(&m_calibrationStartingCoords); - m_blLastCumDistance = blCumDelta; - CalibrationStatus(info, wxString::Format(_("Clearing backlash step %3d"), m_calibrationSteps)); - Debug.Write(wxString::Format("Backlash: %s, Last Delta = %0.2f px, CumDistance = %0.2f px\n", info.msg, blDelta, blCumDelta)); - break; + // Exhausted all the clearing pulses without reaching the goal - but we did move the mount > 3 px (same + // as PHD1) + m_calibrationSteps = 0; + m_calibrationStartingLocation = currentLocation; + dX = 0; + dY = 0; + dist = 0; + Debug.Write( + "Backlash: Reached clearing limit but total displacement > 3px - proceeding with calibration\n"); } else { - // Used up all our attempts - might be ok or not - if (blCumDelta >= BL_MIN_CLEARING_DISTANCE) - { - // Exhausted all the clearing pulses without reaching the goal - but we did move the mount > 3 px (same as PHD1) - m_calibrationSteps = 0; - m_calibrationStartingLocation = currentLocation; - dX = 0; - dY = 0; - dist = 0; - Debug.Write("Backlash: Reached clearing limit but total displacement > 3px - proceeding with calibration\n"); - } - else - { - wxString msg(wxTRANSLATE("Backlash Clearing Failed: star did not move enough")); - const wxString& translated(wxGetTranslation(msg)); - pFrame->Alert(translated); - GuideLog.CalibrationFailed(this, msg); - EvtServer.NotifyCalibrationFailed(this, msg); - throw ERROR_INFO("Clear backlash failed"); - } + wxString msg(wxTRANSLATE("Backlash Clearing Failed: star did not move enough")); + const wxString& translated(wxGetTranslation(msg)); + pFrame->Alert(translated); + GuideLog.CalibrationFailed(this, msg); + EvtServer.NotifyCalibrationFailed(this, msg); + throw ERROR_INFO("Clear backlash failed"); } } - else //Got our 3 moves, move ahead - { - // We know the last backlash clearing move was big enough - include that as a north calibration move - - // log the starting point - CalibrationStepInfo info(this, _T("North"), 0, 0.0, 0.0, m_blMarkerPoint, 0.0); - GuideLog.CalibrationStep(info); - m_calibrationDetails.decSteps.push_back(wxRealPoint(0.0, 0.0)); - - m_calibrationSteps = 1; - m_calibrationStartingLocation = m_blMarkerPoint; - dX = m_blMarkerPoint.dX(currentLocation); - dY = m_blMarkerPoint.dY(currentLocation); - dist = m_blMarkerPoint.Distance(currentLocation); - Debug.Write("Backlash: Got 3 acceptable moves, using last move as step 1 of N calibration\n"); - } + } + else // Got our 3 moves, move ahead + { + // We know the last backlash clearing move was big enough - include that as a north calibration move - m_blDistanceMoved = m_blMarkerPoint.Distance(m_calibrationInitialLocation); // Need this to set nudging limit + // log the starting point + CalibrationStepInfo info(this, _T("North"), 0, 0.0, 0.0, m_blMarkerPoint, 0.0); + GuideLog.CalibrationStep(info); + m_calibrationDetails.decSteps.push_back(wxRealPoint(0.0, 0.0)); + + m_calibrationSteps = 1; + m_calibrationStartingLocation = m_blMarkerPoint; + dX = m_blMarkerPoint.dX(currentLocation); + dY = m_blMarkerPoint.dY(currentLocation); + dist = m_blMarkerPoint.Distance(currentLocation); + Debug.Write("Backlash: Got 3 acceptable moves, using last move as step 1 of N calibration\n"); + } - Debug.Write(wxString::Format("Backlash: North calibration moves starting at {%0.1f,%0.1f}, Offset = %0.1f px\n", - m_blMarkerPoint.X, m_blMarkerPoint.Y, m_blDistanceMoved)); - Debug.Write(wxString::Format("Backlash: Total distance moved = %0.1f\n", - currentLocation.Distance(m_calibrationInitialLocation))); + m_blDistanceMoved = m_blMarkerPoint.Distance(m_calibrationInitialLocation); // Need this to set nudging limit - m_calibrationState = CALIBRATION_STATE_GO_NORTH; - // falling through to start moving north - Debug.Write("Backlash: Falling Through to state GO_NORTH\n"); - } + Debug.Write(wxString::Format("Backlash: North calibration moves starting at {%0.1f,%0.1f}, Offset = %0.1f px\n", + m_blMarkerPoint.X, m_blMarkerPoint.Y, m_blDistanceMoved)); + Debug.Write(wxString::Format( + "Backlash: Total distance moved = %0.1f\n", currentLocation.Distance(m_calibrationInitialLocation))); - case CALIBRATION_STATE_GO_NORTH: { + m_calibrationState = CALIBRATION_STATE_GO_NORTH; + // falling through to start moving north + Debug.Write("Backlash: Falling Through to state GO_NORTH\n"); + } - CalibrationStepInfo info(this, _T("North"), m_calibrationSteps, dX, dY, currentLocation, dist); - GuideLog.CalibrationStep(info); - m_calibrationDetails.decSteps.push_back(wxRealPoint(dX, dY)); + case CALIBRATION_STATE_GO_NORTH: + { - if (dist < dist_crit) - { - if (m_calibrationSteps++ > MAX_CALIBRATION_STEPS) - { - wxString msg(wxTRANSLATE("DEC Calibration Failed: star did not move enough")); - const wxString& translated(wxGetTranslation(msg)); - pFrame->Alert(translated); - GuideLog.CalibrationFailed(this, msg); - EvtServer.NotifyCalibrationFailed(this, msg); - throw ERROR_INFO("Dec calibration failed"); - } - CalibrationStatus(info, wxString::Format(_("North step %3d, dist=%4.1f"), m_calibrationSteps, dist)); - pFrame->ScheduleAxisMove(this, NORTH, m_calibrationDuration, MOVEOPTS_CALIBRATION_MOVE); - break; - } + CalibrationStepInfo info(this, _T("North"), m_calibrationSteps, dX, dY, currentLocation, dist); + GuideLog.CalibrationStep(info); + m_calibrationDetails.decSteps.push_back(wxRealPoint(dX, dY)); - // note: this calculation is reversed from the ra calculation, because - // that one was calibrating WEST, but the angle is really relative - // to EAST - if (m_assumeOrthogonal) - { - double a1 = norm_angle(m_calibration.xAngle + M_PI / 2.); - double a2 = norm_angle(m_calibration.xAngle - M_PI / 2.); - double yAngle = currentLocation.Angle(m_calibrationStartingLocation); - m_calibration.yAngle = fabs(norm_angle(a1 - yAngle)) < fabs(norm_angle(a2 - yAngle)) ? a1 : a2; - double dec_dist = dist * cos(yAngle - m_calibration.yAngle); - m_calibration.yRate = dec_dist / (m_calibrationSteps * m_calibrationDuration); - - Debug.Write(wxString::Format("Assuming orthogonal axes: measured Y angle = %.1f, X angle = %.1f, orthogonal = %.1f, %.1f, best = %.1f, dist = %.2f, dec_dist = %.2f\n", - degrees(yAngle), degrees(m_calibration.xAngle), degrees(a1), degrees(a2), degrees(m_calibration.yAngle), dist, dec_dist)); - } - else + if (dist < dist_crit) + { + if (m_calibrationSteps++ > MAX_CALIBRATION_STEPS) { - m_calibration.yAngle = currentLocation.Angle(m_calibrationStartingLocation); - m_calibration.yRate = dist / (m_calibrationSteps * m_calibrationDuration); + wxString msg(wxTRANSLATE("DEC Calibration Failed: star did not move enough")); + const wxString& translated(wxGetTranslation(msg)); + pFrame->Alert(translated); + GuideLog.CalibrationFailed(this, msg); + EvtServer.NotifyCalibrationFailed(this, msg); + throw ERROR_INFO("Dec calibration failed"); } + CalibrationStatus(info, wxString::Format(_("North step %3d, dist=%4.1f"), m_calibrationSteps, dist)); + pFrame->ScheduleAxisMove(this, NORTH, m_calibrationDuration, MOVEOPTS_CALIBRATION_MOVE); + break; + } - m_decSteps = m_calibrationSteps; + // note: this calculation is reversed from the ra calculation, because + // that one was calibrating WEST, but the angle is really relative + // to EAST + if (m_assumeOrthogonal) + { + double a1 = norm_angle(m_calibration.xAngle + M_PI / 2.); + double a2 = norm_angle(m_calibration.xAngle - M_PI / 2.); + double yAngle = currentLocation.Angle(m_calibrationStartingLocation); + m_calibration.yAngle = fabs(norm_angle(a1 - yAngle)) < fabs(norm_angle(a2 - yAngle)) ? a1 : a2; + double dec_dist = dist * cos(yAngle - m_calibration.yAngle); + m_calibration.yRate = dec_dist / (m_calibrationSteps * m_calibrationDuration); + + Debug.Write(wxString::Format("Assuming orthogonal axes: measured Y angle = %.1f, X angle = %.1f, orthogonal = " + "%.1f, %.1f, best = %.1f, dist = %.2f, dec_dist = %.2f\n", + degrees(yAngle), degrees(m_calibration.xAngle), degrees(a1), degrees(a2), degrees(m_calibration.yAngle), + dist, dec_dist)); + } + else + { + m_calibration.yAngle = currentLocation.Angle(m_calibrationStartingLocation); + m_calibration.yRate = dist / (m_calibrationSteps * m_calibrationDuration); + } - m_calibration.decGuideParity = GUIDE_PARITY_UNKNOWN; - if (m_calibrationStartingCoords.IsValid()) + m_decSteps = m_calibrationSteps; + + m_calibration.decGuideParity = GUIDE_PARITY_UNKNOWN; + if (m_calibrationStartingCoords.IsValid()) + { + PHD_Point endingCoords; + GetRADecCoordinates(&endingCoords); + if (endingCoords.IsValid()) { - PHD_Point endingCoords; - GetRADecCoordinates(&endingCoords); - if (endingCoords.IsValid()) - { - // real Northward motion increases Dec - double ONE_ARCSEC = 1.0 / (60. * 60.); // degrees - double ddec = endingCoords.Y - m_calibrationStartingCoords.Y; - if (ddec > ONE_ARCSEC) - m_calibration.decGuideParity = GUIDE_PARITY_EVEN; - else if (ddec < -ONE_ARCSEC) - m_calibration.decGuideParity = GUIDE_PARITY_ODD; - } + // real Northward motion increases Dec + double ONE_ARCSEC = 1.0 / (60. * 60.); // degrees + double ddec = endingCoords.Y - m_calibrationStartingCoords.Y; + if (ddec > ONE_ARCSEC) + m_calibration.decGuideParity = GUIDE_PARITY_EVEN; + else if (ddec < -ONE_ARCSEC) + m_calibration.decGuideParity = GUIDE_PARITY_ODD; } + } - Debug.Write(wxString::Format("NORTH calibration completes with angle=%.1f rate=%.3f parity=%d\n", - degrees(m_calibration.yAngle), m_calibration.yRate * 1000.0, m_calibration.decGuideParity)); + Debug.Write(wxString::Format("NORTH calibration completes with angle=%.1f rate=%.3f parity=%d\n", + degrees(m_calibration.yAngle), m_calibration.yRate * 1000.0, m_calibration.decGuideParity)); - GuideLog.CalibrationDirectComplete(this, "North", m_calibration.yAngle, m_calibration.yRate, m_calibration.decGuideParity); + GuideLog.CalibrationDirectComplete( + this, "North", m_calibration.yAngle, m_calibration.yRate, m_calibration.decGuideParity); - // for GO_SOUTH m_recenterRemaining contains the total remaining duration. - // Choose the largest pulse size that will not lose the guide star or exceed - // the user-specified max pulse - m_recenterRemaining = m_calibrationSteps * m_calibrationDuration; + // for GO_SOUTH m_recenterRemaining contains the total remaining duration. + // Choose the largest pulse size that will not lose the guide star or exceed + // the user-specified max pulse + m_recenterRemaining = m_calibrationSteps * m_calibrationDuration; - if (pFrame->pGuider->IsFastRecenterEnabled()) - { - m_recenterDuration = (int)floor(0.8 * (double)pFrame->pGuider->GetMaxMovePixels() / m_calibration.yRate); - if (m_recenterDuration > m_maxDecDuration) - m_recenterDuration = m_maxDecDuration; - if (m_recenterDuration < m_calibrationDuration) - m_recenterDuration = m_calibrationDuration; - } - else + if (pFrame->pGuider->IsFastRecenterEnabled()) + { + m_recenterDuration = (int) floor(0.8 * (double) pFrame->pGuider->GetMaxMovePixels() / m_calibration.yRate); + if (m_recenterDuration > m_maxDecDuration) + m_recenterDuration = m_maxDecDuration; + if (m_recenterDuration < m_calibrationDuration) m_recenterDuration = m_calibrationDuration; + } + else + m_recenterDuration = m_calibrationDuration; - m_calibrationSteps = DIV_ROUND_UP(m_recenterRemaining, m_recenterDuration); - m_calibrationState = CALIBRATION_STATE_GO_SOUTH; - m_southStartingLocation = currentLocation; + m_calibrationSteps = DIV_ROUND_UP(m_recenterRemaining, m_recenterDuration); + m_calibrationState = CALIBRATION_STATE_GO_SOUTH; + m_southStartingLocation = currentLocation; - // fall through - Debug.Write("Falling Through to state GO_SOUTH\n"); - } + // fall through + Debug.Write("Falling Through to state GO_SOUTH\n"); + } - case CALIBRATION_STATE_GO_SOUTH: { + case CALIBRATION_STATE_GO_SOUTH: + { - CalibrationStepInfo info(this, _T("South"), m_calibrationSteps, dX, dY, currentLocation, dist); - GuideLog.CalibrationStep(info); - m_calibrationDetails.decSteps.push_back(wxRealPoint(dX, dY)); + CalibrationStepInfo info(this, _T("South"), m_calibrationSteps, dX, dY, currentLocation, dist); + GuideLog.CalibrationStep(info); + m_calibrationDetails.decSteps.push_back(wxRealPoint(dX, dY)); - if (m_recenterRemaining > 0) - { - int duration = m_recenterDuration; - if (duration > m_recenterRemaining) - duration = m_recenterRemaining; + if (m_recenterRemaining > 0) + { + int duration = m_recenterDuration; + if (duration > m_recenterRemaining) + duration = m_recenterRemaining; - CalibrationStatus(info, wxString::Format(_("South step %3d, dist=%4.1f"), m_calibrationSteps, dist)); + CalibrationStatus(info, wxString::Format(_("South step %3d, dist=%4.1f"), m_calibrationSteps, dist)); - m_recenterRemaining -= duration; - --m_calibrationSteps; + m_recenterRemaining -= duration; + --m_calibrationSteps; - pFrame->ScheduleAxisMove(this, SOUTH, duration, MOVEOPTS_CALIBRATION_MOVE); - break; - } + pFrame->ScheduleAxisMove(this, SOUTH, duration, MOVEOPTS_CALIBRATION_MOVE); + break; + } - // Check for obvious guide cable problem and no useful south moves - southDistMoved = m_southStartingLocation.Distance(currentLocation); - northDistMoved = m_calibrationStartingLocation.Distance(m_southStartingLocation); - southAngle = currentLocation.Angle(m_southStartingLocation); - // Want a significant south movement that re-traces the north vector to within 30 degrees - if (fabs(southDistMoved) < 0.25 * northDistMoved || fabs(norm_angle(southAngle - (m_calibration.yAngle + M_PI))) > radians(30)) + // Check for obvious guide cable problem and no useful south moves + southDistMoved = m_southStartingLocation.Distance(currentLocation); + northDistMoved = m_calibrationStartingLocation.Distance(m_southStartingLocation); + southAngle = currentLocation.Angle(m_southStartingLocation); + // Want a significant south movement that re-traces the north vector to within 30 degrees + if (fabs(southDistMoved) < 0.25 * northDistMoved || + fabs(norm_angle(southAngle - (m_calibration.yAngle + M_PI))) > radians(30)) + { + wxString msg; + if (!CanPulseGuide()) { - wxString msg; - if (!CanPulseGuide()) - { - if (fabs(southDistMoved) < 0.10 * northDistMoved) - msg = wxTRANSLATE("Advisory: Calibration succeessful but little or no south movement was measured, so guiding will probably be impaired.\n " - "This is usually caused by a faulty guide cable or very large Dec backlash. \n" - "Check the guide cable and read the online Help for how to identify these types of problems (Manual Guide, Declination backlash)."); - else - msg = wxTRANSLATE("Advisory: Calibration successful but little south movement was measured, so guiding will probably be impaired. \n" - "This is usually caused by very large Dec backlash or other problems with the mount mechanics. \n" - "Read the online Help for how to identify these types of problems (Manual Guide, Declination backlash)."); - } + if (fabs(southDistMoved) < 0.10 * northDistMoved) + msg = wxTRANSLATE("Advisory: Calibration succeessful but little or no south movement was measured, so " + "guiding will probably be impaired.\n " + "This is usually caused by a faulty guide cable or very large Dec backlash. \n" + "Check the guide cable and read the online Help for how to identify these types of " + "problems (Manual Guide, Declination backlash)."); else - msg = wxTRANSLATE("Advisory: Calibration successful but little south movement was measured, so guiding may be impaired.\n " + msg = wxTRANSLATE( + "Advisory: Calibration successful but little south movement was measured, so guiding will probably " + "be impaired. \n" + "This is usually caused by very large Dec backlash or other problems with the mount mechanics. \n" + "Read the online Help for how to identify these types of problems (Manual Guide, Declination " + "backlash)."); + } + else + msg = wxTRANSLATE( + "Advisory: Calibration successful but little south movement was measured, so guiding may be " + "impaired.\n " "This is usually caused by very large Dec backlash or other problems with the mount mechanics. \n" "Read the online help for how to deal with this type of problem (Declination backlash)."); - //if (!m_eastAlertShown) - //{ - // const wxString& translated(wxGetTranslation(msg)); - // pFrame->SuppressableAlert(DecBacklashAlertKey(), translated, SuppressDecBacklashAlert, 0, true); - //} - Debug.Write("Omitted calibration alert: " + msg + "\n"); - } - - m_lastLocation = currentLocation; - // Compute the vector for the north moves we made - use it to make sure any nudging is going in the correct direction - // These are the direction cosines of the vector - m_northDirCosX = m_calibrationInitialLocation.dX(m_southStartingLocation) / m_calibrationInitialLocation.Distance(m_southStartingLocation); - m_northDirCosY = m_calibrationInitialLocation.dY(m_southStartingLocation) / m_calibrationInitialLocation.Distance(m_southStartingLocation); - //Debug.Write(wxString::Format("Nudge: InitStart:{%0.1f,%0.1f}, southStart:{%.1f,%0.1f}, north_l:%0.2f, north_m:%0.2f\n", - // m_calibrationInitialLocation.X, m_calibrationInitialLocation.Y, - // m_southStartingLocation.X, m_southStartingLocation.Y, m_northDirCosX, m_northDirCosY)); - // Get magnitude and sign convention for the south moves we already made - m_totalSouthAmt = MountCoords(m_southStartingLocation - m_lastLocation, m_calibration.xAngle, m_calibration.yAngle).Y; - m_calibrationState = CALIBRATION_STATE_NUDGE_SOUTH; - m_calibrationSteps = 0; - // Fall through to nudging - Debug.Write("Falling Through to state CALIBRATION_STATE_NUDGE_SOUTH\n"); + // if (!m_eastAlertShown) + //{ + // const wxString& translated(wxGetTranslation(msg)); + // pFrame->SuppressableAlert(DecBacklashAlertKey(), translated, SuppressDecBacklashAlert, 0, true); + // } + Debug.Write("Omitted calibration alert: " + msg + "\n"); } - case CALIBRATION_STATE_NUDGE_SOUTH: - // Nudge further South on Dec, get within 2 px North/South of starting point, don't try more than 3 times and don't do nudging at all if - // we're starting too far away from the target - nudge_amt = currentLocation.Distance(m_calibrationInitialLocation); - // Compute the direction cosines for the expected nudge op - nudgeDirCosX = currentLocation.dX(m_calibrationInitialLocation) / nudge_amt; - nudgeDirCosY = currentLocation.dY(m_calibrationInitialLocation) / nudge_amt; - // Compute the angle between the nudge and north move vector - they should be reversed, i.e. something close to 180 deg - cos_theta = nudgeDirCosX * m_northDirCosX + nudgeDirCosY * m_northDirCosY; - theta = acos(cos_theta); - //Debug.Write(wxString::Format("Nudge: currLoc:{%0.1f,%0.1f}, m_nudgeDirCosX: %0.2f, nudgeDirCosY: %0.2f, cos_theta: %0.2f\n", - // currentLocation.X, currentLocation.Y, nudgeDirCosX, nudgeDirCosY, cos_theta)); - Debug.Write(wxString::Format("Nudge: theta = %0.2f\n", theta)); - if (fabs(fabs(theta) * 180.0/M_PI - 180.0) < 40.0) // We're going at least roughly in the right direction + m_lastLocation = currentLocation; + // Compute the vector for the north moves we made - use it to make sure any nudging is going in the correct + // direction These are the direction cosines of the vector + m_northDirCosX = m_calibrationInitialLocation.dX(m_southStartingLocation) / + m_calibrationInitialLocation.Distance(m_southStartingLocation); + m_northDirCosY = m_calibrationInitialLocation.dY(m_southStartingLocation) / + m_calibrationInitialLocation.Distance(m_southStartingLocation); + // Debug.Write(wxString::Format("Nudge: InitStart:{%0.1f,%0.1f}, southStart:{%.1f,%0.1f}, north_l:%0.2f, + // north_m:%0.2f\n", + // m_calibrationInitialLocation.X, m_calibrationInitialLocation.Y, + // m_southStartingLocation.X, m_southStartingLocation.Y, m_northDirCosX, m_northDirCosY)); + // Get magnitude and sign convention for the south moves we already made + m_totalSouthAmt = + MountCoords(m_southStartingLocation - m_lastLocation, m_calibration.xAngle, m_calibration.yAngle).Y; + m_calibrationState = CALIBRATION_STATE_NUDGE_SOUTH; + m_calibrationSteps = 0; + // Fall through to nudging + Debug.Write("Falling Through to state CALIBRATION_STATE_NUDGE_SOUTH\n"); + } + + case CALIBRATION_STATE_NUDGE_SOUTH: + // Nudge further South on Dec, get within 2 px North/South of starting point, don't try more than 3 times and don't + // do nudging at all if we're starting too far away from the target + nudge_amt = currentLocation.Distance(m_calibrationInitialLocation); + // Compute the direction cosines for the expected nudge op + nudgeDirCosX = currentLocation.dX(m_calibrationInitialLocation) / nudge_amt; + nudgeDirCosY = currentLocation.dY(m_calibrationInitialLocation) / nudge_amt; + // Compute the angle between the nudge and north move vector - they should be reversed, i.e. something close to 180 + // deg + cos_theta = nudgeDirCosX * m_northDirCosX + nudgeDirCosY * m_northDirCosY; + theta = acos(cos_theta); + // Debug.Write(wxString::Format("Nudge: currLoc:{%0.1f,%0.1f}, m_nudgeDirCosX: %0.2f, nudgeDirCosY: %0.2f, + // cos_theta: %0.2f\n", + // currentLocation.X, currentLocation.Y, nudgeDirCosX, nudgeDirCosY, cos_theta)); + Debug.Write(wxString::Format("Nudge: theta = %0.2f\n", theta)); + if (fabs(fabs(theta) * 180.0 / M_PI - 180.0) < 40.0) // We're going at least roughly in the right direction + { + if (m_calibrationSteps <= MAX_NUDGES && nudge_amt > NUDGE_TOLERANCE && + nudge_amt < dist_crit + m_blDistanceMoved) { - if (m_calibrationSteps <= MAX_NUDGES && nudge_amt > NUDGE_TOLERANCE && - nudge_amt < dist_crit + m_blDistanceMoved) + // Compute how much more south we need to go + double decAmt = + MountCoords(currentLocation - m_calibrationInitialLocation, m_calibration.xAngle, m_calibration.yAngle) + .Y; + Debug.Write( + wxString::Format("South nudging, decAmt = %.3f, Normal south moves = %.3f\n", decAmt, m_totalSouthAmt)); + + if (decAmt * m_totalSouthAmt > 0.0) // still need to move south to reach target based on matching sign { - // Compute how much more south we need to go - double decAmt = MountCoords(currentLocation - m_calibrationInitialLocation, m_calibration.xAngle, m_calibration.yAngle).Y; - Debug.Write(wxString::Format("South nudging, decAmt = %.3f, Normal south moves = %.3f\n", decAmt, m_totalSouthAmt)); - - if (decAmt * m_totalSouthAmt > 0.0) // still need to move south to reach target based on matching sign - { - decAmt = fabs(decAmt); // Sign doesn't matter now, we're always moving south - decAmt = wxMin(decAmt, (double)pFrame->pGuider->GetMaxMovePixels()); - int pulseAmt = (int)floor(decAmt / m_calibration.yRate); - if (pulseAmt > m_calibrationDuration) - pulseAmt = m_calibrationDuration; // Be conservative, use durations that pushed us north in the first place - Debug.Write(wxString::Format("Sending NudgeSouth pulse of duration %d ms\n", pulseAmt)); - ++m_calibrationSteps; - CalibrationStepInfo info(this, _T("NudgeSouth"), m_calibrationSteps, dX, dY, currentLocation, dist); - CalibrationStatus(info, wxString::Format(_("Nudge South %3d"), m_calibrationSteps)); - pFrame->ScheduleAxisMove(this, SOUTH, pulseAmt, MOVEOPTS_CALIBRATION_MOVE); - break; - } + decAmt = fabs(decAmt); // Sign doesn't matter now, we're always moving south + decAmt = wxMin(decAmt, (double) pFrame->pGuider->GetMaxMovePixels()); + int pulseAmt = (int) floor(decAmt / m_calibration.yRate); + if (pulseAmt > m_calibrationDuration) + pulseAmt = + m_calibrationDuration; // Be conservative, use durations that pushed us north in the first place + Debug.Write(wxString::Format("Sending NudgeSouth pulse of duration %d ms\n", pulseAmt)); + ++m_calibrationSteps; + CalibrationStepInfo info(this, _T("NudgeSouth"), m_calibrationSteps, dX, dY, currentLocation, dist); + CalibrationStatus(info, wxString::Format(_("Nudge South %3d"), m_calibrationSteps)); + pFrame->ScheduleAxisMove(this, SOUTH, pulseAmt, MOVEOPTS_CALIBRATION_MOVE); + break; } } - else - { - Debug.Write(wxString::Format("Nudging discontinued, wrong direction: %0.2f\n", theta)); - } - - Debug.Write(wxString::Format("Final south nudging status: Current loc = {%.3f,%.3f}, targeting {%.3f,%.3f}\n", - currentLocation.X, currentLocation.Y, m_calibrationInitialLocation.X, m_calibrationInitialLocation.Y)); + } + else + { + Debug.Write(wxString::Format("Nudging discontinued, wrong direction: %0.2f\n", theta)); + } - m_calibrationState = CALIBRATION_STATE_COMPLETE; - // fall through - Debug.Write("Falling Through to state CALIBRATION_COMPLETE\n"); - - case CALIBRATION_STATE_COMPLETE: - GetLastCalibration(&m_prevCalibration); - LoadCalibrationDetails(&m_prevCalibrationDetails); - Calibration cal(m_calibration); - cal.declination = pPointingSource->GetDeclinationRadians(); - cal.pierSide = pPointingSource->SideOfPier(); - cal.rotatorAngle = Rotator::RotatorPosition(); - cal.binning = pCamera->Binning; - SetCalibration(cal); - m_calibrationDetails.raStepCount = m_raSteps; - m_calibrationDetails.decStepCount = m_decSteps; - SetCalibrationDetails(m_calibrationDetails, m_calibration.xAngle, m_calibration.yAngle, pCamera->Binning); - if (SANITY_CHECKING_ACTIVE) - SanityCheckCalibration(m_prevCalibration, m_prevCalibrationDetails); // method gets "new" info itself - pFrame->StatusMsg(_("Calibration complete")); - GuideLog.CalibrationComplete(this); - EvtServer.NotifyCalibrationComplete(this); - Debug.Write("Calibration Complete\n"); - pConfig->Flush(); - break; + Debug.Write(wxString::Format("Final south nudging status: Current loc = {%.3f,%.3f}, targeting {%.3f,%.3f}\n", + currentLocation.X, currentLocation.Y, m_calibrationInitialLocation.X, m_calibrationInitialLocation.Y)); + + m_calibrationState = CALIBRATION_STATE_COMPLETE; + // fall through + Debug.Write("Falling Through to state CALIBRATION_COMPLETE\n"); + + case CALIBRATION_STATE_COMPLETE: + GetLastCalibration(&m_prevCalibration); + LoadCalibrationDetails(&m_prevCalibrationDetails); + Calibration cal(m_calibration); + cal.declination = pPointingSource->GetDeclinationRadians(); + cal.pierSide = pPointingSource->SideOfPier(); + cal.rotatorAngle = Rotator::RotatorPosition(); + cal.binning = pCamera->Binning; + SetCalibration(cal); + m_calibrationDetails.raStepCount = m_raSteps; + m_calibrationDetails.decStepCount = m_decSteps; + SetCalibrationDetails(m_calibrationDetails, m_calibration.xAngle, m_calibration.yAngle, pCamera->Binning); + if (SANITY_CHECKING_ACTIVE) + SanityCheckCalibration(m_prevCalibration, m_prevCalibrationDetails); // method gets "new" info itself + pFrame->StatusMsg(_("Calibration complete")); + GuideLog.CalibrationComplete(this); + EvtServer.NotifyCalibrationComplete(this); + Debug.Write("Calibration Complete\n"); + pConfig->Flush(); + break; } } catch (const wxString& Msg) @@ -1764,9 +1836,7 @@ bool Scope::SlewToCoordinatesAsync(double ra, double dec) return true; // error } -void Scope::AbortSlew() -{ -} +void Scope::AbortSlew() { } bool Scope::CanCheckSlewing() { @@ -1794,7 +1864,7 @@ bool Scope::ValidGuideRates(double RAGuideRate, double DecGuideRate) if (spd > 0.1 && spd < 1.2) { spd = DecGuideRate * 3600.0 / (15.0 * siderealSecsPerSec); - if (spd != -1.0) // RA-only tracking devices + if (spd != -1.0) // RA-only tracking devices if (spd < 0.1 || spd > 1.2) err = true; } @@ -1821,8 +1891,8 @@ static wxString GuideSpeedSummary() double raSpeed, decSpeed; if (!scope->GetGuideRates(&raSpeed, &decSpeed)) { - return wxString::Format("RA Guide Speed = %0.1f a-s/s, Dec Guide Speed = %0.1f a-s/s", - 3600.0 * raSpeed, 3600.0 * decSpeed); + return wxString::Format( + "RA Guide Speed = %0.1f a-s/s, Dec Guide Speed = %0.1f a-s/s", 3600.0 * raSpeed, 3600.0 * decSpeed); } else return "RA Guide Speed = Unknown, Dec Guide Speed = Unknown"; @@ -1839,17 +1909,13 @@ wxString Scope::GetSettingsSummary() const // return a loggable summary of current mount settings wxString ret = Mount::GetSettingsSummary() + - wxString::Format( - "Max RA duration = %d, Max DEC duration = %d, DEC guide mode = %s\n", - GetMaxRaDuration(), - GetMaxDecDuration(), - DecGuideModeStr(GetDecGuideMode())); + wxString::Format("Max RA duration = %d, Max DEC duration = %d, DEC guide mode = %s\n", GetMaxRaDuration(), + GetMaxDecDuration(), DecGuideModeStr(GetDecGuideMode())); ret += GuideSpeedSummary() + ", "; - ret += wxString::Format("Cal Dec = %s, Last Cal Issue = %s, Timestamp = %s\n", - DeclinationStr(calInfo.declination, "%0.1f"), Mount::GetIssueString(calDetails.lastIssue), - calDetails.origTimestamp); + ret += wxString::Format("Cal Dec = %s, Last Cal Issue = %s, Timestamp = %s\n", DeclinationStr(calInfo.declination, "%0.1f"), + Mount::GetIssueString(calDetails.lastIssue), calDetails.origTimestamp); return ret; } @@ -1858,9 +1924,8 @@ wxString Scope::CalibrationSettingsSummary() const { return wxString::Format("Calibration Step = %d ms, Calibration Distance = %d px, " "Assume orthogonal axes = %s\n", - GetCalibrationDuration(), GetCalibrationDistance(), - IsAssumeOrthogonal() ? "yes" : "no") + - GuideSpeedSummary(); + GetCalibrationDuration(), GetCalibrationDistance(), IsAssumeOrthogonal() ? "yes" : "no") + + GuideSpeedSummary(); } wxString Scope::GetMountClassName() const @@ -1895,12 +1960,14 @@ void Scope::ScopeConfigDialogPane::UnloadValues() MountConfigDialogPane::UnloadValues(); } -MountConfigDialogCtrlSet *Scope::GetConfigDialogCtrlSet(wxWindow *pParent, Mount *pScope, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +MountConfigDialogCtrlSet *Scope::GetConfigDialogCtrlSet( + wxWindow *pParent, Mount *pScope, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) { return new ScopeConfigDialogCtrlSet(pParent, (Scope *) pScope, pAdvancedDialog, CtrlMap); } -ScopeConfigDialogCtrlSet::ScopeConfigDialogCtrlSet(wxWindow *pParent, Scope *pScope, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) +ScopeConfigDialogCtrlSet::ScopeConfigDialogCtrlSet( + wxWindow *pParent, Scope *pScope, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) : MountConfigDialogCtrlSet(pParent, pScope, pAdvancedDialog, CtrlMap) { int width; @@ -1910,15 +1977,16 @@ ScopeConfigDialogCtrlSet::ScopeConfigDialogCtrlSet(wxWindow *pParent, Scope *pSc width = StringWidth(_T("00000")); wxBoxSizer *pCalibSizer = new wxBoxSizer(wxHORIZONTAL); - m_pCalibrationDuration = pFrame->MakeSpinCtrl(GetParentWindow(AD_szCalibrationDuration), wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 0, 10000, 1000, _T("Cal_Dur")); + m_pCalibrationDuration = pFrame->MakeSpinCtrl(GetParentWindow(AD_szCalibrationDuration), wxID_ANY, wxEmptyString, + wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 10000, 1000, _T("Cal_Dur")); pCalibSizer->Add(MakeLabeledControl(AD_szCalibrationDuration, _("Calibration step (ms)"), m_pCalibrationDuration, _("How long a guide pulse should be used during calibration? Click \"Advanced...\" to compute a suitable value."))); m_pCalibrationDuration->Enable(enableCtrls); // create the 'auto' button and bind it to the associated event-handler - wxButton *pAutoDuration = new wxButton(GetParentWindow(AD_szCalibrationDuration), wxID_OK, _("Advanced...") ); - pAutoDuration->SetToolTip(_("Click to open the Calibration Calculator Dialog to review or change all calibration parameters")); + wxButton *pAutoDuration = new wxButton(GetParentWindow(AD_szCalibrationDuration), wxID_OK, _("Advanced...")); + pAutoDuration->SetToolTip( + _("Click to open the Calibration Calculator Dialog to review or change all calibration parameters")); pAutoDuration->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &ScopeConfigDialogCtrlSet::OnCalcCalibrationStep, this); pAutoDuration->Enable(enableCtrls); @@ -1929,27 +1997,29 @@ ScopeConfigDialogCtrlSet::ScopeConfigDialogCtrlSet(wxWindow *pParent, Scope *pSc AddGroup(CtrlMap, AD_szCalibrationDuration, pCalibGroupSizer); - m_pNeedFlipDec = new wxCheckBox(GetParentWindow(AD_cbReverseDecOnFlip), wxID_ANY, - _("Reverse Dec output after meridian flip")); + m_pNeedFlipDec = + new wxCheckBox(GetParentWindow(AD_cbReverseDecOnFlip), wxID_ANY, _("Reverse Dec output after meridian flip")); AddCtrl(CtrlMap, AD_cbReverseDecOnFlip, m_pNeedFlipDec, - _("Check if your mount needs Dec output reversed after a meridian flip. Changing this setting will clear the existing calibration data")); + _("Check if your mount needs Dec output reversed after a meridian flip. Changing this setting will clear the existing " + "calibration data")); m_pNeedFlipDec->Enable(enableCtrls); bool usingAO = TheAO() != nullptr; if (pScope && pScope->CanCheckSlewing()) { - m_pStopGuidingWhenSlewing = new wxCheckBox(GetParentWindow(AD_cbSlewDetection), wxID_ANY, _("Stop guiding when mount slews")); + m_pStopGuidingWhenSlewing = + new wxCheckBox(GetParentWindow(AD_cbSlewDetection), wxID_ANY, _("Stop guiding when mount slews")); AddCtrl(CtrlMap, AD_cbSlewDetection, m_pStopGuidingWhenSlewing, _("When checked, PHD will stop guiding if the mount starts slewing")); } else m_pStopGuidingWhenSlewing = 0; - m_assumeOrthogonal = new wxCheckBox(GetParentWindow(AD_cbAssumeOrthogonal), wxID_ANY, - _("Assume Dec orthogonal to RA")); + m_assumeOrthogonal = new wxCheckBox(GetParentWindow(AD_cbAssumeOrthogonal), wxID_ANY, _("Assume Dec orthogonal to RA")); m_assumeOrthogonal->Enable(enableCtrls); AddCtrl(CtrlMap, AD_cbAssumeOrthogonal, m_assumeOrthogonal, - _("Assume Dec axis is perpendicular to RA axis, regardless of calibration. Prevents RA periodic error from affecting Dec calibration. Option takes effect when calibrating DEC.")); + _("Assume Dec axis is perpendicular to RA axis, regardless of calibration. Prevents RA periodic error from affecting " + "Dec calibration. Option takes effect when calibrating DEC.")); if (pScope) { @@ -1961,33 +2031,36 @@ ScopeConfigDialogCtrlSet::ScopeConfigDialogCtrlSet(wxWindow *pParent, Scope *pSc blcCtrlId = AD_szBLCompCtrls; wxWindow *blcHostTab = GetParentWindow(blcCtrlId); m_pUseBacklashComp = new wxCheckBox(blcHostTab, wxID_ANY, _("Enable")); - m_pUseBacklashComp->SetToolTip(_("Check this if you want to apply a backlash compensation guide pulse when declination direction is reversed.")); + m_pUseBacklashComp->SetToolTip( + _("Check this if you want to apply a backlash compensation guide pulse when declination direction is reversed.")); pComp1->Add(m_pUseBacklashComp); double const blcMinVal = BacklashComp::GetBacklashPulseMinValue(); double const blcMaxVal = BacklashComp::GetBacklashPulseMaxValue(); - m_pBacklashPulse = pFrame->MakeSpinCtrlDouble(blcHostTab, wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, blcMinVal, blcMaxVal, 450, blcMinVal); - pComp1->Add(MakeLabeledControl(blcCtrlId, _("Amount"), m_pBacklashPulse, - _("Size of backlash compensation guide pulse (mSec)")), wxSizerFlags().Border(wxLEFT, 26)); + m_pBacklashPulse = pFrame->MakeSpinCtrlDouble(blcHostTab, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, blcMinVal, blcMaxVal, 450, blcMinVal); + pComp1->Add( + MakeLabeledControl(blcCtrlId, _("Amount"), m_pBacklashPulse, _("Size of backlash compensation guide pulse (mSec)")), + wxSizerFlags().Border(wxLEFT, 26)); - wxBoxSizer *pCompVert = - new wxStaticBoxSizer(wxVERTICAL, blcHostTab, - usingAO ? _("Mount Backlash Compensation") : _("Backlash Compensation")); + wxBoxSizer *pCompVert = new wxStaticBoxSizer( + wxVERTICAL, blcHostTab, usingAO ? _("Mount Backlash Compensation") : _("Backlash Compensation")); pCompVert->Add(pComp1); - if (!usingAO) // AO doesn't use auto-adjustments, so don't show min/max controls + if (!usingAO) // AO doesn't use auto-adjustments, so don't show min/max controls { wxBoxSizer *pComp2 = new wxBoxSizer(wxHORIZONTAL); m_pBacklashFloor = pFrame->MakeSpinCtrlDouble(blcHostTab, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, blcMinVal, blcMaxVal, 300, blcMinVal); m_pBacklashCeiling = pFrame->MakeSpinCtrlDouble(blcHostTab, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, blcMinVal, blcMaxVal, 300, blcMinVal); - pComp2->Add(MakeLabeledControl(blcCtrlId, _("Min"), m_pBacklashFloor, - _("Minimum length of backlash compensation pulse (mSec).")), wxSizerFlags().Border(wxLEFT, 0)); + pComp2->Add(MakeLabeledControl( + blcCtrlId, _("Min"), m_pBacklashFloor, _("Minimum length of backlash compensation pulse (mSec).")), + wxSizerFlags().Border(wxLEFT, 0)); pComp2->Add(MakeLabeledControl(blcCtrlId, _("Max"), m_pBacklashCeiling, - _("Maximum length of backlash compensation pulse (mSec).")), wxSizerFlags().Border(wxLEFT, 18)); + _("Maximum length of backlash compensation pulse (mSec).")), + wxSizerFlags().Border(wxLEFT, 18)); pCompVert->Add(pComp2); } AddGroup(CtrlMap, blcCtrlId, pCompVert); @@ -1995,19 +2068,18 @@ ScopeConfigDialogCtrlSet::ScopeConfigDialogCtrlSet(wxWindow *pParent, Scope *pSc { m_pUseDecComp = new wxCheckBox(GetParentWindow(AD_cbUseDecComp), wxID_ANY, _("Use Dec compensation")); m_pUseDecComp->Enable(enableCtrls && pPointingSource); - AddCtrl(CtrlMap, AD_cbUseDecComp, m_pUseDecComp, - _("Automatically adjust RA guide rate based on scope declination")); + AddCtrl( + CtrlMap, AD_cbUseDecComp, m_pUseDecComp, _("Automatically adjust RA guide rate based on scope declination")); width = StringWidth(_T("00000")); - m_pMaxRaDuration = pFrame->MakeSpinCtrl(GetParentWindow(AD_szMaxRAAmt), wxID_ANY, wxEmptyString, - wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, MAX_DURATION_MIN, MAX_DURATION_MAX, 150, - _T("MaxRA_Dur")); + m_pMaxRaDuration = pFrame->MakeSpinCtrl(GetParentWindow(AD_szMaxRAAmt), wxID_ANY, wxEmptyString, wxDefaultPosition, + wxSize(width, -1), wxSP_ARROW_KEYS, MAX_DURATION_MIN, MAX_DURATION_MAX, 150, _T("MaxRA_Dur")); AddLabeledCtrl(CtrlMap, AD_szMaxRAAmt, _("Max RA duration"), m_pMaxRaDuration, _("Longest length of pulse to send in RA\nDefault = 2500 ms.")); - m_pMaxDecDuration = pFrame->MakeSpinCtrl(GetParentWindow(AD_szMaxDecAmt), wxID_ANY, wxEmptyString, - wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, MAX_DURATION_MIN, MAX_DURATION_MAX, 150, - _T("MaxDec_Dur")); + m_pMaxDecDuration = + pFrame->MakeSpinCtrl(GetParentWindow(AD_szMaxDecAmt), wxID_ANY, wxEmptyString, wxDefaultPosition, + wxSize(width, -1), wxSP_ARROW_KEYS, MAX_DURATION_MIN, MAX_DURATION_MAX, 150, _T("MaxDec_Dur")); AddLabeledCtrl(CtrlMap, AD_szMaxDecAmt, _("Max Dec duration"), m_pMaxDecDuration, _("Longest length of pulse to send in declination\nDefault = 2500 ms. Increase if drift is fast.")); @@ -2019,9 +2091,10 @@ ScopeConfigDialogCtrlSet::ScopeConfigDialogCtrlSet(wxWindow *pParent, Scope *pSc }; width = StringArrayWidth(dec_choices, WXSIZEOF(dec_choices)); - m_pDecMode = new wxChoice(GetParentWindow(AD_szDecGuideMode), wxID_ANY, wxDefaultPosition, - wxSize(width + 35, -1), WXSIZEOF(dec_choices), dec_choices); - AddLabeledCtrl(CtrlMap, AD_szDecGuideMode, _("Dec guide mode"), m_pDecMode, _("Directions in which Dec guide commands will be issued")); + m_pDecMode = new wxChoice(GetParentWindow(AD_szDecGuideMode), wxID_ANY, wxDefaultPosition, wxSize(width + 35, -1), + WXSIZEOF(dec_choices), dec_choices); + AddLabeledCtrl(CtrlMap, AD_szDecGuideMode, _("Dec guide mode"), m_pDecMode, + _("Directions in which Dec guide commands will be issued")); m_pDecMode->Bind(wxEVT_COMMAND_CHOICE_SELECTED, &ScopeConfigDialogCtrlSet::OnDecModeChoice, this); } m_pScope->currConfigDialogCtrlSet = this; @@ -2053,7 +2126,7 @@ void ScopeConfigDialogCtrlSet::LoadValues() m_pMaxDecDuration->SetValue(m_pScope->GetMaxDecDuration()); int whichDecMode = m_pScope->GetDecGuideMode(); m_pDecMode->SetSelection(whichDecMode); - Mount::MountConfigDialogPane* pCurrMountPane = pFrame->pAdvancedDialog->GetCurrentMountPane(); + Mount::MountConfigDialogPane *pCurrMountPane = pFrame->pAdvancedDialog->GetCurrentMountPane(); pCurrMountPane->EnableDecControls(whichDecMode != DEC_NONE); m_pUseDecComp->SetValue(m_pScope->DecCompensationEnabled()); m_origBLCEnabled = m_pScope->m_backlashComp->IsEnabled(); @@ -2115,10 +2188,9 @@ void ScopeConfigDialogCtrlSet::UnloadValues() { m_pScope->EnableDecCompensation(m_pUseDecComp->GetValue()); m_pScope->SetMaxRaDuration(m_pMaxRaDuration->GetValue()); - if (!m_pScope->m_backlashComp->IsEnabled()) // handled above + if (!m_pScope->m_backlashComp->IsEnabled()) // handled above m_pScope->SetMaxDecDuration(m_pMaxDecDuration->GetValue()); m_pScope->SetDecGuideMode(m_pDecMode->GetSelection()); - } MountConfigDialogCtrlSet::UnloadValues(); } @@ -2131,13 +2203,13 @@ void ScopeConfigDialogCtrlSet::ResetRAParameterUI() void ScopeConfigDialogCtrlSet::ResetDecParameterUI() { m_pMaxDecDuration->SetValue(DefaultMaxDecDuration); - m_pDecMode->SetSelection(1); // 'Auto' + m_pDecMode->SetSelection(1); // 'Auto' m_pUseBacklashComp->SetValue(false); } DEC_GUIDE_MODE ScopeConfigDialogCtrlSet::GetDecGuideModeUI() { - return (DEC_GUIDE_MODE)m_pDecMode->GetSelection(); + return (DEC_GUIDE_MODE) m_pDecMode->GetSelection(); } int ScopeConfigDialogCtrlSet::GetCalStepSizeCtrlValue() @@ -2154,7 +2226,7 @@ void ScopeConfigDialogCtrlSet::OnDecModeChoice(wxCommandEvent& evt) { int which = m_pDecMode->GetSelection(); // User choice of 'none' will disable Dec algo params in UI - Mount::MountConfigDialogPane* pCurrMountPane = pFrame->pAdvancedDialog->GetCurrentMountPane(); + Mount::MountConfigDialogPane *pCurrMountPane = pFrame->pAdvancedDialog->GetCurrentMountPane(); pCurrMountPane->EnableDecControls(which != DEC_NONE); m_pUseDecComp->SetValue(m_pScope->DecCompensationEnabled()); if (which != DEC_AUTO) @@ -2222,7 +2294,8 @@ Scope::ScopeGraphControlPane::ScopeGraphControlPane(wxWindow *pParent, Scope *pS width = StringWidth(_T("0000")); m_pMaxDecDuration = pFrame->MakeSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, MAX_DURATION_MIN, MAX_DURATION_MAX, 0); - m_pMaxDecDuration->SetToolTip(_("Longest length of pulse to send in declination\nDefault = 2500 ms. Increase if drift is fast.")); + m_pMaxDecDuration->SetToolTip( + _("Longest length of pulse to send in declination\nDefault = 2500 ms. Increase if drift is fast.")); m_pMaxDecDuration->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &Scope::ScopeGraphControlPane::OnMaxDecDurationSpinCtrl, this); DoAdd(m_pMaxDecDuration, _("Mx DEC")); @@ -2232,8 +2305,7 @@ Scope::ScopeGraphControlPane::ScopeGraphControlPane(wxWindow *pParent, Scope *pS DecGuideModeLocaleStr(DEC_NORTH), DecGuideModeLocaleStr(DEC_SOUTH), }; - m_pDecMode = new wxChoice(this, wxID_ANY, - wxDefaultPosition,wxDefaultSize, WXSIZEOF(dec_choices), dec_choices ); + m_pDecMode = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, WXSIZEOF(dec_choices), dec_choices); m_pDecMode->SetToolTip(_("Directions in which Dec guide commands will be issued")); m_pDecMode->Bind(wxEVT_COMMAND_CHOICE_SELECTED, &Scope::ScopeGraphControlPane::OnDecModeChoice, this); m_pControlSizer->Add(m_pDecMode); diff --git a/src/scope.h b/src/scope.h index 37f44c0fd..992246198 100644 --- a/src/scope.h +++ b/src/scope.h @@ -57,7 +57,7 @@ class ScopeConfigDialogCtrlSet : public MountConfigDialogCtrlSet wxCheckBox *m_assumeOrthogonal; wxSpinCtrl *m_pMaxRaDuration; wxSpinCtrl *m_pMaxDecDuration; - wxChoice *m_pDecMode; + wxChoice *m_pDecMode; wxCheckBox *m_pUseBacklashComp; wxSpinCtrlDouble *m_pBacklashPulse; wxSpinCtrlDouble *m_pBacklashFloor; @@ -70,7 +70,7 @@ class ScopeConfigDialogCtrlSet : public MountConfigDialogCtrlSet void OnDecModeChoice(wxCommandEvent& evt); public: - ScopeConfigDialogCtrlSet(wxWindow *pParent, Scope *pScope, AdvancedDialog* pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + ScopeConfigDialogCtrlSet(wxWindow *pParent, Scope *pScope, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); virtual ~ScopeConfigDialogCtrlSet() {}; void LoadValues() override; void UnloadValues() override; @@ -100,11 +100,12 @@ class Scope : public Mount int m_calibrationDistance; int m_recenterRemaining; int m_recenterDuration; - PHD_Point m_calibrationInitialLocation; // initial position of guide star - PHD_Point m_calibrationStartingLocation; // position of guide star at start of calibration measurement (after clear backlash etc.) - PHD_Point m_calibrationStartingCoords; // ra,dec coordinates at start of calibration measurement - PHD_Point m_southStartingLocation; // Needed to be sure nudging is in south-only direction - PHD_Point m_eastStartingLocation; // For basic sanity check that east moves worked at all + PHD_Point m_calibrationInitialLocation; // initial position of guide star + PHD_Point + m_calibrationStartingLocation; // position of guide star at start of calibration measurement (after clear backlash etc.) + PHD_Point m_calibrationStartingCoords; // ra,dec coordinates at start of calibration measurement + PHD_Point m_southStartingLocation; // Needed to be sure nudging is in south-only direction + PHD_Point m_eastStartingLocation; // For basic sanity check that east moves worked at all PHD_Point m_lastLocation; double m_totalSouthAmt; double m_northDirCosX; @@ -118,7 +119,12 @@ class Scope : public Mount int m_blAcceptedMoves; double m_blDistanceMoved; int m_blMaxClearingPulses; - enum blConstants { BL_BACKLASH_MIN_COUNT = 3, BL_MAX_CLEARING_TIME = 60000, BL_MIN_CLEARING_DISTANCE = 3 }; + enum blConstants + { + BL_BACKLASH_MIN_COUNT = 3, + BL_MAX_CLEARING_TIME = 60000, + BL_MIN_CLEARING_DISTANCE = 3 + }; Calibration m_calibration; CalibrationDetails m_calibrationDetails; @@ -147,6 +153,7 @@ class Scope : public Mount CALIBRATION_STATE_COMPLETE }; CALIBRATION_STATE m_calibrationState; + public: bool m_CalDetailsValidated; bool m_bogusGuideRatesFlagged; @@ -178,7 +185,7 @@ class Scope : public Mount Scope *m_pScope; wxSpinCtrl *m_pMaxRaDuration; wxSpinCtrl *m_pMaxDecDuration; - wxChoice *m_pDecMode; + wxChoice *m_pDecMode; void OnMaxRaDurationSpinCtrl(wxSpinEvent& evt); void OnMaxDecDurationSpinCtrl(wxSpinEvent& evt); @@ -193,10 +200,9 @@ class Scope : public Mount GUIDE_ALGORITHM DefaultYGuideAlgorithm() const override; public: - - int GetCalibrationDuration() const; // calibration step size, ms + int GetCalibrationDuration() const; // calibration step size, ms bool SetCalibrationDuration(int calibrationDuration); - int GetCalibrationDistance() const; // calibration distance, px + int GetCalibrationDistance() const; // calibration distance, px bool SetCalibrationDistance(int calibrationDistance); int GetMaxDecDuration() const; bool SetMaxDecDuration(int maxDecDuration); @@ -210,7 +216,8 @@ class Scope : public Mount static wxString DecGuideModeLocaleStr(DEC_GUIDE_MODE m); MountConfigDialogPane *GetConfigDialogPane(wxWindow *pParent) override; - MountConfigDialogCtrlSet *GetConfigDialogCtrlSet(wxWindow *pParent, Mount *pScope, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) override; + MountConfigDialogCtrlSet *GetConfigDialogCtrlSet( + wxWindow *pParent, Mount *pScope, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) override; GraphControlPane *GetGraphControlPane(wxWindow *pParent, const wxString& label) override; wxString GetSettingsSummary() const override; @@ -232,7 +239,7 @@ class Scope : public Mount bool UpdateCalibrationState(const PHD_Point& currentLocation) override; static const double DEC_COMP_LIMIT; // declination compensation limit - static const double DEFAULT_MOUNT_GUIDE_SPEED; // Presumptive mount guide speed if no usable mount connection + static const double DEFAULT_MOUNT_GUIDE_SPEED; // Presumptive mount guide speed if no usable mount connection void EnableDecCompensation(bool enable); bool DecCompensationEnabled() const override; @@ -261,7 +268,7 @@ class Scope : public Mount virtual bool CanCheckSlewing(); virtual bool Slewing(); virtual PierSide SideOfPier(); - virtual bool CanReportPosition(); // Can report RA, Dec, side-of-pier, etc. + virtual bool CanReportPosition(); // Can report RA, Dec, side-of-pier, etc. // Will be called before guiding starts, before any call to GetCoordinates, GetDeclination, or SideOfPier. // Does not get called unless guiding was started interactively (by clicking the guide button) virtual bool PreparePositionInteractive(); @@ -274,7 +281,8 @@ class Scope : public Mount private: // functions with an implemenation in Scope that cannot be over-ridden // by a subclass - MOVE_RESULT MoveAxis(GUIDE_DIRECTION direction, int durationMs, unsigned int moveOptions, MoveResultInfo *moveResultInfo) final; + MOVE_RESULT MoveAxis( + GUIDE_DIRECTION direction, int durationMs, unsigned int moveOptions, MoveResultInfo *moveResultInfo) final; MOVE_RESULT MoveAxis(GUIDE_DIRECTION direction, int duration, unsigned int moveOptions) final; int CalibrationMoveSize() override; void CheckCalibrationDuration(int currDuration); @@ -286,7 +294,7 @@ class Scope : public Mount void AlertLimitReached(int duration, GuideAxis axis); -// these MUST be supplied by a subclass + // these MUST be supplied by a subclass private: virtual MOVE_RESULT Guide(GUIDE_DIRECTION direction, int durationMs) = 0; }; diff --git a/src/scope_GC_USBST4.cpp b/src/scope_GC_USBST4.cpp index 1c92af54f..ef4318bb5 100644 --- a/src/scope_GC_USBST4.cpp +++ b/src/scope_GC_USBST4.cpp @@ -34,31 +34,31 @@ #include "phd.h" #ifdef GUIDE_GCUSBST4 -//#include "scope_GC_USBST4.h" -#include -#include +// #include "scope_GC_USBST4.h" +# include +# include -#ifdef __linux__ -#include -#endif +# ifdef __linux__ +# include +# endif -#define _U(String) wxString(String, wxConvUTF8).c_str() +# define _U(String) wxString(String, wxConvUTF8).c_str() -#ifdef __APPLE__ +# ifdef __APPLE__ -#include +# include -#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 120000 -# define IOMainPort IOMasterPort -#endif +# if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 120000 +# define IOMainPort IOMasterPort +# endif -#define IOSSDATALAT _IOW('T', 0, unsigned long) +# define IOSSDATALAT _IOW('T', 0, unsigned long) static kern_return_t createSerialIterator(io_iterator_t *serialIterator) { - kern_return_t kernResult; - mach_port_t masterPort; - CFMutableDictionaryRef classesToMatch; + kern_return_t kernResult; + mach_port_t masterPort; + CFMutableDictionaryRef classesToMatch; if ((kernResult = IOMainPort(0, &masterPort)) != KERN_SUCCESS) { printf("IOMainPort returned %d\n", kernResult); @@ -71,8 +71,8 @@ static kern_return_t createSerialIterator(io_iterator_t *serialIterator) } // GC device is a "modem" CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), -// CFSTR(kIOSerialBSDRS232Type)); - CFSTR(kIOSerialBSDModemType)); + // CFSTR(kIOSerialBSDRS232Type)); + CFSTR(kIOSerialBSDModemType)); kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, serialIterator); if (kernResult != KERN_SUCCESS) { @@ -87,41 +87,42 @@ static char *getRegistryString(io_object_t sObj, const char *propName) // CFTypeRef nameCFstring; CFStringRef nameCFstring; resultStr[0] = 0; - nameCFstring = (CFStringRef) IORegistryEntryCreateCFProperty(sObj, - CFStringCreateWithCString(kCFAllocatorDefault, propName, kCFStringEncodingASCII), - kCFAllocatorDefault, 0); - if (nameCFstring) { - CFStringGetCString(nameCFstring, resultStr, sizeof(resultStr), - kCFStringEncodingASCII); + nameCFstring = (CFStringRef) IORegistryEntryCreateCFProperty( + sObj, CFStringCreateWithCString(kCFAllocatorDefault, propName, kCFStringEncodingASCII), kCFAllocatorDefault, 0); + if (nameCFstring) + { + CFStringGetCString(nameCFstring, resultStr, sizeof(resultStr), kCFStringEncodingASCII); CFRelease(nameCFstring); } return resultStr; } -#endif +# endif Mount::MOVE_RESULT ScopeGCUSBST4::Guide(GUIDE_DIRECTION direction, int duration) { char buf[16]; - switch (direction) { - case NORTH: - snprintf(buf, sizeof(buf), ":Mg0%4d#", duration); - break; - case SOUTH: - snprintf(buf, sizeof(buf), ":Mg1%4d#", duration); - break; - case EAST: - snprintf(buf, sizeof(buf), ":Mg2%4d#", duration); - break; - case WEST: - snprintf(buf, sizeof(buf), ":Mg3%4d#", duration); - break; - case NONE: - return MOVE_OK; + switch (direction) + { + case NORTH: + snprintf(buf, sizeof(buf), ":Mg0%4d#", duration); + break; + case SOUTH: + snprintf(buf, sizeof(buf), ":Mg1%4d#", duration); + break; + case EAST: + snprintf(buf, sizeof(buf), ":Mg2%4d#", duration); + break; + case WEST: + snprintf(buf, sizeof(buf), ":Mg3%4d#", duration); + break; + case NONE: + return MOVE_OK; } - int num_bytes = write(portFID,buf,strlen(buf)); - if (num_bytes == -1) { - pFrame->Alert(wxString::Format(_("Error writing to GC USB ST4: %s(%d)"),_U(strerror(errno)),errno)); + int num_bytes = write(portFID, buf, strlen(buf)); + if (num_bytes == -1) + { + pFrame->Alert(wxString::Format(_("Error writing to GC USB ST4: %s(%d)"), _U(strerror(errno)), errno)); } WorkerThread::MilliSleep(duration + 50); return MOVE_OK; @@ -129,16 +130,17 @@ Mount::MOVE_RESULT ScopeGCUSBST4::Guide(GUIDE_DIRECTION direction, int duration) bool ScopeGCUSBST4::Connect() { -#ifdef __APPLE__ +# ifdef __APPLE__ wxArrayString DeviceNames; wxArrayString PortNames; char tempstr[256]; - io_iterator_t theSerialIterator; - io_object_t theObject; + io_iterator_t theSerialIterator; + io_object_t theObject; - if (createSerialIterator(&theSerialIterator) != KERN_SUCCESS) { - wxMessageBox(_T("Error in finding serial ports"),_("Error")); + if (createSerialIterator(&theSerialIterator) != KERN_SUCCESS) + { + wxMessageBox(_T("Error in finding serial ports"), _("Error")); return false; } bool found_device = false; @@ -155,31 +157,34 @@ bool ScopeGCUSBST4::Connect() } IOObjectRelease(theSerialIterator); // Release the iterator. - if (!found_device) { - wxMessageBox("Could not find device - searched for usbmodem* to no avail...",_("Error")); + if (!found_device) + { + wxMessageBox("Could not find device - searched for usbmodem* to no avail...", _("Error")); return true; } -#endif //__APPLE__ +# endif //__APPLE__ -#ifdef __linux__ - char tempstr[256] = "/dev/ttyACM0"; -#endif +# ifdef __linux__ + char tempstr[256] = "/dev/ttyACM0"; +# endif portFID = open(tempstr, O_RDWR | O_NOCTTY | O_NONBLOCK); - if (portFID == -1) { // error on opening - wxMessageBox(wxString::Format(_T("Error opening serial port %s: %s(%d)"), - _U(tempstr), _U(strerror(errno)), errno),_("Error")); + if (portFID == -1) + { // error on opening + wxMessageBox( + wxString::Format(_T("Error opening serial port %s: %s(%d)"), _U(tempstr), _U(strerror(errno)), errno), _("Error")); return true; } ioctl(portFID, TIOCEXCL); fcntl(portFID, F_SETFL, 0); // Setup port - struct termios options; - //options = gOriginalTTYAttrs; - if (tcgetattr(portFID, &options) == -1) { - wxMessageBox(_T("Error getting port options"),_("Error")); + struct termios options; + // options = gOriginalTTYAttrs; + if (tcgetattr(portFID, &options) == -1) + { + wxMessageBox(_T("Error getting port options"), _("Error")); close(portFID); return true; } @@ -187,69 +192,75 @@ bool ScopeGCUSBST4::Connect() options.c_cflag = CREAD | CLOCAL; options.c_cflag |= CS8; options.c_iflag |= IXON | IXOFF; -// options.c_cc[VMIN] = 1; - // options.c_cc[VTIME] = 10; - options.c_cc[VSTART]=0x11; - options.c_cc[VSTOP]=0x13; + // options.c_cc[VMIN] = 1; + // options.c_cc[VTIME] = 10; + options.c_cc[VSTART] = 0x11; + options.c_cc[VSTOP] = 0x13; cfsetspeed(&options, B9600); - //options.c_cflag = 0x8b00; + // options.c_cflag = 0x8b00; /*wxMessageBox(wxString::Format("SET termios: iFlag %x oFlag %x cFlag %x lFlag %x speed %d\n", options.c_iflag, options.c_oflag, options.c_cflag, options.c_lflag, options.c_ispeed));*/ - if (tcsetattr(portFID, TCSANOW, &options) == -1) { - wxMessageBox(_T("Error setting port options"),_("Error")); + if (tcsetattr(portFID, TCSANOW, &options) == -1) + { + wxMessageBox(_T("Error setting port options"), _("Error")); close(portFID); return true; } -/* int handshake; - if (ioctl(portFID, TIOCMGET, &handshake) == -1) { - wxMessageBox("Error getting port handshake"); - close(portFID); - return false; - } - unsigned long mics = 1UL; - if (ioctl(portFID, IOSSDATALAT, &mics) == -1) { - wxMessageBox("Error setting port latency"); - close(portFID); - return false; + /* int handshake; + if (ioctl(portFID, TIOCMGET, &handshake) == -1) { + wxMessageBox("Error getting port handshake"); + close(portFID); + return false; + } + unsigned long mics = 1UL; + if (ioctl(portFID, IOSSDATALAT, &mics) == -1) { + wxMessageBox("Error setting port latency"); + close(portFID); + return false; - }*/ -// wxMessageBox(wxString::Format("%d",(int) cfgetispeed(&options))); + }*/ + // wxMessageBox(wxString::Format("%d",(int) cfgetispeed(&options))); // Init / check the device char buf[2]; int num_bytes; // Send the '#' needed to kickstart things - buf[0]='#'; - buf[1]=0; - num_bytes = write(portFID,buf,1); - if (num_bytes == -1) { - wxMessageBox(wxString::Format(_T("Error during initial kickstart: %s(%d)"),_U(strerror(errno)),errno),_("Error")); + buf[0] = '#'; + buf[1] = 0; + num_bytes = write(portFID, buf, 1); + if (num_bytes == -1) + { + wxMessageBox(wxString::Format(_T("Error during initial kickstart: %s(%d)"), _U(strerror(errno)), errno), _("Error")); close(portFID); return true; } // Do a quick check - buf[0]=0x6; - buf[1]=0; - num_bytes = write(portFID,buf,1); - if (num_bytes == -1) { - wxMessageBox(wxString::Format(_T("Error during test polling of device: %s(%d)"),_U(strerror(errno)),errno),_("Error")); + buf[0] = 0x6; + buf[1] = 0; + num_bytes = write(portFID, buf, 1); + if (num_bytes == -1) + { + wxMessageBox( + wxString::Format(_T("Error during test polling of device: %s(%d)"), _U(strerror(errno)), errno), _("Error")); close(portFID); return true; } - num_bytes = read(portFID,buf,1); - if (num_bytes == -1) { + num_bytes = read(portFID, buf, 1); + if (num_bytes == -1) + { wxMessageBox(_T("Error during test read of device")); close(portFID); return true; } - if (buf[0] != 'A') { - wxMessageBox(wxString::Format(_T("Device returned %x instead of %x on test poll"),buf[0],'A')); + if (buf[0] != 'A') + { + wxMessageBox(wxString::Format(_T("Device returned %x instead of %x on test poll"), buf[0], 'A')); close(portFID); return true; } @@ -259,8 +270,10 @@ bool ScopeGCUSBST4::Connect() return false; } -bool ScopeGCUSBST4::Disconnect() { - if (portFID > 0) { +bool ScopeGCUSBST4::Disconnect() +{ + if (portFID > 0) + { close(portFID); portFID = 0; } @@ -269,4 +282,4 @@ bool ScopeGCUSBST4::Disconnect() { return false; } -#endif //GUIDE_GCUSBST4 +#endif // GUIDE_GCUSBST4 diff --git a/src/scope_GC_USBST4.h b/src/scope_GC_USBST4.h index 80b3aee11..6bd5151ab 100644 --- a/src/scope_GC_USBST4.h +++ b/src/scope_GC_USBST4.h @@ -31,17 +31,14 @@ * POSSIBILITY OF SUCH DAMAGE. * */ -#ifdef GUIDE_GCUSBST4 +#ifdef GUIDE_GCUSBST4 class ScopeGCUSBST4 : public Scope { int portFID; public: - - ScopeGCUSBST4() { - m_Name = wxString("GCUSB-ST4"); - } + ScopeGCUSBST4() { m_Name = wxString("GCUSB-ST4"); } bool Connect() override; diff --git a/src/scope_ascom.cpp b/src/scope_ascom.cpp index 1a8499150..099389703 100644 --- a/src/scope_ascom.cpp +++ b/src/scope_ascom.cpp @@ -40,21 +40,21 @@ #ifdef GUIDE_ASCOM -#include "comdispatch.h" +# include "comdispatch.h" -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include ScopeASCOM::ScopeASCOM(const wxString& choice) { m_choice = choice; - m_canPulseGuide = false; // will get updated in Connect() + m_canPulseGuide = false; // will get updated in Connect() dispid_connected = DISPID_UNKNOWN; dispid_ispulseguiding = DISPID_UNKNOWN; @@ -72,9 +72,7 @@ ScopeASCOM::ScopeASCOM(const wxString& choice) dispid_abortslew = DISPID_UNKNOWN; } -ScopeASCOM::~ScopeASCOM() -{ -} +ScopeASCOM::~ScopeASCOM() { } static wxString displayName(const wxString& ascomName) { @@ -94,7 +92,8 @@ wxArrayString ScopeASCOM::EnumAscomScopes() { DispatchObj profile; if (!profile.Create(L"ASCOM.Utilities.Profile")) - throw ERROR_INFO("ASCOM Scope: could not instantiate ASCOM profile class ASCOM.Utilities.Profile. Is ASCOM installed?"); + throw ERROR_INFO( + "ASCOM Scope: could not instantiate ASCOM profile class ASCOM.Utilities.Profile. Is ASCOM installed?"); Variant res; if (!profile.InvokeMethod(&res, L"RegisteredDevices", L"Telescope")) @@ -213,7 +212,7 @@ bool ScopeASCOM::Connect() if (IsConnected()) { - wxMessageBox("Scope already connected",_("Error")); + wxMessageBox("Scope already connected", _("Error")); throw ERROR_INFO("ASCOM Scope: Connected - Already Connected"); } @@ -229,7 +228,7 @@ bool ScopeASCOM::Connect() // ... get the dispatch ID for the Connected property ... if (!pScopeDriver.GetDispatchId(&dispid_connected, L"Connected")) { - wxMessageBox(_T("ASCOM driver problem -- cannot connect"),_("Error"), wxOK | wxICON_ERROR); + wxMessageBox(_T("ASCOM driver problem -- cannot connect"), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the Connected property"); } @@ -245,14 +244,14 @@ bool ScopeASCOM::Connect() // ... get the dispatch ID for the "Slewing" property .... if (!pScopeDriver.GetDispatchId(&dispid_isslewing, L"Slewing")) { - wxMessageBox(_T("ASCOM driver missing the Slewing property"),_("Error"), wxOK | wxICON_ERROR); + wxMessageBox(_T("ASCOM driver missing the Slewing property"), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the Slewing property"); } // ... get the dispatch ID for the "PulseGuide" property .... if (!pScopeDriver.GetDispatchId(&dispid_pulseguide, L"PulseGuide")) { - wxMessageBox(_T("ASCOM driver missing the PulseGuide property"),_("Error"), wxOK | wxICON_ERROR); + wxMessageBox(_T("ASCOM driver missing the PulseGuide property"), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("ASCOM Scope: Could not get the dispatch id for the PulseGuide property"); } @@ -290,9 +289,9 @@ bool ScopeASCOM::Connect() Debug.Write("cannot get dispid_slewtocoordinates\n"); } - // ... get the dispatch IDs for the two guide rate properties - if we can't get them, no sweat, doesn't matter for actual guiding - // Used for things like calibration sanity checking, backlash clearing, etc. - m_canGetGuideRates = true; // Likely case, required for any ASCOM driver at V2 or later + // ... get the dispatch IDs for the two guide rate properties - if we can't get them, no sweat, doesn't matter for + // actual guiding Used for things like calibration sanity checking, backlash clearing, etc. + m_canGetGuideRates = true; // Likely case, required for any ASCOM driver at V2 or later if (!pScopeDriver.GetDispatchId(&dispid_decguiderate, L"GuideRateDeclination")) { Debug.Write("cannot get dispid_decguiderate\n"); @@ -321,7 +320,10 @@ bool ScopeASCOM::Connect() struct ConnectInBg : public ConnectMountInBg { ScopeASCOM *sa; - ConnectInBg(ScopeASCOM *sa_) : sa(sa_) { } + ConnectInBg(ScopeASCOM *sa_) + : sa(sa_) + { + } bool Entry() { GITObjRef scope(sa->m_gitEntry); @@ -339,8 +341,7 @@ bool ScopeASCOM::Connect() // set the Connected property to true in a background thread if (bg.Run()) { - wxMessageBox(_T("ASCOM driver problem during connection: ") + bg.GetErrorMsg(), - _("Error"), wxOK | wxICON_ERROR); + wxMessageBox(_T("ASCOM driver problem during connection: ") + bg.GetErrorMsg(), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("ASCOM Scope: Could not set Connected property to true"); } @@ -372,11 +373,12 @@ bool ScopeASCOM::Connect() if (m_Name.Find(_T("AstroPhysicsV2")) != wxNOT_FOUND) { - // The Astro-Physics VB6 driver apparently uses timing functions that fire its COM message pump at inappropriate times. - // This can cause unpredictable delays in the execution of pulse-guide commands when running on low-end dual-core - // PCs with other clients also connected to the driver. The problem is exacerbated if the user has switched to "synchronous - // pulse guiding" (not the default driver setting). Since the problems can occur regardless of this setting, it just confuses - // users if we fire an alert - so we will simply log the situation for support purposes. Fortunately, it happens pretty rarely. + // The Astro-Physics VB6 driver apparently uses timing functions that fire its COM message pump at inappropriate + // times. This can cause unpredictable delays in the execution of pulse-guide commands when running on low-end + // dual-core PCs with other clients also connected to the driver. The problem is exacerbated if the user has + // switched to "synchronous pulse guiding" (not the default driver setting). Since the problems can occur + // regardless of this setting, it just confuses users if we fire an alert - so we will simply log the situation for + // support purposes. Fortunately, it happens pretty rarely. Debug.Write("ASCOM scope: enabling sync pulse guide check\n"); m_checkForSyncPulseGuide = true; } @@ -466,18 +468,20 @@ bool ScopeASCOM::Disconnect() return bError; } -#define CheckSlewing(dispobj, result) \ - do { \ - if (IsStopGuidingWhenSlewingEnabled() && IsSlewing(dispobj)) \ - { \ - *(result) = MOVE_ERROR_SLEWING; \ - throw ERROR_INFO("attempt to guide while slewing"); \ - } \ - } while (0) +# define CheckSlewing(dispobj, result) \ + do \ + { \ + if (IsStopGuidingWhenSlewingEnabled() && IsSlewing(dispobj)) \ + { \ + *(result) = MOVE_ERROR_SLEWING; \ + throw ERROR_INFO("attempt to guide while slewing"); \ + } \ + } while (0) static wxString SlewWarningEnabledKey() { - // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting to be per-profile + // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting + // to be per-profile return wxString::Format("/Confirm/%d/SlewWarningEnabled", pConfig->GetCurrentProfileId()); } @@ -489,7 +493,8 @@ static void SuppressSlewAlert(long) static wxString PulseGuideFailedAlertEnabledKey() { - // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting to be per-profile + // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting + // to be per-profile return wxString::Format("/Confirm/%d/PulseGuideFailedAlertEnabled", pConfig->GetCurrentProfileId()); } @@ -583,8 +588,8 @@ Mount::MOVE_RESULT ScopeASCOM::Guide(GUIDE_DIRECTION direction, int duration) ExcepInfo excep; Variant vRes; - if (FAILED(hr = scope.IDisp()->Invoke(dispid_pulseguide, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, - &dispParms, &vRes, &excep, NULL))) + if (FAILED(hr = scope.IDisp()->Invoke( + dispid_pulseguide, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispParms, &vRes, &excep, NULL))) { Debug.Write(wxString::Format("pulseguide: [%x] %s\n", hr, _com_error(hr).ErrorMessage())); @@ -607,15 +612,16 @@ Mount::MOVE_RESULT ScopeASCOM::Guide(GUIDE_DIRECTION direction, int duration) if (duration >= 250 && elapsed >= duration - 30) { Debug.Write(wxString::Format("SyncPulseGuide alert: sync pulseguide or slow thread dispatch detected. " - "Duration = %d Elapsed = %ld\n", duration, elapsed)); + "Duration = %d Elapsed = %ld\n", + duration, elapsed)); // only log the event once m_checkForSyncPulseGuide = false; } } - if (elapsed < (long)duration) + if (elapsed < (long) duration) { - unsigned long rem = (unsigned long)((long)duration - elapsed); + unsigned long rem = (unsigned long) ((long) duration - elapsed); Debug.Write(wxString::Format("PulseGuide returned control before completion, sleep %lu\n", rem + 10)); @@ -630,8 +636,11 @@ Mount::MOVE_RESULT ScopeASCOM::Guide(GUIDE_DIRECTION direction, int duration) // try waiting a little longer. If scope does not stop moving after 1 second, try doing AbortSlew // if it still does not stop after 2 seconds, bail out with an error - enum { GRACE_PERIOD_MS = 1000, - TIMEOUT_MS = GRACE_PERIOD_MS + 1000, }; + enum + { + GRACE_PERIOD_MS = 1000, + TIMEOUT_MS = GRACE_PERIOD_MS + 1000, + }; bool timeoutExceeded = false; bool didAbortSlew = false; @@ -647,7 +656,8 @@ Mount::MOVE_RESULT ScopeASCOM::Guide(GUIDE_DIRECTION direction, int duration) if (!IsGuiding(&scope)) { - Debug.Write(wxString::Format("scope move finished after %ld + %ld ms\n", (long)duration, swatch.Time() - (long)duration)); + Debug.Write(wxString::Format( + "scope move finished after %ld + %ld ms\n", (long) duration, swatch.Time() - (long) duration)); break; } @@ -655,7 +665,8 @@ Mount::MOVE_RESULT ScopeASCOM::Guide(GUIDE_DIRECTION direction, int duration) if (!didAbortSlew && now > duration + GRACE_PERIOD_MS && m_abortSlewWhenGuidingStuck) { - Debug.Write(wxString::Format("scope still moving after %ld + %ld ms, try aborting slew\n", (long)duration, now - (long)duration)); + Debug.Write(wxString::Format( + "scope still moving after %ld + %ld ms, try aborting slew\n", (long) duration, now - (long) duration)); AbortSlew(&scope); didAbortSlew = true; continue; @@ -684,7 +695,8 @@ Mount::MOVE_RESULT ScopeASCOM::Guide(GUIDE_DIRECTION direction, int duration) if (!WorkerThread::InterruptRequested()) { - pFrame->SuppressableAlert(PulseGuideFailedAlertEnabledKey(), _("PulseGuide command to mount has failed - guiding is likely to be ineffective."), + pFrame->SuppressableAlert(PulseGuideFailedAlertEnabledKey(), + _("PulseGuide command to mount has failed - guiding is likely to be ineffective."), SuppressPulseGuideFailedAlert, 0); } } @@ -692,8 +704,8 @@ Mount::MOVE_RESULT ScopeASCOM::Guide(GUIDE_DIRECTION direction, int duration) if (result == MOVE_ERROR_SLEWING) { - pFrame->SuppressableAlert(SlewWarningEnabledKey(), _("Guiding stopped: the scope started slewing."), - SuppressSlewAlert, 0); + pFrame->SuppressableAlert( + SlewWarningEnabledKey(), _("Guiding stopped: the scope started slewing."), SuppressSlewAlert, 0); } return result; @@ -707,8 +719,8 @@ bool ScopeASCOM::IsGuiding(DispatchObj *scope) { if (!m_canCheckPulseGuiding) { - // Assume all is good - best we can do as this is really a fail-safe check. If we can't call this property (lame driver) guides will have to - // enforce the wait. But, enough don't support this that we can't throw an error. + // Assume all is good - best we can do as this is really a fail-safe check. If we can't call this property (lame + // driver) guides will have to enforce the wait. But, enough don't support this that we can't throw an error. throw ERROR_INFO("ASCOM Scope: IsGuiding - !m_canCheckPulseGuiding"); } @@ -871,13 +883,13 @@ bool ScopeASCOM::GetGuideRates(double *pRAGuideRate, double *pDecGuideRate) { if (!m_bogusGuideRatesFlagged) { - pFrame->Alert(_("The mount's ASCOM driver is reporting invalid guide speeds. Some guiding functions including PPEC will be impaired. Contact the ASCOM driver provider or mount vendor for support."), + pFrame->Alert(_("The mount's ASCOM driver is reporting invalid guide speeds. Some guiding functions including " + "PPEC will be impaired. Contact the ASCOM driver provider or mount vendor for support."), 0, wxEmptyString, 0, 0, true); m_bogusGuideRatesFlagged = true; } throw THROW_INFO("ASCOM Scope: mount reporting invalid guide speeds"); } - } catch (const wxString& Msg) { @@ -1131,9 +1143,14 @@ PierSide ScopeASCOM::SideOfPier() throw ERROR_INFO("ASCOM Scope: SideOfPier failed: " + ExcepMsg(scope.Excep())); } - switch (vRes.intVal) { - case 0: pierSide = PIER_SIDE_EAST; break; - case 1: pierSide = PIER_SIDE_WEST; break; + switch (vRes.intVal) + { + case 0: + pierSide = PIER_SIDE_EAST; + break; + case 1: + pierSide = PIER_SIDE_WEST; + break; } } catch (const wxString& Msg) diff --git a/src/scope_ascom.h b/src/scope_ascom.h index 28365ee10..ec403f0c0 100644 --- a/src/scope_ascom.h +++ b/src/scope_ascom.h @@ -42,7 +42,7 @@ #ifdef GUIDE_ASCOM -#include "comdispatch.h" +# include "comdispatch.h" class ScopeASCOM : public Scope { diff --git a/src/scope_eqmac.cpp b/src/scope_eqmac.cpp index 5aa2f5891..dd26a02fa 100644 --- a/src/scope_eqmac.cpp +++ b/src/scope_eqmac.cpp @@ -36,80 +36,88 @@ #ifdef GUIDE_EQMAC -#if defined (__APPLE__) -#include -//#include -//#include -//#include -//#include +# if defined(__APPLE__) +# include +// #include +// #include +// #include +// #include // Code originally from Darryl @ Equinox -OSErr ScopeEQMac::E6AESendRoutine(double ewCorrection, double nsCorrection, int mountcode) { -// correction values (+- seconds) to send to E6 +OSErr ScopeEQMac::E6AESendRoutine(double ewCorrection, double nsCorrection, int mountcode) +{ + // correction values (+- seconds) to send to E6 OSErr err; - FourCharCode E6Sig = 'MPj6'; // the Equinox 6 creator signature + FourCharCode E6Sig = 'MPj6'; // the Equinox 6 creator signature if (mountcode == SCOPE_EQMAC) E6Sig = 'EQMC'; - FourCharCode phdSig = 'PhDG'; // ***** you need to fill in your app signature here ****** + FourCharCode phdSig = 'PhDG'; // ***** you need to fill in your app signature here ****** AEAddressDesc addDesc; - AEEventClass evClass = 'phdG'; // the phd guide class. - AEEventID evID = 'evGD'; // the phd guide event. - AEKeyword keyObject; - AESendMode mode = kAEWaitReply; // you want something back + AEEventClass evClass = 'phdG'; // the phd guide class. + AEEventID evID = 'evGD'; // the phd guide event. + AEKeyword keyObject; + AESendMode mode = kAEWaitReply; // you want something back // create Apple Event with Equinox 6 signature - err = AECreateDesc( typeApplSignature, (Ptr) &E6Sig, sizeof(FourCharCode), &addDesc ); // make a description - if( err != noErr ) return err; + err = AECreateDesc(typeApplSignature, (Ptr) &E6Sig, sizeof(FourCharCode), &addDesc); // make a description + if (err != noErr) + return err; - err = AECreateAppleEvent( evClass, evID, &addDesc, kAutoGenerateReturnID, kAnyTransactionID, &E6Event ); // create the AE - if( err != noErr ) { - AEDisposeDesc( &addDesc ); + err = AECreateAppleEvent(evClass, evID, &addDesc, kAutoGenerateReturnID, kAnyTransactionID, &E6Event); // create the AE + if (err != noErr) + { + AEDisposeDesc(&addDesc); return err; } // create the return Apple Event with your signature (so I know where to send it) - err = AECreateDesc( typeApplSignature, (Ptr) &phdSig, sizeof(FourCharCode), &addDesc ); - if( err != noErr ) { - AEDisposeDesc( &E6Event ); + err = AECreateDesc(typeApplSignature, (Ptr) &phdSig, sizeof(FourCharCode), &addDesc); + if (err != noErr) + { + AEDisposeDesc(&E6Event); return err; } - err = AECreateAppleEvent( evClass, evID, &addDesc, kAutoGenerateReturnID, kAnyTransactionID, &E6Return ); - if( err != noErr ) { - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + err = AECreateAppleEvent(evClass, evID, &addDesc, kAutoGenerateReturnID, kAnyTransactionID, &E6Return); + if (err != noErr) + { + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return err; } // put the correction values into parameters - I have used doubles for a ew and ns seconds correction - keyObject = 'prEW'; // EW correction AE parameter (+ = east, - = west) - err = AEPutParamPtr( &E6Event, keyObject, typeIEEE64BitFloatingPoint, &ewCorrection, sizeof(double) ); - if( err != noErr ) { - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + keyObject = 'prEW'; // EW correction AE parameter (+ = east, - = west) + err = AEPutParamPtr(&E6Event, keyObject, typeIEEE64BitFloatingPoint, &ewCorrection, sizeof(double)); + if (err != noErr) + { + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return err; } - keyObject = 'prNS'; // NS correction AE parameter (+ = north, - = south) - err = AEPutParamPtr( &E6Event, keyObject, typeIEEE64BitFloatingPoint, &nsCorrection, sizeof(double) ); - if( err != noErr ) { - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + keyObject = 'prNS'; // NS correction AE parameter (+ = north, - = south) + err = AEPutParamPtr(&E6Event, keyObject, typeIEEE64BitFloatingPoint, &nsCorrection, sizeof(double)); + if (err != noErr) + { + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return err; } // you now have the send AE, the return AE and the correction values in AE parameters - so send it! - err = AESendMessage( &E6Event, &E6Return, mode, kAEDefaultTimeout ); // you can specify a wait time (in ticks) - if( err != noErr ) { // Note: an error of -600 means E6 is not currently running - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + err = AESendMessage(&E6Event, &E6Return, mode, kAEDefaultTimeout); // you can specify a wait time (in ticks) + if (err != noErr) + { // Note: an error of -600 means E6 is not currently running + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return err; } @@ -117,26 +125,29 @@ OSErr ScopeEQMac::E6AESendRoutine(double ewCorrection, double nsCorrection, int // the return code could indicate that E6 got the AE, can do it, or can't for some reason. You do NOT want to wait // until the corrections have been applied - you should time that on your own. - keyObject = 'prRC'; // get return code + keyObject = 'prRC'; // get return code Size returnSize; DescType returnType; - err = AEGetParamPtr( &E6Return, keyObject, typeSInt16, &returnType, &E6ReturnCode, sizeof(SInt16), &returnSize ); + err = AEGetParamPtr(&E6Return, keyObject, typeSInt16, &returnType, &E6ReturnCode, sizeof(SInt16), &returnSize); - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return 0; } -bool ScopeEQMac::Connect() { +bool ScopeEQMac::Connect() +{ // Check the E6 connection by sending 0,0 to it and checking E6Return - OSErr err = E6AESendRoutine(0.0,0.0,SCOPE_EQMAC); + OSErr err = E6AESendRoutine(0.0, 0.0, SCOPE_EQMAC); wxString prefix = "EQMAC"; - if (E6ReturnCode == -1) { - wxMessageBox (prefix + " responded it's not connected to a mount",_("Error")); + if (E6ReturnCode == -1) + { + wxMessageBox(prefix + " responded it's not connected to a mount", _("Error")); return true; } - else if (err == -600) { - wxMessageBox (prefix + " not running",_("Error")); + else if (err == -600) + { + wxMessageBox(prefix + " not running", _("Error")); return true; } @@ -150,29 +161,32 @@ Mount::MOVE_RESULT ScopeEQMac::Guide(GUIDE_DIRECTION direction, int duration) double NSTime = 0.0; double EWTime = 0.0; - switch (direction) { - case NORTH: - NSTime = (double) duration / 1000.0; - break; - case SOUTH: - NSTime = (double) duration / -1000.0; - break; - case EAST: - EWTime = (double) duration / 1000.0; - break; - case WEST: - EWTime = (double) duration / -1000.0; - break; - case NONE: - break; + switch (direction) + { + case NORTH: + NSTime = (double) duration / 1000.0; + break; + case SOUTH: + NSTime = (double) duration / -1000.0; + break; + case EAST: + EWTime = (double) duration / 1000.0; + break; + case WEST: + EWTime = (double) duration / -1000.0; + break; + case NONE: + break; } OSErr err = E6AESendRoutine(EWTime, NSTime, SCOPE_EQMAC); wxString prefix = "EQMAC"; - if (E6ReturnCode == -1) { + if (E6ReturnCode == -1) + { pFrame->Alert(prefix + _(" responded it's not connected to a mount")); return MOVE_ERROR; } - else if (err == -600) { + else if (err == -600) + { pFrame->Alert(prefix + _(" not running")); return MOVE_ERROR; } @@ -181,5 +195,5 @@ Mount::MOVE_RESULT ScopeEQMac::Guide(GUIDE_DIRECTION direction, int duration) return MOVE_OK; } -#endif +# endif #endif /* GUIDE_EQMAC */ diff --git a/src/scope_eqmac.h b/src/scope_eqmac.h index 0a45d7787..8fd344dbd 100644 --- a/src/scope_eqmac.h +++ b/src/scope_eqmac.h @@ -38,16 +38,11 @@ class ScopeEQMac : public Scope { public: - ScopeEQMac() { - m_Name = wxString("EQMac"); - } + ScopeEQMac() { m_Name = wxString("EQMac"); } bool Connect() override; - bool Disconnect() override - { - return false; - } + bool Disconnect() override { return false; } MOVE_RESULT Guide(GUIDE_DIRECTION direction, int durationMs) override; @@ -57,7 +52,6 @@ class ScopeEQMac : public Scope SInt16 E6ReturnCode; OSErr E6AESendRoutine(double ewCorrection, double nsCorrection, int mountcode); - }; #endif /* GUIDE_EQUINOX */ diff --git a/src/scope_equinox.cpp b/src/scope_equinox.cpp index c945611e4..ba2177a96 100644 --- a/src/scope_equinox.cpp +++ b/src/scope_equinox.cpp @@ -36,81 +36,88 @@ #ifdef GUIDE_EQUINOX -#if defined (__APPLE__) -#include -//#include -//#include -//#include -//#include +# if defined(__APPLE__) +# include +// #include +// #include +// #include +// #include // Code originally from Darryl @ Equinox OSErr ScopeEquinox::E6AESendRoutine(double ewCorrection, double nsCorrection, int mountcode) { -// correction values (+- seconds) to send to E6 + // correction values (+- seconds) to send to E6 OSErr err; - FourCharCode E6Sig = 'MPj6'; // the Equinox 6 creator signature + FourCharCode E6Sig = 'MPj6'; // the Equinox 6 creator signature if (mountcode == SCOPE_EQMAC) E6Sig = 'EQMC'; - FourCharCode phdSig = 'PhDG'; // ***** you need to fill in your app signature here ****** + FourCharCode phdSig = 'PhDG'; // ***** you need to fill in your app signature here ****** AEAddressDesc addDesc; - AEEventClass evClass = 'phdG'; // the phd guide class. - AEEventID evID = 'evGD'; // the phd guide event. - AEKeyword keyObject; - AESendMode mode = kAEWaitReply; // you want something back + AEEventClass evClass = 'phdG'; // the phd guide class. + AEEventID evID = 'evGD'; // the phd guide event. + AEKeyword keyObject; + AESendMode mode = kAEWaitReply; // you want something back // create Apple Event with Equinox 6 signature - err = AECreateDesc( typeApplSignature, (Ptr) &E6Sig, sizeof(FourCharCode), &addDesc ); // make a description - if( err != noErr ) return err; + err = AECreateDesc(typeApplSignature, (Ptr) &E6Sig, sizeof(FourCharCode), &addDesc); // make a description + if (err != noErr) + return err; - err = AECreateAppleEvent( evClass, evID, &addDesc, kAutoGenerateReturnID, kAnyTransactionID, &E6Event ); // create the AE - if( err != noErr ) { - AEDisposeDesc( &addDesc ); + err = AECreateAppleEvent(evClass, evID, &addDesc, kAutoGenerateReturnID, kAnyTransactionID, &E6Event); // create the AE + if (err != noErr) + { + AEDisposeDesc(&addDesc); return err; } // create the return Apple Event with your signature (so I know where to send it) - err = AECreateDesc( typeApplSignature, (Ptr) &phdSig, sizeof(FourCharCode), &addDesc ); - if( err != noErr ) { - AEDisposeDesc( &E6Event ); + err = AECreateDesc(typeApplSignature, (Ptr) &phdSig, sizeof(FourCharCode), &addDesc); + if (err != noErr) + { + AEDisposeDesc(&E6Event); return err; } - err = AECreateAppleEvent( evClass, evID, &addDesc, kAutoGenerateReturnID, kAnyTransactionID, &E6Return ); - if( err != noErr ) { - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + err = AECreateAppleEvent(evClass, evID, &addDesc, kAutoGenerateReturnID, kAnyTransactionID, &E6Return); + if (err != noErr) + { + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return err; } // put the correction values into parameters - I have used doubles for a ew and ns seconds correction - keyObject = 'prEW'; // EW correction AE parameter (+ = east, - = west) - err = AEPutParamPtr( &E6Event, keyObject, typeIEEE64BitFloatingPoint, &ewCorrection, sizeof(double) ); - if( err != noErr ) { - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + keyObject = 'prEW'; // EW correction AE parameter (+ = east, - = west) + err = AEPutParamPtr(&E6Event, keyObject, typeIEEE64BitFloatingPoint, &ewCorrection, sizeof(double)); + if (err != noErr) + { + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return err; } - keyObject = 'prNS'; // NS correction AE parameter (+ = north, - = south) - err = AEPutParamPtr( &E6Event, keyObject, typeIEEE64BitFloatingPoint, &nsCorrection, sizeof(double) ); - if( err != noErr ) { - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + keyObject = 'prNS'; // NS correction AE parameter (+ = north, - = south) + err = AEPutParamPtr(&E6Event, keyObject, typeIEEE64BitFloatingPoint, &nsCorrection, sizeof(double)); + if (err != noErr) + { + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return err; } // you now have the send AE, the return AE and the correction values in AE parameters - so send it! - err = AESendMessage( &E6Event, &E6Return, mode, kAEDefaultTimeout ); // you can specify a wait time (in ticks) - if( err != noErr ) { // Note: an error of -600 means E6 is not currently running - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + err = AESendMessage(&E6Event, &E6Return, mode, kAEDefaultTimeout); // you can specify a wait time (in ticks) + if (err != noErr) + { // Note: an error of -600 means E6 is not currently running + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return err; } @@ -118,28 +125,30 @@ OSErr ScopeEquinox::E6AESendRoutine(double ewCorrection, double nsCorrection, in // the return code could indicate that E6 got the AE, can do it, or can't for some reason. You do NOT want to wait // until the corrections have been applied - you should time that on your own. - keyObject = 'prRC'; // get return code + keyObject = 'prRC'; // get return code Size returnSize; DescType returnType; - err = AEGetParamPtr( &E6Return, keyObject, typeSInt16, &returnType, &E6ReturnCode, sizeof(SInt16), &returnSize ); + err = AEGetParamPtr(&E6Return, keyObject, typeSInt16, &returnType, &E6ReturnCode, sizeof(SInt16), &returnSize); - AEDisposeDesc( &E6Event ); - AEDisposeDesc( &addDesc ); + AEDisposeDesc(&E6Event); + AEDisposeDesc(&addDesc); return 0; } bool ScopeEquinox::Connect() { // Check the E6 connection by sending 0,0 to it and checking E6Return - OSErr err = E6AESendRoutine(0.0,0.0,SCOPE_EQUINOX); + OSErr err = E6AESendRoutine(0.0, 0.0, SCOPE_EQUINOX); wxString prefix = "E6"; -// if (mountcode == SCOPE_EQMAC) prefix = "EQMAC"; - if (E6ReturnCode == -1) { - wxMessageBox (prefix + " responded it's not connected to a mount",_("Error")); + // if (mountcode == SCOPE_EQMAC) prefix = "EQMAC"; + if (E6ReturnCode == -1) + { + wxMessageBox(prefix + " responded it's not connected to a mount", _("Error")); return true; } - else if (err == -600) { - wxMessageBox (prefix + " not running",_("Error")); + else if (err == -600) + { + wxMessageBox(prefix + " not running", _("Error")); return true; } @@ -153,31 +162,34 @@ Mount::MOVE_RESULT ScopeEquinox::Guide(GUIDE_DIRECTION direction, int duration) double NSTime = 0.0; double EWTime = 0.0; - switch (direction) { - case NORTH: - NSTime = (double) duration / 1000.0; - break; - case SOUTH: - NSTime = (double) duration / -1000.0; - break; - case EAST: - EWTime = (double) duration / 1000.0; - break; - case WEST: - EWTime = (double) duration / -1000.0; - break; - case NONE: - break; + switch (direction) + { + case NORTH: + NSTime = (double) duration / 1000.0; + break; + case SOUTH: + NSTime = (double) duration / -1000.0; + break; + case EAST: + EWTime = (double) duration / 1000.0; + break; + case WEST: + EWTime = (double) duration / -1000.0; + break; + case NONE: + break; } - OSErr err = E6AESendRoutine(EWTime, NSTime,SCOPE_EQUINOX); + OSErr err = E6AESendRoutine(EWTime, NSTime, SCOPE_EQUINOX); wxString prefix = "E6"; - //if (mountcode == SCOPE_EQMAC) prefix = "EQMAC"; - if (E6ReturnCode == -1) { + // if (mountcode == SCOPE_EQMAC) prefix = "EQMAC"; + if (E6ReturnCode == -1) + { pFrame->Alert(prefix + _(" responded it's not connected to a mount")); return MOVE_ERROR; } - else if (err == -600) { + else if (err == -600) + { pFrame->Alert(prefix + _(" not running")); return MOVE_ERROR; } @@ -186,5 +198,5 @@ Mount::MOVE_RESULT ScopeEquinox::Guide(GUIDE_DIRECTION direction, int duration) return MOVE_OK; } -#endif +# endif #endif /* GUIDE_EQUINOX */ diff --git a/src/scope_equinox.h b/src/scope_equinox.h index dfd80f32b..216c8d459 100644 --- a/src/scope_equinox.h +++ b/src/scope_equinox.h @@ -35,21 +35,16 @@ #ifdef GUIDE_EQUINOX -#include +# include class ScopeEquinox : public Scope { public: - ScopeEquinox() { - m_Name = wxString("Equinox"); - } + ScopeEquinox() { m_Name = wxString("Equinox"); } bool Connect() override; - bool Disconnect() override - { - return false; - } + bool Disconnect() override { return false; } MOVE_RESULT Guide(GUIDE_DIRECTION direction, int durationMs) override; @@ -59,6 +54,5 @@ class ScopeEquinox : public Scope SInt16 E6ReturnCode; OSErr E6AESendRoutine(double ewCorrection, double nsCorrection, int mountcode); - }; #endif /* GUIDE_EQUINOX */ diff --git a/src/scope_gpint.cpp b/src/scope_gpint.cpp index 8d6baab81..1d7013aca 100644 --- a/src/scope_gpint.cpp +++ b/src/scope_gpint.cpp @@ -46,8 +46,8 @@ bool ScopeGpInt::Connect(void) { short reg = Inp32(port); - reg = reg & 0x0F; // Deassert all directions, protect low bits - Out32(port,reg); + reg = reg & 0x0F; // Deassert all directions, protect low bits + Out32(port, reg); Scope::Connect(); return false; } @@ -56,8 +56,8 @@ bool ScopeGpInt::Disconnect(void) { short reg = Inp32(port); - reg = reg & 0x0F; // Deassert all directions, protect low bits - Out32(port,reg); + reg = reg & 0x0F; // Deassert all directions, protect low bits + Out32(port, reg); Scope::Disconnect(); return false; } @@ -66,17 +66,26 @@ Mount::MOVE_RESULT ScopeGpInt::Guide(GUIDE_DIRECTION direction, int duration) { short reg = Inp32(port); - reg = reg & 0x0F; // Deassert all directions - switch (direction) { - case NORTH: reg = reg ^ 0x80; break; // Dec+ - case SOUTH: reg = reg ^ 0x40; break; // Dec- - case EAST: reg = reg ^ 0x10; break; // RA- - case WEST: reg = reg ^ 0x20; break; // RA+ + reg = reg & 0x0F; // Deassert all directions + switch (direction) + { + case NORTH: + reg = reg ^ 0x80; + break; // Dec+ + case SOUTH: + reg = reg ^ 0x40; + break; // Dec- + case EAST: + reg = reg ^ 0x10; + break; // RA- + case WEST: + reg = reg ^ 0x20; + break; // RA+ } - Out32(port,reg); + Out32(port, reg); WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY); - reg = reg & 0x0F; // Deassert all directions - Out32(port,reg); + reg = reg & 0x0F; // Deassert all directions + Out32(port, reg); return MOVE_OK; } diff --git a/src/scope_gpint.h b/src/scope_gpint.h index c17829c8f..030c7ef5e 100644 --- a/src/scope_gpint.h +++ b/src/scope_gpint.h @@ -40,17 +40,13 @@ class ScopeGpInt : public Scope short port; public: - ScopeGpInt(short port) { m_Name = wxString("GPINT"); this->port = port; } - virtual ~ScopeGpInt(void) - { - Disconnect(); - } + virtual ~ScopeGpInt(void) { Disconnect(); } bool Connect(void) override; bool Disconnect(void) override; diff --git a/src/scope_gpusb.cpp b/src/scope_gpusb.cpp index ffe514d75..f1f82903a 100644 --- a/src/scope_gpusb.cpp +++ b/src/scope_gpusb.cpp @@ -36,11 +36,11 @@ #ifdef GUIDE_GPUSB -#if defined (__WINDOWS__) -#include "ShoestringGPUSB_DLL.h" -#elif defined (__APPLE__) // ------------------------------ Apple routines ---------------------------- +# if defined(__WINDOWS__) +# include "ShoestringGPUSB_DLL.h" +# elif defined(__APPLE__) // ------------------------------ Apple routines ---------------------------- -#include +# include static IOHIDDeviceRef pGPUSB; static int GPUSB_Model; @@ -68,21 +68,18 @@ static bool FindDevice(long vendorId, long productId) } } -#if 1 // workaround problem with crash on re-connect +# if 1 // workaround problem with crash on re-connect if (!first) { pFrame->Alert(_("Please restart PHD2 to re-connect to the GPUSB")); return false; } -#endif +# endif // setup dictionary - CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable( - kCFAllocatorDefault, - 2, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + CFMutableDictionaryRef dictionary = + CFDictionaryCreateMutable(kCFAllocatorDefault, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFNumberRef cfVendorId = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongType, &vendorId); CFStringRef cfVendorSt = CFStringCreateWithCString(kCFAllocatorDefault, kIOHIDVendorIDKey, kCFStringEncodingUTF8); @@ -149,10 +146,10 @@ static IOHIDElementRef GetFirstOutputElement(IOHIDDeviceRef device) IOHIDElementRef output = NULL; CFArrayRef arrayElements = IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone); CFIndex elementCount = CFArrayGetCount(arrayElements); - for(CFIndex i = 0; i < elementCount; i++) + for (CFIndex i = 0; i < elementCount; i++) { IOHIDElementRef tIOHIDElementRef = (IOHIDElementRef) CFArrayGetValueAtIndex(arrayElements, i); - if(!tIOHIDElementRef) + if (!tIOHIDElementRef) { continue; } @@ -160,13 +157,13 @@ static IOHIDElementRef GetFirstOutputElement(IOHIDDeviceRef device) switch (type) { - case kIOHIDElementTypeOutput: - { - output = tIOHIDElementRef; - break; - } - default: - break; + case kIOHIDElementTypeOutput: + { + output = tIOHIDElementRef; + break; + } + default: + break; } if (output) @@ -195,7 +192,7 @@ static IOHIDElementRef GetNextOutputElement(IOHIDDeviceRef device, IOHIDElementR if (!found) { - if(previousElement == tIOHIDElementRef) + if (previousElement == tIOHIDElementRef) { CFRelease(previousElement); // do we need this ? found = true; @@ -207,13 +204,13 @@ static IOHIDElementRef GetNextOutputElement(IOHIDDeviceRef device, IOHIDElementR switch (type) { - case kIOHIDElementTypeOutput: - { - output = tIOHIDElementRef; - break; - } - default: - break; + case kIOHIDElementTypeOutput: + { + output = tIOHIDElementRef; + break; + } + default: + break; } if (output) @@ -228,7 +225,8 @@ static IOHIDElementRef GetNextOutputElement(IOHIDDeviceRef device, IOHIDElementR static bool GPUSB_Open() { - enum { + enum + { VID = 4938, PID = 36896 }; @@ -252,7 +250,7 @@ static bool GPUSB_Open() } IOHIDElementType type = IOHIDElementGetType(tIOHIDElementRef); - switch ( type ) + switch (type) { case kIOHIDElementTypeInput_Misc: case kIOHIDElementTypeInput_Button: @@ -298,7 +296,7 @@ static void GPUSB_SetBit(int bit, int val) IOHIDElementRef pCurrentHIDElement = NULL; int i; - static int bitarray[8]={0,0,0,0,1,1,0,0}; + static int bitarray[8] = { 0, 0, 0, 0, 1, 1, 0, 0 }; static unsigned char GPUSB_reg = 0x30; if (GPUSB_Model) @@ -334,11 +332,7 @@ static void GPUSB_SetBit(int bit, int val) assert(IOHIDValueGetLength(valueToSend) == 1); IOHIDValueRef valueToSendCopied = IOHIDValueCreateWithBytes( - kCFAllocatorDefault, - pCurrentHIDElement, - IOHIDValueGetTimeStamp(valueToSend), - &GPUSB_reg, - 1); + kCFAllocatorDefault, pCurrentHIDElement, IOHIDValueGetTimeStamp(valueToSend), &GPUSB_reg, 1); tIOReturn = IOHIDDeviceSetValue(pGPUSB, pCurrentHIDElement, valueToSendCopied); if (tIOReturn != kIOReturnSuccess) @@ -350,15 +344,13 @@ static void GPUSB_SetBit(int bit, int val) CFRelease(pCurrentHIDElement); } - else { + else + { // Generic bit-set routine. For older adapters, we can't send a whole // byte and things are setup as SInt32's per bit with 8 bits total... - IOHIDTransactionRef transaction = IOHIDTransactionCreate( - kCFAllocatorDefault, - pGPUSB, - kIOHIDTransactionDirectionTypeOutput, - kIOHIDOptionsTypeNone); + IOHIDTransactionRef transaction = + IOHIDTransactionCreate(kCFAllocatorDefault, pGPUSB, kIOHIDTransactionDirectionTypeOutput, kIOHIDOptionsTypeNone); if (transaction == NULL) { @@ -388,10 +380,7 @@ static void GPUSB_SetBit(int bit, int val) } IOHIDValueRef valueToSendCopied = IOHIDValueCreateWithIntegerValue( - kCFAllocatorDefault, - pCurrentHIDElement, - IOHIDValueGetTimeStamp(valueToSend), - bitarray[i]); + kCFAllocatorDefault, pCurrentHIDElement, IOHIDValueGetTimeStamp(valueToSend), bitarray[i]); IOHIDTransactionAddElement(transaction, pCurrentHIDElement); IOHIDTransactionSetValue(transaction, pCurrentHIDElement, valueToSendCopied, 0); @@ -407,7 +396,7 @@ static bool GPUSB_LEDOn() if (!pGPUSB) return false; - GPUSB_SetBit(5,1); + GPUSB_SetBit(5, 1); return true; } @@ -418,7 +407,7 @@ static bool GPUSB_LEDOff() if (!pGPUSB) return false; - GPUSB_SetBit(5,0); + GPUSB_SetBit(5, 0); return true; } @@ -429,7 +418,7 @@ static bool GPUSB_LEDRed() if (!pGPUSB) return false; - GPUSB_SetBit(4,1); + GPUSB_SetBit(4, 1); return true; } @@ -440,7 +429,7 @@ static bool GPUSB_LEDGreen() if (!pGPUSB) return false; - GPUSB_SetBit(4,0); + GPUSB_SetBit(4, 0); return true; } @@ -449,7 +438,7 @@ static bool GPUSB_DecPAssert() if (!pGPUSB) return false; - GPUSB_SetBit(3,1); + GPUSB_SetBit(3, 1); return true; } @@ -458,7 +447,7 @@ static bool GPUSB_DecMAssert() if (!pGPUSB) return false; - GPUSB_SetBit(2,1); + GPUSB_SetBit(2, 1); return true; } @@ -467,7 +456,7 @@ static bool GPUSB_RAPAssert() if (!pGPUSB) return false; - GPUSB_SetBit(1,1); + GPUSB_SetBit(1, 1); return true; } @@ -476,7 +465,7 @@ static bool GPUSB_RAMAssert() if (!pGPUSB) return false; - GPUSB_SetBit(0,1); + GPUSB_SetBit(0, 1); return true; } @@ -485,15 +474,15 @@ static bool GPUSB_AllDirDeassert() if (!pGPUSB) return false; - GPUSB_SetBit(0,0); - GPUSB_SetBit(1,0); - GPUSB_SetBit(2,0); - GPUSB_SetBit(3,0); + GPUSB_SetBit(0, 0); + GPUSB_SetBit(1, 0); + GPUSB_SetBit(2, 0); + GPUSB_SetBit(3, 0); return true; } -#endif // ------------------------------ Apple routines ---------------------------- +# endif // ------------------------------ Apple routines ---------------------------- bool ScopeGpUsb::Connect() { @@ -521,12 +510,22 @@ Mount::MOVE_RESULT ScopeGpUsb::Guide(GUIDE_DIRECTION direction, int duration) { GPUSB_AllDirDeassert(); GPUSB_LEDGreen(); - switch (direction) { - case NORTH: GPUSB_DecPAssert(); break; - case SOUTH: GPUSB_DecMAssert(); break; - case EAST: GPUSB_RAMAssert(); break; - case WEST: GPUSB_RAPAssert(); break; - case NONE: break; + switch (direction) + { + case NORTH: + GPUSB_DecPAssert(); + break; + case SOUTH: + GPUSB_DecMAssert(); + break; + case EAST: + GPUSB_RAMAssert(); + break; + case WEST: + GPUSB_RAPAssert(); + break; + case NONE: + break; } WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY); GPUSB_AllDirDeassert(); diff --git a/src/scope_gpusb.h b/src/scope_gpusb.h index 06e84e501..314059e1c 100644 --- a/src/scope_gpusb.h +++ b/src/scope_gpusb.h @@ -38,10 +38,7 @@ class ScopeGpUsb : public Scope { public: - ScopeGpUsb(void) - { - m_Name = wxString("GPUSB"); - } + ScopeGpUsb(void) { m_Name = wxString("GPUSB"); } bool Connect(void) override; bool Disconnect(void) override; diff --git a/src/scope_indi.cpp b/src/scope_indi.cpp index ce3162533..a65d706f5 100644 --- a/src/scope_indi.cpp +++ b/src/scope_indi.cpp @@ -38,121 +38,108 @@ #ifdef GUIDE_INDI -#include "config_indi.h" -#include +# include "config_indi.h" +# include -#ifdef LIBNOVA -# include -# include -#endif +# ifdef LIBNOVA +# include +# include +# endif -#include -#include +# include +# include class RunInBg; class ScopeINDI : public Scope, public INDI::BaseClient { - private: - ISwitchVectorProperty *connection_prop; - INumberVectorProperty *coord_prop; - INumberVectorProperty *MotionRate_prop; - ISwitchVectorProperty *moveNS_prop; - ISwitch *moveN_prop; - ISwitch *moveS_prop; - ISwitchVectorProperty *moveEW_prop; - ISwitch *moveE_prop; - ISwitch *moveW_prop; - INumberVectorProperty *GuideRate_prop; - INumberVectorProperty *pulseGuideNS_prop; - INumber *pulseN_prop; - INumber *pulseS_prop; - INumberVectorProperty *pulseGuideEW_prop; - INumber *pulseE_prop; - INumber *pulseW_prop; - ISwitchVectorProperty *oncoordset_prop; - ISwitch *setslew_prop; - ISwitch *settrack_prop; - ISwitch *setsync_prop; - INumberVectorProperty *GeographicCoord_prop; - INumberVectorProperty *SiderealTime_prop; - ITextVectorProperty *scope_port; - ISwitchVectorProperty *pierside_prop; - ISwitch *piersideEast_prop; - ISwitch *piersideWest_prop; - ISwitchVectorProperty *AbortMotion_prop; - ISwitch *Abort_prop; - - wxMutex sync_lock; - wxCondition sync_cond; - bool guide_active; - GuideAxis guide_active_axis; - - long INDIport; - wxString INDIhost; - wxString INDIMountName; - bool Connected {false}; - bool m_modal; - bool m_ready; - bool eod_coord; - - bool ConnectToDriver(RunInBg *ctx); - void ClearStatus(); - void CheckState(); - - protected: - void newDevice(INDI::BaseDevice dp) override; - void removeDevice(INDI::BaseDevice dp) override; - void newProperty(INDI::Property property) override; - void removeProperty(INDI::Property property) override {} - void updateProperty(INDI::Property property) override; - void newMessage(INDI::BaseDevice dp, int messageID) override; - void serverDisconnected(int exit_code) override; - - public: - ScopeINDI(); - ~ScopeINDI(); - - bool Connect() override; - bool Disconnect() override; - bool HasSetupDialog() const override; - void SetupDialog() override; - - MOVE_RESULT Guide(GUIDE_DIRECTION direction, int duration) override; - bool HasNonGuiMove() override; - - bool CanPulseGuide() override - { - return (pulseGuideNS_prop && pulseGuideEW_prop); - } - bool CanReportPosition() override - { - return coord_prop ? true : false; - } - bool CanSlew() override - { - return coord_prop ? true : false; - } - bool CanSlewAsync() override; - bool CanCheckSlewing() override - { - return coord_prop ? true : false; - } - - double GetDeclinationRadians() override; - bool GetGuideRates(double *pRAGuideRate, double *pDecGuideRate) override; - bool GetCoordinates(double *ra, double *dec, double *siderealTime) override; - bool GetSiteLatLong(double *latitude, double *longitude) override; - bool SlewToCoordinates(double ra, double dec) override; - bool SlewToCoordinatesAsync(double ra, double dec) override; - void AbortSlew() override; - bool Slewing() override; - PierSide SideOfPier() override; +private: + ISwitchVectorProperty *connection_prop; + INumberVectorProperty *coord_prop; + INumberVectorProperty *MotionRate_prop; + ISwitchVectorProperty *moveNS_prop; + ISwitch *moveN_prop; + ISwitch *moveS_prop; + ISwitchVectorProperty *moveEW_prop; + ISwitch *moveE_prop; + ISwitch *moveW_prop; + INumberVectorProperty *GuideRate_prop; + INumberVectorProperty *pulseGuideNS_prop; + INumber *pulseN_prop; + INumber *pulseS_prop; + INumberVectorProperty *pulseGuideEW_prop; + INumber *pulseE_prop; + INumber *pulseW_prop; + ISwitchVectorProperty *oncoordset_prop; + ISwitch *setslew_prop; + ISwitch *settrack_prop; + ISwitch *setsync_prop; + INumberVectorProperty *GeographicCoord_prop; + INumberVectorProperty *SiderealTime_prop; + ITextVectorProperty *scope_port; + ISwitchVectorProperty *pierside_prop; + ISwitch *piersideEast_prop; + ISwitch *piersideWest_prop; + ISwitchVectorProperty *AbortMotion_prop; + ISwitch *Abort_prop; + + wxMutex sync_lock; + wxCondition sync_cond; + bool guide_active; + GuideAxis guide_active_axis; + + long INDIport; + wxString INDIhost; + wxString INDIMountName; + bool Connected { false }; + bool m_modal; + bool m_ready; + bool eod_coord; + + bool ConnectToDriver(RunInBg *ctx); + void ClearStatus(); + void CheckState(); + +protected: + void newDevice(INDI::BaseDevice dp) override; + void removeDevice(INDI::BaseDevice dp) override; + void newProperty(INDI::Property property) override; + void removeProperty(INDI::Property property) override { } + void updateProperty(INDI::Property property) override; + void newMessage(INDI::BaseDevice dp, int messageID) override; + void serverDisconnected(int exit_code) override; + +public: + ScopeINDI(); + ~ScopeINDI(); + + bool Connect() override; + bool Disconnect() override; + bool HasSetupDialog() const override; + void SetupDialog() override; + + MOVE_RESULT Guide(GUIDE_DIRECTION direction, int duration) override; + bool HasNonGuiMove() override; + + bool CanPulseGuide() override { return (pulseGuideNS_prop && pulseGuideEW_prop); } + bool CanReportPosition() override { return coord_prop ? true : false; } + bool CanSlew() override { return coord_prop ? true : false; } + bool CanSlewAsync() override; + bool CanCheckSlewing() override { return coord_prop ? true : false; } + + double GetDeclinationRadians() override; + bool GetGuideRates(double *pRAGuideRate, double *pDecGuideRate) override; + bool GetCoordinates(double *ra, double *dec, double *siderealTime) override; + bool GetSiteLatLong(double *latitude, double *longitude) override; + bool SlewToCoordinates(double ra, double dec) override; + bool SlewToCoordinatesAsync(double ra, double dec) override; + void AbortSlew() override; + bool Slewing() override; + PierSide SideOfPier() override; }; ScopeINDI::ScopeINDI() - : - sync_cond(sync_lock) + : sync_cond(sync_lock) { ClearStatus(); // load the values from the current profile @@ -212,8 +199,7 @@ void ScopeINDI::CheckState() else { // guiding mount requires guiding props - if (!(MotionRate_prop && moveNS_prop && moveEW_prop) && - !(pulseGuideNS_prop && pulseGuideEW_prop)) + if (!(MotionRate_prop && moveNS_prop && moveEW_prop) && !(pulseGuideNS_prop && pulseGuideEW_prop)) { return; } @@ -221,10 +207,8 @@ void ScopeINDI::CheckState() Debug.Write(wxString::Format("INDI Telescope%s is ready " "MotionRate=%d moveNS=%d moveEW=%d guideNS=%d guideEW=%d coord=%d\n", - isAuxMount ? " (AUX)" : "", - MotionRate_prop ? 1 : 0, moveNS_prop ? 1 : 0, moveEW_prop ? 1 : 0, - pulseGuideNS_prop ? 1 : 0, pulseGuideEW_prop ? 1 : 0, - coord_prop ? 1 : 0)); + isAuxMount ? " (AUX)" : "", MotionRate_prop ? 1 : 0, moveNS_prop ? 1 : 0, moveEW_prop ? 1 : 0, + pulseGuideNS_prop ? 1 : 0, pulseGuideEW_prop ? 1 : 0, coord_prop ? 1 : 0)); m_ready = true; @@ -304,11 +288,14 @@ bool ScopeINDI::Connect() struct ConnectInBg : public ConnectMountInBg { ScopeINDI *scope; - ConnectInBg(ScopeINDI *scope_) : scope(scope_) { } + ConnectInBg(ScopeINDI *scope_) + : scope(scope_) + { + } bool Entry() { - //Wait for driver to establish a device connection + // Wait for driver to establish a device connection if (scope->connectServer()) { int i = 0; @@ -323,7 +310,6 @@ bool ScopeINDI::Connect() // We need to return FALSE if we are successful return !scope->Connected; - } }; @@ -421,91 +407,90 @@ void ScopeINDI::updateProperty(INDI::Property property) { switch (property.getType()) { - case INDI_SWITCH: + case INDI_SWITCH: + { + auto svp = property.getSwitch(); + // we go here every time a Switch state change + if (INDIConfig::Verbose()) + Debug.Write(wxString::Format("INDI Mount: Receiving Switch: %s = %i\n", svp->name, svp->sp->s)); + + if (strcmp(svp->name, "CONNECTION") == 0) { - auto svp = property.getSwitch(); - // we go here every time a Switch state change - if (INDIConfig::Verbose()) - Debug.Write(wxString::Format("INDI Mount: Receiving Switch: %s = %i\n", svp->name, svp->sp->s)); + ISwitch *connectswitch = IUFindSwitch(svp, "CONNECT"); - if (strcmp(svp->name, "CONNECTION") == 0) + if (connectswitch->s == ISS_ON) { - ISwitch *connectswitch = IUFindSwitch(svp, "CONNECT"); - - if (connectswitch->s == ISS_ON) - { - Connected = true; - Scope::Connect(); - } - else + Connected = true; + Scope::Connect(); + } + else + { + if (m_ready) { - if (m_ready) - { - ClearStatus(); + ClearStatus(); - // call Disconnect in the main thread since that will - // want to join the INDI worker thread which is - // probably the current thread + // call Disconnect in the main thread since that will + // want to join the INDI worker thread which is + // probably the current thread - PhdApp::ExecInMainThread( - [this]() + PhdApp::ExecInMainThread( + [this]() { pFrame->Alert(_("INDI mount was disconnected")); Connected = false; Disconnect(); }); - } } } } - break; + } + break; - case INDI_NUMBER: - { - auto nvp = property.getNumber(); + case INDI_NUMBER: + { + auto nvp = property.getNumber(); - if (INDIConfig::Verbose()) - { - if (strcmp(nvp->name, "EQUATORIAL_EOD_COORD") != 0) // too noisy - Debug.Write(wxString::Format("INDI Mount: Receiving Number: %s = %g state = %s\n", nvp->name, nvp->np->value, - property.getStateAsString())); - } + if (INDIConfig::Verbose()) + { + if (strcmp(nvp->name, "EQUATORIAL_EOD_COORD") != 0) // too noisy + Debug.Write(wxString::Format("INDI Mount: Receiving Number: %s = %g state = %s\n", nvp->name, nvp->np->value, + property.getStateAsString())); + } - if (nvp == pulseGuideEW_prop || nvp == pulseGuideNS_prop) + if (nvp == pulseGuideEW_prop || nvp == pulseGuideNS_prop) + { + bool notify = false; { - bool notify = false; + wxMutexLocker lck(sync_lock); + if (guide_active && nvp->s != IPS_BUSY && + ((guide_active_axis == GUIDE_RA && nvp == pulseGuideEW_prop) || + (guide_active_axis == GUIDE_DEC && nvp == pulseGuideNS_prop))) + { + guide_active = false; + notify = true; + } + else if (!guide_active && nvp->s == IPS_BUSY) { - wxMutexLocker lck(sync_lock); - if (guide_active && nvp->s != IPS_BUSY && - ((guide_active_axis == GUIDE_RA && nvp == pulseGuideEW_prop) || (guide_active_axis == GUIDE_DEC - && nvp == pulseGuideNS_prop))) - { - guide_active = false; - notify = true; - } - else if (!guide_active && nvp->s == IPS_BUSY) - { - guide_active = true; - guide_active_axis = nvp == pulseGuideEW_prop ? GUIDE_RA : GUIDE_DEC; - } + guide_active = true; + guide_active_axis = nvp == pulseGuideEW_prop ? GUIDE_RA : GUIDE_DEC; } - if (notify) - sync_cond.Broadcast(); } - + if (notify) + sync_cond.Broadcast(); } - break; - case INDI_TEXT: - { - auto tvp = property.getText(); + } + break; + case INDI_TEXT: + { + auto tvp = property.getText(); - // we go here every time a Text value change - if (INDIConfig::Verbose()) - Debug.Write(wxString::Format("INDI Mount: Receiving Text: %s = %s\n", tvp->name, tvp->tp->text)); - } + // we go here every time a Text value change + if (INDIConfig::Verbose()) + Debug.Write(wxString::Format("INDI Mount: Receiving Text: %s = %s\n", tvp->name, tvp->tp->text)); + } + break; + default: break; - default: - break; } } @@ -629,14 +614,14 @@ Mount::MOVE_RESULT ScopeINDI::Guide(GUIDE_DIRECTION direction, int duration) switch (direction) { - case EAST: - case WEST: - case NORTH: - case SOUTH: - break; - default: - Debug.Write("INDI Mount error ScopeINDI::Guide NONE\n"); - return MOVE_ERROR; + case EAST: + case WEST: + case NORTH: + case SOUTH: + break; + default: + Debug.Write("INDI Mount error ScopeINDI::Guide NONE\n"); + return MOVE_ERROR; } // set guide active before initiating the pulse @@ -659,28 +644,28 @@ Mount::MOVE_RESULT ScopeINDI::Guide(GUIDE_DIRECTION direction, int duration) // despite what is said in INDI standard properties description, every telescope driver expect the guided time in msec. switch (direction) { - case EAST: - pulseE_prop->value = duration; - pulseW_prop->value = 0; - sendNewNumber(pulseGuideEW_prop); - break; - case WEST: - pulseE_prop->value = 0; - pulseW_prop->value = duration; - sendNewNumber(pulseGuideEW_prop); - break; - case NORTH: - pulseN_prop->value = duration; - pulseS_prop->value = 0; - sendNewNumber(pulseGuideNS_prop); - break; - case SOUTH: - pulseN_prop->value = 0; - pulseS_prop->value = duration; - sendNewNumber(pulseGuideNS_prop); - break; - default: - break; + case EAST: + pulseE_prop->value = duration; + pulseW_prop->value = 0; + sendNewNumber(pulseGuideEW_prop); + break; + case WEST: + pulseE_prop->value = 0; + pulseW_prop->value = duration; + sendNewNumber(pulseGuideEW_prop); + break; + case NORTH: + pulseN_prop->value = duration; + pulseS_prop->value = 0; + sendNewNumber(pulseGuideNS_prop); + break; + case SOUTH: + pulseN_prop->value = 0; + pulseS_prop->value = duration; + sendNewNumber(pulseGuideNS_prop); + break; + default: + break; } if (INDIConfig::Verbose()) @@ -712,50 +697,50 @@ Mount::MOVE_RESULT ScopeINDI::Guide(GUIDE_DIRECTION direction, int duration) if (INDIConfig::Verbose()) Debug.Write(wxString::Format("INDI Mount: motion rate guide dir %d dur %d ms\n", direction, duration)); - MotionRate_prop->np->value = 0.3 * 15 / 60; // set 0.3 sidereal in arcmin/sec + MotionRate_prop->np->value = 0.3 * 15 / 60; // set 0.3 sidereal in arcmin/sec sendNewNumber(MotionRate_prop); switch (direction) { - case EAST: - moveW_prop->s = ISS_OFF; - moveE_prop->s = ISS_ON; - sendNewSwitch(moveEW_prop); - wxMilliSleep(duration); - moveW_prop->s = ISS_OFF; - moveE_prop->s = ISS_OFF; - sendNewSwitch(moveEW_prop); - break; - case WEST: - moveW_prop->s = ISS_ON; - moveE_prop->s = ISS_OFF; - sendNewSwitch(moveEW_prop); - wxMilliSleep(duration); - moveW_prop->s = ISS_OFF; - moveE_prop->s = ISS_OFF; - sendNewSwitch(moveEW_prop); - break; - case NORTH: - moveN_prop->s = ISS_ON; - moveS_prop->s = ISS_OFF; - sendNewSwitch(moveNS_prop); - wxMilliSleep(duration); - moveN_prop->s = ISS_OFF; - moveS_prop->s = ISS_OFF; - sendNewSwitch(moveNS_prop); - break; - case SOUTH: - moveN_prop->s = ISS_OFF; - moveS_prop->s = ISS_ON; - sendNewSwitch(moveNS_prop); - wxMilliSleep(duration); - moveN_prop->s = ISS_OFF; - moveS_prop->s = ISS_OFF; - sendNewSwitch(moveNS_prop); - break; - case NONE: - Debug.Write("INDI Mount: error ScopeINDI::Guide NONE\n"); - break; + case EAST: + moveW_prop->s = ISS_OFF; + moveE_prop->s = ISS_ON; + sendNewSwitch(moveEW_prop); + wxMilliSleep(duration); + moveW_prop->s = ISS_OFF; + moveE_prop->s = ISS_OFF; + sendNewSwitch(moveEW_prop); + break; + case WEST: + moveW_prop->s = ISS_ON; + moveE_prop->s = ISS_OFF; + sendNewSwitch(moveEW_prop); + wxMilliSleep(duration); + moveW_prop->s = ISS_OFF; + moveE_prop->s = ISS_OFF; + sendNewSwitch(moveEW_prop); + break; + case NORTH: + moveN_prop->s = ISS_ON; + moveS_prop->s = ISS_OFF; + sendNewSwitch(moveNS_prop); + wxMilliSleep(duration); + moveN_prop->s = ISS_OFF; + moveS_prop->s = ISS_OFF; + sendNewSwitch(moveNS_prop); + break; + case SOUTH: + moveN_prop->s = ISS_OFF; + moveS_prop->s = ISS_ON; + sendNewSwitch(moveNS_prop); + wxMilliSleep(duration); + moveN_prop->s = ISS_OFF; + moveS_prop->s = ISS_OFF; + sendNewSwitch(moveNS_prop); + break; + case NONE: + Debug.Write("INDI Mount: error ScopeINDI::Guide NONE\n"); + break; } return MOVE_OK; @@ -774,9 +759,11 @@ double ScopeINDI::GetDeclinationRadians() INumber *decprop = IUFindNumber(coord_prop, "DEC"); if (decprop) { - double dec = decprop->value; // Degrees - if (dec > 89.0) dec = 89.0; // avoid crash when dividing by cos(dec) - if (dec < -89.0) dec = -89.0; + double dec = decprop->value; // Degrees + if (dec > 89.0) + dec = 89.0; // avoid crash when dividing by cos(dec) + if (dec < -89.0) + dec = -89.0; return radians(dec); } } @@ -795,11 +782,11 @@ bool ScopeINDI::GetGuideRates(double *pRAGuideRate, double *pDecGuideRate) if (ratera && ratedec) { const double dSiderealSecondPerSec = 0.9973; - double gra = ratera->value; // sidereal rate + double gra = ratera->value; // sidereal rate double gdec = ratedec->value; - gra *= (15.0 * dSiderealSecondPerSec) / 3600.; // ASCOM compatible - gdec *= (15.0 * dSiderealSecondPerSec) / 3600.; // Degrees/sec - *pRAGuideRate = gra; + gra *= (15.0 * dSiderealSecondPerSec) / 3600.; // ASCOM compatible + gdec *= (15.0 * dSiderealSecondPerSec) / 3600.; // Degrees/sec + *pRAGuideRate = gra; *pDecGuideRate = gdec; err = false; } @@ -810,7 +797,7 @@ bool ScopeINDI::GetGuideRates(double *pRAGuideRate, double *pDecGuideRate) static double libnova_LST(ScopeINDI *scope) { -#ifdef LIBNOVA +# ifdef LIBNOVA double jd = ln_get_julian_from_sys(); double lst = ln_get_apparent_sidereal_time(jd); @@ -822,9 +809,9 @@ static double libnova_LST(ScopeINDI *scope) return norm(lst + lon / 15.0, 0.0, 24.0); -#else +# else return 0.0; -#endif +# endif } bool ScopeINDI::GetCoordinates(double *ra, double *dec, double *siderealTime) @@ -837,7 +824,7 @@ bool ScopeINDI::GetCoordinates(double *ra, double *dec, double *siderealTime) INumber *decprop = IUFindNumber(coord_prop, "DEC"); if (raprop && decprop) { - *ra = raprop->value; // hours + *ra = raprop->value; // hours *dec = decprop->value; // degrees err = false; } diff --git a/src/scope_indi.h b/src/scope_indi.h index 23084675a..454365a01 100644 --- a/src/scope_indi.h +++ b/src/scope_indi.h @@ -40,8 +40,8 @@ class INDIScopeFactory { - public: - static Scope *MakeINDIScope(); +public: + static Scope *MakeINDIScope(); }; #endif diff --git a/src/scope_manual_pointing.cpp b/src/scope_manual_pointing.cpp index 5cd92821c..57946cbe1 100644 --- a/src/scope_manual_pointing.cpp +++ b/src/scope_manual_pointing.cpp @@ -40,35 +40,38 @@ struct ScopePointingDlg : public wxDialog { double m_latitudeVal, m_longitudeVal; - wxSpinCtrl* m_dec; - wxRadioButton* m_radioBtnWest; - wxRadioButton* m_radioBtnEast; - wxRadioButton* m_radioBtnUnspecified; - wxSpinCtrl* m_raHr; - wxSpinCtrl* m_raMin; - wxTextCtrl* m_latitude; - wxTextCtrl* m_longitude; - wxButton* m_OK; - wxButton* m_Cancel; - - ScopePointingDlg(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Scope Pointing"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(332, 358), long style = wxDEFAULT_DIALOG_STYLE); + wxSpinCtrl *m_dec; + wxRadioButton *m_radioBtnWest; + wxRadioButton *m_radioBtnEast; + wxRadioButton *m_radioBtnUnspecified; + wxSpinCtrl *m_raHr; + wxSpinCtrl *m_raMin; + wxTextCtrl *m_latitude; + wxTextCtrl *m_longitude; + wxButton *m_OK; + wxButton *m_Cancel; + + ScopePointingDlg(wxWindow *parent, wxWindowID id = wxID_ANY, const wxString& title = _("Scope Pointing"), + const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(332, 358), long style = wxDEFAULT_DIALOG_STYLE); ~ScopePointingDlg(); }; -ScopePointingDlg::ScopePointingDlg(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) +ScopePointingDlg::ScopePointingDlg( + wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) + : wxDialog(parent, id, title, pos, size, style) { this->SetSizeHints(wxDefaultSize, wxDefaultSize); - wxBoxSizer* bSizer1; + wxBoxSizer *bSizer1; bSizer1 = new wxBoxSizer(wxVERTICAL); - wxStaticBoxSizer* sbSizer2; + wxStaticBoxSizer *sbSizer2; sbSizer2 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, _("Guiding")), wxVERTICAL); - wxBoxSizer* bSizer2; + wxBoxSizer *bSizer2; bSizer2 = new wxBoxSizer(wxVERTICAL); - wxBoxSizer* bSizer3; + wxBoxSizer *bSizer3; bSizer3 = new wxBoxSizer(wxHORIZONTAL); wxStaticText *staticText1 = new wxStaticText(sbSizer2->GetStaticBox(), wxID_ANY, @@ -85,21 +88,27 @@ ScopePointingDlg::ScopePointingDlg(wxWindow* parent, wxWindowID id, const wxStri bSizer2->Add(bSizer3, 0, wxALIGN_CENTER_HORIZONTAL, 5); - wxStaticBoxSizer* sbSizer4; + wxStaticBoxSizer *sbSizer4; sbSizer4 = new wxStaticBoxSizer(new wxStaticBox(sbSizer2->GetStaticBox(), wxID_ANY, _("Side of Pier")), wxVERTICAL); - m_radioBtnWest = new wxRadioButton(sbSizer4->GetStaticBox(), wxID_ANY, _("West (pointing East)"), wxDefaultPosition, wxDefaultSize, 0); - m_radioBtnWest->SetToolTip(_("Telescope is on the West side of the pier, typically pointing East, before the meridian flip")); + m_radioBtnWest = + new wxRadioButton(sbSizer4->GetStaticBox(), wxID_ANY, _("West (pointing East)"), wxDefaultPosition, wxDefaultSize, 0); + m_radioBtnWest->SetToolTip( + _("Telescope is on the West side of the pier, typically pointing East, before the meridian flip")); sbSizer4->Add(m_radioBtnWest, 0, wxALL, 5); - m_radioBtnEast = new wxRadioButton(sbSizer4->GetStaticBox(), wxID_ANY, _("East (pointing West)"), wxDefaultPosition, wxDefaultSize, 0); - m_radioBtnEast->SetToolTip(_("Telescope is on the East side of the pier, typically pointing West, after the meridian flip")); + m_radioBtnEast = + new wxRadioButton(sbSizer4->GetStaticBox(), wxID_ANY, _("East (pointing West)"), wxDefaultPosition, wxDefaultSize, 0); + m_radioBtnEast->SetToolTip( + _("Telescope is on the East side of the pier, typically pointing West, after the meridian flip")); sbSizer4->Add(m_radioBtnEast, 0, wxALL, 5); - m_radioBtnUnspecified = new wxRadioButton(sbSizer4->GetStaticBox(), wxID_ANY, _("Unspecified"), wxDefaultPosition, wxDefaultSize, 0); - m_radioBtnUnspecified->SetToolTip(_("Select Unspecified if you do not want PHD2 to flip your calibration data for side of pier changes")); + m_radioBtnUnspecified = + new wxRadioButton(sbSizer4->GetStaticBox(), wxID_ANY, _("Unspecified"), wxDefaultPosition, wxDefaultSize, 0); + m_radioBtnUnspecified->SetToolTip( + _("Select Unspecified if you do not want PHD2 to flip your calibration data for side of pier changes")); sbSizer4->Add(m_radioBtnUnspecified, 0, wxALL, 5); @@ -112,17 +121,19 @@ ScopePointingDlg::ScopePointingDlg(wxWindow* parent, wxWindowID id, const wxStri m_raHr = 0; if (pFrame->pDriftTool) { - wxStaticBoxSizer* sbSizer3; + wxStaticBoxSizer *sbSizer3; sbSizer3 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, _("Drift Alignment")), wxVERTICAL); - wxBoxSizer* bSizer31; + wxBoxSizer *bSizer31; bSizer31 = new wxBoxSizer(wxHORIZONTAL); - wxStaticText *staticText11 = new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, _("Right Ascension"), wxDefaultPosition, wxDefaultSize, 0); + wxStaticText *staticText11 = + new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, _("Right Ascension"), wxDefaultPosition, wxDefaultSize, 0); staticText11->Wrap(-1); bSizer31->Add(staticText11, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); - wxStaticText *staticText111 = new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, _("hr"), wxDefaultPosition, wxDefaultSize, 0); + wxStaticText *staticText111 = + new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, _("hr"), wxDefaultPosition, wxDefaultSize, 0); staticText111->Wrap(-1); bSizer31->Add(staticText111, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); @@ -132,7 +143,8 @@ ScopePointingDlg::ScopePointingDlg(wxWindow* parent, wxWindowID id, const wxStri bSizer31->Add(m_raHr, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); - wxStaticText *staticText1111 = new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, _("min"), wxDefaultPosition, wxDefaultSize, 0); + wxStaticText *staticText1111 = + new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, _("min"), wxDefaultPosition, wxDefaultSize, 0); staticText1111->Wrap(-1); bSizer31->Add(staticText1111, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); @@ -144,30 +156,32 @@ ScopePointingDlg::ScopePointingDlg(wxWindow* parent, wxWindowID id, const wxStri sbSizer3->Add(bSizer31, 0, 0, 5); - wxBoxSizer* bSizer8; + wxBoxSizer *bSizer8; bSizer8 = new wxBoxSizer(wxHORIZONTAL); - wxStaticText *staticText13 = new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, - wxString::Format(_("Latitude (%s)"), DEGREES_SYMBOL)); + wxStaticText *staticText13 = + new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, wxString::Format(_("Latitude (%s)"), DEGREES_SYMBOL)); staticText13->Wrap(-1); bSizer8->Add(staticText13, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); wxFloatingPointValidator val1(3, &m_latitudeVal, wxNUM_VAL_ZERO_AS_BLANK); val1.SetRange(-90.0, 90.0); - m_latitude = new wxTextCtrl(sbSizer3->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, val1); + m_latitude = + new wxTextCtrl(sbSizer3->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, val1); m_latitude->SetToolTip(_("Site latitude")); m_latitude->SetMaxSize(wxSize(70, -1)); bSizer8->Add(m_latitude, 0, wxALL, 5); - wxStaticText *staticText131 = new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, - wxString::Format(_("Longitude (%s)"), DEGREES_SYMBOL)); + wxStaticText *staticText131 = + new wxStaticText(sbSizer3->GetStaticBox(), wxID_ANY, wxString::Format(_("Longitude (%s)"), DEGREES_SYMBOL)); staticText131->Wrap(-1); bSizer8->Add(staticText131, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); wxFloatingPointValidator val2(3, &m_longitudeVal, wxNUM_VAL_ZERO_AS_BLANK); val2.SetRange(-180.0, 180.0); - m_longitude = new wxTextCtrl(sbSizer3->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, val2); + m_longitude = + new wxTextCtrl(sbSizer3->GetStaticBox(), wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, val2); m_longitude->SetToolTip(_("Site longitude, degrees East of Greenwich. Longitudes West of Greenwich are negative.")); m_longitude->SetMaxSize(wxSize(70, -1)); @@ -195,9 +209,7 @@ ScopePointingDlg::ScopePointingDlg(wxWindow* parent, wxWindowID id, const wxStri this->Centre(wxBOTH); } -ScopePointingDlg::~ScopePointingDlg() -{ -} +ScopePointingDlg::~ScopePointingDlg() { } wxString ScopeManualPointing::GetDisplayName() { @@ -268,10 +280,17 @@ bool ScopeManualPointing::PreparePositionInteractive(void) // load values dlg.m_dec->SetValue((int) degrees(m_dec)); wxRadioButton *btn; - switch (m_sideOfPier) { - case PIER_SIDE_EAST: btn = dlg.m_radioBtnEast; break; - case PIER_SIDE_WEST: btn = dlg.m_radioBtnWest; break; - default: btn = dlg.m_radioBtnUnspecified; break; + switch (m_sideOfPier) + { + case PIER_SIDE_EAST: + btn = dlg.m_radioBtnEast; + break; + case PIER_SIDE_WEST: + btn = dlg.m_radioBtnWest; + break; + default: + btn = dlg.m_radioBtnUnspecified; + break; } btn->SetValue(true); if (dlg.m_raHr) @@ -309,19 +328,19 @@ bool ScopeManualPointing::PreparePositionInteractive(void) m_ra = (double) dlg.m_raHr->GetValue() + (double) dlg.m_raMin->GetValue() / 60.0; // TODO: figure out why data transfer not working - #if 0 +#if 0 m_latitude = dlg.m_latitudeVal; m_longitude = dlg.m_longitudeVal; - #else +#else dlg.m_latitude->GetValue().ToDouble(&m_latitude); dlg.m_longitude->GetValue().ToDouble(&m_longitude); - #endif +#endif pConfig->Profile.SetDouble("/scope/manual_pointing/latitude", m_latitude); pConfig->Profile.SetDouble("/scope/manual_pointing/longitude", m_longitude); } Debug.Write(wxString::Format("ScopeManualPointing%s coords %.3f,%.3f pierside %d site %.3f,%.3f\n", - dlg.m_raHr ? " (driftalign)" : "", m_ra, degrees(m_dec), m_sideOfPier, m_latitude, m_longitude)); + dlg.m_raHr ? " (driftalign)" : "", m_ra, degrees(m_dec), m_sideOfPier, m_latitude, m_longitude)); return false; } diff --git a/src/scope_onboard_st4.cpp b/src/scope_onboard_st4.cpp index 1e8eb063e..f8529da4b 100644 --- a/src/scope_onboard_st4.cpp +++ b/src/scope_onboard_st4.cpp @@ -37,8 +37,7 @@ #include "scope_onboard_st4.h" ScopeOnboardST4::ScopeOnboardST4(void) - : - m_pOnboardHost(nullptr) + : m_pOnboardHost(nullptr) { } @@ -137,7 +136,7 @@ Mount::MOVE_RESULT ScopeOnboardST4::Guide(GUIDE_DIRECTION direction, int duratio throw ERROR_INFO("Attempt to Guide On Camera mount when camera is not connected"); } - if (m_pOnboardHost->ST4PulseGuideScope(direction,duration)) + if (m_pOnboardHost->ST4PulseGuideScope(direction, duration)) { result = MOVE_ERROR; } diff --git a/src/scope_oncamera.cpp b/src/scope_oncamera.cpp index 5d0088454..8858571b1 100644 --- a/src/scope_oncamera.cpp +++ b/src/scope_oncamera.cpp @@ -39,12 +39,10 @@ ScopeOnCamera::ScopeOnCamera() { - m_Name = "On Camera"; + m_Name = "On Camera"; } -ScopeOnCamera::~ScopeOnCamera() -{ -} +ScopeOnCamera::~ScopeOnCamera() { } bool ScopeOnCamera::Connect() { diff --git a/src/scope_oncamera.h b/src/scope_oncamera.h index 1076c0a67..03e19db5e 100644 --- a/src/scope_oncamera.h +++ b/src/scope_oncamera.h @@ -35,7 +35,7 @@ #ifdef GUIDE_ONCAMERA -#include "scope_onboard_st4.h" +# include "scope_onboard_st4.h" class ScopeOnCamera : public ScopeOnboardST4 { diff --git a/src/scope_onstepguider.cpp b/src/scope_onstepguider.cpp index 81f098b11..1732f9a14 100644 --- a/src/scope_onstepguider.cpp +++ b/src/scope_onstepguider.cpp @@ -39,12 +39,10 @@ ScopeOnStepGuider::ScopeOnStepGuider(void) { - m_Name = "On StepGuider"; + m_Name = "On StepGuider"; } -ScopeOnStepGuider::~ScopeOnStepGuider(void) -{ -} +ScopeOnStepGuider::~ScopeOnStepGuider(void) { } bool ScopeOnStepGuider::Connect(void) { diff --git a/src/scope_onstepguider.h b/src/scope_onstepguider.h index 2d1eba34e..160a49c45 100644 --- a/src/scope_onstepguider.h +++ b/src/scope_onstepguider.h @@ -35,7 +35,7 @@ #ifdef GUIDE_ONSTEPGUIDER -#include "scope_onboard_st4.h" +# include "scope_onboard_st4.h" class ScopeOnStepGuider : public ScopeOnboardST4 { diff --git a/src/scope_voyager.cpp b/src/scope_voyager.cpp index 3820d7bee..cca3140d5 100644 --- a/src/scope_voyager.cpp +++ b/src/scope_voyager.cpp @@ -49,7 +49,8 @@ bool ScopeVoyager::Connect(const wxString& hostname) VoyagerClient.Connect(addr, false); VoyagerClient.WaitOnConnect(5); - if (VoyagerClient.IsConnected()) { + if (VoyagerClient.IsConnected()) + { wxMessageBox(_("Connection established")); bError = false; } @@ -87,40 +88,41 @@ Mount::MOVE_RESULT ScopeVoyager::Guide(GUIDE_DIRECTION direction, int duration) } // Disable input notification - VoyagerClient.SetNotify(wxSOCKET_LOST_FLAG); // Disable input for now + VoyagerClient.SetNotify(wxSOCKET_LOST_FLAG); // Disable input for now VoyagerClient.SetTimeout(2); // set to 2s timeout char msg[64], dir; snprintf(msg, sizeof(msg), "RATE 100\n\n"); - VoyagerClient.Write(msg,strlen(msg)); - VoyagerClient.Read(&msg,10); + VoyagerClient.Write(msg, strlen(msg)); + VoyagerClient.Read(&msg, 10); - if (strstr(msg,"ERROR")) + if (strstr(msg, "ERROR")) { throw ERROR_INFO("Voyager Scope: error setting rate"); } - switch (direction) { - case NORTH: - dir = 'N'; - break; - case SOUTH: - dir = 'S'; - break; - case EAST: - dir = 'E'; - break; - case WEST: - dir = 'W'; - break; + switch (direction) + { + case NORTH: + dir = 'N'; + break; + case SOUTH: + dir = 'S'; + break; + case EAST: + dir = 'E'; + break; + case WEST: + dir = 'W'; + break; } snprintf(msg, sizeof(msg), "MOVE %c\n\n", dir); - VoyagerClient.Write(msg,strlen(msg)); - VoyagerClient.Read(&msg,10); + VoyagerClient.Write(msg, strlen(msg)); + VoyagerClient.Read(&msg, 10); WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY); snprintf(msg, sizeof(msg), "STOP %c\n\n", dir); - VoyagerClient.Write(msg,strlen(msg)); - VoyagerClient.Read(&msg,10); + VoyagerClient.Write(msg, strlen(msg)); + VoyagerClient.Read(&msg, 10); } catch (const wxString& Msg) { diff --git a/src/scope_voyager.h b/src/scope_voyager.h index eadf7b911..178879b8d 100644 --- a/src/scope_voyager.h +++ b/src/scope_voyager.h @@ -35,20 +35,15 @@ #ifdef GUIDE_VOYAGER -class ScopeVoyager:public Scope +class ScopeVoyager : public Scope { private: wxSocketClient VoyagerClient; public: - ScopeVoyager() - { - } + ScopeVoyager() { } - virtual ~ScopeVoyager() - { - VoyagerClient.Close(); - } + virtual ~ScopeVoyager() { VoyagerClient.Close(); } bool Connect(const wxString& hostname); bool Connect() override; diff --git a/src/scopes.h b/src/scopes.h index 472ac2819..c606b5498 100644 --- a/src/scopes.h +++ b/src/scopes.h @@ -35,32 +35,32 @@ #ifndef SCOPES_H_INCLUDED #define SCOPES_H_INCLUDED -#if defined (__WINDOWS__) +#if defined(__WINDOWS__) - #define GUIDE_ONCAMERA - #define GUIDE_ONSTEPGUIDER - #define GUIDE_ASCOM - #define GUIDE_GPUSB - #define GUIDE_GPINT - #define GUIDE_INDI +# define GUIDE_ONCAMERA +# define GUIDE_ONSTEPGUIDER +# define GUIDE_ASCOM +# define GUIDE_GPUSB +# define GUIDE_GPINT +# define GUIDE_INDI -#elif defined (__APPLE__) +#elif defined(__APPLE__) - #define GUIDE_ONCAMERA - #define GUIDE_ONSTEPGUIDER - #define GUIDE_GPUSB - #define GUIDE_GCUSBST4 - #define GUIDE_INDI - #define GUIDE_EQUINOX - //#define GUIDE_VOYAGER - //#define GUIDE_NEB - #define GUIDE_EQMAC +# define GUIDE_ONCAMERA +# define GUIDE_ONSTEPGUIDER +# define GUIDE_GPUSB +# define GUIDE_GCUSBST4 +# define GUIDE_INDI +# define GUIDE_EQUINOX +// #define GUIDE_VOYAGER +// #define GUIDE_NEB +# define GUIDE_EQMAC -#elif defined (__linux__) || defined (__FreeBSD__) +#elif defined(__linux__) || defined(__FreeBSD__) - #define GUIDE_ONCAMERA - #define GUIDE_ONSTEPGUIDER - #define GUIDE_INDI +# define GUIDE_ONCAMERA +# define GUIDE_ONSTEPGUIDER +# define GUIDE_INDI #endif // WINDOWS/APPLE/LINUX diff --git a/src/serialport.cpp b/src/serialport.cpp index b0f430f5b..b1dca1ac2 100644 --- a/src/serialport.cpp +++ b/src/serialport.cpp @@ -35,13 +35,9 @@ #include "phd.h" -SerialPort::SerialPort(void) -{ -} +SerialPort::SerialPort(void) { } -SerialPort::~SerialPort(void) -{ -} +SerialPort::~SerialPort(void) { } SerialPort *SerialPort::SerialPortFactory(void) { diff --git a/src/serialport.h b/src/serialport.h index cfd8b550d..aeb774042 100644 --- a/src/serialport.h +++ b/src/serialport.h @@ -41,10 +41,10 @@ class SerialPort public: enum PARITY { - ParityNone = 0, - ParityOdd = 1, - ParityEven = 2, - ParityMark = 3, + ParityNone = 0, + ParityOdd = 1, + ParityEven = 2, + ParityMark = 3, ParitySpace = 4, }; @@ -54,7 +54,8 @@ class SerialPort SerialPort(void); virtual ~SerialPort(void); - virtual bool Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) = 0; + virtual bool Connect( + const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) = 0; virtual bool Disconnect(void) = 0; virtual bool Send(const unsigned char *pData, unsigned count) = 0; diff --git a/src/serialport_loopback.cpp b/src/serialport_loopback.cpp index c92420505..b9bd29854 100644 --- a/src/serialport_loopback.cpp +++ b/src/serialport_loopback.cpp @@ -60,11 +60,10 @@ SerialPortLoopback::SerialPortLoopback(void) m_data = 0; } -SerialPortLoopback::~SerialPortLoopback(void) -{ -} +SerialPortLoopback::~SerialPortLoopback(void) { } -bool SerialPortLoopback::Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) +bool SerialPortLoopback::Connect( + const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) { bool bError = false; diff --git a/src/serialport_loopback.h b/src/serialport_loopback.h index fc620c737..5ce7a2801 100644 --- a/src/serialport_loopback.h +++ b/src/serialport_loopback.h @@ -34,7 +34,7 @@ */ #if !defined(SERIALPORT_LOOPBACK_H_INCLUDED) -#define SERIALPORT_LOOPBACK_H_INCLUDED +# define SERIALPORT_LOOPBACK_H_INCLUDED class SerialPortLoopback : public SerialPort { @@ -42,13 +42,13 @@ class SerialPortLoopback : public SerialPort char m_data; public: - wxArrayString GetSerialPortList() override; SerialPortLoopback(); virtual ~SerialPortLoopback(); - bool Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) override; + bool Connect( + const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) override; bool Disconnect() override; bool Send(const unsigned char *pData, unsigned count) override; diff --git a/src/serialport_mac.cpp b/src/serialport_mac.cpp index d2d8a3eef..182c5f5f7 100644 --- a/src/serialport_mac.cpp +++ b/src/serialport_mac.cpp @@ -34,18 +34,18 @@ #ifdef __APPLE__ -#include "phd.h" -#include +# include "phd.h" +# include -#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 120000 -# define IOMainPort IOMasterPort -#endif +# if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 120000 +# define IOMainPort IOMasterPort +# endif static kern_return_t createSerialIterator(io_iterator_t *serialIterator) { - kern_return_t kernResult; - mach_port_t masterPort; - CFMutableDictionaryRef classesToMatch; + kern_return_t kernResult; + mach_port_t masterPort; + CFMutableDictionaryRef classesToMatch; if ((kernResult = IOMainPort(0, &masterPort)) != KERN_SUCCESS) { @@ -59,7 +59,7 @@ static kern_return_t createSerialIterator(io_iterator_t *serialIterator) return kernResult; } - CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey),CFSTR(kIOSerialBSDAllTypes)); + CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes)); kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, serialIterator); if (kernResult != KERN_SUCCESS) { @@ -75,12 +75,11 @@ static const char *getRegistryString(io_object_t sObj, const char *propName) // CFTypeRef nameCFstring; CFStringRef nameCFstring; resultStr[0] = 0; - nameCFstring = (CFStringRef) IORegistryEntryCreateCFProperty(sObj, - CFStringCreateWithCString(kCFAllocatorDefault, propName, kCFStringEncodingASCII), - kCFAllocatorDefault, 0); - if (nameCFstring) { - CFStringGetCString(nameCFstring, resultStr, sizeof(resultStr), - kCFStringEncodingASCII); + nameCFstring = (CFStringRef) IORegistryEntryCreateCFProperty( + sObj, CFStringCreateWithCString(kCFAllocatorDefault, propName, kCFStringEncodingASCII), kCFAllocatorDefault, 0); + if (nameCFstring) + { + CFStringGetCString(nameCFstring, resultStr, sizeof(resultStr), kCFStringEncodingASCII); CFRelease(nameCFstring); } return resultStr; @@ -92,11 +91,14 @@ wxArrayString SerialPortMac::GetSerialPortList(void) io_iterator_t iterator; kern_return_t result = createSerialIterator(&iterator); - if (result == KERN_SUCCESS){ + if (result == KERN_SUCCESS) + { io_object_t port; - while ((port = IOIteratorNext(iterator)) != 0){ - const char* name = getRegistryString(port,kIOCalloutDeviceKey); - if (name){ + while ((port = IOIteratorNext(iterator)) != 0) + { + const char *name = getRegistryString(port, kIOCalloutDeviceKey); + if (name) + { ret.Add(name); } IOObjectRelease(port); diff --git a/src/serialport_mac.h b/src/serialport_mac.h index 8dc46e2d3..14720455b 100644 --- a/src/serialport_mac.h +++ b/src/serialport_mac.h @@ -32,10 +32,10 @@ * */ -#if !defined(SERIALPORT_MAC_H_INCLUDED) && defined (__APPLE__) -#define SERIALPORT_MAC_H_INCLUDED +#if !defined(SERIALPORT_MAC_H_INCLUDED) && defined(__APPLE__) +# define SERIALPORT_MAC_H_INCLUDED -#include "serialport_posix.h" +# include "serialport_posix.h" class SerialPortMac : public SerialPortPosix { @@ -43,4 +43,4 @@ class SerialPortMac : public SerialPortPosix wxArrayString GetSerialPortList() override; }; -#endif // SERIALPORT_MAC_H_INCLUDED +#endif // SERIALPORT_MAC_H_INCLUDED diff --git a/src/serialport_posix.cpp b/src/serialport_posix.cpp index 935f3b2b1..a54ade94f 100644 --- a/src/serialport_posix.cpp +++ b/src/serialport_posix.cpp @@ -34,12 +34,12 @@ #include "phd.h" -#if defined (__linux__) || defined (__APPLE__) || defined (__FreeBSD__) +#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) -#include -#include -#include -#include +# include +# include +# include +# include wxArrayString SerialPortPosix::GetSerialPortList(void) { @@ -62,51 +62,57 @@ SerialPortPosix::SerialPortPosix(void) SerialPortPosix::~SerialPortPosix(void) { - if (m_fd > 0) { + if (m_fd > 0) + { close(m_fd); m_fd = -1; } } -bool SerialPortPosix::Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) +bool SerialPortPosix::Connect( + const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) { bool bError = false; try { - if ((m_fd = open(portName.mb_str(), O_RDWR|O_NOCTTY)) < 0) { - wxString exposeToUser = wxString::Format("open %s failed %s(%d)", portName, strerror((int)errno), (int)errno); + if ((m_fd = open(portName.mb_str(), O_RDWR | O_NOCTTY)) < 0) + { + wxString exposeToUser = wxString::Format("open %s failed %s(%d)", portName, strerror((int) errno), (int) errno); throw ERROR_INFO("SerialPortPosix::Connect " + exposeToUser); } struct termios attr; - if (tcgetattr(m_fd, &attr) < 0) { - wxString errorWxs = wxString::Format("tcgetattr failed %s(%d)", strerror((int)errno), (int)errno); + if (tcgetattr(m_fd, &attr) < 0) + { + wxString errorWxs = wxString::Format("tcgetattr failed %s(%d)", strerror((int) errno), (int) errno); throw ERROR_INFO("SerialPortPosix::Connect " + errorWxs); } -#if defined (__APPLE__) +# if defined(__APPLE__) m_originalAttrs = attr; cfmakeraw(&attr); -#endif +# endif attr.c_iflag = 0; // input modes attr.c_oflag = 0; // output modes - attr.c_cflag = CLOCAL; // CLOCAL == Ignore modem control lines. - attr.c_cflag |= CREAD ; // CREAD == Enable receiver. - switch (dataBits) { + attr.c_cflag = CLOCAL; // CLOCAL == Ignore modem control lines. + attr.c_cflag |= CREAD; // CREAD == Enable receiver. + switch (dataBits) + { case 7: - attr.c_cflag |= CS7; // 7 bit Character size mask. + attr.c_cflag |= CS7; // 7 bit Character size mask. break; case 8: - attr.c_cflag |= CS8; // 8 bit Character size mask. + attr.c_cflag |= CS8; // 8 bit Character size mask. break; default: throw ERROR_INFO("SerialPortPosix::Connect unsupported amount of dataBits"); break; } - switch (stopBits) { + switch (stopBits) + { case 1: break; case 2: @@ -116,7 +122,8 @@ bool SerialPortPosix::Connect(const wxString& portName, int baud, int dataBits, throw ERROR_INFO("SerialPortPosix::Connect invalid amount of stopBits"); break; } - switch (Parity) { + switch (Parity) + { case ParityNone: break; case ParityOdd: @@ -125,52 +132,71 @@ bool SerialPortPosix::Connect(const wxString& portName, int baud, int dataBits, case ParityEven: attr.c_cflag |= PARENB; // Enable parity generation on output and parity checking for input. break; - case ParityMark: // TODO, not in POSIX. CMSPAR + case ParityMark: // TODO, not in POSIX. CMSPAR case ParitySpace: // TODO, not in POSIX. CMSPAR default: throw ERROR_INFO("SerialPortPosix::Connect invalid parity"); break; } attr.c_lflag &= ~ICANON; // Do not wait for a line delimiter. Work in noncanonical mode. - attr.c_lflag &= ~( ECHO | ECHOE | ISIG | IEXTEN | NOFLSH | TOSTOP); // local modes - attr.c_lflag |= NOFLSH; - attr.c_cc[VTIME] = (uint8_t)0; // timeout in deciseconds - attr.c_cc[VMIN] = (uint8_t)0; // minimum number of characters for noncanonical read + attr.c_lflag &= ~(ECHO | ECHOE | ISIG | IEXTEN | NOFLSH | TOSTOP); // local modes + attr.c_lflag |= NOFLSH; + attr.c_cc[VTIME] = (uint8_t) 0; // timeout in deciseconds + attr.c_cc[VMIN] = (uint8_t) 0; // minimum number of characters for noncanonical read unsigned int speed = B0; - switch (baud) { - case 9600: speed = B9600; break; - case 19200: speed = B19200; break; - case 38400: speed = B38400; break; - case 57600: speed = B57600; break; - case 115200: speed = B115200; break; - case 230400: speed = B230400; break; + switch (baud) + { + case 9600: + speed = B9600; + break; + case 19200: + speed = B19200; + break; + case 38400: + speed = B38400; + break; + case 57600: + speed = B57600; + break; + case 115200: + speed = B115200; + break; + case 230400: + speed = B230400; + break; default: throw ERROR_INFO("SerialPortPosix::Connect unsupported baudrate"); break; } - if (cfsetispeed(&attr, speed) < 0 || cfsetospeed(&attr, speed) < 0) { + if (cfsetispeed(&attr, speed) < 0 || cfsetospeed(&attr, speed) < 0) + { throw ERROR_INFO("cfsetispeed failed"); } - if (tcsetattr(m_fd, TCSAFLUSH, &attr) < 0 ) { - wxString errowWxs = wxString::Format("tcsetattr failed %s(%d)", strerror((int)errno), (int)errno); + if (tcsetattr(m_fd, TCSAFLUSH, &attr) < 0) + { + wxString errowWxs = wxString::Format("tcsetattr failed %s(%d)", strerror((int) errno), (int) errno); throw ERROR_INFO("SerialPortPosix::Connect " + errowWxs); } int ioctl_ret = 0; unsigned int argp; - if ((ioctl_ret = ioctl(m_fd, TIOCMGET, &argp)) < 0) { + if ((ioctl_ret = ioctl(m_fd, TIOCMGET, &argp)) < 0) + { throw ERROR_INFO("ioctl TIOCMGET"); } - if (useDTR) { + if (useDTR) + { argp |= TIOCM_DTR; } - if (useRTS) { + if (useRTS) + { argp |= TIOCM_RTS; } - if ((ioctl_ret = ioctl(m_fd, TIOCMSET, &argp)) < 0) { + if ((ioctl_ret = ioctl(m_fd, TIOCMSET, &argp)) < 0) + { throw ERROR_INFO("ioctl TIOCMSET"); } } @@ -189,15 +215,18 @@ bool SerialPortPosix::Disconnect(void) try { -#if defined (__APPLE__) - if (tcdrain(m_fd) == -1) { - fprintf(stderr,"Error waiting for drain - %s(%d).\n",strerror(errno), errno); +# if defined(__APPLE__) + if (tcdrain(m_fd) == -1) + { + fprintf(stderr, "Error waiting for drain - %s(%d).\n", strerror(errno), errno); } - if (tcsetattr(m_fd, TCSANOW, &m_originalAttrs) == -1) { - fprintf(stderr,"Error resetting tty attributes - %s(%d).\n",strerror(errno),errno); + if (tcsetattr(m_fd, TCSANOW, &m_originalAttrs) == -1) + { + fprintf(stderr, "Error resetting tty attributes - %s(%d).\n", strerror(errno), errno); } -#endif - if (close(m_fd) == -1) { +# endif + if (close(m_fd) == -1) + { throw ERROR_INFO("SerialPortPosix: close failed"); } } @@ -222,12 +251,14 @@ bool SerialPortPosix::SetReceiveTimeout(int timeoutMilliSeconds) { struct termios attr; - if (tcgetattr(m_fd, &attr) < 0) { + if (tcgetattr(m_fd, &attr) < 0) + { throw ERROR_INFO("tcgetattr failed"); } int timeoutDeciSeconds = (timeoutMilliSeconds + 99) / 100; - attr.c_cc[VTIME] = (uint8_t)timeoutDeciSeconds; - if (tcsetattr(m_fd, TCSAFLUSH, &attr) < 0) { + attr.c_cc[VTIME] = (uint8_t) timeoutDeciSeconds; + if (tcsetattr(m_fd, TCSAFLUSH, &attr) < 0) + { throw ERROR_INFO("tcsetattr failed"); } } @@ -293,8 +324,10 @@ bool SerialPortPosix::Receive(unsigned char *pData, unsigned int count) pData += receiveCount; } - if (rem > 0) { - throw ERROR_INFO("SerialPortPosix: " + wxString::Format(wxT("%i"), rem) + " remaining bytes to read at eof " + ", expected total of " + wxString::Format(wxT("%i"), count)); + if (rem > 0) + { + throw ERROR_INFO("SerialPortPosix: " + wxString::Format(wxT("%i"), rem) + " remaining bytes to read at eof " + + ", expected total of " + wxString::Format(wxT("%i"), count)); } } catch (const wxString& Msg) diff --git a/src/serialport_posix.h b/src/serialport_posix.h index 78435c383..a3ec5846f 100644 --- a/src/serialport_posix.h +++ b/src/serialport_posix.h @@ -33,27 +33,27 @@ */ #if !defined(SERIALPORT_POSIX_H_INCLUDED) -#define SERIALPORT_POSIX_H_INCLUDED +# define SERIALPORT_POSIX_H_INCLUDED -#if defined (__linux__) || defined (__APPLE__) || defined (__FreeBSD__) +# if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) -#include +# include class SerialPortPosix : public SerialPort { int m_fd; -#if defined (__APPLE__) +# if defined(__APPLE__) struct termios m_originalAttrs; -#endif +# endif public: - wxArrayString GetSerialPortList() override; SerialPortPosix(); virtual ~SerialPortPosix(); - bool Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) override; + bool Connect( + const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) override; bool Disconnect() override; bool Send(const unsigned char *pData, unsigned count) override; @@ -65,6 +65,6 @@ class SerialPortPosix : public SerialPort bool SetDTR(bool asserted) override; }; -#endif // __linux__ || __APPLE__ +# endif // __linux__ || __APPLE__ #endif // SERIALPORT_POSIX_H_INCLUDED diff --git a/src/serialport_win32.cpp b/src/serialport_win32.cpp index ebaf19c14..4d7f7053d 100644 --- a/src/serialport_win32.cpp +++ b/src/serialport_win32.cpp @@ -50,7 +50,7 @@ wxArrayString SerialPortWin32::GetSerialPortList(void) do { bufferSize *= 2; - delete [] pBuffer; + delete[] pBuffer; pBuffer = new char[bufferSize]; if (pBuffer == NULL) { @@ -64,7 +64,7 @@ wxArrayString SerialPortWin32::GetSerialPortList(void) throw ERROR_INFO("QueryDosDevice failed"); } - for (char *pEntry=pBuffer;*pEntry; pEntry += strlen(pEntry) + 1) + for (char *pEntry = pBuffer; *pEntry; pEntry += strlen(pEntry) + 1) { if (strncmp(pEntry, "COM", 3) == 0) { @@ -77,7 +77,7 @@ wxArrayString SerialPortWin32::GetSerialPortList(void) POSSIBLY_UNUSED(Msg); } - delete [] pBuffer; + delete[] pBuffer; return ret; } @@ -95,24 +95,24 @@ SerialPortWin32::~SerialPortWin32(void) } } -bool SerialPortWin32::Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) +bool SerialPortWin32::Connect( + const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) { bool bError = false; try { wxString portPath = "\\\\.\\" + portName; - m_handle = CreateFile(portPath, - GENERIC_READ | GENERIC_WRITE, - 0, // must be opened with exclusive-access - NULL, // no security attributes - OPEN_EXISTING, // must use OPEN_EXISTING - 0, // not overlapped I/O - NULL // hTemplate must be NULL for comm devices - ); + m_handle = CreateFile(portPath, GENERIC_READ | GENERIC_WRITE, + 0, // must be opened with exclusive-access + NULL, // no security attributes + OPEN_EXISTING, // must use OPEN_EXISTING + 0, // not overlapped I/O + NULL // hTemplate must be NULL for comm devices + ); if (m_handle == INVALID_HANDLE_VALUE) { - throw ERROR_INFO("SerialPortWin32: CreateFile("+portName+") failed"); + throw ERROR_INFO("SerialPortWin32: CreateFile(" + portName + ") failed"); } DCB dcb; @@ -127,15 +127,15 @@ bool SerialPortWin32::Connect(const wxString& portName, int baud, int dataBits, switch (stopBits) { - case 1: - dcb.StopBits = ONESTOPBIT; - break; - case 2: - dcb.StopBits = TWOSTOPBITS; - break; - default: - throw ERROR_INFO("SerialPortWin32: invalid stopBits"); - break; + case 1: + dcb.StopBits = ONESTOPBIT; + break; + case 2: + dcb.StopBits = TWOSTOPBITS; + break; + default: + throw ERROR_INFO("SerialPortWin32: invalid stopBits"); + break; } // no need to map the parity enum --- ours matches theirs @@ -227,7 +227,6 @@ bool SerialPortWin32::Send(const unsigned char *pData, unsigned count) { throw ERROR_INFO("SerialPortWin32: nBytesWritten != count"); } - } catch (const wxString& Msg) { @@ -291,12 +290,12 @@ bool SerialPortWin32::EscapeFunction(DWORD command) bool SerialPortWin32::SetRTS(bool asserted) { - return SerialPortWin32::EscapeFunction(asserted?SETRTS:CLRRTS); + return SerialPortWin32::EscapeFunction(asserted ? SETRTS : CLRRTS); } bool SerialPortWin32::SetDTR(bool asserted) { - return SerialPortWin32::EscapeFunction(asserted?SETDTR:CLRDTR); + return SerialPortWin32::EscapeFunction(asserted ? SETDTR : CLRDTR); } #endif // _WINDOWS_ diff --git a/src/serialport_win32.h b/src/serialport_win32.h index 521ff9a95..fbc45db22 100644 --- a/src/serialport_win32.h +++ b/src/serialport_win32.h @@ -33,8 +33,8 @@ * */ -#if !defined(SERIALPORT_WIN32_H_INCLUDED) && defined (__WINDOWS__) -#define SERIALPORT_WIN32_H_INCLUDED +#if !defined(SERIALPORT_WIN32_H_INCLUDED) && defined(__WINDOWS__) +# define SERIALPORT_WIN32_H_INCLUDED class SerialPortWin32 : public SerialPort { @@ -43,13 +43,13 @@ class SerialPortWin32 : public SerialPort bool SerialPortWin32::EscapeFunction(DWORD command); public: - wxArrayString GetSerialPortList() override; SerialPortWin32(); virtual ~SerialPortWin32(); - bool Connect(const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) override; + bool Connect( + const wxString& portName, int baud, int dataBits, int stopBits, PARITY Parity, bool useRTS, bool useDTR) override; bool Disconnect() override; bool Send(const unsigned char *pData, unsigned count) override; diff --git a/src/serialports.h b/src/serialports.h index 718c255a3..6f81d624c 100644 --- a/src/serialports.h +++ b/src/serialports.h @@ -42,7 +42,7 @@ #include "serialport_posix.h" #ifdef USE_LOOPBACK_SERIAL -#include "serialport_loopback.h" +# include "serialport_loopback.h" #endif #endif // SERIALPORTS_H_INCLUDED diff --git a/src/sha1.cpp b/src/sha1.cpp index 1c5a2ef60..951c18baa 100644 --- a/src/sha1.cpp +++ b/src/sha1.cpp @@ -20,130 +20,140 @@ /*********************** FUNCTION DEFINITIONS ***********************/ void sha1_transform(SHA1_CTX *ctx, const SHA1_BYTE data[]) { - SHA1_WORD a, b, c, d, e, i, j, t, m[80]; + SHA1_WORD a, b, c, d, e, i, j, t, m[80]; - for (i = 0, j = 0; i < 16; ++i, j += 4) - m[i] = (data[j] << 24) + (data[j + 1] << 16) + (data[j + 2] << 8) + (data[j + 3]); - for ( ; i < 80; ++i) { - m[i] = (m[i - 3] ^ m[i - 8] ^ m[i - 14] ^ m[i - 16]); - m[i] = (m[i] << 1) | (m[i] >> 31); - } + for (i = 0, j = 0; i < 16; ++i, j += 4) + m[i] = (data[j] << 24) + (data[j + 1] << 16) + (data[j + 2] << 8) + (data[j + 3]); + for (; i < 80; ++i) + { + m[i] = (m[i - 3] ^ m[i - 8] ^ m[i - 14] ^ m[i - 16]); + m[i] = (m[i] << 1) | (m[i] >> 31); + } - a = ctx->state[0]; - b = ctx->state[1]; - c = ctx->state[2]; - d = ctx->state[3]; - e = ctx->state[4]; + a = ctx->state[0]; + b = ctx->state[1]; + c = ctx->state[2]; + d = ctx->state[3]; + e = ctx->state[4]; - for (i = 0; i < 20; ++i) { - t = ROTLEFT(a, 5) + ((b & c) ^ (~b & d)) + e + ctx->k[0] + m[i]; - e = d; - d = c; - c = ROTLEFT(b, 30); - b = a; - a = t; - } - for ( ; i < 40; ++i) { - t = ROTLEFT(a, 5) + (b ^ c ^ d) + e + ctx->k[1] + m[i]; - e = d; - d = c; - c = ROTLEFT(b, 30); - b = a; - a = t; - } - for ( ; i < 60; ++i) { - t = ROTLEFT(a, 5) + ((b & c) ^ (b & d) ^ (c & d)) + e + ctx->k[2] + m[i]; - e = d; - d = c; - c = ROTLEFT(b, 30); - b = a; - a = t; - } - for ( ; i < 80; ++i) { - t = ROTLEFT(a, 5) + (b ^ c ^ d) + e + ctx->k[3] + m[i]; - e = d; - d = c; - c = ROTLEFT(b, 30); - b = a; - a = t; - } + for (i = 0; i < 20; ++i) + { + t = ROTLEFT(a, 5) + ((b & c) ^ (~b & d)) + e + ctx->k[0] + m[i]; + e = d; + d = c; + c = ROTLEFT(b, 30); + b = a; + a = t; + } + for (; i < 40; ++i) + { + t = ROTLEFT(a, 5) + (b ^ c ^ d) + e + ctx->k[1] + m[i]; + e = d; + d = c; + c = ROTLEFT(b, 30); + b = a; + a = t; + } + for (; i < 60; ++i) + { + t = ROTLEFT(a, 5) + ((b & c) ^ (b & d) ^ (c & d)) + e + ctx->k[2] + m[i]; + e = d; + d = c; + c = ROTLEFT(b, 30); + b = a; + a = t; + } + for (; i < 80; ++i) + { + t = ROTLEFT(a, 5) + (b ^ c ^ d) + e + ctx->k[3] + m[i]; + e = d; + d = c; + c = ROTLEFT(b, 30); + b = a; + a = t; + } - ctx->state[0] += a; - ctx->state[1] += b; - ctx->state[2] += c; - ctx->state[3] += d; - ctx->state[4] += e; + ctx->state[0] += a; + ctx->state[1] += b; + ctx->state[2] += c; + ctx->state[3] += d; + ctx->state[4] += e; } void sha1_init(SHA1_CTX *ctx) { - ctx->datalen = 0; - ctx->bitlen = 0; - ctx->state[0] = 0x67452301; - ctx->state[1] = 0xEFCDAB89; - ctx->state[2] = 0x98BADCFE; - ctx->state[3] = 0x10325476; - ctx->state[4] = 0xc3d2e1f0; - ctx->k[0] = 0x5a827999; - ctx->k[1] = 0x6ed9eba1; - ctx->k[2] = 0x8f1bbcdc; - ctx->k[3] = 0xca62c1d6; + ctx->datalen = 0; + ctx->bitlen = 0; + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xEFCDAB89; + ctx->state[2] = 0x98BADCFE; + ctx->state[3] = 0x10325476; + ctx->state[4] = 0xc3d2e1f0; + ctx->k[0] = 0x5a827999; + ctx->k[1] = 0x6ed9eba1; + ctx->k[2] = 0x8f1bbcdc; + ctx->k[3] = 0xca62c1d6; } void sha1_update(SHA1_CTX *ctx, const SHA1_BYTE data[], size_t len) { - size_t i; + size_t i; - for (i = 0; i < len; ++i) { - ctx->data[ctx->datalen] = data[i]; - ctx->datalen++; - if (ctx->datalen == 64) { - sha1_transform(ctx, ctx->data); - ctx->bitlen += 512; - ctx->datalen = 0; - } - } + for (i = 0; i < len; ++i) + { + ctx->data[ctx->datalen] = data[i]; + ctx->datalen++; + if (ctx->datalen == 64) + { + sha1_transform(ctx, ctx->data); + ctx->bitlen += 512; + ctx->datalen = 0; + } + } } void sha1_final(SHA1_CTX *ctx, SHA1_BYTE hash[]) { - SHA1_WORD i; + SHA1_WORD i; - i = ctx->datalen; + i = ctx->datalen; - // Pad whatever data is left in the buffer. - if (ctx->datalen < 56) { - ctx->data[i++] = 0x80; - while (i < 56) - ctx->data[i++] = 0x00; - } - else { - ctx->data[i++] = 0x80; - while (i < 64) - ctx->data[i++] = 0x00; - sha1_transform(ctx, ctx->data); - memset(ctx->data, 0, 56); - } + // Pad whatever data is left in the buffer. + if (ctx->datalen < 56) + { + ctx->data[i++] = 0x80; + while (i < 56) + ctx->data[i++] = 0x00; + } + else + { + ctx->data[i++] = 0x80; + while (i < 64) + ctx->data[i++] = 0x00; + sha1_transform(ctx, ctx->data); + memset(ctx->data, 0, 56); + } - // Append to the padding the total message's length in bits and transform. - ctx->bitlen += ctx->datalen * 8; - ctx->data[63] = ctx->bitlen; - ctx->data[62] = ctx->bitlen >> 8; - ctx->data[61] = ctx->bitlen >> 16; - ctx->data[60] = ctx->bitlen >> 24; - ctx->data[59] = ctx->bitlen >> 32; - ctx->data[58] = ctx->bitlen >> 40; - ctx->data[57] = ctx->bitlen >> 48; - ctx->data[56] = ctx->bitlen >> 56; - sha1_transform(ctx, ctx->data); + // Append to the padding the total message's length in bits and transform. + ctx->bitlen += ctx->datalen * 8; + ctx->data[63] = ctx->bitlen; + ctx->data[62] = ctx->bitlen >> 8; + ctx->data[61] = ctx->bitlen >> 16; + ctx->data[60] = ctx->bitlen >> 24; + ctx->data[59] = ctx->bitlen >> 32; + ctx->data[58] = ctx->bitlen >> 40; + ctx->data[57] = ctx->bitlen >> 48; + ctx->data[56] = ctx->bitlen >> 56; + sha1_transform(ctx, ctx->data); - // Since this implementation uses little endian byte ordering and MD uses big endian, - // reverse all the bytes when copying the final state to the output hash. - for (i = 0; i < 4; ++i) { - hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff; - hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff; - hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff; - hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff; - hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff; - } + // Since this implementation uses little endian byte ordering and MD uses big endian, + // reverse all the bytes when copying the final state to the output hash. + for (i = 0; i < 4; ++i) + { + hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff; + hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff; + hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff; + hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff; + hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff; + } } diff --git a/src/sha1.h b/src/sha1.h index 76921adaa..f10f41ac7 100644 --- a/src/sha1.h +++ b/src/sha1.h @@ -1,10 +1,10 @@ /********************************************************************* -* Filename: sha1.h -* Author: Brad Conte (brad AT bradconte.com) -* Copyright: -* Disclaimer: This code is presented "as is" without any guarantees. -* Details: Defines the API for the corresponding SHA1 implementation. -*********************************************************************/ + * Filename: sha1.h + * Author: Brad Conte (brad AT bradconte.com) + * Copyright: + * Disclaimer: This code is presented "as is" without any guarantees. + * Details: Defines the API for the corresponding SHA1 implementation. + *********************************************************************/ #ifndef SHA1_H #define SHA1_H @@ -13,18 +13,19 @@ #include /****************************** MACROS ******************************/ -#define SHA1_BLOCK_SIZE 20 // SHA1 outputs a 20 byte digest +#define SHA1_BLOCK_SIZE 20 // SHA1 outputs a 20 byte digest /**************************** DATA TYPES ****************************/ -typedef unsigned char SHA1_BYTE; // 8-bit byte -typedef unsigned int SHA1_WORD; // 32-bit word, change to "long" for 16-bit machines +typedef unsigned char SHA1_BYTE; // 8-bit byte +typedef unsigned int SHA1_WORD; // 32-bit word, change to "long" for 16-bit machines -typedef struct { - SHA1_BYTE data[64]; - SHA1_WORD datalen; - unsigned long long bitlen; - SHA1_WORD state[5]; - SHA1_WORD k[4]; +typedef struct +{ + SHA1_BYTE data[64]; + SHA1_WORD datalen; + unsigned long long bitlen; + SHA1_WORD state[5]; + SHA1_WORD k[4]; } SHA1_CTX; /*********************** FUNCTION DECLARATIONS **********************/ @@ -32,4 +33,4 @@ void sha1_init(SHA1_CTX *ctx); void sha1_update(SHA1_CTX *ctx, const SHA1_BYTE data[], size_t len); void sha1_final(SHA1_CTX *ctx, SHA1_BYTE hash[]); -#endif // SHA1_H +#endif // SHA1_H diff --git a/src/socket_server.cpp b/src/socket_server.cpp index a954d756a..0181f2be0 100644 --- a/src/socket_server.cpp +++ b/src/socket_server.cpp @@ -42,7 +42,8 @@ static std::set s_clients; -enum { +enum +{ MSG_PAUSE = 1, MSG_RESUME, MSG_MOVE1, @@ -57,19 +58,19 @@ enum { MSG_MOVE4, MSG_MOVE5, MSG_AUTOFINDSTAR, - MSG_SETLOCKPOSITION, //15 - MSG_FLIPRACAL, //16 - MSG_GETSTATUS, //17 - MSG_STOP, //18 - MSG_LOOP, //19 - MSG_STARTGUIDING, //20 - MSG_LOOPFRAMECOUNT, //21 - MSG_CLEARCAL, //22 - MSG_FLIP_SIM_CAMERA, //23 - MSG_DESELECT, //24 + MSG_SETLOCKPOSITION, // 15 + MSG_FLIPRACAL, // 16 + MSG_GETSTATUS, // 17 + MSG_STOP, // 18 + MSG_LOOP, // 19 + MSG_STARTGUIDING, // 20 + MSG_LOOPFRAMECOUNT, // 21 + MSG_CLEARCAL, // 22 + MSG_FLIP_SIM_CAMERA, // 23 + MSG_DESELECT, // 24 }; -void MyFrame::OnServerMenu(wxCommandEvent &evt) +void MyFrame::OnServerMenu(wxCommandEvent& evt) { SetServerMode(evt.IsChecked()); StartServer(GetServerMode()); @@ -120,7 +121,8 @@ bool MyFrame::StartServer(bool state) Debug.AddLine(wxString::Format("Server started, listening on port %u", port)); StatusMsg(_("Server started")); } - else { + else + { if (!SocketServer) { Debug.AddLine("stop server, server already stopped"); @@ -148,8 +150,8 @@ void MyFrame::OnSockServerEvent(wxSocketEvent& event) if (event.GetSocketEvent() != wxSOCKET_CONNECTION) { - Debug.AddLine(wxString::Format("socket server event expected %d, got %d. ignoring it.", - wxSOCKET_CONNECTION, event.GetSocketEvent())); + Debug.AddLine(wxString::Format( + "socket server event expected %d, got %d. ignoring it.", wxSOCKET_CONNECTION, event.GetSocketEvent())); return; } @@ -175,12 +177,18 @@ void MyFrame::OnSockServerEvent(wxSocketEvent& event) double MyFrame::GetDitherAmount(int ditherType) { - switch (ditherType) { - case 1: return 0.5; - case 2: return 1.0; - case 3: return 2.0; - case 4: return 3.0; - case 5: return 5.0; + switch (ditherType) + { + case 1: + return 0.5; + case 2: + return 1.0; + case 3: + return 2.0; + case 4: + return 3.0; + case 5: + return 5.0; } return 1.0; } @@ -204,195 +212,205 @@ void MyFrame::HandleSockServerInput(wxSocketBase *sock) switch (c) { - case MSG_PAUSE: - case 'p': - Debug.AddLine("processing socket request PAUSE"); - SetPaused(PAUSE_GUIDING); - break; - - case MSG_RESUME: - case 'r': - Debug.AddLine("processing socket request RESUME"); - SetPaused(PAUSE_NONE); - break; + case MSG_PAUSE: + case 'p': + Debug.AddLine("processing socket request PAUSE"); + SetPaused(PAUSE_GUIDING); + break; + + case MSG_RESUME: + case 'r': + Debug.AddLine("processing socket request RESUME"); + SetPaused(PAUSE_NONE); + break; + + case MSG_MOVE1: // +/- 0.5 + case MSG_MOVE2: // +/- 1.0 + case MSG_MOVE3: // +/- 2.0 + case MSG_MOVE4: // +/- 3.0 + case MSG_MOVE5: // +/- 5.0 + { + Debug.AddLine("processing socket request MOVEn"); - case MSG_MOVE1: // +/- 0.5 - case MSG_MOVE2: // +/- 1.0 - case MSG_MOVE3: // +/- 2.0 - case MSG_MOVE4: // +/- 3.0 - case MSG_MOVE5: // +/- 5.0 + int ditherType = 3; + switch (c) { - Debug.AddLine("processing socket request MOVEn"); - - int ditherType = 3; - switch (c) - { - case MSG_MOVE1: ditherType = 1; break; - case MSG_MOVE2: ditherType = 2; break; - case MSG_MOVE3: ditherType = 3; break; - case MSG_MOVE4: ditherType = 4; break; - case MSG_MOVE5: ditherType = 5; break; - } - - double size = GetDitherAmount(ditherType); - - wxString errMsg; - bool ok = PhdController::DitherCompat(size, &errMsg); - if (!ok) - { - throw ERROR_INFO(+errMsg); - } - - rval = RequestedExposureDuration() / 1000; - if (rval < 1) - { - rval = 1; - } + case MSG_MOVE1: + ditherType = 1; + break; + case MSG_MOVE2: + ditherType = 2; + break; + case MSG_MOVE3: + ditherType = 3; + break; + case MSG_MOVE4: + ditherType = 4; + break; + case MSG_MOVE5: + ditherType = 5; break; } - case MSG_REQDIST: + double size = GetDitherAmount(ditherType); + + wxString errMsg; + bool ok = PhdController::DitherCompat(size, &errMsg); + if (!ok) { - Debug.AddLine("processing socket request REQDIST"); - if (!pGuider->IsGuiding()) - { - throw ERROR_INFO("cannot request distance if not guiding"); - } - - double currentError = CurrentGuideError(); - - if (currentError > 2.55) - { - rval = 255; - } - else - { - rval = (unsigned char) (currentError * 100); - } - - Debug.AddLine(wxString::Format("SOCKSVR: Sending pixel error of %.2f", (float) rval / 100.0)); - break; + throw ERROR_INFO(+errMsg); } - case MSG_AUTOFINDSTAR: - Debug.AddLine("processing socket request AUTOFINDSTAR"); - bool error; - error = pFrame->AutoSelectStar(); - rval = error ? 0 : 1; - if (!error) - { - StartLooping(); - } - GuideLog.ServerCommand(pGuider, "AUTO FIND STAR"); - break; + rval = RequestedExposureDuration() / 1000; + if (rval < 1) + { + rval = 1; + } + break; + } - case MSG_SETLOCKPOSITION: + case MSG_REQDIST: + { + Debug.AddLine("processing socket request REQDIST"); + if (!pGuider->IsGuiding()) { - // Sets LockX and LockY to be user-specified - unsigned short x,y; - sock->Read(&x, 2); - sock->Read(&y, 2); - sock->Discard(); // Clean out anything else - - if (!pFrame->pGuider->SetLockPosToStarAtPosition(PHD_Point(x,y))) - { - Debug.Write(wxString::Format("processing socket request SETLOCKPOSITION for (%d, %d) succeeded\n", x, y)); - pFrame->StatusMsg(wxString::Format(_("Lock set to %d,%d"), x, y)); - GuideLog.NotifySetLockPosition(pGuider); - } - else - { - Debug.Write(wxString::Format("processing socket request SETLOCKPOSITION for (%d, %d) failed\n", x, y)); - } - break; + throw ERROR_INFO("cannot request distance if not guiding"); } - case MSG_FLIPRACAL: + double currentError = CurrentGuideError(); + + if (currentError > 2.55) { - Debug.AddLine("processing socket request FLIPRACAL"); - PauseType prev = pGuider->SetPaused(PAUSE_GUIDING); - // return 1 for success, 0 for failure - rval = 1; - if (FlipCalibrationData()) - { - rval = 0; - } - pGuider->SetPaused(prev); - GuideLog.ServerCommand(pGuider, "FLIP RA CAL"); - break; + rval = 255; + } + else + { + rval = (unsigned char) (currentError * 100); } - case MSG_GETSTATUS: - Debug.AddLine("processing socket request GETSTATUS"); - rval = Guider::GetExposedState(); - break; + Debug.AddLine(wxString::Format("SOCKSVR: Sending pixel error of %.2f", (float) rval / 100.0)); + break; + } - case MSG_LOOP: + case MSG_AUTOFINDSTAR: + Debug.AddLine("processing socket request AUTOFINDSTAR"); + bool error; + error = pFrame->AutoSelectStar(); + rval = error ? 0 : 1; + if (!error) { - Debug.AddLine("processing socket request LOOP"); StartLooping(); - GuideLog.ServerCommand(pGuider, "LOOP"); - break; } + GuideLog.ServerCommand(pGuider, "AUTO FIND STAR"); + break; + + case MSG_SETLOCKPOSITION: + { + // Sets LockX and LockY to be user-specified + unsigned short x, y; + sock->Read(&x, 2); + sock->Read(&y, 2); + sock->Discard(); // Clean out anything else - case MSG_STOP: + if (!pFrame->pGuider->SetLockPosToStarAtPosition(PHD_Point(x, y))) { - Debug.AddLine("processing socket request STOP"); - StopCapturing(); - GuideLog.ServerCommand(pGuider, "STOP"); - break; + Debug.Write(wxString::Format("processing socket request SETLOCKPOSITION for (%d, %d) succeeded\n", x, y)); + pFrame->StatusMsg(wxString::Format(_("Lock set to %d,%d"), x, y)); + GuideLog.NotifySetLockPosition(pGuider); + } + else + { + Debug.Write(wxString::Format("processing socket request SETLOCKPOSITION for (%d, %d) failed\n", x, y)); } + break; + } - case MSG_STARTGUIDING: + case MSG_FLIPRACAL: + { + Debug.AddLine("processing socket request FLIPRACAL"); + PauseType prev = pGuider->SetPaused(PAUSE_GUIDING); + // return 1 for success, 0 for failure + rval = 1; + if (FlipCalibrationData()) { - Debug.AddLine("processing socket request STARTGUIDING"); - bool err = StartGuiding(); - Debug.AddLine(wxString::Format("StartGuiding returned %d, guider state is %d", err, pFrame->pGuider->GetState())); - GuideLog.ServerCommand(pGuider, "START GUIDING"); - break; + rval = 0; } + pGuider->SetPaused(prev); + GuideLog.ServerCommand(pGuider, "FLIP RA CAL"); + break; + } - case MSG_LOOPFRAMECOUNT: - Debug.AddLine("processing socket request LOOPFRAMECOUNT"); - if (!CaptureActive) - { - rval = 0; - } - else if (m_frameCounter > UCHAR_MAX) - { - rval = UCHAR_MAX; - } - else - { - rval = m_frameCounter; - } - break; + case MSG_GETSTATUS: + Debug.AddLine("processing socket request GETSTATUS"); + rval = Guider::GetExposedState(); + break; - case MSG_CLEARCAL: - Debug.AddLine("processing socket request CLEARCAL"); + case MSG_LOOP: + { + Debug.AddLine("processing socket request LOOP"); + StartLooping(); + GuideLog.ServerCommand(pGuider, "LOOP"); + break; + } - if (pMount) - pMount->ClearCalibration(); - if (pSecondaryMount) - pSecondaryMount->ClearCalibration(); + case MSG_STOP: + { + Debug.AddLine("processing socket request STOP"); + StopCapturing(); + GuideLog.ServerCommand(pGuider, "STOP"); + break; + } - GuideLog.ServerCommand(pGuider, "CLEAR CAL"); - break; + case MSG_STARTGUIDING: + { + Debug.AddLine("processing socket request STARTGUIDING"); + bool err = StartGuiding(); + Debug.AddLine(wxString::Format("StartGuiding returned %d, guider state is %d", err, pFrame->pGuider->GetState())); + GuideLog.ServerCommand(pGuider, "START GUIDING"); + break; + } - case MSG_FLIP_SIM_CAMERA: - Debug.AddLine("processing socket request flip camera simulator"); - GearSimulator::FlipPierSide(pCamera); - break; + case MSG_LOOPFRAMECOUNT: + Debug.AddLine("processing socket request LOOPFRAMECOUNT"); + if (!CaptureActive) + { + rval = 0; + } + else if (m_frameCounter > UCHAR_MAX) + { + rval = UCHAR_MAX; + } + else + { + rval = m_frameCounter; + } + break; - case MSG_DESELECT: - Debug.AddLine("processing socket request deselect"); - pFrame->pGuider->Reset(true); - break; + case MSG_CLEARCAL: + Debug.AddLine("processing socket request CLEARCAL"); - default: - Debug.AddLine(wxString::Format("SOCKSVR: Unknown command char received from client: %d\n", (int) c)); - rval = 1; - break; + if (pMount) + pMount->ClearCalibration(); + if (pSecondaryMount) + pSecondaryMount->ClearCalibration(); + + GuideLog.ServerCommand(pGuider, "CLEAR CAL"); + break; + + case MSG_FLIP_SIM_CAMERA: + Debug.AddLine("processing socket request flip camera simulator"); + GearSimulator::FlipPierSide(pCamera); + break; + + case MSG_DESELECT: + Debug.AddLine("processing socket request deselect"); + pFrame->pGuider->Reset(true); + break; + + default: + Debug.AddLine(wxString::Format("SOCKSVR: Unknown command char received from client: %d\n", (int) c)); + rval = 1; + break; } } catch (const wxString& Msg) @@ -403,7 +421,7 @@ void MyFrame::HandleSockServerInput(wxSocketBase *sock) Debug.Write(wxString::Format("Sending socket response %d (0x%x)\n", rval, rval)); // Send response - sock->Write(&rval,1); + sock->Write(&rval, 1); // Enable input events again. sock->SetNotify(wxSOCKET_LOST_FLAG | wxSOCKET_INPUT_FLAG); @@ -423,18 +441,18 @@ void MyFrame::OnSockServerClientEvent(wxSocketEvent& event) // Now we process the event switch (event.GetSocketEvent()) { - case wxSOCKET_INPUT: - HandleSockServerInput(sock); - break; - case wxSOCKET_LOST: - Debug.AddLine("SOCKSVR: Client disconnected, deleting socket"); - size_t n; - n = s_clients.erase(sock); - assert(n > 0); - sock->Destroy(); - break; - default: - break; + case wxSOCKET_INPUT: + HandleSockServerInput(sock); + break; + case wxSOCKET_LOST: + Debug.AddLine("SOCKSVR: Client disconnected, deleting socket"); + size_t n; + n = s_clients.erase(sock); + assert(n > 0); + sock->Destroy(); + break; + default: + break; } } catch (const wxString& Msg) @@ -450,7 +468,8 @@ void MyFrame::OnSockServerClientEvent(wxSocketEvent& event) static int SocketConnections; static wxSocketBase *ServerEndpoint; -bool ServerSendGuideCommand (int direction, int duration) { +bool ServerSendGuideCommand(int direction, int duration) +{ // Sends a guide command to Nebulosity if (!pFrame->SocketServer || !SocketConnections) return true; @@ -458,21 +477,23 @@ bool ServerSendGuideCommand (int direction, int duration) { unsigned char cmd = MSG_GUIDE; unsigned char rval = 0; Debug.AddLine(wxString::Format("Sending guide: %d %d", direction, duration)); -// cmd = 'Z'; + // cmd = 'Z'; ServerEndpoint->Write(&cmd, 1); if (pFrame->SocketServer->Error()) Debug.AddLine(_T("Error sending Neb command")); - else { + else + { Debug.AddLine(_T("Cmd done - sending data")); ServerEndpoint->Write(&direction, sizeof(int)); ServerEndpoint->Write(&duration, sizeof(int)); - ServerEndpoint->Read(&rval,1); + ServerEndpoint->Read(&rval, 1); Debug.Write(wxString::Format("Sent guide command - returned %d\n", (int) rval)); } return false; } -bool ServerSendCamConnect(int& xsize, int& ysize) { +bool ServerSendCamConnect(int& xsize, int& ysize) +{ if (!pFrame->SocketServer || !SocketConnections) return true; Debug.AddLine(_T("Sending cam connect request")); @@ -480,27 +501,31 @@ bool ServerSendCamConnect(int& xsize, int& ysize) { unsigned char rval = 0; ServerEndpoint->Write(&cmd, 1); - if (pFrame->SocketServer->Error()) { + if (pFrame->SocketServer->Error()) + { Debug.AddLine(_T("Error sending Neb command")); return true; } - else { -// unsigned char c; + else + { + // unsigned char c; ServerEndpoint->Read(&rval, 1); Debug.Write(wxString::Format("Cmd done - returned %d\n", (int) rval)); } if (rval) return true; - else { // cam connected OK + else + { // cam connected OK // Should get x and y size back - ServerEndpoint->Read(&xsize,sizeof(int)); - ServerEndpoint->Read(&ysize,sizeof(int)); + ServerEndpoint->Read(&xsize, sizeof(int)); + ServerEndpoint->Read(&ysize, sizeof(int)); Debug.Write(wxString::Format("Guide chip reported as %d x %d\n", xsize, ysize)); return false; } } -bool ServerSendCamDisconnect() { +bool ServerSendCamDisconnect() +{ if (!pFrame->SocketServer || !SocketConnections) return true; @@ -509,22 +534,25 @@ bool ServerSendCamDisconnect() { unsigned char rval = 0; ServerEndpoint->Write(&cmd, 1); - if (pFrame->SocketServer->Error()) { + if (pFrame->SocketServer->Error()) + { Debug.AddLine(_T("Error sending Neb command")); return true; } - else { -// unsigned char c; + else + { + // unsigned char c; ServerEndpoint->Read(&rval, 1); Debug.Write(wxString::Format("Cmd done - returned %d\n", (int) rval)); } if (rval) return true; else - return false; // cam disconnected OK + return false; // cam disconnected OK } -bool ServerReqFrame(int duration, usImage& img) { +bool ServerReqFrame(int duration, usImage& img) +{ if (!pFrame->SocketServer || !SocketConnections) return true; Debug.AddLine(_T("Sending guide frame request")); @@ -532,20 +560,23 @@ bool ServerReqFrame(int duration, usImage& img) { unsigned char rval = 0; ServerEndpoint->Write(&cmd, 1); - if (pFrame->SocketServer->Error()) { + if (pFrame->SocketServer->Error()) + { Debug.AddLine(_T("Error sending Neb command")); return true; } - else { -// unsigned char c; + else + { + // unsigned char c; ServerEndpoint->Read(&rval, 1); Debug.Write(wxString::Format("Cmd done - returned %d\n", (int) rval)); } if (rval) return true; - else { // grab frame data + else + { // grab frame data // Send duration request - ServerEndpoint->Write(&duration,sizeof(int)); + ServerEndpoint->Write(&duration, sizeof(int)); Debug.Write(wxString::Format("Starting %d ms frame\n", duration)); wxMilliSleep(duration); // might as well wait here nicely at least this long Debug.Write(wxString::Format("Reading frame - looking for %u pixels (%u bytes)\n", img.NPixels, img.NPixels * 2)); @@ -556,30 +587,34 @@ bool ServerReqFrame(int duration, usImage& img) { xsize = img.Size.GetWidth(); ysize = img.Size.GetHeight(); pixels_left = img.NPixels; - packet_size = 256; // # pixels to get - int j=0; - while (pixels_left > 0) { - ServerEndpoint->Read(&buffer,packet_size * 2); + packet_size = 256; // # pixels to get + int j = 0; + while (pixels_left > 0) + { + ServerEndpoint->Read(&buffer, packet_size * 2); pixels_left -= packet_size; if ((j % 100) == 0) Debug.Write(wxString::Format("%d left\n", pixels_left)); - for (i=0; iWrite(&cmd,1); + ServerEndpoint->Write(&cmd, 1); j++; } int min = 9999999; int max = -999999; dataptr = img.ImageData; - for (i=0; i<(xsize * ysize); i++, dataptr++) { - if (*dataptr > max) max = (int) *dataptr; - else if (*dataptr < min) min = (int) *dataptr; + for (i = 0; i < (xsize * ysize); i++, dataptr++) + { + if (*dataptr > max) + max = (int) *dataptr; + else if (*dataptr < min) + min = (int) *dataptr; } Debug.Write(wxString::Format("Frame received min=%d max=%d\n", min, max)); -// ServerEndpoint->ReadMsg(img.ImageData,(xsize * ysize * 2)); + // ServerEndpoint->ReadMsg(img.ImageData,(xsize * ysize * 2)); Debug.AddLine("Frame read"); } diff --git a/src/socket_server.h b/src/socket_server.h index 2bb010cdd..c98045189 100644 --- a/src/socket_server.h +++ b/src/socket_server.h @@ -39,6 +39,6 @@ extern bool ServerSendCamDisconnect(); extern bool ServerReqFrame(int duration, usImage& img); #endif #ifdef __APPLE__ -#include +# include extern OSErr E6AESendRoutine(double ewCorrection, double nsCorrection, int mountcode); #endif diff --git a/src/star.cpp b/src/star.cpp index 2cad4d2ca..bcb6d32bc 100644 --- a/src/star.cpp +++ b/src/star.cpp @@ -76,7 +76,11 @@ struct R2M wxPoint p; double m; R2M() { } - R2M(int x, int y, double m_) : p(x, y), m(m_) { } + R2M(int x, int y, double m_) + : p(x, y) + , m(m_) + { + } bool operator<(const R2M& rhs) const { return r2 < rhs.r2; } }; @@ -123,7 +127,8 @@ static double hfr(std::vector& vec, double cx, double cy, double mass) return hfr; } -bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, FindMode mode, double minHFD, double maxHFD, unsigned short maxADU, StarFindLogType loggingControl) +bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, FindMode mode, double minHFD, double maxHFD, + unsigned short maxADU, StarFindLogType loggingControl) { FindResult Result = STAR_OK; double newX = base_x; @@ -132,8 +137,9 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F try { if (loggingControl == FIND_LOGGING_VERBOSE) - Debug.Write(wxString::Format("Star::Find(%d, %d, %d, %d, (%d,%d,%d,%d), %.1f, %0.1f, %hu) frame %u\n", searchRegion, base_x, base_y, mode, - pImg->Subframe.x, pImg->Subframe.y, pImg->Subframe.width, pImg->Subframe.height, minHFD, maxHFD, maxADU, pImg->FrameNum)); + Debug.Write(wxString::Format("Star::Find(%d, %d, %d, %d, (%d,%d,%d,%d), %.1f, %0.1f, %hu) frame %u\n", searchRegion, + base_x, base_y, mode, pImg->Subframe.x, pImg->Subframe.y, pImg->Subframe.width, pImg->Subframe.height, minHFD, + maxHFD, maxADU, pImg->FrameNum)); int minx, miny, maxx, maxy; @@ -153,9 +159,9 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F // search region bounds int start_x = wxMax(base_x - searchRegion, minx); - int end_x = wxMin(base_x + searchRegion, maxx); + int end_x = wxMin(base_x + searchRegion, maxx); int start_y = wxMax(base_y - searchRegion, miny); - int end_y = wxMin(base_y + searchRegion, maxy); + int end_y = wxMin(base_y + searchRegion, maxy); if (end_x <= start_x || end_y <= start_y) { @@ -198,15 +204,10 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F for (int x = start_x + 1; x <= end_x - 1; x++) { unsigned short p = imgdata[y * rowsize + x]; - unsigned int val = - 4 * (unsigned int) p + - imgdata[(y - 1) * rowsize + (x - 1)] + - imgdata[(y - 1) * rowsize + (x + 1)] + - imgdata[(y + 1) * rowsize + (x - 1)] + - imgdata[(y + 1) * rowsize + (x + 1)] + - 2 * imgdata[(y - 1) * rowsize + (x + 0)] + - 2 * imgdata[(y + 0) * rowsize + (x - 1)] + - 2 * imgdata[(y + 0) * rowsize + (x + 1)] + + unsigned int val = 4 * (unsigned int) p + imgdata[(y - 1) * rowsize + (x - 1)] + + imgdata[(y - 1) * rowsize + (x + 1)] + imgdata[(y + 1) * rowsize + (x - 1)] + + imgdata[(y + 1) * rowsize + (x + 1)] + 2 * imgdata[(y - 1) * rowsize + (x + 0)] + + 2 * imgdata[(y + 0) * rowsize + (x - 1)] + 2 * imgdata[(y + 0) * rowsize + (x + 1)] + 2 * imgdata[(y + 1) * rowsize + (x + 0)]; if (val > peak_val) @@ -225,13 +226,13 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F } } - PeakVal = max3[0]; // raw peak val + PeakVal = max3[0]; // raw peak val peak_val /= 16; // smoothed peak value } // measure noise in the annulus with inner radius A and outer radius B - int const A = 7; // inner radius - int const B = 12; // outer radius + int const A = 7; // inner radius + int const B = 12; // outer radius int const A2 = A * A; int const B2 = B * B; @@ -285,8 +286,8 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F if (nbg < 10) // only possible after the first iteration { - Debug.Write(wxString::Format("Star::Find: too few background points! nbg=%u mean=%.1f sigma=%.1f\n", - nbg, mean_bg, sigma_bg)); + Debug.Write(wxString::Format( + "Star::Find: too few background points! nbg=%u mean=%.1f sigma=%.1f\n", nbg, mean_bg, sigma_bg)); break; } @@ -316,7 +317,7 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F } else { - thresh = (unsigned short)(mean_bg + 3.0 * sigma_bg + 0.5); + thresh = (unsigned short) (mean_bg + 3.0 * sigma_bg + 0.5); // find pixels over threshold within aperture; compute mass and centroid @@ -362,7 +363,8 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F Mass = mass; - // SNR estimate from: Measuring the Signal-to-Noise Ratio S/N of the CCD Image of a Star or Nebula, J.H.Simonetti, 2004 January 8 + // SNR estimate from: Measuring the Signal-to-Noise Ratio S/N of the CCD Image of a Star or Nebula, J.H.Simonetti, 2004 + // January 8 // http://www.phys.vt.edu/~jhs/phys3154/snr20040108.pdf double const gain = .5; // electrons per ADU, nominal SNR = n > 0 ? mass / sqrt(mass / gain + sigma2_bg * (double) n * (1.0 + 1.0 / (double) nbg)) : 0.0; @@ -373,7 +375,8 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F // avoid this by requiring the smoothed peak value to be above the threshold if (peak_val <= thresh && SNR >= LOW_SNR) { - Debug.Write(wxString::Format("Star::Find false star n=%u nbg=%u bg=%.1f sigma=%.1f thresh=%u peak=%u\n", n, nbg, mean_bg, sigma_bg, thresh, peak_val)); + Debug.Write(wxString::Format("Star::Find false star n=%u nbg=%u bg=%.1f sigma=%.1f thresh=%u peak=%u\n", n, nbg, + mean_bg, sigma_bg, thresh, peak_val)); SNR = LOW_SNR - 0.1; } @@ -472,12 +475,13 @@ bool Star::Find(const usImage *pImg, int searchRegion, int base_x, int base_y, F if (loggingControl == FIND_LOGGING_VERBOSE) Debug.Write(wxString::Format("Star::Find returns %d (%d), X=%.2f, Y=%.2f, Mass=%.f, SNR=%.1f, Peak=%hu HFD=%.1f\n", - wasFound, Result, newX, newY, Mass, SNR, PeakVal, HFD)); + wasFound, Result, newX, newY, Mass, SNR, PeakVal, HFD)); return wasFound; } -bool Star::Find(const usImage *pImg, int searchRegion, FindMode mode, double minHFD, double maxHFD, unsigned short saturation, StarFindLogType loggingControl) +bool Star::Find(const usImage *pImg, int searchRegion, FindMode mode, double minHFD, double maxHFD, unsigned short saturation, + StarFindLogType loggingControl) { return Find(pImg, searchRegion, X, Y, mode, minHFD, maxHFD, saturation, loggingControl); } @@ -488,16 +492,36 @@ struct FloatImg wxSize Size; unsigned int NPixels; - FloatImg() : px(0) { } - FloatImg(const wxSize& size) : px(0) { Init(size); } - FloatImg(const usImage& img) : px(0) { + FloatImg() + : px(0) + { + } + FloatImg(const wxSize& size) + : px(0) + { + Init(size); + } + FloatImg(const usImage& img) + : px(0) + { Init(img.Size); for (unsigned int i = 0; i < NPixels; i++) px[i] = (float) img.ImageData[i]; } ~FloatImg() { delete[] px; } - void Init(const wxSize& sz) { delete[] px; Size = sz; NPixels = Size.GetWidth() * Size.GetHeight(); px = new float[NPixels]; } - void Swap(FloatImg& other) { std::swap(px, other.px); std::swap(Size, other.Size); std::swap(NPixels, other.NPixels); } + void Init(const wxSize& sz) + { + delete[] px; + Size = sz; + NPixels = Size.GetWidth() * Size.GetHeight(); + px = new float[NPixels]; + } + void Swap(FloatImg& other) + { + std::swap(px, other.px); + std::swap(Size, other.Size); + std::swap(NPixels, other.NPixels); + } }; static void GetStats(double *mean, double *stdev, const FloatImg& img, const wxRect& win) @@ -532,7 +556,7 @@ static void GetStats(double *mean, double *stdev, const FloatImg& img, const wxR } // un-comment to save the intermediate autofind image -//#define SAVE_AUTOFIND_IMG +// #define SAVE_AUTOFIND_IMG static void SaveImage(const FloatImg& img, const char *name) { @@ -552,7 +576,7 @@ static void SaveImage(const FloatImg& img, const char *name) tmp.Init(img.Size); for (unsigned int i = 0; i < tmp.NPixels; i++) { - tmp.ImageData[i] = (unsigned short)(((double) img.px[i] - minv) * 65535.0 / (maxv - minv)); + tmp.ImageData[i] = (unsigned short) (((double) img.px[i] - minv) * 65535.0 / (maxv - minv)); } tmp.Save(wxFileName(Debug.GetLogDir(), name).GetFullPath()); @@ -597,7 +621,7 @@ static void psf_conv(FloatImg& dst, const FloatImg& src) float A, B1, B2, C1, C2, C3, D1, D2, D3; #define PX(dx, dy) *(src.px + width * (y + (dy)) + x + (dx)) - A = PX(+0, +0); + A = PX(+0, +0); B1 = PX(+0, -1) + PX(+0, +1) + PX(+1, +0) + PX(-1, +0); B2 = PX(-1, -1) + PX(+1, -1) + PX(-1, +1) + PX(+1, +1); C1 = PX(+0, -2) + PX(-2, +0) + PX(+2, +0) + PX(+0, +2); @@ -605,7 +629,8 @@ static void psf_conv(FloatImg& dst, const FloatImg& src) C3 = PX(-2, -2) + PX(+2, -2) + PX(-2, +2) + PX(+2, +2); D1 = PX(+0, -3) + PX(-3, +0) + PX(+3, +0) + PX(+0, +3); D2 = PX(-1, -3) + PX(+1, -3) + PX(-3, -1) + PX(+3, -1) + PX(-3, +1) + PX(+3, +1) + PX(-1, +3) + PX(+1, +3); - D3 = PX(-4, -2) + PX(-3, -2) + PX(+3, -2) + PX(+4, -2) + PX(-4, -1) + PX(+4, -1) + PX(-4, +0) + PX(+4, +0) + PX(-4, +1) + PX(+4, +1) + PX(-4, +2) + PX(-3, +2) + PX(+3, +2) + PX(+4, +2); + D3 = PX(-4, -2) + PX(-3, -2) + PX(+3, -2) + PX(+4, -2) + PX(-4, -1) + PX(+4, -1) + PX(-4, +0) + PX(+4, +0) + + PX(-4, +1) + PX(+4, +1) + PX(-4, +2) + PX(-3, +2) + PX(+3, +2) + PX(+4, +2); #undef PX int i; const float *uptr; @@ -673,7 +698,12 @@ struct Peak float val; Peak() { } - Peak(int x_, int y_, float val_) : x(x_), y(y_), val(val_) { } + Peak(int x_, int y_, float val_) + : x(x_) + , y(y_) + , val(val_) + { + } bool operator<(const Peak& rhs) const { return val < rhs.val; } }; @@ -714,9 +744,8 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc wxBusyCursor busy; Debug.Write(wxString::Format("Star::AutoFind called with edgeAllowance = %d " - "searchRegion = %d roi = %dx%d@%d,%d\n", - extraEdgeAllowance, searchRegion, roi.width, roi.height, - roi.x, roi.y)); + "searchRegion = %d roi = %dx%d@%d,%d\n", + extraEdgeAllowance, searchRegion, roi.width, roi.height, roi.x, roi.y)); // run a 3x3 median first to eliminate hot pixels usImage smoothed; @@ -728,16 +757,12 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc smoothed.Subframe = roi; smoothed.Subframe.Intersect(wxRect(smoothed.Size)); - Debug.Write(wxString::Format("AutoFind: using ROI %dx%d@%d,%d\n", - smoothed.Subframe.width, smoothed.Subframe.height, + Debug.Write(wxString::Format("AutoFind: using ROI %dx%d@%d,%d\n", smoothed.Subframe.width, smoothed.Subframe.height, smoothed.Subframe.x, smoothed.Subframe.y)); - if (smoothed.Subframe.width < searchRegion || - smoothed.Subframe.height < searchRegion) + if (smoothed.Subframe.width < searchRegion || smoothed.Subframe.height < searchRegion) { - Debug.Write(wxString::Format("AutoFind: bad ROI %dx%d\n", - smoothed.Subframe.width, - smoothed.Subframe.height)); + Debug.Write(wxString::Format("AutoFind: bad ROI %dx%d\n", smoothed.Subframe.width, smoothed.Subframe.height)); return false; } } @@ -775,15 +800,21 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc conv.Swap(tmp); } - enum { CONV_RADIUS = 4 }; - int dw = conv.Size.GetWidth(); // width of the downsampled image - int dh = conv.Size.GetHeight(); // height of the downsampled image - wxRect convRect(CONV_RADIUS, CONV_RADIUS, dw - 2 * CONV_RADIUS, dh - 2 * CONV_RADIUS); // region containing valid data + enum + { + CONV_RADIUS = 4 + }; + int dw = conv.Size.GetWidth(); // width of the downsampled image + int dh = conv.Size.GetHeight(); // height of the downsampled image + wxRect convRect(CONV_RADIUS, CONV_RADIUS, dw - 2 * CONV_RADIUS, dh - 2 * CONV_RADIUS); // region containing valid data SaveImage(conv, "PHD2_AutoFind.fit"); - enum { TOP_N = 100 }; // keep track of the brightest stars - std::set stars; // sorted by ascending intensity + enum + { + TOP_N = 100 + }; // keep track of the brightest stars + std::set stars; // sorted by ascending intensity double global_mean, global_stdev; GetStats(&global_mean, &global_stdev, conv, convRect); @@ -866,7 +897,8 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc if (d2 < minlimitsq) { // very close, treat as single star - Debug.Write(wxString::Format("AutoFind: merge [%d, %d] %.1f - [%d, %d] %.1f\n", a->x, a->y, a->val, b->x, b->y, b->val)); + Debug.Write(wxString::Format( + "AutoFind: merge [%d, %d] %.1f - [%d, %d] %.1f\n", a->x, a->y, a->val, b->x, b->y, b->val)); // erase the dimmer one stars.erase(a); goto repeat; @@ -895,11 +927,13 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc // but do not let a very dim star eliminate a very bright star if (b->val / a->val >= 5.0) { - Debug.Write(wxString::Format("AutoFind: close dim-bright [%d, %d] %.1f - [%d, %d] %.1f\n", a->x, a->y, a->val, b->x, b->y, b->val)); + Debug.Write(wxString::Format("AutoFind: close dim-bright [%d, %d] %.1f - [%d, %d] %.1f\n", a->x, a->y, + a->val, b->x, b->y, b->val)); } else { - Debug.Write(wxString::Format("AutoFind: too close [%d, %d] %.1f - [%d, %d] %.1f\n", a->x, a->y, a->val, b->x, b->y, b->val)); + Debug.Write(wxString::Format( + "AutoFind: too close [%d, %d] %.1f - [%d, %d] %.1f\n", a->x, a->y, a->val, b->x, b->y, b->val)); to_erase.insert(std::distance(stars.begin(), a)); to_erase.insert(std::distance(stars.begin(), b)); } @@ -918,8 +952,8 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc { std::set::iterator next = it; ++next; - if (it->x <= edgeDist || it->x >= image.Size.GetWidth() - edgeDist || - it->y <= edgeDist || it->y >= image.Size.GetHeight() - edgeDist) + if (it->x <= edgeDist || it->x >= image.Size.GetWidth() - edgeDist || it->y <= edgeDist || + it->y >= image.Size.GetHeight() - edgeDist) { Debug.Write(wxString::Format("AutoFind: too close to edge [%d, %d] %.1f\n", it->x, it->y, it->val)); stars.erase(it); @@ -946,21 +980,23 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc // first, find the peak pixel overall unsigned short maxVal = 0; for (unsigned int i = 0; i < image.NPixels; i++) - if (image.ImageData[i] > maxVal) - maxVal = image.ImageData[i]; + if (image.ImageData[i] > maxVal) + maxVal = image.ImageData[i]; // next see if any of the stars has a flat-top bool foundSaturated = false; for (std::set::reverse_iterator it = stars.rbegin(); it != stars.rend(); ++it) { Star tmp; - tmp.Find(&image, searchRegion, it->x, it->y, FIND_CENTROID, pFrame->pGuider->GetMinStarHFD(), pFrame->pGuider->GetMaxStarHFD(), pCamera->GetSaturationADU(), FIND_LOGGING_VERBOSE); + tmp.Find(&image, searchRegion, it->x, it->y, FIND_CENTROID, pFrame->pGuider->GetMinStarHFD(), + pFrame->pGuider->GetMaxStarHFD(), pCamera->GetSaturationADU(), FIND_LOGGING_VERBOSE); if (tmp.WasFound() && tmp.GetError() == STAR_SATURATED) { if ((maxVal - tmp.PeakVal) * 255U > maxVal) { // false positive saturation, flat top but below maxVal - Debug.Write(wxString::Format("AutoFind: false positive saturation peak = %hu, max = %hu\n", tmp.PeakVal, maxVal)); + Debug.Write( + wxString::Format("AutoFind: false positive saturation peak = %hu, max = %hu\n", tmp.PeakVal, maxVal)); } else { @@ -981,8 +1017,8 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc { // no saturated stars found, can't make any assumption about whether the max val is saturated - Debug.Write(wxString::Format("AutoFind: using saturation level from BPP %u and pedestal %hu\n", - image.BitsPerPixel, image.Pedestal)); + Debug.Write(wxString::Format( + "AutoFind: using saturation level from BPP %u and pedestal %hu\n", image.BitsPerPixel, image.Pedestal)); sat_level = ((1U << image.BitsPerPixel) - 1) + image.Pedestal; } @@ -990,12 +1026,13 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc unsigned int range = sat_level > image.Pedestal ? sat_level - image.Pedestal : 0U; // "near-saturation" threshold at 90% saturation - unsigned int tmp = (unsigned int)image.Pedestal + 9 * range / 10; - if (tmp > 65535) tmp = 65535; - unsigned short sat_thresh = (unsigned short)tmp; + unsigned int tmp = (unsigned int) image.Pedestal + 9 * range / 10; + if (tmp > 65535) + tmp = 65535; + unsigned short sat_thresh = (unsigned short) tmp; - Debug.Write(wxString::Format("AutoFind: BPP = %u, saturation at %u, pedestal %hu, thresh = %hu\n", - image.BitsPerPixel, sat_level, image.Pedestal, sat_thresh)); + Debug.Write(wxString::Format("AutoFind: BPP = %u, saturation at %u, pedestal %hu, thresh = %hu\n", image.BitsPerPixel, + sat_level, image.Pedestal, sat_thresh)); // Before sifting for the best star, collect all the viable candidates double minSNR = pFrame->pGuider->GetAFMinStarSNR(); @@ -1004,12 +1041,13 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc for (std::set::reverse_iterator it = stars.rbegin(); it != stars.rend(); ++it) { GuideStar tmp; - tmp.Find(&image, searchRegion, it->x, it->y, FIND_CENTROID, pFrame->pGuider->GetMinStarHFD(), maxHFD, pCamera->GetSaturationADU(), FIND_LOGGING_VERBOSE); + tmp.Find(&image, searchRegion, it->x, it->y, FIND_CENTROID, pFrame->pGuider->GetMinStarHFD(), maxHFD, + pCamera->GetSaturationADU(), FIND_LOGGING_VERBOSE); // We're repeating the find, so we're vulnerable to hot pixels and creation of unwanted duplicates if (tmp.WasFound() && tmp.SNR >= minSNR) { bool duplicate = std::find_if(foundStars.begin(), foundStars.end(), - [&tmp](const GuideStar& other) { return CloseToReference(tmp, other); }) != foundStars.end(); + [&tmp](const GuideStar& other) { return CloseToReference(tmp, other); }) != foundStars.end(); if (!duplicate) { @@ -1033,14 +1071,16 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc for (std::set::reverse_iterator it = stars.rbegin(); it != stars.rend(); ++it) { GuideStar tmp; - tmp.Find(&image, searchRegion, it->x, it->y, FIND_CENTROID, pFrame->pGuider->GetMinStarHFD(), maxHFD, pCamera->GetSaturationADU(), FIND_LOGGING_VERBOSE); + tmp.Find(&image, searchRegion, it->x, it->y, FIND_CENTROID, pFrame->pGuider->GetMinStarHFD(), maxHFD, + pCamera->GetSaturationADU(), FIND_LOGGING_VERBOSE); if (tmp.WasFound()) { if (pass == 1) { if (tmp.PeakVal > sat_thresh) { - Debug.Write(wxString::Format("AutoFind: near-saturated [%d, %d] %.1f Mass %.f SNR %.1f Peak %hu\n", it->x, it->y, it->val, tmp.Mass, tmp.SNR, tmp.PeakVal)); + Debug.Write(wxString::Format("AutoFind: near-saturated [%d, %d] %.1f Mass %.f SNR %.1f Peak %hu\n", + it->x, it->y, it->val, tmp.Mass, tmp.SNR, tmp.PeakVal)); continue; } if (tmp.GetError() == STAR_SATURATED || tmp.SNR < minSNR) @@ -1050,14 +1090,16 @@ bool GuideStar::AutoFind(const usImage& image, int extraEdgeAllowance, int searc { if (tmp.GetError() == STAR_SATURATED || tmp.SNR < minSNR) { - Debug.Write(wxString::Format("AutoFind: star saturated or too dim [%d, %d] %.1f Mass %.f SNR %.1f\n", it->x, it->y, it->val, tmp.Mass, tmp.SNR)); + Debug.Write(wxString::Format("AutoFind: star saturated or too dim [%d, %d] %.1f Mass %.f SNR %.1f\n", + it->x, it->y, it->val, tmp.Mass, tmp.SNR)); continue; } } // star accepted SetXY(it->x, it->y); - Debug.Write(wxString::Format("AutoFind returns star at [%d, %d] %.1f Mass %.f SNR %.1f\n", it->x, it->y, it->val, tmp.Mass, tmp.SNR)); + Debug.Write(wxString::Format( + "AutoFind returns star at [%d, %d] %.1f Mass %.f SNR %.1f\n", it->x, it->y, it->val, tmp.Mass, tmp.SNR)); if (maxStars > 1) { // Find the chosen star in the list and compute the offsetFromPrimary for all secondary stars diff --git a/src/star.h b/src/star.h index 22fb02d0f..6be951eff 100644 --- a/src/star.h +++ b/src/star.h @@ -80,8 +80,10 @@ class Star : public PHD_Point * a boolean indicating success instead of a boolean indicating an * error */ - bool Find(const usImage *pImg, int searchRegion, FindMode mode, double min_hfd, double max_hfd, unsigned short saturation, StarFindLogType loggingControl); - bool Find(const usImage *pImg, int searchRegion, int X, int Y, FindMode mode, double min_hfd, double max_hfd, unsigned short saturation, StarFindLogType loggingControl); + bool Find(const usImage *pImg, int searchRegion, FindMode mode, double min_hfd, double max_hfd, unsigned short saturation, + StarFindLogType loggingControl); + bool Find(const usImage *pImg, int searchRegion, int X, int Y, FindMode mode, double min_hfd, double max_hfd, + unsigned short saturation, StarFindLogType loggingControl); static bool WasFound(FindResult result); bool WasFound() const; @@ -104,27 +106,25 @@ class GuideStar : public Star PHD_Point referencePoint; unsigned int missCount; unsigned int zeroCount; - PHD_Point offsetFromPrimary; // X,y offset from primary star location, set in AutoFind, used for dither recovery + PHD_Point offsetFromPrimary; // X,y offset from primary star location, set in AutoFind, used for dither recovery bool wasLost; GuideStar() - : - referencePoint(0., 0.), - missCount(0), - zeroCount(0), - offsetFromPrimary(0., 0.), - wasLost(false) + : referencePoint(0., 0.) + , missCount(0) + , zeroCount(0) + , offsetFromPrimary(0., 0.) + , wasLost(false) { } GuideStar(const Star& star) - : - Star(star), - referencePoint(star), - missCount(0), - zeroCount(0), - offsetFromPrimary(0., 0.), - wasLost(false) + : Star(star) + , referencePoint(star) + , missCount(0) + , zeroCount(0) + , offsetFromPrimary(0., 0.) + , wasLost(false) { } diff --git a/src/star_profile.cpp b/src/star_profile.cpp index 62fc123de..ffe604b53 100644 --- a/src/star_profile.cpp +++ b/src/star_profile.cpp @@ -48,8 +48,8 @@ enum FULLW = 2 * HALFW + 1, }; -ProfileWindow::ProfileWindow(wxWindow *parent) : - wxWindow(parent,wxID_ANY,wxDefaultPosition,wxDefaultSize, wxFULL_REPAINT_ON_RESIZE,_("Profile")) +ProfileWindow::ProfileWindow(wxWindow *parent) + : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE, _("Profile")) { SetBackgroundStyle(wxBG_STYLE_PAINT); @@ -57,7 +57,7 @@ ProfileWindow::ProfileWindow(wxWindow *parent) : this->mode = 0; // 2D profile rawMode = pConfig->Global.GetBoolean("/ProfileRawMode", false); this->SetBackgroundStyle(wxBG_STYLE_CUSTOM); - this->data = new unsigned short[FULLW * FULLW]; // 21x21 subframe + this->data = new unsigned short[FULLW * FULLW]; // 21x21 subframe memset(midrow_profile, 0, sizeof(midrow_profile)); memset(vert_profile, 0, sizeof(vert_profile)); @@ -81,7 +81,8 @@ void ProfileWindow::OnLClick(wxMouseEvent& mevent) else { this->mode = this->mode + 1; - if (this->mode > 2) this->mode = 0; + if (this->mode > 2) + this->mode = 0; } Refresh(); } @@ -95,23 +96,28 @@ void ProfileWindow::SetState(bool is_active) void ProfileWindow::UpdateData(const usImage *img, float xpos, float ypos) { - if (this->data == NULL) return; + if (this->data == NULL) + return; int xstart = ROUNDF(xpos) - HALFW; int ystart = ROUNDF(ypos) - HALFW; - if (xstart < 0) xstart = 0; + if (xstart < 0) + xstart = 0; else if (xstart > (img->Size.GetWidth() - (FULLW + 1))) xstart = img->Size.GetWidth() - (FULLW + 1); - if (ystart < 0) ystart = 0; + if (ystart < 0) + ystart = 0; else if (ystart > (img->Size.GetHeight() - (FULLW + 1))) ystart = img->Size.GetHeight() - (FULLW + 1); - int x,y; + int x, y; unsigned short *uptr = this->data; const int xrowsize = img->Size.GetWidth(); for (x = 0; x < FULLW; x++) horiz_profile[x] = vert_profile[x] = midrow_profile[x] = 0; - for (y = 0; y < FULLW; y++) { - for (x = 0; x < FULLW; x++, uptr++) { + for (y = 0; y < FULLW; y++) + { + for (x = 0; x < FULLW; x++, uptr++) + { *uptr = *(img->ImageData + xstart + x + (ystart + y) * xrowsize); horiz_profile[x] += (int) *uptr; vert_profile[y] += (int) *uptr; @@ -137,7 +143,7 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) const int xsize = this->GetSize().GetX(); const int ysize = this->GetSize().GetY(); -#if defined (__APPLE__) +#if defined(__APPLE__) const wxFont& smallFont = *wxSMALL_FONT; #else const wxFont& smallFont = *wxSWISS_FONT; @@ -145,13 +151,14 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) dc.SetFont(smallFont); int smallFontHeight = dc.GetTextExtent("0").GetHeight(); - bool inFocusingMode = (ysize > xsize/2 + 20); + bool inFocusingMode = (ysize > xsize / 2 + 20); wxFont largeFont; int largeFontHeight; int labelTextHeight; - if (inFocusingMode) { + if (inFocusingMode) + { // To compute the scale factor, we use the following formula, which maximizes the use of all available // window width (xsize) while displaying HFD metrics in the exact format. The scaling value is calculated // on the premise that both large font digits are fixed-width, and that font scaling is linear. @@ -161,8 +168,8 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) // therefore, scale = (xsize - 10 - smallFontTextWidth) / (sfw * strlen(largeFontTextWithoutDot) + dotw) const Star& star = pFrame->pGuider->PrimaryStar(); float hfd = star.HFD; - float sfw = (float)dc.GetTextExtent("0").GetWidth(); - float dotw = (float)dc.GetTextExtent(".").GetWidth(); + float sfw = (float) dc.GetTextExtent("0").GetWidth(); + float dotw = (float) dc.GetTextExtent(".").GetWidth(); float hfdArcSec = hfd * pFrame->GetCameraPixelScale(); wxString smallFontText = wxString::Format("HFD: " /* ... */ " %.2f\"", hfdArcSec); @@ -175,7 +182,7 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) // smallFontHeight * scale should be at most 1/2 of the window height // Note: the text extent of the large font based on ths scale factor is only an approximation, // but it's good enough for our purpose. - scale = wxMin(scale, (float)ysize / (2.0 * smallFontHeight)); + scale = wxMin(scale, (float) ysize / (2.0 * smallFontHeight)); largeFont = smallFont.Scaled(scale); dc.SetFont(largeFont); @@ -183,17 +190,18 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) dc.SetFont(smallFont); labelTextHeight = 5 + smallFontHeight + largeFontHeight + 5; } - else { + else + { labelTextHeight = 5 + smallFontHeight + 5; } - wxPen RedPen(wxColour(255,0,0)); + wxPen RedPen(wxColour(255, 0, 0)); int i; int *profptr; wxString profileLabel; switch (this->mode) - { // Figure which profile to use + { // Figure which profile to use case 0: // mid-row default: profptr = midrow_profile; @@ -229,12 +237,13 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) { Prof_Mid = (Prof_Max - Prof_Min) / 2 + Prof_Min; // Figure the actual points in the window - float Prof_Range = (float)(Prof_Max - Prof_Min) / (float)(ysize - labelTextHeight - 5); - if (!Prof_Range) Prof_Range = 1; + float Prof_Range = (float) (Prof_Max - Prof_Min) / (float) (ysize - labelTextHeight - 5); + if (!Prof_Range) + Prof_Range = 1; int wprof = (xsize - 15) / 2 - 5; wprof /= 20; for (i = 0; i < FULLW; i++) - Prof[i] = wxPoint(5 + i * wprof, ysize - labelTextHeight - ((float)(*(profptr + i) - Prof_Min) / Prof_Range)); + Prof[i] = wxPoint(5 + i * wprof, ysize - labelTextHeight - ((float) (*(profptr + i) - Prof_Min) / Prof_Range)); // fwhm int x1 = 0; @@ -252,10 +261,10 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) } profval = *(profptr + x1); profvalprec = *(profptr + x1 - 1); - float f1 = (float)x1 - (float)(profval - Prof_Mid) / (float)(profval - profvalprec); + float f1 = (float) x1 - (float) (profval - Prof_Mid) / (float) (profval - profvalprec); profval = *(profptr + x2); profvalprec = *(profptr + x2 - 1); - float f2 = (float)x2 - (float)(profvalprec - Prof_Mid) / (float)(profvalprec - profval); + float f2 = (float) x2 - (float) (profvalprec - Prof_Mid) / (float) (profvalprec - profval); fwhm = f2 - f1; // Draw it @@ -264,16 +273,17 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) } // Prioritize rendering star image before rendering text - dc.SetTextForeground(wxColour(255,0,0)); + dc.SetTextForeground(wxColour(255, 0, 0)); // JBW: draw zoomed guidestar subframe (todo: make constants symbolic) - wxImage* img = pFrame->pGuider->DisplayedImage(); + wxImage *img = pFrame->pGuider->DisplayedImage(); double scaleFactor = pFrame->pGuider->ScaleFactor(); imageLeftMargin = (xsize - 15) / 2; if (img) { int width = xsize - imageLeftMargin - 5; - if (width > ysize + 5) width = ysize - 5; + if (width > ysize + 5) + width = ysize - 5; int midwidth = width / 2; // grab width(30) px box around lock pos, scale by 2 & display next to profile double LockX = pFrame->pGuider->LockPosition().X * scaleFactor; @@ -326,7 +336,8 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) if (sz > 0) { // and a small cross at the centroid - double starX = imageLeftMargin + midwidth - dStarX * (width / (sz * 2.0)) + 1, starY = midwidth - dStarY * (width / (sz * 2.0)) + 1 + imgTop; + double starX = imageLeftMargin + midwidth - dStarX * (width / (sz * 2.0)) + 1, + starY = midwidth - dStarY * (width / (sz * 2.0)) + 1 + imgTop; if (starX >= imageLeftMargin) { dc.SetPen(RedPen); @@ -355,7 +366,9 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) // Show X/Y of centroid if there's room if ((imageLeftMargin > fwhmLineWidth + 20) && (ysize - labelTextHeight + 5 > imageBottom)) - dc.DrawText(wxString::Format("X: %0.2f, Y: %0.2f", pFrame->pGuider->CurrentPosition().X, pFrame->pGuider->CurrentPosition().Y), imageLeftMargin, ysize - labelTextHeight + 5); + dc.DrawText(wxString::Format("X: %0.2f, Y: %0.2f", pFrame->pGuider->CurrentPosition().X, + pFrame->pGuider->CurrentPosition().Y), + imageLeftMargin, ysize - labelTextHeight + 5); int x = 5; wxString s(_("HFD: ")); dc.DrawText(s, x, ysize - largeFontHeight / 2 - smallFontHeight / 2); @@ -372,7 +385,8 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) } else { - dc.DrawText(wxString::Format(_("%s FWHM: %.2f, HFD: %.2f (%.2f\")"), profileLabel, fwhm, hfd, hfdArcSec), 5, ysize - smallFontHeight - 5); + dc.DrawText(wxString::Format(_("%s FWHM: %.2f, HFD: %.2f (%.2f\")"), profileLabel, fwhm, hfd, hfdArcSec), 5, + ysize - smallFontHeight - 5); } } else @@ -380,4 +394,3 @@ void ProfileWindow::OnPaint(wxPaintEvent& WXUNUSED(evt)) dc.DrawText(wxString::Format(_("%s FWHM: %.2f"), profileLabel, fwhm), 5, ysize - smallFontHeight - 5); } } - diff --git a/src/star_profile.h b/src/star_profile.h index aafd20d12..f777990cb 100644 --- a/src/star_profile.h +++ b/src/star_profile.h @@ -45,6 +45,7 @@ class ProfileWindow : public wxWindow void OnPaint(wxPaintEvent& evt); void SetState(bool is_active); void OnLClick(wxMouseEvent& evt); + private: int mode; // 0= 2D profile of mid-row, 1=2D of avg_row, 2=2D of avg_col bool rawMode; diff --git a/src/starcross_test.cpp b/src/starcross_test.cpp index 0d685c608..d6a74f246 100644 --- a/src/starcross_test.cpp +++ b/src/starcross_test.cpp @@ -32,8 +32,8 @@ * POSSIBILITY OF SUCH DAMAGE. * */ - #include "phd.h" - #include "starcross_test.h" +#include "phd.h" +#include "starcross_test.h" // clang-format off wxBEGIN_EVENT_TABLE(StarCrossDialog, wxDialog) @@ -53,11 +53,11 @@ static void AddTableEntryPair(wxWindow *parent, wxFlexGridSizer *pTable, const w pTable->Add(pControl, 1, wxALL, 5); } -static wxSpinCtrlDouble *NewSpinner(wxWindow *parent, int width, double val, double minval, double maxval, double inc, unsigned int decimals, - const wxString& tooltip) +static wxSpinCtrlDouble *NewSpinner(wxWindow *parent, int width, double val, double minval, double maxval, double inc, + unsigned int decimals, const wxString& tooltip) { - wxSpinCtrlDouble *pNewCtrl = pFrame->MakeSpinCtrlDouble(parent, wxID_ANY, _T("foo2"), wxPoint(-1, -1), - wxSize(width, -1), wxSP_ARROW_KEYS, minval, maxval, val, inc); + wxSpinCtrlDouble *pNewCtrl = pFrame->MakeSpinCtrlDouble( + parent, wxID_ANY, _T("foo2"), wxPoint(-1, -1), wxSize(width, -1), wxSP_ARROW_KEYS, minval, maxval, val, inc); pNewCtrl->SetValue(val); pNewCtrl->SetToolTip(tooltip); pNewCtrl->SetDigits(decimals); @@ -71,13 +71,13 @@ static void MakeBold(wxControl *ctrl) ctrl->SetFont(font); } -StarCrossDialog::StarCrossDialog(wxWindow *parent) : - wxDialog(parent, wxID_ANY, _("Star-Cross Test"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) +StarCrossDialog::StarCrossDialog(wxWindow *parent) + : wxDialog(parent, wxID_ANY, _("Star-Cross Test"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) { - wxBoxSizer* vSizer = new wxBoxSizer(wxVERTICAL); - wxFlexGridSizer* mountSpecSizer = new wxFlexGridSizer(2, 6, 5, 15); - wxFlexGridSizer* testSpecSizer = new wxFlexGridSizer(1, 5, 5, 15); - wxFlexGridSizer* testSummarySizer = new wxFlexGridSizer(1, 5, 5, 15); + wxBoxSizer *vSizer = new wxBoxSizer(wxVERTICAL); + wxFlexGridSizer *mountSpecSizer = new wxFlexGridSizer(2, 6, 5, 15); + wxFlexGridSizer *testSpecSizer = new wxFlexGridSizer(1, 5, 5, 15); + wxFlexGridSizer *testSummarySizer = new wxFlexGridSizer(1, 5, 5, 15); double guideSpeedDec = 0.0; double guideSpeedRA = 0.0; double guideSpeedMultiple; @@ -88,41 +88,40 @@ StarCrossDialog::StarCrossDialog(wxWindow *parent) : // Populate top flex grid with parameters relating to image scale and mount properties - these are needed // for future use of the guide camera instead of the main camera // Focal length - wxStaticBoxSizer* configGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Configuration")); + wxStaticBoxSizer *configGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Configuration")); - // Guide speed - use best available info, either from ASCOM if available or from whatever the user entered in the new-profile-wizard - guideSpeedMultiple = pConfig->Profile.GetDouble ("/CalStepCalc/GuideSpeed", SCT_DEFAULT_GUIDESPEED); + // Guide speed - use best available info, either from ASCOM if available or from whatever the user entered in the + // new-profile-wizard + guideSpeedMultiple = pConfig->Profile.GetDouble("/CalStepCalc/GuideSpeed", SCT_DEFAULT_GUIDESPEED); if (pPointingSource && pPointingSource->CanReportPosition()) { if (!pPointingSource->GetGuideRates(&guideSpeedRA, &guideSpeedDec)) { if (guideSpeedRA >= guideSpeedDec) - guideSpeedMultiple = guideSpeedRA * 3600.0 / (15.0 * siderealSecondPerSec); // Degrees/sec to Degrees/hour, 15 degrees/hour is roughly sidereal rate + guideSpeedMultiple = guideSpeedRA * 3600.0 / + (15.0 * siderealSecondPerSec); // Degrees/sec to Degrees/hour, 15 degrees/hour is roughly sidereal rate else guideSpeedMultiple = guideSpeedDec * 3600.0 / (15.0 * siderealSecondPerSec); knownGuideSpeed = true; - } } m_CtlGuideSpeed = NewSpinner(this, width, guideSpeedMultiple, 0.1, 1.0, 0.1, 2, - /* xgettext:no-c-format */ _("Guide speed, multiple of sidereal rate; if your mount's guide speed is 50% sidereal rate, enter 0.5")); + /* xgettext:no-c-format */ + _("Guide speed, multiple of sidereal rate; if your mount's guide speed is 50% sidereal rate, enter 0.5")); m_CtlGuideSpeed->Bind(wxEVT_SPINCTRLDOUBLE, &StarCrossDialog::OnGuideSpeedChange, this); AddTableEntryPair(this, mountSpecSizer, _("Guide speed, n.n x sidereal"), m_CtlGuideSpeed); configGroup->Add(mountSpecSizer, wxSizerFlags().Border(wxALL, 5)); // Add the controls for doing the test // Test summary - leg duration, details button - wxStaticBoxSizer* summaryGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Test Summary")); + wxStaticBoxSizer *summaryGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Test Summary")); int pulseCount = pConfig->Profile.GetDouble("/SCT/PulseCount", SCT_DEFAULT_PULSE_COUNT); int pulseSize = pConfig->Profile.GetDouble("/SCT/PulseSize", SCT_DEFAULT_PULSE_SIZE); - int leg = pulseCount * pulseSize/1000.; - m_CtlLegDuration = NewSpinner(this, width, leg, 3, 40, 1, 0, - _("Total guide pulse duration in EACH of 4 directions")); + int leg = pulseCount * pulseSize / 1000.; + m_CtlLegDuration = NewSpinner(this, width, leg, 3, 40, 1, 0, _("Total guide pulse duration in EACH of 4 directions")); m_CtlLegDuration->Bind(wxEVT_SPINCTRLDOUBLE, &StarCrossDialog::OnLegDurationChange, this); - AddTableEntryPair(this, testSummarySizer, _("Total guide duration, \nEACH direction (s)"), - m_CtlLegDuration); - m_CtlTotalDuration = NewSpinner(this, width, 8 * leg, 24, 600, 1, 0, - _("Total duration of test (s)")); + AddTableEntryPair(this, testSummarySizer, _("Total guide duration, \nEACH direction (s)"), m_CtlLegDuration); + m_CtlTotalDuration = NewSpinner(this, width, 8 * leg, 24, 600, 1, 0, _("Total duration of test (s)")); AddTableEntryPair(this, testSummarySizer, _("Total test duration (s)"), m_CtlTotalDuration); m_CtlTotalDuration->Enable(false); m_ViewControlBtn = new wxButton(this, wxID_ANY, _("Show Details")); @@ -132,42 +131,37 @@ StarCrossDialog::StarCrossDialog(wxWindow *parent) : // Test details - pulse size, #pulses m_DetailsGroup = new wxStaticBoxSizer(wxVERTICAL, this, _("Test Details")); - m_CtlNumPulses = NewSpinner(this, width, - pulseCount, 5, 40, 1, 0, _("Number of guide pulses in EACH direction")); // Default of 20 pulses + m_CtlNumPulses = + NewSpinner(this, width, pulseCount, 5, 40, 1, 0, _("Number of guide pulses in EACH direction")); // Default of 20 pulses m_CtlNumPulses->Bind(wxEVT_SPINCTRLDOUBLE, &StarCrossDialog::OnPulseCountChange, this); AddTableEntryPair(this, testSpecSizer, _("Number of guide pulses"), m_CtlNumPulses); // Pulse size - m_CtlPulseSize = NewSpinner(this, width, - pulseSize, 500, 5000, 50, 0, _("Guide pulse size (ms)")); // Default of 1-sec pulse + m_CtlPulseSize = NewSpinner(this, width, pulseSize, 500, 5000, 50, 0, _("Guide pulse size (ms)")); // Default of 1-sec pulse m_CtlPulseSize->Bind(wxEVT_SPINCTRLDOUBLE, &StarCrossDialog::OnPulseSizeChange, this); AddTableEntryPair(this, testSpecSizer, _("Pulse size (ms)"), m_CtlPulseSize); // Suggestion button - wxButton* resetBtn = new wxButton(this, wxID_ANY, _("Reset")); + wxButton *resetBtn = new wxButton(this, wxID_ANY, _("Reset")); resetBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &StarCrossDialog::OnSuggest, this); testSpecSizer->Add(resetBtn, 1, wxALL, 5); m_DetailsGroup->Add(testSpecSizer, wxSizerFlags().Border(wxTOP | wxBOTTOM | wxRIGHT, 5).Border(wxLEFT, 20)); // Put an explanation block and progress bar right above the buttons - m_Explanations = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(500,-1), wxALIGN_CENTER); + m_Explanations = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(500, -1), wxALIGN_CENTER); m_Explanations->SetLabel(_("Verify or adjust your parameters, click 'Start' to begin")); MakeBold(m_Explanations); m_Progress = new wxGauge(this, wxID_ANY, 100, wxDefaultPosition, wxSize(500, -1)); - // Start/stop buttons - wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); + // Start/stop buttons + wxBoxSizer *btnSizer = new wxBoxSizer(wxHORIZONTAL); m_StartBtn = new wxButton(this, wxID_ANY, _("Start")); m_StartBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &StarCrossDialog::OnStart, this); m_StopBtn = new wxButton(this, wxID_ANY, _("Stop")); m_StopBtn->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &StarCrossDialog::OnCancel, this); m_StopBtn->Enable(false); - btnSizer->Add( - m_StartBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); - btnSizer->Add( - m_StopBtn, - wxSizerFlags(0).Align(0).Border(wxALL, 10)); + btnSizer->Add(m_StartBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); + btnSizer->Add(m_StopBtn, wxSizerFlags(0).Align(0).Border(wxALL, 10)); // Stack up the UI elements in the vertical sizer m_ShowDetails = false; @@ -182,7 +176,7 @@ StarCrossDialog::StarCrossDialog(wxWindow *parent) : SetSizerAndFit(vSizer); if (!pConfig->Profile.HasEntry("/SCT/PulseCount")) - SuggestParams(); // Offer suggestions unless user has already completed a test + SuggestParams(); // Offer suggestions unless user has already completed a test } StarCrossDialog::~StarCrossDialog() @@ -196,7 +190,7 @@ void StarCrossDialog::SuggestParams() double guideSpeed; // Want to handle mounts with 25 sec of backlash at guide speed of 0.5x guideSpeed = m_CtlGuideSpeed->GetValue(); - m_CtlNumPulses->SetValue((int)ceil((24.0 * 0.5 / guideSpeed))); + m_CtlNumPulses->SetValue((int) ceil((24.0 * 0.5 / guideSpeed))); m_CtlPulseSize->SetValue(1000); SynchSummarySliders(); } @@ -294,9 +288,9 @@ void StarCrossDialog::ExecuteTest() wxString dirString; wxString logMsg; SCT_StepInfo currStep = { 0, NONE, SCT_STATE_NONE }; - Mount* theMount; + Mount *theMount; - m_Amount = m_CtlPulseSize->GetValue(); // Don't allow changes until done + m_Amount = m_CtlPulseSize->GetValue(); // Don't allow changes until done m_DirectionalPulseCount = m_CtlNumPulses->GetValue(); totalPulses = 8 * m_DirectionalPulseCount; m_StartBtn->Enable(false); @@ -313,8 +307,8 @@ void StarCrossDialog::ExecuteTest() } m_CancelTest = false; // Leave plenty of room for camera exposure and mount response overhead - wxMessageBox(wxString::Format(_("Start a %d exposure on your main camera, then click 'Ok'"), - (2 * totalPulses * m_Amount) / 1000)); + wxMessageBox( + wxString::Format(_("Start a %d exposure on your main camera, then click 'Ok'"), (2 * totalPulses * m_Amount) / 1000)); while (!done && !m_CancelTest) { if (dirCount == currStep.pulseCount) @@ -326,14 +320,11 @@ void StarCrossDialog::ExecuteTest() { Debug.Write("Star-cross test completed\n"); m_Explanations->SetLabel(Explanation(currStep, dirCount)); - wxMessageBox( - _("Wait for the main camera exposure to complete, then save that image for review") - ); + wxMessageBox(_("Wait for the main camera exposure to complete, then save that image for review")); pConfig->Profile.SetDouble("/SCT/PulseCount", m_DirectionalPulseCount); pConfig->Profile.SetDouble("/SCT/PulseSize", m_Amount); done = true; } - } if (pMount && pMount->IsConnected()) { @@ -341,7 +332,7 @@ void StarCrossDialog::ExecuteTest() { count++; dirCount++; - logMsg = wxString::Format("Star-cross move %d/%d, %s for %d ms", count, totalPulses, dirString, m_Amount ); + logMsg = wxString::Format("Star-cross move %d/%d, %s for %d ms", count, totalPulses, dirString, m_Amount); Debug.Write(logMsg + "\n"); m_Explanations->SetLabel(Explanation(currStep, dirCount)); moveRslt = theMount->MoveAxis(currStep.direction, m_Amount, MOVEOPTS_CALIBRATION_MOVE); @@ -376,7 +367,6 @@ void StarCrossDialog::ExecuteTest() } m_StartBtn->Enable(true); m_StopBtn->Enable(false); - } // Make sure we get unloaded when user is done, start-up becomes deterministic @@ -402,7 +392,6 @@ void StarCrossDialog::SynchDetailSliders() { int leg = m_CtlLegDuration->GetValue(); m_CtlNumPulses->SetValue((int) ceil(leg * 1000. / m_CtlPulseSize->GetValue())); - } // Note: these events are fired only via user actions @@ -461,4 +450,3 @@ void StarCrossDialog::OnViewControl(wxCommandEvent& evt) Layout(); GetSizer()->Fit(this); } - diff --git a/src/starcross_test.h b/src/starcross_test.h index 6d85008f9..0f4df2bf4 100644 --- a/src/starcross_test.h +++ b/src/starcross_test.h @@ -62,19 +62,19 @@ class StarCrossDialog : public wxDialog public: StarCrossDialog(wxWindow *parent); ~StarCrossDialog(); -private: - wxSpinCtrlDouble* m_CtlGuideSpeed; - wxSpinCtrlDouble* m_CtlNumPulses; - wxSpinCtrlDouble* m_CtlPulseSize; - wxSpinCtrlDouble* m_CtlLegDuration; - wxSpinCtrlDouble* m_CtlTotalDuration; - wxStaticBoxSizer* m_DetailsGroup; - wxGauge* m_Progress; - wxButton* m_StartBtn; - wxButton* m_StopBtn; - wxButton* m_ViewControlBtn; - wxStaticText* m_Explanations; +private: + wxSpinCtrlDouble *m_CtlGuideSpeed; + wxSpinCtrlDouble *m_CtlNumPulses; + wxSpinCtrlDouble *m_CtlPulseSize; + wxSpinCtrlDouble *m_CtlLegDuration; + wxSpinCtrlDouble *m_CtlTotalDuration; + wxStaticBoxSizer *m_DetailsGroup; + wxGauge *m_Progress; + wxButton *m_StartBtn; + wxButton *m_StopBtn; + wxButton *m_ViewControlBtn; + wxStaticText *m_Explanations; bool m_CancelTest; int m_DirectionalPulseCount; int m_Amount; @@ -83,6 +83,7 @@ class StarCrossDialog : public wxDialog void SuggestParams(); void SynchDetailSliders(); void SynchSummarySliders(); + public: void OnSuggest(wxCommandEvent& evt); void OnViewControl(wxCommandEvent& evt); diff --git a/src/staticpa_tool.h b/src/staticpa_tool.h index 73b98d3a9..0b5244e09 100644 --- a/src/staticpa_tool.h +++ b/src/staticpa_tool.h @@ -37,6 +37,7 @@ class StaticPaTool { StaticPaTool() = delete; + public: static wxWindow *CreateStaticPaToolWindow(); static void PaintHelper(wxAutoBufferedPaintDCBase& dc, double scale); diff --git a/src/staticpa_toolwin.cpp b/src/staticpa_toolwin.cpp index a0b52297d..28b624d8f 100644 --- a/src/staticpa_toolwin.cpp +++ b/src/staticpa_toolwin.cpp @@ -67,9 +67,9 @@ wxBEGIN_EVENT_TABLE(StaticPaToolWin::PolePanel, wxPanel) wxEND_EVENT_TABLE(); // clang-format on -StaticPaToolWin::PolePanel::PolePanel(StaticPaToolWin* parent): - wxPanel(parent, wxID_ANY, wxDefaultPosition, wxSize(320, 240), wxBU_AUTODRAW | wxBU_EXACTFIT), - paParent(parent) +StaticPaToolWin::PolePanel::PolePanel(StaticPaToolWin *parent) + : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxSize(320, 240), wxBU_AUTODRAW | wxBU_EXACTFIT) + , paParent(parent) { m_origPt.x = 160; m_origPt.y = 120; @@ -108,14 +108,13 @@ wxWindow *StaticPaTool::CreateStaticPaToolWindow() // confirm that image scale is specified if (pFrame->GetCameraPixelScale() == 1.0) { - bool confirmed = ConfirmDialog::Confirm(_( - "The Static Align tool is most effective when PHD2 knows your guide\n" - "scope focal length and camera pixel size.\n" - "\n" - "Enter your guide scope focal length on the Global tab in the Brain.\n" - "Enter your camera pixel size on the Camera tab in the Brain.\n" - "\n" - "Would you like to run the tool anyway?"), + bool confirmed = ConfirmDialog::Confirm(_("The Static Align tool is most effective when PHD2 knows your guide\n" + "scope focal length and camera pixel size.\n" + "\n" + "Enter your guide scope focal length on the Global tab in the Brain.\n" + "Enter your camera pixel size on the Camera tab in the Brain.\n" + "\n" + "Would you like to run the tool anyway?"), "/rotate_tool_without_pixscale"); if (!confirmed) @@ -164,8 +163,9 @@ bool StaticPaTool::UpdateState() } StaticPaToolWin::StaticPaToolWin() -: wxFrame(pFrame, wxID_ANY, _("Static Polar Alignment"), wxDefaultPosition, wxDefaultSize, -wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxFRAME_FLOAT_ON_PARENT | wxFRAME_NO_TASKBAR) + : wxFrame(pFrame, wxID_ANY, _("Static Polar Alignment"), wxDefaultPosition, wxDefaultSize, + wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxFRAME_FLOAT_ON_PARENT | + wxFRAME_NO_TASKBAR) { m_numPos = 0; m_devpx = 5; @@ -177,12 +177,12 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF double scalefactor = pFrame->pGuider->ScaleFactor(); double xpx = pDispImg->GetWidth() / scalefactor; double ypx = pDispImg->GetHeight() / scalefactor; - m_pxCentre.X = xpx/2; - m_pxCentre.Y = ypx/2; + m_pxCentre.X = xpx / 2; + m_pxCentre.Y = ypx / 2; m_pxScale = pFrame->GetCameraPixelScale(); // Fullsize is easier but the camera simulator does not set this. -// wxSize camsize = pCamera->FullSize; - m_camWidth = pCamera->FullSize.GetWidth() == 0 ? xpx: pCamera->FullSize.GetWidth(); + // wxSize camsize = pCamera->FullSize; + m_camWidth = pCamera->FullSize.GetWidth() == 0 ? xpx : pCamera->FullSize.GetWidth(); m_camAngle = 0.0; double camAngle_rad = 0.0; @@ -193,12 +193,15 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF Debug.AddLine(wxString::Format("StaticPA: Camera angle %.1f", degrees(camAngle_rad))); wxString prefix = "/" + pMount->GetMountClassName() + "/calibration/"; int ipier = pConfig->Profile.GetInt(prefix + "pierSide", PIER_SIDE_UNKNOWN); - PierSide calPierSide = ipier == PIER_SIDE_EAST ? PIER_SIDE_EAST : ipier == PIER_SIDE_WEST ? PIER_SIDE_WEST : PIER_SIDE_UNKNOWN; + PierSide calPierSide = ipier == PIER_SIDE_EAST ? PIER_SIDE_EAST + : ipier == PIER_SIDE_WEST ? PIER_SIDE_WEST + : PIER_SIDE_UNKNOWN; PierSide currPierSide = pPointingSource->SideOfPier(); - Debug.AddLine(wxString::Format("StaticPA: calPierSide %s; currPierSide %s", pMount->PierSideStr(calPierSide), pMount->PierSideStr(currPierSide))); - if (currPierSide != calPierSide && currPierSide != PIER_SIDE_UNKNOWN) + Debug.AddLine(wxString::Format( + "StaticPA: calPierSide %s; currPierSide %s", pMount->PierSideStr(calPierSide), pMount->PierSideStr(currPierSide))); + if (currPierSide != calPierSide && currPierSide != PIER_SIDE_UNKNOWN) { - m_flip = true; + m_flip = true; Debug.AddLine(wxString::Format("StaticPA: Flipped Camera angle")); } m_camAngle = degrees(camAngle_rad); @@ -214,7 +217,8 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF Star("G: HD99685", 149.13626, -89.7824, 7.8), Star("H: HD98784", 134.64254, -89.8312, 8.9), }; - for (int is = 0; is < c_SthStars.size(); is++) { + for (int is = 0; is < c_SthStars.size(); is++) + { PHD_Point radec_now = J2000Now(PHD_Point(c_SthStars.at(is).ra2000, c_SthStars.at(is).dec2000)); c_SthStars.at(is).ra = radec_now.X; c_SthStars.at(is).dec = radec_now.Y; @@ -230,7 +234,8 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF Star("G: HD1687", 9.92515, 89.4443, 8.1), Star("H: TYC-4629-37-1", 70.70722, 89.6301, 9.15), }; - for (int is = 0; is < c_NthStars.size(); is++) { + for (int is = 0; is < c_NthStars.size(); is++) + { PHD_Point radec_now = J2000Now(PHD_Point(c_NthStars.at(is).ra2000, c_NthStars.at(is).dec2000)); c_NthStars.at(is).ra = radec_now.X; c_NthStars.at(is).dec = radec_now.Y; @@ -254,37 +259,34 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF pFrame->StartLoopingInteractive(_T("StaticPA:start")); } m_instr = false; - c_autoInstr = _( - "Slew to near the Celestial Pole.
" - "Choose a Reference Star from the list.
" - "Use the Star Map to help identify a Reference Star.
" - "Select it as the guide star on the main display.
" - "Click Rotate to start the alignment.
" - "Wait for the adjustments to display.
" - "Adjust your mount's altitude and azimuth as displayed.
" - "Red=Altitude; Blue=Azimuth
" - ); - c_manualInstr = _( - "Slew to near the Celestial Pole.
" - "Choose a Reference Star from the list.
" - "Use the Star Map to help identify a Reference Star.
" - "Select it as the guide star on the main display.
" - "Click Get first position.
" - "Slew at least 0h20m west in RA.
" - "Ensure the Reference Star is still selected.
" - "Click Get second position.
" - "Repeat for the third position.
" - "Wait for the adjustments to display.
" - "Adjust your mount's altitude and azimuth to place " - "three reference stars on their orbits\n" - ); + c_autoInstr = _("Slew to near the Celestial Pole.
" + "Choose a Reference Star from the list.
" + "Use the Star Map to help identify a Reference Star.
" + "Select it as the guide star on the main display.
" + "Click Rotate to start the alignment.
" + "Wait for the adjustments to display.
" + "Adjust your mount's altitude and azimuth as displayed.
" + "Red=Altitude; Blue=Azimuth
"); + c_manualInstr = _("Slew to near the Celestial Pole.
" + "Choose a Reference Star from the list.
" + "Use the Star Map to help identify a Reference Star.
" + "Select it as the guide star on the main display.
" + "Click Get first position.
" + "Slew at least 0h20m west in RA.
" + "Ensure the Reference Star is still selected.
" + "Click Get second position.
" + "Repeat for the third position.
" + "Wait for the adjustments to display.
" + "Adjust your mount's altitude and azimuth to place " + "three reference stars on their orbits\n"); // can mount slew? m_auto = true; m_drawOrbit = true; m_canSlew = pPointingSource && pPointingSource->CanSlewAsync(); m_ha = 0.0; - if (!m_canSlew){ + if (!m_canSlew) + { m_auto = false; m_ha = 270.0; } @@ -343,7 +345,8 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF // Next row of grid gridRow++; - m_hourAngleSpin = new wxSpinCtrlDouble(this, ID_HA, wxEmptyString, wxDefaultPosition, wxSize(10, -1), wxSP_ARROW_KEYS | wxSP_WRAP, 0.0, 24.0, m_ha/15.0, 0.1); + m_hourAngleSpin = new wxSpinCtrlDouble(this, ID_HA, wxEmptyString, wxDefaultPosition, wxSize(10, -1), + wxSP_ARROW_KEYS | wxSP_WRAP, 0.0, 24.0, m_ha / 15.0, 0.1); m_hourAngleSpin->SetToolTip(_("Set your scope hour angle")); gbSizer->Add(m_hourAngleSpin, wxGBPosition(gridRow, 0), wxGBSpan(1, 1), wxEXPAND | wxALL | wxFIXED_MINSIZE, 5); m_hourAngleSpin->SetDigits(1); @@ -361,7 +364,7 @@ wxCAPTION | wxCLOSE_BOX | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxF m_refStarChoice->SetToolTip(_("Select the star used for checking alignment.")); refSizer->Add(m_refStarChoice, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0); - m_gotoButton = new wxButton(this, ID_GOTO, _(">"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT ); + m_gotoButton = new wxButton(this, ID_GOTO, _(">"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); refSizer->Add(m_gotoButton, 0, wxALIGN_CENTER_HORIZONTAL | wxALL, 0); gbSizer->Add(refSizer, wxGBPosition(gridRow, 2), wxGBSpan(1, 1), wxALL, 5); @@ -526,7 +529,8 @@ void StaticPaToolWin::OnNotes(wxCommandEvent& evt) void StaticPaToolWin::OnRotate(wxCommandEvent& evt) { - if (m_aligning && m_auto){ // STOP rotating + if (m_aligning && m_auto) + { // STOP rotating pPointingSource->AbortSlew(); m_aligning = false; m_numPos = 0; @@ -547,7 +551,8 @@ void StaticPaToolWin::OnRotate(wxCommandEvent& evt) return; } m_numPos = 1; - if(m_auto) ClearState(); + if (m_auto) + ClearState(); m_aligning = true; FillPanel(); return; @@ -574,7 +579,7 @@ void StaticPaToolWin::OnGoto(wxCommandEvent& evt) PHD_Point stardeg = PHD_Point(m_poleStars->at(is).ra, m_poleStars->at(is).dec); PHD_Point starpx = Radec2Px(stardeg); - m_polePanel->m_currPt = wxPoint(starpx.X*scale, starpx.Y*scale); + m_polePanel->m_currPt = wxPoint(starpx.X * scale, starpx.Y * scale); FillPanel(); return; } @@ -631,16 +636,19 @@ void StaticPaToolWin::FillPanel() m_hourAngleSpin->Enable(true); - if (!m_canSlew){ + if (!m_canSlew) + { m_manualCheck->Hide(); } m_manualCheck->SetValue(!m_auto); - wxString html = wxString::Format("%s", m_auto ? c_autoInstr : c_manualInstr); + wxString html = wxString::Format( + "%s", m_auto ? c_autoInstr : c_manualInstr); m_instructionsText->SetPage(html); m_star1Button->SetLabel(_("Rotate")); - if (m_aligning) { + if (m_aligning) + { m_star1Button->SetLabel(_("Stop")); } m_star2Button->Hide(); @@ -657,7 +665,8 @@ void StaticPaToolWin::FillPanel() m_poleStars = m_hemi >= 0 ? &c_NthStars : &c_SthStars; m_refStarChoice->Clear(); std::string starname; - for (int is = 0; is < m_poleStars->size(); is++) { + for (int is = 0; is < m_poleStars->size(); is++) + { m_refStarChoice->AppendString(m_poleStars->at(is).name); } m_refStarChoice->SetSelection(m_refStar); @@ -684,7 +693,8 @@ void StaticPaToolWin::CalcRotationCentre(void) double m11, m12, m13, m14; x3 = m_pxPos[2].X; y3 = m_pxPos[2].Y; - Debug.AddLine(wxString::Format("StaticPA: Manual CalcCoR: P1(%.1f,%.1f); P2(%.1f,%.1f); P3(%.1f,%.1f)", x1, y1, x2, y2, x3, y3)); + Debug.AddLine( + wxString::Format("StaticPA: Manual CalcCoR: P1(%.1f,%.1f); P2(%.1f,%.1f); P3(%.1f,%.1f)", x1, y1, x2, y2, x3, y3)); // |A| = aei + bfg + cdh -ceg -bdi -afh // a b c // d e f @@ -712,11 +722,12 @@ void StaticPaToolWin::CalcRotationCentre(void) m14 = a * f * k + b * g * i + c * e * j - c * f * i - b * e * k - a * g * j; cx = (1. / 2.) * m12 / m11; cy = (-1. / 2.) * m13 / m11; - cr = sqrt(cx * cx + cy *cy + m14 / m11); + cr = sqrt(cx * cx + cy * cy + m14 / m11); } else { - Debug.AddLine(wxString::Format("StaticPA Auto CalcCoR: P1(%.1f,%.1f); P2(%.1f,%.1f); RA: %.1f %.1f", x1, y1, x2, y2, m_raPos[0] * 15., m_raPos[1] * 15.)); + Debug.AddLine(wxString::Format("StaticPA Auto CalcCoR: P1(%.1f,%.1f); P2(%.1f,%.1f); RA: %.1f %.1f", x1, y1, x2, y2, + m_raPos[0] * 15., m_raPos[1] * 15.)); // Alternative algorithm based on two points and angle rotated double radiff, theta2; // Get RA change. For westward movement RA decreases. @@ -724,20 +735,21 @@ void StaticPaToolWin::CalcRotationCentre(void) // Convert to radians radians(mult by 15) // Convert to RH system (mult by m_hemi) // normalise to +/- PI - radiff = norm_angle(radians((m_raPos[0] - m_raPos[1])*15.0*m_hemi)); + radiff = norm_angle(radians((m_raPos[0] - m_raPos[1]) * 15.0 * m_hemi)); theta2 = radiff / 2.0; // Half the image rotation for midpoint of chord double lenchord = hypot((x1 - x2), (y1 - y2)); cr = fabs(lenchord / 2.0 / sin(theta2)); - double lenbase = fabs(cr*cos(theta2)); + double lenbase = fabs(cr * cos(theta2)); // Calculate the slope of the chord in pixels // We know the image is moving clockwise in NH and anti-clockwise in SH // So subtract PI/2 in NH or add PI/2 in SH to get the slope to the CoR // Invert y values as pixels are +ve downwards - double slopebase = atan2(y1 - y2, x2 - x1) - m_hemi* M_PI / 2.0; + double slopebase = atan2(y1 - y2, x2 - x1) - m_hemi * M_PI / 2.0; cx = (x1 + x2) / 2.0 + lenbase * cos(slopebase); cy = (y1 + y2) / 2.0 - lenbase * sin(slopebase); // subtract for pixels - Debug.AddLine(wxString::Format("StaticPA CalcCoR: radiff(deg): %.1f; cr: %.1f; slopebase(deg) %.1f", degrees(radiff), cr, degrees(slopebase))); + Debug.AddLine(wxString::Format( + "StaticPA CalcCoR: radiff(deg): %.1f; cr: %.1f; slopebase(deg) %.1f", degrees(radiff), cr, degrees(slopebase))); } m_pxCentre.X = cx; m_pxCentre.Y = cy; @@ -796,13 +808,13 @@ void StaticPaToolWin::CalcAdjustments(void) // Let harot = camera rotation from Alt axis // Alt axis is at HA+90 // This is camera rotation from RA minus(?) LST angle - double hcor_r = hypot((xt - xs), (yt - ys)); //xt,yt: target, xs,ys: measured - double hcor_a = degrees(atan2((yt - ys), (xt - xs))); + double hcor_r = hypot((xt - xs), (yt - ys)); // xt,yt: target, xs,ys: measured + double hcor_a = degrees(atan2((yt - ys), (xt - xs))); double ra_hrs, dec_deg, st_hrs, ha_deg; ha_deg = m_ha; if (pPointingSource && !pPointingSource->GetCoordinates(&ra_hrs, &dec_deg, &st_hrs)) { - ha_deg = norm((st_hrs - ra_hrs)*15.0 + m_ha, 0, 360); + ha_deg = norm((st_hrs - ra_hrs) * 15.0 + m_ha, 0, 360); } double rarot = -m_camAngle; double harot = norm(rarot - (90 + ha_deg), 0, 360); @@ -815,10 +827,11 @@ void StaticPaToolWin::CalcAdjustments(void) m_AzCorr.Y = az_r * cos(radians(harot)); m_AltCorr.X = alt_r * cos(radians(harot)); m_AltCorr.Y = alt_r * sin(radians(harot)); - Debug.AddLine(wxString::Format("StaticPA CalcAdjust: Angles: rarot %.1f; ha_deg %.1f; m_ha %.1f; hcor_a %.1f; harot: %.1f", rarot, ha_deg, m_ha, hcor_a, harot)); + Debug.AddLine(wxString::Format("StaticPA CalcAdjust: Angles: rarot %.1f; ha_deg %.1f; m_ha %.1f; hcor_a %.1f; harot: %.1f", + rarot, ha_deg, m_ha, hcor_a, harot)); Debug.AddLine(wxString::Format("StaticPA CalcAdjust: Errors(px): alt %.1f; az %.1f; tot %.1f", alt_r, az_r, hcor_r)); SetStatusText(wxString::Format(_("Polar Alignment Error (arcmin): Alt %.1f; Az %.1f Tot %.1f"), - fabs(alt_r)*m_pxScale/60, fabs(az_r)*m_pxScale/60, fabs(hcor_r)*m_pxScale/60)); + fabs(alt_r) * m_pxScale / 60, fabs(az_r) * m_pxScale / 60, fabs(hcor_r) * m_pxScale / 60)); } PHD_Point StaticPaToolWin::Radec2Px(const PHD_Point& radec) @@ -838,7 +851,7 @@ PHD_Point StaticPaToolWin::Radec2Px(const PHD_Point& radec) // If not a goto mount calculate ra_deg from LST assuming mount is in the home position (HA=18h) tm j2000_info; j2000_info.tm_year = 100; - j2000_info.tm_mon = 0; // January is month 0 + j2000_info.tm_mon = 0; // January is month 0 j2000_info.tm_mday = 1; j2000_info.tm_hour = 12; j2000_info.tm_min = 0; @@ -850,7 +863,7 @@ PHD_Point StaticPaToolWin::Radec2Px(const PHD_Point& radec) time_t now = mktime(nowinfo); double since = difftime(now, j2000) / 86400.0; double hadeg = m_ha; - ra_deg = norm((280.46061837 + 360.98564736629 * since - hadeg),0,360); + ra_deg = norm((280.46061837 + 360.98564736629 * since - hadeg), 0, 360); } // Target hour angle - or rather the rotation needed to correct. @@ -874,7 +887,7 @@ PHD_Point StaticPaToolWin::J2000Now(const PHD_Point& radec) { tm j2000_info; j2000_info.tm_year = 100; - j2000_info.tm_mon = 0; // January is month 0 + j2000_info.tm_mon = 0; // January is month 0 j2000_info.tm_mday = 1; j2000_info.tm_hour = 12; j2000_info.tm_min = 0; @@ -889,36 +902,36 @@ PHD_Point StaticPaToolWin::J2000Now(const PHD_Point& radec) Improvement of the IAU 2000 precession model N. Capitaine, P. T. Wallace, J. Chapront https://www.aanda.org/articles/aa/full/2005/10/aa1908/aa1908.html - The order of polynomial to be used was found to be t^5 and the precision of the coefficients 0.1 uas. The following series with - a 0.1 uas level of precision matches the canonical 4-rotation series to sub-microarcsecond accuracy over 4 centuries: + The order of polynomial to be used was found to be t^5 and the precision of the coefficients 0.1 uas. The following series + with a 0.1 uas level of precision matches the canonical 4-rotation series to sub-microarcsecond accuracy over 4 centuries: zetaA = 2.5976176 + 2306.0809506 t + 0.3019015 t^2 + 0.0179663 t^3 - 0.0000327 t^4 - 0.0000002 t^5 zedA = -2.5976176 + 2306.0803226 t + 1.0947790 t^2 + 0.0182273 t^3 + 0.0000470 t^4 - 0.0000003 t^5 thetaA = 2004.1917476 t - 0.4269353 t^2 - 0.0418251 t^3 - 0.0000601 t^4 - 0.0000001 t^5 In this implementation we use coefficients up to t^3 */ - double tnow = JDnow / 36525; // JDNow is days since J2000.0 so no need to subtract JD2000 + double tnow = JDnow / 36525; // JDNow is days since J2000.0 so no need to subtract JD2000 double t2 = pow(tnow, 2); double t3 = pow(tnow, 3); - double zed, zeta, theta; // arcseconds + double zed, zeta, theta; // arcseconds double zedrad, zetarad, thetarad; - zeta = 2.5976176 + 2306.0809506*tnow + 0.3019015*t2 + 0.0179663*t3; + zeta = 2.5976176 + 2306.0809506 * tnow + 0.3019015 * t2 + 0.0179663 * t3; zetarad = radians(zeta / 3600); - zed = -2.5976176 + 2306.0803226*tnow + 1.0947790*t2 + 0.0182273*t3; + zed = -2.5976176 + 2306.0803226 * tnow + 1.0947790 * t2 + 0.0182273 * t3; zedrad = radians(zed / 3600); - theta = 2004.1917476*tnow - 0.4269353*t2 - 0.0418251*t3; + theta = 2004.1917476 * tnow - 0.4269353 * t2 - 0.0418251 * t3; thetarad = radians(theta / 3600); -// Build the transformation matrix + // Build the transformation matrix double Xx, Xy, Xz, Yx, Yy, Yz, Zx, Zy, Zz; - Xx = cos(zedrad)*cos(thetarad)*cos(zetarad) - sin(zedrad)*sin(zetarad); - Yx = -cos(zedrad)*cos(thetarad)*sin(zetarad) - sin(zedrad)*cos(zetarad); - Zx = -cos(zedrad)*sin(thetarad); - Xy = sin(zedrad)*cos(thetarad)*cos(zetarad) + cos(zedrad)*sin(zetarad); - Yy = -sin(zedrad)*cos(thetarad)*sin(zetarad) + cos(zedrad)*cos(zetarad); - Zy = -sin(zedrad)*sin(thetarad); - Xz = sin(thetarad)*cos(zetarad); - Yz = -sin(thetarad)*sin(zetarad); + Xx = cos(zedrad) * cos(thetarad) * cos(zetarad) - sin(zedrad) * sin(zetarad); + Yx = -cos(zedrad) * cos(thetarad) * sin(zetarad) - sin(zedrad) * cos(zetarad); + Zx = -cos(zedrad) * sin(thetarad); + Xy = sin(zedrad) * cos(thetarad) * cos(zetarad) + cos(zedrad) * sin(zetarad); + Yy = -sin(zedrad) * cos(thetarad) * sin(zetarad) + cos(zedrad) * cos(zetarad); + Zy = -sin(zedrad) * sin(thetarad); + Xz = sin(thetarad) * cos(zetarad); + Yz = -sin(thetarad) * sin(zetarad); Zz = cos(thetarad); // Transform coordinates; @@ -927,9 +940,9 @@ PHD_Point StaticPaToolWin::J2000Now(const PHD_Point& radec) x0 = cos(radians(radec.Y)) * cos(radians(radec.X)); y0 = cos(radians(radec.Y)) * sin(radians(radec.X)); z0 = sin(radians(radec.Y)); - x = Xx * x0 + Yx * y0 + Zx*z0; - y = Xy * x0 + Yy * y0 + Zy*z0; - z = Xz * x0 + Yz * y0 + Zz*z0; + x = Xx * x0 + Yx * y0 + Zx * z0; + y = Xy * x0 + Yy * y0 + Zy * z0; + z = Xz * x0 + Yz * y0 + Zz * z0; double radeg, decdeg; radeg = norm(degrees(atan2(y, x)), 0, 360); decdeg = degrees(atan2(z, sqrt(1 - z * z))); @@ -944,9 +957,9 @@ void StaticPaToolWin::PaintHelper(wxAutoBufferedPaintDCBase& dc, double scale) for (int i = 0; i < 3; i++) { - if (HasState(i+1)) + if (HasState(i + 1)) { - dc.DrawCircle(m_pxPos[i].X*scale, m_pxPos[i].Y*scale, 12 * scale); + dc.DrawCircle(m_pxPos[i].X * scale, m_pxPos[i].Y * scale, 12 * scale); } } if (!IsCalced()) @@ -957,22 +970,22 @@ void StaticPaToolWin::PaintHelper(wxAutoBufferedPaintDCBase& dc, double scale) dc.SetPen(wxPen(wxColor(intens, 0, intens), 1, wxPENSTYLE_DOT)); if (m_drawOrbit) { - dc.DrawCircle(m_pxCentre.X*scale, m_pxCentre.Y*scale, m_radius*scale); + dc.DrawCircle(m_pxCentre.X * scale, m_pxCentre.Y * scale, m_radius * scale); } // draw the centre of the circle as a red cross dc.SetBrush(*wxTRANSPARENT_BRUSH); dc.SetPen(wxPen(wxColor(255, 0, 0), 1, wxPENSTYLE_SOLID)); int region = 10; - dc.DrawLine((m_pxCentre.X - region)*scale, m_pxCentre.Y*scale, (m_pxCentre.X + region)*scale, m_pxCentre.Y*scale); - dc.DrawLine(m_pxCentre.X*scale, (m_pxCentre.Y - region)*scale, m_pxCentre.X*scale, (m_pxCentre.Y + region)*scale); + dc.DrawLine((m_pxCentre.X - region) * scale, m_pxCentre.Y * scale, (m_pxCentre.X + region) * scale, m_pxCentre.Y * scale); + dc.DrawLine(m_pxCentre.X * scale, (m_pxCentre.Y - region) * scale, m_pxCentre.X * scale, (m_pxCentre.Y + region) * scale); // Show the centre of the display wth a grey cross double xsc = m_dispSz[0] / 2; double ysc = m_dispSz[1] / 2; dc.SetPen(wxPen(wxColor(intens, intens, intens), 1, wxPENSTYLE_SOLID)); - dc.DrawLine((xsc - region)*scale, ysc*scale, (xsc + region)*scale, ysc*scale); - dc.DrawLine(xsc*scale, (ysc - region)*scale, xsc*scale, (ysc + region)*scale); + dc.DrawLine((xsc - region) * scale, ysc * scale, (xsc + region) * scale, ysc * scale); + dc.DrawLine(xsc * scale, (ysc - region) * scale, xsc * scale, (ysc + region) * scale); // Draw orbits for each reference star // Caclulate pixel values for the reference stars @@ -998,24 +1011,24 @@ void StaticPaToolWin::PaintHelper(wxAutoBufferedPaintDCBase& dc, double scale) dc.DrawCircle(m_pxCentre.X * scale, m_pxCentre.Y * scale, radpx * scale); } dc.SetPen(wxPen(line_color, 1, wxPENSTYLE_SOLID)); - dc.DrawCircle((m_pxCentre.X + starpx.X) * scale, (m_pxCentre.Y + starpx.Y) * scale, region*scale); + dc.DrawCircle((m_pxCentre.X + starpx.X) * scale, (m_pxCentre.Y + starpx.Y) * scale, region * scale); dc.SetTextForeground(line_color); - dc.DrawText(wxString::Format("%c", alpha[is]), (m_pxCentre.X + starpx.X + region) * scale, (m_pxCentre.Y + starpx.Y) * scale); + dc.DrawText( + wxString::Format("%c", alpha[is]), (m_pxCentre.X + starpx.X + region) * scale, (m_pxCentre.Y + starpx.Y) * scale); } // Draw adjustment lines for centring the CoR on the display in blue (dec) and red (cone error) bool drawCone = false; - if (drawCone){ + if (drawCone) + { double xr = m_pxCentre.X * scale; double yr = m_pxCentre.Y * scale; dc.SetPen(wxPen(wxColor(intens, 0, 0), 1, wxPENSTYLE_SOLID)); dc.DrawLine(xr, yr, xr + m_ConeCorr.X * scale, yr + m_ConeCorr.Y * scale); dc.SetPen(wxPen(wxColor(0, 0, intens), 1, wxPENSTYLE_SOLID)); - dc.DrawLine(xr + m_ConeCorr.X * scale, yr + m_ConeCorr.Y * scale, - xr + m_DecCorr.X * scale + m_ConeCorr.X * scale, + dc.DrawLine(xr + m_ConeCorr.X * scale, yr + m_ConeCorr.Y * scale, xr + m_DecCorr.X * scale + m_ConeCorr.X * scale, yr + m_DecCorr.Y * scale + m_ConeCorr.Y * scale); dc.SetPen(wxPen(wxColor(intens, intens, intens), 1, wxPENSTYLE_SOLID)); - dc.DrawLine(xr, yr, xr + m_DecCorr.X * scale + m_ConeCorr.X * scale, - yr + m_DecCorr.Y * scale + m_ConeCorr.Y * scale); + dc.DrawLine(xr, yr, xr + m_DecCorr.X * scale + m_ConeCorr.X * scale, yr + m_DecCorr.Y * scale + m_ConeCorr.Y * scale); } // Draw adjustment lines for placing the guide star in its correct position relative to the CoR // Blue (azimuth) and Red (altitude) @@ -1029,12 +1042,11 @@ void StaticPaToolWin::PaintHelper(wxAutoBufferedPaintDCBase& dc, double scale) double ys = m_pxPos[idx].Y * scale; dc.SetPen(wxPen(wxColor(intens, 0, 0), 1, wxPENSTYLE_DOT)); dc.DrawLine(xs, ys, xs + m_AltCorr.X * scale, ys + m_AltCorr.Y * scale); - dc.SetPen(wxPen(wxColor(0, 188.0*intens / 255.0, intens), 1, wxPENSTYLE_DOT)); - dc.DrawLine(xs + m_AltCorr.X * scale, ys + m_AltCorr.Y * scale, - xs + m_AltCorr.X * scale + m_AzCorr.X * scale, ys + m_AzCorr.Y * scale + m_AltCorr.Y * scale); - dc.SetPen(wxPen(wxColor(intens*2/3, intens*2/3, intens*2/3), 1, wxPENSTYLE_DOT)); - dc.DrawLine(xs, ys, xs + m_AltCorr.X * scale + m_AzCorr.X * scale, - ys + m_AltCorr.Y * scale + m_AzCorr.Y * scale); + dc.SetPen(wxPen(wxColor(0, 188.0 * intens / 255.0, intens), 1, wxPENSTYLE_DOT)); + dc.DrawLine(xs + m_AltCorr.X * scale, ys + m_AltCorr.Y * scale, xs + m_AltCorr.X * scale + m_AzCorr.X * scale, + ys + m_AzCorr.Y * scale + m_AltCorr.Y * scale); + dc.SetPen(wxPen(wxColor(intens * 2 / 3, intens * 2 / 3, intens * 2 / 3), 1, wxPENSTYLE_DOT)); + dc.DrawLine(xs, ys, xs + m_AltCorr.X * scale + m_AzCorr.X * scale, ys + m_AltCorr.Y * scale + m_AzCorr.Y * scale); } } @@ -1086,14 +1098,17 @@ bool StaticPaToolWin::RotateMount() } m_numPos++; m_aligning = false; - if (IsAligned()){ + if (IsAligned()) + { CalcRotationCentre(); } return true; } - SetStatusText(wxString::Format(_("Star Pos#2 Step=%d / %d Rotated=%.1f / %.1f deg"), m_nStep, m_reqStep, m_totRot, m_reqRot)); - Debug.AddLine(wxString::Format("StaticPA: Star Pos#2 m_nStep=%d / %d m_totRot=%.1f / %.1f deg", m_nStep, m_reqStep, m_totRot, m_reqRot)); - if (pPointingSource->Slewing()) // Wait till the mount has stopped + SetStatusText( + wxString::Format(_("Star Pos#2 Step=%d / %d Rotated=%.1f / %.1f deg"), m_nStep, m_reqStep, m_totRot, m_reqRot)); + Debug.AddLine(wxString::Format( + "StaticPA: Star Pos#2 m_nStep=%d / %d m_totRot=%.1f / %.1f deg", m_nStep, m_reqStep, m_totRot, m_reqRot)); + if (pPointingSource->Slewing()) // Wait till the mount has stopped { return true; } @@ -1124,12 +1139,14 @@ bool StaticPaToolWin::RotateMount() double actpix = hypot((m_pxPos[1].X - m_pxPos[0].X), (m_pxPos[1].Y - m_pxPos[0].Y)); double actsec = actpix * m_pxScale; double actoffsetdeg = 90 - degrees(acos(actsec / 3600 / m_reqRot)); - Debug.AddLine(wxString::Format("StaticPA: Star Pos#2 actpix=%.1f actsec=%.1f m_pxScale=%.1f", actpix, actsec, m_pxScale)); + Debug.AddLine( + wxString::Format("StaticPA: Star Pos#2 actpix=%.1f actsec=%.1f m_pxScale=%.1f", actpix, actsec, m_pxScale)); if (actoffsetdeg == 0) { Debug.AddLine(wxString::Format("StaticPA: Star Pos#2 Mount did not move actoffsetdeg=%.1f", actoffsetdeg)); - return RotateFail(wxString::Format(_("Star Pos#2 Mount did not move. Calculated polar offset=%.1f deg"), actoffsetdeg)); + return RotateFail( + wxString::Format(_("Star Pos#2 Mount did not move. Calculated polar offset=%.1f deg"), actoffsetdeg)); } double prev_rotdg = m_reqRot; if (!SetParams(actoffsetdeg)) @@ -1147,13 +1164,16 @@ bool StaticPaToolWin::RotateMount() } else if (m_reqRot > 45) { - Debug.AddLine(wxString::Format("StaticPA: Pos#2 Too close to CoR actoffsetdeg=%.1f m_reqRot=%.1f", actoffsetdeg, m_reqRot)); - return RotateFail(wxString::Format(_("Star is too close to CoR (%.1f deg) - try another reference star"), actoffsetdeg )); + Debug.AddLine(wxString::Format( + "StaticPA: Pos#2 Too close to CoR actoffsetdeg=%.1f m_reqRot=%.1f", actoffsetdeg, m_reqRot)); + return RotateFail( + wxString::Format(_("Star is too close to CoR (%.1f deg) - try another reference star"), actoffsetdeg)); } else { - m_nStep = int(m_reqStep * m_totRot/m_reqRot); - Debug.AddLine(wxString::Format("StaticPA: Star Pos#2 m_nStep=%d / %d m_totRot=%.1f / %.1f", m_nStep, m_reqStep, m_totRot, m_reqRot)); + m_nStep = int(m_reqStep * m_totRot / m_reqRot); + Debug.AddLine(wxString::Format( + "StaticPA: Star Pos#2 m_nStep=%d / %d m_totRot=%.1f / %.1f", m_nStep, m_reqStep, m_totRot, m_reqRot)); } } return true; @@ -1169,7 +1189,8 @@ bool StaticPaToolWin::RotateMount() } m_numPos++; m_aligning = false; - if (IsAligned()){ + if (IsAligned()) + { CalcRotationCentre(); } return true; @@ -1225,10 +1246,12 @@ bool StaticPaToolWin::SetParams(double newoffset) { double offsetdeg = newoffset; double m_offsetpx = offsetdeg * 3600 / m_pxScale; - Debug.AddLine(wxString::Format("StaticPA:SetParams(newoffset=%.1f) m_pxScale=%.1f m_offsetpx=%.1f m_devpx=%.1f", newoffset, m_pxScale, m_offsetpx, m_devpx)); + Debug.AddLine(wxString::Format("StaticPA:SetParams(newoffset=%.1f) m_pxScale=%.1f m_offsetpx=%.1f m_devpx=%.1f", newoffset, + m_pxScale, m_offsetpx, m_devpx)); if (m_offsetpx < m_devpx) { - Debug.AddLine(wxString::Format("StaticPA: SetParams() Too close to CoR: m_offsetpx=%.1f m_devpx=%.1f", m_offsetpx, m_devpx)); + Debug.AddLine( + wxString::Format("StaticPA: SetParams() Too close to CoR: m_offsetpx=%.1f m_devpx=%.1f", m_offsetpx, m_devpx)); return false; } m_reqRot = degrees(acos(1 - m_devpx / m_offsetpx)); @@ -1240,7 +1263,8 @@ bool StaticPaToolWin::SetParams(double newoffset) { m_reqStep = int(ceil(m_rotpx / region)); } - Debug.AddLine(wxString::Format("StaticPA: SetParams() m_reqRot=%.1f m_rotpx=%.1f m_reqStep=%d region=%d", m_reqRot, m_rotpx, m_reqStep, region)); + Debug.AddLine(wxString::Format( + "StaticPA: SetParams() m_reqRot=%.1f m_rotpx=%.1f m_reqStep=%d region=%d", m_reqRot, m_rotpx, m_reqStep, region)); return true; } bool StaticPaToolWin::MoveWestBy(double thetadeg) @@ -1252,7 +1276,7 @@ bool StaticPaToolWin::MoveWestBy(double thetadeg) return false; } double slew_ra = norm_ra(cur_ra - thetadeg * 24.0 / 360.0); -// slew_ra = slew_ra - 24.0 * floor(slew_ra / 24.0); + // slew_ra = slew_ra - 24.0 * floor(slew_ra / 24.0); Debug.AddLine(wxString::Format("StaticPA: Slewing from RA hrs: %.3f to:%.3f", cur_ra, slew_ra)); if (pPointingSource->SlewToCoordinatesAsync(slew_ra, cur_dec)) { @@ -1292,23 +1316,23 @@ void StaticPaToolWin::CreateStarTemplate(wxDC& dc, const wxPoint& m_currPt) double starsz, starmag; // Draw position of each alignment star for (int is = 0; is < m_poleStars->size(); is++) - { + { stardeg = PHD_Point(m_poleStars->at(is).ra, m_poleStars->at(is).dec); starmag = m_poleStars->at(is).mag; - starsz = 356.0*exp(-0.3*starmag) / m_pxScale; + starsz = 356.0 * exp(-0.3 * starmag) / m_pxScale; starpx = Radec2Px(stardeg); dc.SetPen(*wxYELLOW_PEN); dc.SetBrush(*wxYELLOW_BRUSH); - wxPoint starPt = wxPoint(starpx.X*scale, starpx.Y*scale) - m_currPt + wxPoint(160, 120); - dc.DrawCircle(starPt.x, starPt.y, starsz*scale); - dc.DrawText(wxString::Format("%c", alpha[is]), starPt.x + starsz*scale, starPt.y); + wxPoint starPt = wxPoint(starpx.X * scale, starpx.Y * scale) - m_currPt + wxPoint(160, 120); + dc.DrawCircle(starPt.x, starPt.y, starsz * scale); + dc.DrawText(wxString::Format("%c", alpha[is]), starPt.x + starsz * scale, starPt.y); } // draw the pole as a red cross dc.SetBrush(*wxTRANSPARENT_BRUSH); dc.SetPen(wxPen(wxColor(255, 0, 0), 1, wxPENSTYLE_SOLID)); - dc.DrawLine(160- region*scale, 120, 160 + region*scale, 120); - dc.DrawLine(160, 120 - region*scale, 160, 120 + region*scale); - dc.DrawLine(160, 120, 160-m_currPt.x, 120-m_currPt.y); + dc.DrawLine(160 - region * scale, 120, 160 + region * scale, 120); + dc.DrawLine(160, 120 - region * scale, 160, 120 + region * scale); + dc.DrawLine(160, 120, 160 - m_currPt.x, 120 - m_currPt.y); return; } \ No newline at end of file diff --git a/src/staticpa_toolwin.h b/src/staticpa_toolwin.h index 3670b7397..7f14d61ea 100644 --- a/src/staticpa_toolwin.h +++ b/src/staticpa_toolwin.h @@ -50,32 +50,32 @@ struct StaticPaToolWin : public wxFrame */ wxHtmlWindow *m_instructionsText; wxTextCtrl *m_camScaleText; // Text box for camera pixel scale - wxTextCtrl *m_camRotText; // Text box for camera rotation + wxTextCtrl *m_camRotText; // Text box for camera rotation wxSpinCtrlDouble *m_hourAngleSpin; // Spinner to manually set HA - wxCheckBox *m_manualCheck; // Checkbox for auto/manual slewing - wxCheckBox *m_flipCheck; // Checkbox to flip camera - wxCheckBox *m_orbitCheck; // Checkbox t show/hide orbits - wxButton *m_instrButton; // Button to toggle instructions/map - wxButton *m_star1Button; // Button for manual get of point 1 - wxButton *m_star2Button; // Button for manual get of point 2 - wxButton *m_star3Button; // Button for manual get of point 3 + wxCheckBox *m_manualCheck; // Checkbox for auto/manual slewing + wxCheckBox *m_flipCheck; // Checkbox to flip camera + wxCheckBox *m_orbitCheck; // Checkbox t show/hide orbits + wxButton *m_instrButton; // Button to toggle instructions/map + wxButton *m_star1Button; // Button for manual get of point 1 + wxButton *m_star2Button; // Button for manual get of point 2 + wxButton *m_star3Button; // Button for manual get of point 3 wxStaticText *m_notesLabel; wxTextCtrl *m_notesText; - wxButton *m_gotoButton; // Button to clear display - wxButton *m_clearButton; // Button to clear display - wxButton *m_closeButton; // Close button + wxButton *m_gotoButton; // Button to clear display + wxButton *m_clearButton; // Button to clear display + wxButton *m_closeButton; // Close button wxStatusBar *m_statusBar; - wxChoice *m_refStarChoice; // Listbox for reference stars - wxChoice *m_hemiChoice; // Listbox for manual hemisphere choice + wxChoice *m_refStarChoice; // Listbox for reference stars + wxChoice *m_hemiChoice; // Listbox for manual hemisphere choice class PolePanel : public wxPanel { public: wxPoint m_origPt, m_currPt; - PolePanel(StaticPaToolWin* parent); + PolePanel(StaticPaToolWin *parent); StaticPaToolWin *paParent; - void OnClick(wxMouseEvent &evt); - void OnPaint(wxPaintEvent &evt); + void OnClick(wxMouseEvent& evt); + void OnPaint(wxPaintEvent& evt); void Paint(); wxDECLARE_EVENT_TABLE(); }; @@ -92,7 +92,13 @@ struct StaticPaToolWin : public wxFrame public: std::string name; double ra2000, dec2000, mag, ra, dec; - Star(const char* a, double b, double c, double d) :name(a), ra2000(b), dec2000(c), mag(d), ra(-1), dec(-1) {}; + Star(const char *a, double b, double c, double d) + : name(a) + , ra2000(b) + , dec2000(c) + , mag(d) + , ra(-1) + , dec(-1) {}; }; std::vector c_SthStars, c_NthStars; // Stars around the poles std::vector *m_poleStars; @@ -113,36 +119,36 @@ struct StaticPaToolWin : public wxFrame ID_CLEAR, ID_CLOSE, }; - bool m_canSlew; // Mount can slew - double m_pxScale; // Camera pixel scale - double m_camAngle; // Camera angle to RA - double m_camWidth; // Camera width - - bool m_instr; // Instructions displayed va Map displayed - double m_devpx; // Number of pixels deviation needed to detect an arc - int m_refStar; // Selected reference star - bool m_auto; // Auto slewing - must be manual if mount cannot slew - int m_hemi; // Hemisphere of the observer - double m_ha; // Manual hour angle - bool m_drawOrbit; // Draw the star orbits - bool m_flip; // Flip the camera angle - - bool m_aligning; // Indicates that alignment points are being collected - unsigned int m_state; // state of the alignment process - int m_numPos; // Number of alignment points - double m_reqRot; // Amount of rotation required - int m_reqStep; // Number of steps needed - double m_totRot; // Rotation so far - int m_nStep; // Number of steps taken so far - - double m_raPos[3]; // RA readings at each point - PHD_Point m_pxPos[3]; // Alignment points - in pixels - PHD_Point m_pxCentre; // Centre of Rotation in pixels - double m_radius; // Radius of centre of rotation to reference star - - double m_dispSz[2]; // Display size (dynamic) + bool m_canSlew; // Mount can slew + double m_pxScale; // Camera pixel scale + double m_camAngle; // Camera angle to RA + double m_camWidth; // Camera width + + bool m_instr; // Instructions displayed va Map displayed + double m_devpx; // Number of pixels deviation needed to detect an arc + int m_refStar; // Selected reference star + bool m_auto; // Auto slewing - must be manual if mount cannot slew + int m_hemi; // Hemisphere of the observer + double m_ha; // Manual hour angle + bool m_drawOrbit; // Draw the star orbits + bool m_flip; // Flip the camera angle + + bool m_aligning; // Indicates that alignment points are being collected + unsigned int m_state; // state of the alignment process + int m_numPos; // Number of alignment points + double m_reqRot; // Amount of rotation required + int m_reqStep; // Number of steps needed + double m_totRot; // Rotation so far + int m_nStep; // Number of steps taken so far + + double m_raPos[3]; // RA readings at each point + PHD_Point m_pxPos[3]; // Alignment points - in pixels + PHD_Point m_pxCentre; // Centre of Rotation in pixels + double m_radius; // Radius of centre of rotation to reference star + + double m_dispSz[2]; // Display size (dynamic) PHD_Point m_AzCorr, m_AltCorr; // Calculated Alt and Az corrections - PHD_Point m_ConeCorr, m_DecCorr; //Calculated Dec and Cone offsets + PHD_Point m_ConeCorr, m_DecCorr; // Calculated Dec and Cone offsets void FillPanel(); @@ -162,18 +168,18 @@ struct StaticPaToolWin : public wxFrame void OnCloseBtn(wxCommandEvent& evt); void OnClose(wxCloseEvent& evt); - void CreateStarTemplate(wxDC &dc, const wxPoint& m_currPt); - bool IsAligning(){ return m_aligning; }; + void CreateStarTemplate(wxDC& dc, const wxPoint& m_currPt); + bool IsAligning() { return m_aligning; }; bool RotateMount(); bool RotateFail(const wxString& msg); bool SetParams(double newoffset); bool MoveWestBy(double thetadeg); bool SetStar(int idx); - bool IsAligned(){ return m_auto ? ((m_state>>1) & 3) ==3 : ((m_state>>1) & 7)==7; } - bool IsCalced(){ return HasState(0); } + bool IsAligned() { return m_auto ? ((m_state >> 1) & 3) == 3 : ((m_state >> 1) & 7) == 7; } + bool IsCalced() { return HasState(0); } void CalcRotationCentre(void); void CalcAdjustments(void); - bool HasState(int ipos) { return (m_state & (1 << ipos)) > 0; } + bool HasState(int ipos) { return (m_state & (1 << ipos)) > 0; } void SetState(int ipos) { m_state = m_state | (1 << ipos); } void UnsetState(int ipos) { m_state = m_state & ~(1 << ipos) & 15; } void ClearState() { m_state = 0; } @@ -185,4 +191,3 @@ struct StaticPaToolWin : public wxFrame }; #endif - diff --git a/src/statswindow.cpp b/src/statswindow.cpp index 557b22659..2f4f37b98 100644 --- a/src/statswindow.cpp +++ b/src/statswindow.cpp @@ -1,41 +1,42 @@ /* -* statswindow.cpp -* PHD Guiding -* -* Created by Andy Galasso -* Copyright (c) 2014 Andy Galasso -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of Craig Stark, Stark Labs nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * statswindow.cpp + * PHD Guiding + * + * Created by Andy Galasso + * Copyright (c) 2014 Andy Galasso + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of Craig Stark, Stark Labs nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #include "phd.h" #include "statswindow.h" -enum { +enum +{ TIMER_ID_COOLER = 101, }; @@ -49,10 +50,10 @@ wxEND_EVENT_TABLE(); // clang-format on StatsWindow::StatsWindow(wxWindow *parent) - : wxWindow(parent, wxID_ANY), - m_visible(false), - m_coolerTimer(this, TIMER_ID_COOLER), - m_lastFrameSize(wxDefaultSize) + : wxWindow(parent, wxID_ANY) + , m_visible(false) + , m_coolerTimer(this, TIMER_ID_COOLER) + , m_lastFrameSize(wxDefaultSize) { SetBackgroundColour(*wxBLACK); @@ -155,9 +156,7 @@ StatsWindow::StatsWindow(wxWindow *parent) SetSizerAndFit(sizer2); } -StatsWindow::~StatsWindow(void) -{ -} +StatsWindow::~StatsWindow(void) { } void StatsWindow::SetState(bool is_active) { @@ -219,13 +218,15 @@ void StatsWindow::UpdateStats(void) m_grid2->SetCellTextColour(row, col, wxColour(185, 20, 0)); else m_grid2->SetCellTextColour(row, col, *wxLIGHT_GREY); - m_grid2->SetCellValue(row++, col, wxString::Format(" %u (%.f%%)", stats.ra_limit_cnt, stats.ra_limit_cnt * 100. / historyItems)); + m_grid2->SetCellValue( + row++, col, wxString::Format(" %u (%.f%%)", stats.ra_limit_cnt, stats.ra_limit_cnt * 100. / historyItems)); if (stats.dec_limit_cnt > 0) m_grid2->SetCellTextColour(row, col, wxColour(185, 20, 0)); else m_grid2->SetCellTextColour(row, col, *wxLIGHT_GREY); - m_grid2->SetCellValue(row++, col, wxString::Format(" %u (%.f%%)", stats.dec_limit_cnt, stats.dec_limit_cnt * 100. / historyItems)); + m_grid2->SetCellValue( + row++, col, wxString::Format(" %u (%.f%%)", stats.dec_limit_cnt, stats.dec_limit_cnt * 100. / historyItems)); m_grid2->SetCellValue(row++, col, wxString::Format(" %u", stats.star_lost_cnt)); @@ -259,7 +260,10 @@ void StatsWindow::UpdateCooler() if (pCamera->HasCooler) { s = CamCoolerStatus(); - enum { COOLER_POLL_INTERVAL_MS = 10000 }; + enum + { + COOLER_POLL_INTERVAL_MS = 10000 + }; m_coolerTimer.StartOnce(COOLER_POLL_INTERVAL_MS); } else @@ -271,7 +275,8 @@ void StatsWindow::UpdateCooler() static wxString fov(const wxSize& sensorFormat, double sampling) { if (sampling != 1.0) - return wxString::Format("%4.1f x %4.1f %s", sensorFormat.x * sampling / 60.0, sensorFormat.y * sampling / 60.0, _("arc-min")); + return wxString::Format( + "%4.1f x %4.1f %s", sensorFormat.x * sampling / 60.0, sensorFormat.y * sampling / 60.0, _("arc-min")); else return " "; } @@ -334,8 +339,8 @@ void StatsWindow::OnButtonLength(wxCommandEvent& WXUNUSED(evt)) { wxMenu *menu = pFrame->pGraphLog->GetLengthMenu(); - PopupMenu(menu, m_pLengthButton->GetPosition().x, - m_pLengthButton->GetPosition().y + m_pLengthButton->GetSize().GetHeight()); + PopupMenu( + menu, m_pLengthButton->GetPosition().x, m_pLengthButton->GetPosition().y + m_pLengthButton->GetSize().GetHeight()); delete menu; } diff --git a/src/stepguider.cpp b/src/stepguider.cpp index 548e4bfd9..0059fe253 100644 --- a/src/stepguider.cpp +++ b/src/stepguider.cpp @@ -72,7 +72,8 @@ StepGuider::StepGuider() double bumpMaxStepsPerCycle = pConfig->Profile.GetDouble(prefix + "/BumpMaxStepsPerCycle", DefaultBumpMaxStepsPerCycle); SetBumpMaxStepsPerCycle(bumpMaxStepsPerCycle); - int calibrationStepsPerIteration = pConfig->Profile.GetInt(prefix + "/CalibrationStepsPerIteration", DefaultCalibrationStepsPerIteration); + int calibrationStepsPerIteration = + pConfig->Profile.GetInt(prefix + "/CalibrationStepsPerIteration", DefaultCalibrationStepsPerIteration); SetCalibrationStepsPerIteration(calibrationStepsPerIteration); int xGuideAlgorithm = pConfig->Profile.GetInt(prefix + "/XGuideAlgorithm", DefaultGuideAlgorithm); @@ -84,9 +85,7 @@ StepGuider::StepGuider() m_bumpOnDither = pConfig->Profile.GetBoolean("/stepguider/BumpOnDither", true); } -StepGuider::~StepGuider() -{ -} +StepGuider::~StepGuider() { } GUIDE_ALGORITHM StepGuider::DefaultXGuideAlgorithm() const { @@ -226,10 +225,14 @@ void StepGuider::InitBumpPositions() m_yBumpPos1 = IntegerPercent(m_bumpPercentage, MaxPosition(UP)); m_yBumpPos2 = IntegerPercent(limit2Pct, MaxPosition(UP)); - enum { BumpCenterTolerancePct = 10 }; // end bump when position is within 10 pct of center + enum + { + BumpCenterTolerancePct = 10 + }; // end bump when position is within 10 pct of center m_bumpCenterTolerance = IntegerPercent(BumpCenterTolerancePct, 2 * MaxPosition(UP)); - Debug.Write(wxString::Format("StepGuider: Bump Limits: X: %d, %d; Y: %d, %d; center: %d\n", m_xBumpPos1, m_xBumpPos2, m_yBumpPos1, m_yBumpPos2, m_bumpCenterTolerance)); + Debug.Write(wxString::Format("StepGuider: Bump Limits: X: %d, %d; Y: %d, %d; center: %d\n", m_xBumpPos1, m_xBumpPos2, + m_yBumpPos1, m_yBumpPos2, m_bumpCenterTolerance)); } int StepGuider::GetSamplesToAverage() const @@ -443,20 +446,20 @@ int StepGuider::CurrentPosition(GUIDE_DIRECTION direction) switch (direction) { - case UP: - ret = m_yOffset; - break; - case DOWN: - ret = -m_yOffset; - break; - case RIGHT: - ret = m_xOffset; - break; - case LEFT: - ret = -m_xOffset; - break; - case NONE: - break; + case UP: + ret = m_yOffset; + break; + case DOWN: + ret = -m_yOffset; + break; + case RIGHT: + ret = m_xOffset; + break; + case LEFT: + ret = -m_xOffset; + break; + case NONE: + break; } return ret; @@ -543,14 +546,18 @@ bool StepGuider::UpdateCalibrationState(const PHD_Point& currentLocation) try { - enum { MAX_CALIBRATION_MOVE_ERRORS = 12 }; + enum + { + MAX_CALIBRATION_MOVE_ERRORS = 12 + }; if (ErrorCount() > MAX_CALIBRATION_MOVE_ERRORS) { - pFrame->Alert(_("The AO is failing to move and calibration cannot complete. Check the Debug Log for more information.")); + pFrame->Alert( + _("The AO is failing to move and calibration cannot complete. Check the Debug Log for more information.")); - Debug.Write(wxString::Format("stepguider calibration failure, current pos = %+d,%+d, required range = %+d..%+d,%+d..%+d\n", - m_xOffset, m_yOffset, -(MaxPosition(LEFT) - 1), MaxPosition(RIGHT) - 1, -(MaxPosition(DOWN) - 1), - MaxPosition(UP) - 1)); + Debug.Write(wxString::Format( + "stepguider calibration failure, current pos = %+d,%+d, required range = %+d..%+d,%+d..%+d\n", m_xOffset, + m_yOffset, -(MaxPosition(LEFT) - 1), MaxPosition(RIGHT) - 1, -(MaxPosition(DOWN) - 1), MaxPosition(UP) - 1)); throw ERROR_INFO("too many move errors during calibration"); } @@ -559,16 +566,16 @@ bool StepGuider::UpdateCalibrationState(const PHD_Point& currentLocation) { m_calibrationStartingLocation = currentLocation; - Debug.Write(wxString::Format("Stepguider::UpdateCalibrationstate: starting location = %.2f,%.2f\n", - currentLocation.X, currentLocation.Y)); + Debug.Write(wxString::Format( + "Stepguider::UpdateCalibrationstate: starting location = %.2f,%.2f\n", currentLocation.X, currentLocation.Y)); } wxString status0, status1; int stepsRemainingUp = MaxPosition(UP) - 1 - CurrentPosition(UP); int stepsRemainingDown = MaxPosition(DOWN) - 1 - CurrentPosition(DOWN); - int stepsRemainingRight = MaxPosition(RIGHT) - 1 - CurrentPosition(RIGHT); - int stepsRemainingLeft = MaxPosition(LEFT) - 1 - CurrentPosition(LEFT); + int stepsRemainingRight = MaxPosition(RIGHT) - 1 - CurrentPosition(RIGHT); + int stepsRemainingLeft = MaxPosition(LEFT) - 1 - CurrentPosition(LEFT); int iterRemainingUp = DIV_ROUND_UP(stepsRemainingUp, m_calibrationStepsPerIteration); int iterRemainingDown = DIV_ROUND_UP(stepsRemainingDown, m_calibrationStepsPerIteration); @@ -585,204 +592,205 @@ bool StepGuider::UpdateCalibrationState(const PHD_Point& currentLocation) bool moveUp = false; bool moveDown = false; - bool moveRight = false; - bool moveLeft = false; + bool moveRight = false; + bool moveLeft = false; double x_dist; double y_dist; switch (m_calibrationState) { - case CALIBRATION_STATE_GOTO_LOWER_RIGHT_CORNER: - if (iterRemainingDownAndRight > 0) - { - status0.Printf(_("Init Calibration: %3d"), iterRemainingDownAndRight); - moveDown = stepsRemainingDown > 0; - moveRight = stepsRemainingRight > 0; - break; - } - - Debug.Write(wxString::Format("Falling through to state AVERAGE_STARTING_LOCATION, position=(%.2f, %.2f)\n", - currentLocation.X, currentLocation.Y)); - - m_calibrationAverageSamples = 0; - m_calibrationAveragedLocation.SetXY(0.0, 0.0); - m_calibrationState = CALIBRATION_STATE_AVERAGE_STARTING_LOCATION; - // fall through - case CALIBRATION_STATE_AVERAGE_STARTING_LOCATION: - m_calibrationAverageSamples++; - m_calibrationAveragedLocation += currentLocation; - status0.Printf(_("Averaging: %3d"), m_samplesToAverage - m_calibrationAverageSamples + 1); - if (m_calibrationAverageSamples < m_samplesToAverage ) - { - break; - } - m_calibrationAveragedLocation /= m_calibrationAverageSamples; - m_calibrationStartingLocation = m_calibrationAveragedLocation; - m_calibrationIterations = 0; + case CALIBRATION_STATE_GOTO_LOWER_RIGHT_CORNER: + if (iterRemainingDownAndRight > 0) + { + status0.Printf(_("Init Calibration: %3d"), iterRemainingDownAndRight); + moveDown = stepsRemainingDown > 0; + moveRight = stepsRemainingRight > 0; + break; + } - Debug.Write(wxString::Format("Falling through to state GO_LEFT, startinglocation=(%.2f, %.2f)\n", - m_calibrationStartingLocation.X, m_calibrationStartingLocation.Y)); + Debug.Write(wxString::Format("Falling through to state AVERAGE_STARTING_LOCATION, position=(%.2f, %.2f)\n", + currentLocation.X, currentLocation.Y)); + + m_calibrationAverageSamples = 0; + m_calibrationAveragedLocation.SetXY(0.0, 0.0); + m_calibrationState = CALIBRATION_STATE_AVERAGE_STARTING_LOCATION; + // fall through + case CALIBRATION_STATE_AVERAGE_STARTING_LOCATION: + m_calibrationAverageSamples++; + m_calibrationAveragedLocation += currentLocation; + status0.Printf(_("Averaging: %3d"), m_samplesToAverage - m_calibrationAverageSamples + 1); + if (m_calibrationAverageSamples < m_samplesToAverage) + { + break; + } + m_calibrationAveragedLocation /= m_calibrationAverageSamples; + m_calibrationStartingLocation = m_calibrationAveragedLocation; + m_calibrationIterations = 0; - m_calibrationState = CALIBRATION_STATE_GO_LEFT; - // fall through - case CALIBRATION_STATE_GO_LEFT: - if (stepsRemainingLeft > 0) - { - status0.Printf(_("Left Calibration: %3d"), iterRemainingLeft); - ++m_calibrationIterations; - moveLeft = true; - x_dist = m_calibrationStartingLocation.dX(currentLocation); - y_dist = m_calibrationStartingLocation.dY(currentLocation); - CalibrationStepInfo info(this, _T("Left"), iterRemainingLeft, x_dist, y_dist, - currentLocation, m_calibrationStartingLocation.Distance(currentLocation), - status0); - GuideLog.CalibrationStep(info); - EvtServer.NotifyCalibrationStep(info); - m_calibrationDetails.raSteps.push_back(wxRealPoint(x_dist, y_dist)); // Just put "left" in "ra" steps - break; - } + Debug.Write(wxString::Format("Falling through to state GO_LEFT, startinglocation=(%.2f, %.2f)\n", + m_calibrationStartingLocation.X, m_calibrationStartingLocation.Y)); - Debug.Write(wxString::Format("Falling through to state AVERAGE_CENTER_LOCATION, position=(%.2f, %.2f)\n", - currentLocation.X, currentLocation.Y)); - - m_calibrationAverageSamples = 0; - m_calibrationAveragedLocation.SetXY(0.0, 0.0); - m_calibrationState = CALIBRATION_STATE_AVERAGE_CENTER_LOCATION; - // fall through - case CALIBRATION_STATE_AVERAGE_CENTER_LOCATION: - m_calibrationAverageSamples++; - m_calibrationAveragedLocation += currentLocation; - status0.Printf(_("Averaging: %3d"), m_samplesToAverage - m_calibrationAverageSamples + 1); - if (m_calibrationAverageSamples < m_samplesToAverage ) - { - break; - } + m_calibrationState = CALIBRATION_STATE_GO_LEFT; + // fall through + case CALIBRATION_STATE_GO_LEFT: + if (stepsRemainingLeft > 0) + { + status0.Printf(_("Left Calibration: %3d"), iterRemainingLeft); + ++m_calibrationIterations; + moveLeft = true; + x_dist = m_calibrationStartingLocation.dX(currentLocation); + y_dist = m_calibrationStartingLocation.dY(currentLocation); + CalibrationStepInfo info(this, _T("Left"), iterRemainingLeft, x_dist, y_dist, currentLocation, + m_calibrationStartingLocation.Distance(currentLocation), status0); + GuideLog.CalibrationStep(info); + EvtServer.NotifyCalibrationStep(info); + m_calibrationDetails.raSteps.push_back(wxRealPoint(x_dist, y_dist)); // Just put "left" in "ra" steps + break; + } - m_calibrationAveragedLocation /= m_calibrationAverageSamples; - m_calibration.xAngle = m_calibrationStartingLocation.Angle(m_calibrationAveragedLocation); - m_calibration.xRate = m_calibrationStartingLocation.Distance(m_calibrationAveragedLocation) / - ((MaxPosition(LEFT) - 1) + (MaxPosition(RIGHT) - 1)); + Debug.Write(wxString::Format("Falling through to state AVERAGE_CENTER_LOCATION, position=(%.2f, %.2f)\n", + currentLocation.X, currentLocation.Y)); + + m_calibrationAverageSamples = 0; + m_calibrationAveragedLocation.SetXY(0.0, 0.0); + m_calibrationState = CALIBRATION_STATE_AVERAGE_CENTER_LOCATION; + // fall through + case CALIBRATION_STATE_AVERAGE_CENTER_LOCATION: + m_calibrationAverageSamples++; + m_calibrationAveragedLocation += currentLocation; + status0.Printf(_("Averaging: %3d"), m_samplesToAverage - m_calibrationAverageSamples + 1); + if (m_calibrationAverageSamples < m_samplesToAverage) + { + break; + } - GuideLog.CalibrationDirectComplete(this, "Left", m_calibration.xAngle, m_calibration.xRate, GUIDE_PARITY_UNKNOWN); + m_calibrationAveragedLocation /= m_calibrationAverageSamples; + m_calibration.xAngle = m_calibrationStartingLocation.Angle(m_calibrationAveragedLocation); + m_calibration.xRate = m_calibrationStartingLocation.Distance(m_calibrationAveragedLocation) / + ((MaxPosition(LEFT) - 1) + (MaxPosition(RIGHT) - 1)); - Debug.Write(wxString::Format("LEFT calibration completes with angle=%.1f rate=%.2f\n", - degrees(m_calibration.xAngle), m_calibration.xRate)); - Debug.Write(wxString::Format("distance=%.2f iterations=%d\n", - m_calibrationStartingLocation.Distance(m_calibrationAveragedLocation), - m_calibrationIterations)); + GuideLog.CalibrationDirectComplete(this, "Left", m_calibration.xAngle, m_calibration.xRate, GUIDE_PARITY_UNKNOWN); - m_calibrationStartingLocation = m_calibrationAveragedLocation; - m_calibrationIterations = 0; - m_calibrationState = CALIBRATION_STATE_GO_UP; + Debug.Write(wxString::Format( + "LEFT calibration completes with angle=%.1f rate=%.2f\n", degrees(m_calibration.xAngle), m_calibration.xRate)); + Debug.Write(wxString::Format("distance=%.2f iterations=%d\n", + m_calibrationStartingLocation.Distance(m_calibrationAveragedLocation), m_calibrationIterations)); - Debug.Write(wxString::Format("Falling through to state GO_UP, startinglocation=(%.2f, %.2f)\n", - m_calibrationStartingLocation.X, m_calibrationStartingLocation.Y)); - // fall through - case CALIBRATION_STATE_GO_UP: - if (stepsRemainingUp > 0) - { - status0.Printf(_("Up Calibration: %3d"), iterRemainingUp); - ++m_calibrationIterations; - moveUp = true; - x_dist = m_calibrationStartingLocation.dX(currentLocation); - y_dist = m_calibrationStartingLocation.dY(currentLocation); - CalibrationStepInfo info(this, _T("Up"), iterRemainingUp, x_dist, y_dist, - currentLocation, m_calibrationStartingLocation.Distance(currentLocation), - status0); - GuideLog.CalibrationStep(info); - EvtServer.NotifyCalibrationStep(info); - m_calibrationDetails.decSteps.push_back(wxRealPoint(x_dist, y_dist)); // Just put "up" in "dec" steps - break; - } + m_calibrationStartingLocation = m_calibrationAveragedLocation; + m_calibrationIterations = 0; + m_calibrationState = CALIBRATION_STATE_GO_UP; - Debug.Write(wxString::Format("Falling through to state AVERAGE_ENDING_LOCATION, position=(%.2f, %.2f)\n", - currentLocation.X, currentLocation.Y)); - - m_calibrationAverageSamples = 0; - m_calibrationAveragedLocation.SetXY(0.0, 0.0); - m_calibrationState = CALIBRATION_STATE_AVERAGE_ENDING_LOCATION; - // fall through - case CALIBRATION_STATE_AVERAGE_ENDING_LOCATION: - m_calibrationAverageSamples++; - m_calibrationAveragedLocation += currentLocation; - status0.Printf(_("Averaging: %3d"), m_samplesToAverage - m_calibrationAverageSamples + 1); - if (m_calibrationAverageSamples < m_samplesToAverage ) - { - break; - } + Debug.Write(wxString::Format("Falling through to state GO_UP, startinglocation=(%.2f, %.2f)\n", + m_calibrationStartingLocation.X, m_calibrationStartingLocation.Y)); + // fall through + case CALIBRATION_STATE_GO_UP: + if (stepsRemainingUp > 0) + { + status0.Printf(_("Up Calibration: %3d"), iterRemainingUp); + ++m_calibrationIterations; + moveUp = true; + x_dist = m_calibrationStartingLocation.dX(currentLocation); + y_dist = m_calibrationStartingLocation.dY(currentLocation); + CalibrationStepInfo info(this, _T("Up"), iterRemainingUp, x_dist, y_dist, currentLocation, + m_calibrationStartingLocation.Distance(currentLocation), status0); + GuideLog.CalibrationStep(info); + EvtServer.NotifyCalibrationStep(info); + m_calibrationDetails.decSteps.push_back(wxRealPoint(x_dist, y_dist)); // Just put "up" in "dec" steps + break; + } - m_calibrationAveragedLocation /= m_calibrationAverageSamples; - m_calibration.yAngle = m_calibrationAveragedLocation.Angle(m_calibrationStartingLocation); - m_calibration.yRate = m_calibrationStartingLocation.Distance(m_calibrationAveragedLocation) / - ((MaxPosition(UP) - 1) + (MaxPosition(DOWN) - 1)); - - GuideLog.CalibrationDirectComplete(this, "Up", m_calibration.yAngle, m_calibration.yRate, GUIDE_PARITY_UNKNOWN); - - Debug.Write(wxString::Format("UP calibration completes with angle=%.1f rate=%.2f\n", - degrees(m_calibration.yAngle), m_calibration.yRate)); - Debug.Write(wxString::Format("distance=%.2f iterations=%d\n", - m_calibrationStartingLocation.Distance(m_calibrationAveragedLocation), m_calibrationIterations)); - - m_calibrationStartingLocation = m_calibrationAveragedLocation; - m_calibrationState = CALIBRATION_STATE_RECENTER; - - Debug.Write(wxString::Format("Falling through to state RECENTER, position=(%.2f, %.2f)\n", - currentLocation.X, currentLocation.Y)); - // fall through - case CALIBRATION_STATE_RECENTER: - status0.Printf(_("Re-centering: %3d"), iterRemainingDownAndRight / 2); - moveRight = (CurrentPosition(LEFT) >= m_calibrationStepsPerIteration); - moveDown = (CurrentPosition(UP) >= m_calibrationStepsPerIteration); - if (moveRight || moveDown) - { - Debug.Write(wxString::Format("CurrentPosition(LEFT)=%d CurrentPosition(UP)=%d\n", - CurrentPosition(LEFT), CurrentPosition(UP))); - break; - } - m_calibrationState = CALIBRATION_STATE_COMPLETE; - - Debug.Write(wxString::Format("Falling through to state COMPLETE, position=(%.2f, %.2f)\n", - currentLocation.X, currentLocation.Y)); - // fall through - case CALIBRATION_STATE_COMPLETE: - m_calibration.declination = UNKNOWN_DECLINATION; - m_calibration.pierSide = PIER_SIDE_UNKNOWN; - m_calibration.raGuideParity = m_calibration.decGuideParity = GUIDE_PARITY_UNKNOWN; - m_calibration.rotatorAngle = Rotator::RotatorPosition(); - m_calibration.binning = pCamera->Binning; - SetCalibration(m_calibration); - SetCalibrationDetails(m_calibrationDetails, m_calibration.xAngle, m_calibration.yAngle, pCamera->Binning); - status0 = _("Calibration complete"); - GuideLog.CalibrationComplete(this); - Debug.Write("Calibration Complete\n"); + Debug.Write(wxString::Format("Falling through to state AVERAGE_ENDING_LOCATION, position=(%.2f, %.2f)\n", + currentLocation.X, currentLocation.Y)); + + m_calibrationAverageSamples = 0; + m_calibrationAveragedLocation.SetXY(0.0, 0.0); + m_calibrationState = CALIBRATION_STATE_AVERAGE_ENDING_LOCATION; + // fall through + case CALIBRATION_STATE_AVERAGE_ENDING_LOCATION: + m_calibrationAverageSamples++; + m_calibrationAveragedLocation += currentLocation; + status0.Printf(_("Averaging: %3d"), m_samplesToAverage - m_calibrationAverageSamples + 1); + if (m_calibrationAverageSamples < m_samplesToAverage) + { break; - default: - assert(false); + } + + m_calibrationAveragedLocation /= m_calibrationAverageSamples; + m_calibration.yAngle = m_calibrationAveragedLocation.Angle(m_calibrationStartingLocation); + m_calibration.yRate = m_calibrationStartingLocation.Distance(m_calibrationAveragedLocation) / + ((MaxPosition(UP) - 1) + (MaxPosition(DOWN) - 1)); + + GuideLog.CalibrationDirectComplete(this, "Up", m_calibration.yAngle, m_calibration.yRate, GUIDE_PARITY_UNKNOWN); + + Debug.Write(wxString::Format( + "UP calibration completes with angle=%.1f rate=%.2f\n", degrees(m_calibration.yAngle), m_calibration.yRate)); + Debug.Write(wxString::Format("distance=%.2f iterations=%d\n", + m_calibrationStartingLocation.Distance(m_calibrationAveragedLocation), m_calibrationIterations)); + + m_calibrationStartingLocation = m_calibrationAveragedLocation; + m_calibrationState = CALIBRATION_STATE_RECENTER; + + Debug.Write(wxString::Format( + "Falling through to state RECENTER, position=(%.2f, %.2f)\n", currentLocation.X, currentLocation.Y)); + // fall through + case CALIBRATION_STATE_RECENTER: + status0.Printf(_("Re-centering: %3d"), iterRemainingDownAndRight / 2); + moveRight = (CurrentPosition(LEFT) >= m_calibrationStepsPerIteration); + moveDown = (CurrentPosition(UP) >= m_calibrationStepsPerIteration); + if (moveRight || moveDown) + { + Debug.Write(wxString::Format( + "CurrentPosition(LEFT)=%d CurrentPosition(UP)=%d\n", CurrentPosition(LEFT), CurrentPosition(UP))); break; + } + m_calibrationState = CALIBRATION_STATE_COMPLETE; + + Debug.Write(wxString::Format( + "Falling through to state COMPLETE, position=(%.2f, %.2f)\n", currentLocation.X, currentLocation.Y)); + // fall through + case CALIBRATION_STATE_COMPLETE: + m_calibration.declination = UNKNOWN_DECLINATION; + m_calibration.pierSide = PIER_SIDE_UNKNOWN; + m_calibration.raGuideParity = m_calibration.decGuideParity = GUIDE_PARITY_UNKNOWN; + m_calibration.rotatorAngle = Rotator::RotatorPosition(); + m_calibration.binning = pCamera->Binning; + SetCalibration(m_calibration); + SetCalibrationDetails(m_calibrationDetails, m_calibration.xAngle, m_calibration.yAngle, pCamera->Binning); + status0 = _("Calibration complete"); + GuideLog.CalibrationComplete(this); + Debug.Write("Calibration Complete\n"); + break; + default: + assert(false); + break; } if (moveUp) { assert(!moveDown); - pFrame->ScheduleAxisMove(this, UP, wxMin(stepsRemainingUp, m_calibrationStepsPerIteration), MOVEOPTS_CALIBRATION_MOVE); + pFrame->ScheduleAxisMove( + this, UP, wxMin(stepsRemainingUp, m_calibrationStepsPerIteration), MOVEOPTS_CALIBRATION_MOVE); } if (moveDown) { assert(!moveUp); - pFrame->ScheduleAxisMove(this, DOWN, wxMin(stepsRemainingDown, m_calibrationStepsPerIteration), MOVEOPTS_CALIBRATION_MOVE); + pFrame->ScheduleAxisMove( + this, DOWN, wxMin(stepsRemainingDown, m_calibrationStepsPerIteration), MOVEOPTS_CALIBRATION_MOVE); } if (moveRight) { assert(!moveLeft); - pFrame->ScheduleAxisMove(this, RIGHT, wxMin(stepsRemainingRight, m_calibrationStepsPerIteration), MOVEOPTS_CALIBRATION_MOVE); + pFrame->ScheduleAxisMove( + this, RIGHT, wxMin(stepsRemainingRight, m_calibrationStepsPerIteration), MOVEOPTS_CALIBRATION_MOVE); } if (moveLeft) { assert(!moveRight); - pFrame->ScheduleAxisMove(this, LEFT, wxMin(stepsRemainingLeft, m_calibrationStepsPerIteration), MOVEOPTS_CALIBRATION_MOVE); + pFrame->ScheduleAxisMove( + this, LEFT, wxMin(stepsRemainingLeft, m_calibrationStepsPerIteration), MOVEOPTS_CALIBRATION_MOVE); } if (m_calibrationState != CALIBRATION_STATE_COMPLETE) @@ -844,16 +852,13 @@ void StepGuider::NotifyGuidingDithered(double dx, double dy, bool mountCoords) m_avgOffset.Invalidate(); } -void StepGuider::ShowPropertyDialog() -{ -} +void StepGuider::ShowPropertyDialog() { } Mount::MOVE_RESULT StepGuider::MoveAxis(GUIDE_DIRECTION direction, int steps, unsigned int moveOptions) { MOVE_RESULT result = MOVE_OK; - Debug.Write(wxString::Format("stepguider move axis dir= %d steps= %d opts= 0x%x\n", - direction, steps, moveOptions)); + Debug.Write(wxString::Format("stepguider move axis dir= %d steps= %d opts= 0x%x\n", direction, steps, moveOptions)); try { @@ -885,18 +890,23 @@ int StepGuider::CalibrationTotDistance() // we really have no way of knowing how many pixels calibration will // require, since calibration is step-based and not pixel-based. // For now, let's just assume 25 pixels is sufficient - enum { AO_CALIBRATION_PIXELS_NEEDED = 25 }; + enum + { + AO_CALIBRATION_PIXELS_NEEDED = 25 + }; return AO_CALIBRATION_PIXELS_NEEDED; } -Mount::MOVE_RESULT StepGuider::MoveAxis(GUIDE_DIRECTION direction, int steps, unsigned int moveOptions, MoveResultInfo *moveResult) +Mount::MOVE_RESULT StepGuider::MoveAxis( + GUIDE_DIRECTION direction, int steps, unsigned int moveOptions, MoveResultInfo *moveResult) { MOVE_RESULT result = MOVE_OK; bool limitReached = false; try { - Debug.Write(wxString::Format("MoveAxis(%s, %d, %s)\n", DirectionChar(direction), steps, DumpMoveOptionBits(moveOptions))); + Debug.Write( + wxString::Format("MoveAxis(%s, %d, %s)\n", DirectionChar(direction), steps, DumpMoveOptionBits(moveOptions))); // Compute the required guide steps if (!m_guidingEnabled && (moveOptions & MOVEOPT_MANUAL) == 0) @@ -914,34 +924,35 @@ Mount::MOVE_RESULT StepGuider::MoveAxis(GUIDE_DIRECTION direction, int steps, un switch (direction) { - case UP: - yDirection = 1; - break; - case DOWN: - yDirection = -1; - break; - case RIGHT: - xDirection = 1; - break; - case LEFT: - xDirection = -1; - break; - default: - throw ERROR_INFO("StepGuider::Move(): invalid direction"); - break; + case UP: + yDirection = 1; + break; + case DOWN: + yDirection = -1; + break; + case RIGHT: + xDirection = 1; + break; + case LEFT: + xDirection = -1; + break; + default: + throw ERROR_INFO("StepGuider::Move(): invalid direction"); + break; } assert(yDirection == 0 || xDirection == 0); assert(yDirection != 0 || xDirection != 0); - Debug.Write(wxString::Format("stepping (%d, %d) + (%d, %d)\n", m_xOffset, m_yOffset, steps * xDirection, steps * yDirection)); + Debug.Write(wxString::Format( + "stepping (%d, %d) + (%d, %d)\n", m_xOffset, m_yOffset, steps * xDirection, steps * yDirection)); if (WouldHitLimit(direction, steps)) { int new_steps = MaxPosition(direction) - 1 - CurrentPosition(direction); Debug.Write(wxString::Format("StepGuider step would hit limit: truncate move to (%d, %d) + (%d, %d)\n", - m_xOffset, m_yOffset, new_steps * xDirection, new_steps * yDirection)); + m_xOffset, m_yOffset, new_steps * xDirection, new_steps * yDirection)); steps = new_steps; limitReached = true; @@ -998,7 +1009,8 @@ Mount::MOVE_RESULT StepGuider::MoveAxis(GUIDE_DIRECTION direction, int steps, un static wxString SlowBumpWarningEnabledKey() { - // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting to be per-profile + // we want the key to be under "/Confirm" so ConfirmDialog::ResetAllDontAskAgain() resets it, but we also want the setting + // to be per-profile return wxString::Format("/Confirm/%d/SlowBumpWarningEnabled", pConfig->GetCurrentProfileId()); } @@ -1009,9 +1021,7 @@ static void SuppressSlowBumpWarning(long) inline static void UpdateAOGraphPos(const wxPoint& pos, const PHD_Point& avgpos) { - PhdApp::ExecInMainThread([pos, avgpos]() { - pFrame->pStepGuiderGraph->AppendData(pos, avgpos); - }); + PhdApp::ExecInMainThread([pos, avgpos]() { pFrame->pStepGuiderGraph->AppendData(pos, avgpos); }); } Mount::MOVE_RESULT StepGuider::MoveOffset(GuiderOffset *ofs, unsigned int moveOptions) @@ -1072,12 +1082,14 @@ Mount::MOVE_RESULT StepGuider::MoveOffset(GuiderOffset *ofs, unsigned int moveOp { if (absX > m_xBumpPos2 || absY > m_yBumpPos2) { - Debug.Write(wxString::Format("FAR outside bump range, increase bump weight %.2f => %.2f\n", m_bumpStepWeight, m_bumpStepWeight + 1.0)); + Debug.Write(wxString::Format("FAR outside bump range, increase bump weight %.2f => %.2f\n", + m_bumpStepWeight, m_bumpStepWeight + 1.0)); m_bumpStepWeight += 1.0; } else { - Debug.Write(wxString::Format("outside bump range, increase bump weight %.2f => %.2f\n", m_bumpStepWeight, m_bumpStepWeight + 1. / 6.)); + Debug.Write(wxString::Format("outside bump range, increase bump weight %.2f => %.2f\n", m_bumpStepWeight, + m_bumpStepWeight + 1. / 6.)); m_bumpStepWeight += 1. / 6.; } @@ -1103,8 +1115,8 @@ Mount::MOVE_RESULT StepGuider::MoveOffset(GuiderOffset *ofs, unsigned int moveOp if (m_bumpStepWeight < 1.0) m_bumpStepWeight = 1.0; - Debug.Write(wxString::Format("back inside bump range: decrease bump weight %.2f => %.2f\n", - prior, m_bumpStepWeight)); + Debug.Write( + wxString::Format("back inside bump range: decrease bump weight %.2f => %.2f\n", prior, m_bumpStepWeight)); } if (m_bumpInProgress && !m_bumpTimeoutAlertSent) @@ -1113,10 +1125,10 @@ Mount::MOVE_RESULT StepGuider::MoveOffset(GuiderOffset *ofs, unsigned int moveOp if (now - m_bumpStartTime > BumpWarnTime) { pFrame->SuppressableAlert(SlowBumpWarningEnabledKey(), - _("A mount \"bump\" was needed to bring the AO back to its center position,\n" - "but the bump did not complete in a reasonable amount of time.\n" - "You probably need to increase the AO Bump Step setting."), - SuppressSlowBumpWarning, 0, false, wxICON_INFORMATION); + _("A mount \"bump\" was needed to bring the AO back to its center position,\n" + "but the bump did not complete in a reasonable amount of time.\n" + "You probably need to increase the AO Bump Step setting."), + SuppressSlowBumpWarning, 0, false, wxICON_INFORMATION); m_bumpTimeoutAlertSent = true; } } @@ -1139,9 +1151,7 @@ Mount::MOVE_RESULT StepGuider::MoveOffset(GuiderOffset *ofs, unsigned int moveOp { Debug.Write("Stop bumping, close enough to center -- clearing m_bumpInProgress\n"); m_bumpInProgress = false; - PhdApp::ExecInMainThread([]() { - pFrame->pStepGuiderGraph->ShowBump(PHD_Point()); - }); + PhdApp::ExecInMainThread([]() { pFrame->pStepGuiderGraph->ShowBump(PHD_Point()); }); } } } @@ -1192,7 +1202,8 @@ Mount::MOVE_RESULT StepGuider::MoveOffset(GuiderOffset *ofs, unsigned int moveOp throw ERROR_INFO("MountToCamera failed"); } - Debug.Write(wxString::Format("incremental bump (%.3f, %.3f) isValid = %d\n", bumpVec.X, bumpVec.Y, bumpVec.IsValid())); + Debug.Write( + wxString::Format("incremental bump (%.3f, %.3f) isValid = %d\n", bumpVec.X, bumpVec.Y, bumpVec.IsValid())); double weight = m_bumpStepWeight; @@ -1219,8 +1230,7 @@ Mount::MOVE_RESULT StepGuider::MoveOffset(GuiderOffset *ofs, unsigned int moveOp // limit the bump size to no larger than the guide star offset; // any larger bump could cause an over-shoot double pixels2 = xBumpSize * xBumpSize + yBumpSize * yBumpSize; - double maxDist2 = ofs->cameraOfs.X * ofs->cameraOfs.X + - ofs->cameraOfs.Y * ofs->cameraOfs.Y; + double maxDist2 = ofs->cameraOfs.X * ofs->cameraOfs.X + ofs->cameraOfs.Y * ofs->cameraOfs.Y; if (pixels2 > maxDist2) { thisBump *= sqrt(maxDist2 / pixels2); @@ -1233,9 +1243,7 @@ Mount::MOVE_RESULT StepGuider::MoveOffset(GuiderOffset *ofs, unsigned int moveOp TransformCameraCoordinatesToMountCoordinates(thisBump, tcur, false); tcur.X /= xRate(); tcur.Y /= yRate(); - PhdApp::ExecInMainThread([tcur]() { - pFrame->pStepGuiderGraph->ShowBump(tcur); - }); + PhdApp::ExecInMainThread([tcur]() { pFrame->pStepGuiderGraph->ShowBump(tcur); }); } Debug.Write(wxString::Format("Scheduling Mount bump of (%.3f, %.3f)\n", thisBump.X, thisBump.Y)); @@ -1281,16 +1289,14 @@ wxString StepGuider::GetSettingsSummary() const LoadCalibrationDetails(&calDetail); return Mount::GetSettingsSummary() + - wxString::Format("Bump percentage = %d, Bump step = %.2f, Timestamp = %s\n", - GetBumpPercentage(), - GetBumpMaxStepsPerCycle(), - calDetail.origTimestamp); + wxString::Format("Bump percentage = %d, Bump step = %.2f, Timestamp = %s\n", GetBumpPercentage(), + GetBumpMaxStepsPerCycle(), calDetail.origTimestamp); } wxString StepGuider::CalibrationSettingsSummary() const { - return wxString::Format("Calibration steps = %d, Samples to average = %d", - GetCalibrationStepsPerIteration(), GetSamplesToAverage()); + return wxString::Format( + "Calibration steps = %d, Samples to average = %d", GetCalibrationStepsPerIteration(), GetSamplesToAverage()); } wxString StepGuider::GetMountClassName() const @@ -1325,8 +1331,7 @@ void StepGuider::AdjustCalibrationForScopePointing() cal.binning = binning; Debug.Write(wxString::Format("Stepguider Cal: Binning %hu -> %hu, rates (%.3f, %.3f) -> (%.3f, %.3f)\n", - m_calibration.binning, binning, m_calibration.xRate, m_calibration.yRate, - cal.xRate, cal.yRate)); + m_calibration.binning, binning, m_calibration.xRate, m_calibration.yRate, cal.xRate, cal.yRate)); SetCalibration(cal); } @@ -1345,26 +1350,40 @@ wxPoint StepGuider::GetAoMaxPos() const const char *StepGuider::DirectionStr(GUIDE_DIRECTION d) const { // these are used internally in the guide log and event server and are not translated - switch (d) { - case NONE: return "None"; - case UP: return "Up"; - case DOWN: return "Down"; - case RIGHT: return "Right"; - case LEFT: return "Left"; - default: return "?"; + switch (d) + { + case NONE: + return "None"; + case UP: + return "Up"; + case DOWN: + return "Down"; + case RIGHT: + return "Right"; + case LEFT: + return "Left"; + default: + return "?"; } } const char *StepGuider::DirectionChar(GUIDE_DIRECTION d) const { // these are used internally in the guide log and event server and are not translated - switch (d) { - case NONE: return "-"; - case UP: return "U"; - case DOWN: return "D"; - case RIGHT: return "R"; - case LEFT: return "L"; - default: return "?"; + switch (d) + { + case NONE: + return "-"; + case UP: + return "U"; + case DOWN: + return "D"; + case RIGHT: + return "R"; + case LEFT: + return "L"; + default: + return "?"; } } @@ -1420,8 +1439,8 @@ void AOConfigDialogPane::LayoutControls(wxPanel *pParent, BrainCtrlIdMap& CtrlMa } // UI controls for properties unique to step-guider. Mount controls for guide algos are handled by MountConfigDialogPane -AOConfigDialogCtrlSet::AOConfigDialogCtrlSet(wxWindow *pParent, Mount *pStepGuider, AdvancedDialog *pAdvancedDialog, - BrainCtrlIdMap& CtrlMap) +AOConfigDialogCtrlSet::AOConfigDialogCtrlSet( + wxWindow *pParent, Mount *pStepGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) : ConfigDialogCtrlSet(pParent, pAdvancedDialog, CtrlMap) { int width; @@ -1429,46 +1448,44 @@ AOConfigDialogCtrlSet::AOConfigDialogCtrlSet(wxWindow *pParent, Mount *pStepGuid m_pStepGuider = (StepGuider *) pStepGuider; width = StringWidth(_T("000")); - m_travel = pFrame->MakeSpinCtrl(GetParentWindow(AD_AOTravel), wxID_ANY, wxEmptyString, wxDefaultPosition, - wxSize(width, -1), wxSP_ARROW_KEYS, 10, 45, 1); - AddGroup(CtrlMap, AD_AOTravel, MakeLabeledControl(AD_AOTravel, _("AO Travel"), m_travel, - _("Maximum number of steps the AO can move in each direction"))); + m_travel = pFrame->MakeSpinCtrl(GetParentWindow(AD_AOTravel), wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(width, -1), + wxSP_ARROW_KEYS, 10, 45, 1); + AddGroup(CtrlMap, AD_AOTravel, + MakeLabeledControl( + AD_AOTravel, _("AO Travel"), m_travel, _("Maximum number of steps the AO can move in each direction"))); width = StringWidth(_T("000")); wxString tip = wxString::Format(_("How many steps should be issued per calibration cycle. Default = %d, " "increase for short f/l scopes and decrease for longer f/l scopes"), - DefaultCalibrationStepsPerIteration); - m_pCalibrationStepsPerIteration = pFrame->MakeSpinCtrl(GetParentWindow(AD_szCalStepsPerIteration), wxID_ANY, - wxEmptyString, wxDefaultPosition, wxSize(width, -1), - wxSP_ARROW_KEYS, 0, 10, 3, _T("Cal_Steps")); - AddGroup(CtrlMap, AD_szCalStepsPerIteration, MakeLabeledControl(AD_szCalStepsPerIteration, _("Cal steps"), - m_pCalibrationStepsPerIteration, tip)); + DefaultCalibrationStepsPerIteration); + m_pCalibrationStepsPerIteration = pFrame->MakeSpinCtrl(GetParentWindow(AD_szCalStepsPerIteration), wxID_ANY, wxEmptyString, + wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 10, 3, _T("Cal_Steps")); + AddGroup(CtrlMap, AD_szCalStepsPerIteration, + MakeLabeledControl(AD_szCalStepsPerIteration, _("Cal steps"), m_pCalibrationStepsPerIteration, tip)); width = StringWidth(_T("000")); tip = wxString::Format(_("When calibrating, how many samples should be averaged. Default = %d, increase " - "for worse seeing and small imaging scales"), DefaultSamplesToAverage); + "for worse seeing and small imaging scales"), + DefaultSamplesToAverage); m_pSamplesToAverage = pFrame->MakeSpinCtrl(GetParentWindow(AD_szSamplesToAverage), wxID_ANY, wxEmptyString, - wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 9, 0, - _T("Samples_To_Average")); - AddGroup(CtrlMap, AD_szSamplesToAverage, MakeLabeledControl(AD_szSamplesToAverage, _("Samples to average"), - m_pSamplesToAverage, tip)); + wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 9, 0, _T("Samples_To_Average")); + AddGroup(CtrlMap, AD_szSamplesToAverage, + MakeLabeledControl(AD_szSamplesToAverage, _("Samples to average"), m_pSamplesToAverage, tip)); width = StringWidth(_T("000")); - tip = wxString::Format(_("What percentage of the AO travel can be used before bumping the mount. Default = %d"), - DefaultBumpPercentage); - m_pBumpPercentage = pFrame->MakeSpinCtrl(GetParentWindow(AD_szBumpPercentage), wxID_ANY, wxEmptyString, - wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0, 99, 0, - _T("Bump_Percentage")); - AddGroup(CtrlMap, AD_szBumpPercentage, MakeLabeledControl(AD_szBumpPercentage, _("Bump percentage"), - m_pBumpPercentage, tip)); + tip = wxString::Format( + _("What percentage of the AO travel can be used before bumping the mount. Default = %d"), DefaultBumpPercentage); + m_pBumpPercentage = pFrame->MakeSpinCtrl(GetParentWindow(AD_szBumpPercentage), wxID_ANY, wxEmptyString, wxDefaultPosition, + wxSize(width, -1), wxSP_ARROW_KEYS, 0, 99, 0, _T("Bump_Percentage")); + AddGroup( + CtrlMap, AD_szBumpPercentage, MakeLabeledControl(AD_szBumpPercentage, _("Bump percentage"), m_pBumpPercentage, tip)); width = StringWidth(_T("00.00")); tip = wxString::Format(_("How far should a mount bump move the mount between images (in AO steps). " "Default = %.2f, decrease if mount bumps cause spikes on the graph"), - DefaultBumpMaxStepsPerCycle); + DefaultBumpMaxStepsPerCycle); m_pBumpMaxStepsPerCycle = pFrame->MakeSpinCtrlDouble(GetParentWindow(AD_szBumpSteps), wxID_ANY, wxEmptyString, - wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, - 0.01, 99.99, 0.0, 0.25, _T("Bump_steps")); + wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.01, 99.99, 0.0, 0.25, _T("Bump_steps")); AddGroup(CtrlMap, AD_szBumpSteps, MakeLabeledControl(AD_szBumpSteps, _("Bump steps"), m_pBumpMaxStepsPerCycle, tip)); m_bumpOnDither = new wxCheckBox(GetParentWindow(AD_cbBumpOnDither), wxID_ANY, _("Bump on dither")); @@ -1477,10 +1494,10 @@ AOConfigDialogCtrlSet::AOConfigDialogCtrlSet(wxWindow *pParent, Mount *pStepGuid m_pClearAOCalibration = new wxCheckBox(GetParentWindow(AD_cbClearAOCalibration), wxID_ANY, _("Clear AO calibration")); m_pClearAOCalibration->Enable(m_pStepGuider && m_pStepGuider->IsConnected()); AddCtrl(CtrlMap, AD_cbClearAOCalibration, m_pClearAOCalibration, - _("Clear the current AO calibration data - calibration will be re-done when guiding is started")); + _("Clear the current AO calibration data - calibration will be re-done when guiding is started")); m_pEnableAOGuide = new wxCheckBox(GetParentWindow(AD_cbEnableAOGuiding), wxID_ANY, _("Enable AO corrections")); AddCtrl(CtrlMap, AD_cbEnableAOGuiding, m_pEnableAOGuide, - _("Keep this checked for AO guiding. Un-check to disable AO corrections and use only mount guiding")); + _("Keep this checked for AO guiding. Un-check to disable AO corrections and use only mount guiding")); m_pStepGuider->currConfigDialogCtrlSet = this; } diff --git a/src/stepguider.h b/src/stepguider.h index b3551cd23..e8411dc2e 100644 --- a/src/stepguider.h +++ b/src/stepguider.h @@ -38,8 +38,9 @@ class StepGuider; -// The AO has two representations in AdvancedDialog. One is as a 'mount' sub-class where the AO algorithms are shown in the Algos tab. The second -// is as a unique device appearing on the Other_Devices tab. So there are two distinct ConfigDialogCtrlSet classes to support these two views +// The AO has two representations in AdvancedDialog. One is as a 'mount' sub-class where the AO algorithms are shown in the +// Algos tab. The second is as a unique device appearing on the Other_Devices tab. So there are two distinct +// ConfigDialogCtrlSet classes to support these two views class AOConfigDialogCtrlSet : ConfigDialogCtrlSet { StepGuider *m_pStepGuider; @@ -53,7 +54,7 @@ class AOConfigDialogCtrlSet : ConfigDialogCtrlSet wxCheckBox *m_pEnableAOGuide; public: - AOConfigDialogCtrlSet(wxWindow *pParent, Mount *pStepGuider, AdvancedDialog* pAdvancedDialog, BrainCtrlIdMap& CtrlMap); + AOConfigDialogCtrlSet(wxWindow *pParent, Mount *pStepGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap); ~AOConfigDialogCtrlSet() {}; virtual void LoadValues(); @@ -105,13 +106,13 @@ class StepGuider : public Mount, public OnboardST4 long m_bumpStartTime; double m_bumpStepWeight; - StepInfo m_failedStep; // position info for failed ao step + StepInfo m_failedStep; // position info for failed ao step // Calibration variables - int m_calibrationStepsPerIteration; - int m_calibrationIterations; + int m_calibrationStepsPerIteration; + int m_calibrationIterations; PHD_Point m_calibrationStartingLocation; - int m_calibrationAverageSamples; + int m_calibrationAverageSamples; PHD_Point m_calibrationAveragedLocation; Calibration m_calibration; @@ -149,7 +150,7 @@ class StepGuider : public Mount, public OnboardST4 virtual bool SetSamplesToAverage(int samplesToAverage); virtual int GetBumpPercentage() const; - virtual bool SetBumpPercentage(int bumpPercentage, bool updateGraph=false); + virtual bool SetBumpPercentage(int bumpPercentage, bool updateGraph = false); virtual double GetBumpMaxStepsPerCycle() const; virtual bool SetBumpMaxStepsPerCycle(double maxBumpPerCycle); @@ -166,12 +167,16 @@ class StepGuider : public Mount, public OnboardST4 public: MountConfigDialogPane *GetConfigDialogPane(wxWindow *pParent) override; - MountConfigDialogCtrlSet *GetConfigDialogCtrlSet(wxWindow *pParent, Mount *pStepGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) override { return nullptr; }; + MountConfigDialogCtrlSet *GetConfigDialogCtrlSet( + wxWindow *pParent, Mount *pStepGuider, AdvancedDialog *pAdvancedDialog, BrainCtrlIdMap& CtrlMap) override + { + return nullptr; + }; wxString GetSettingsSummary() const override; wxString CalibrationSettingsSummary() const override; wxString GetMountClassName() const override; void AdjustCalibrationForScopePointing() override; - bool IsStepGuider() const override; + bool IsStepGuider() const override; wxPoint GetAoPos() const override; wxPoint GetAoMaxPos() const override; const char *DirectionStr(GUIDE_DIRECTION d) const override; @@ -219,13 +224,15 @@ class StepGuider : public Mount, public OnboardST4 void InitBumpPositions(); double CalibrationTime(int nCalibrationSteps); + protected: void ZeroCurrentPosition(); - enum STEP_RESULT { - STEP_OK, // step succeeded - STEP_LIMIT_REACHED, // step failed and limit was reached, must recenter - STEP_ERROR, // step failed for some other unspecified reason + enum STEP_RESULT + { + STEP_OK, // step succeeded + STEP_LIMIT_REACHED, // step failed and limit was reached, must recenter + STEP_ERROR, // step failed for some other unspecified reason }; // pure virutal functions -- these MUST be overridden by a subclass diff --git a/src/stepguider_sbigao_indi.cpp b/src/stepguider_sbigao_indi.cpp index 862921680..2cb1d4804 100644 --- a/src/stepguider_sbigao_indi.cpp +++ b/src/stepguider_sbigao_indi.cpp @@ -40,89 +40,89 @@ #ifdef STEPGUIDER_SBIGAO_INDI -#include "stepguider_sbigao_indi.h" -#include "config_indi.h" -#include +# include "stepguider_sbigao_indi.h" +# include "config_indi.h" +# include -#include -#include +# include +# include class StepGuiderSbigAoINDI : public StepGuider, public INDI::BaseClient { - private: - // INDI parts - static const int MaxDeviceInitWaitMilliSeconds = 2000; - static const int MaxDevicePropertiesWaitMilliSeconds = 5000; - long INDIport; - wxString INDIhost; - wxString INDIaoDeviceName; - bool modal; - bool ready; - void ClearStatus(); - void CheckState(); - - INumberVectorProperty *pulseGuideNS_prop; - INumber *pulseN_prop; - INumber *pulseS_prop; - INumberVectorProperty *pulseGuideWE_prop; - INumber *pulseW_prop; - INumber *pulseE_prop; - INumberVectorProperty *aoNS_prop; - INumber *aoN_prop; - INumber *aoS_prop; - INumberVectorProperty *aoWE_prop; - INumber *aoW_prop; - INumber *aoE_prop; - ISwitchVectorProperty *aoCenterSW_prop; - ISwitch *aoCenter_prop; - INDI::BaseDevice ao_device; - ITextVectorProperty *ao_driverInfo; - IText *ao_driverName; - IText *ao_driverExec; - IText *ao_driverVersion; - IText *ao_driverInterface; - - // StepGuider parts - static const int DefaultMaxSteps = 45; - wxString m_Name; - int m_maxSteps; - bool Connected {false}; - - bool Center() override; - STEP_RESULT Step(GUIDE_DIRECTION direction, int steps) override; - int MaxPosition(GUIDE_DIRECTION direction) const override; - bool SetMaxPosition(int steps) override; - bool IsAtLimit(GUIDE_DIRECTION direction, bool *isAtLimit) override; - - bool ST4HasGuideOutput() override; - bool ST4HostConnected() override; - bool ST4HasNonGuiMove() override; - bool ST4PulseGuideScope(int direction, int duration) override; - - protected: - // INDI parts - void newDevice(INDI::BaseDevice dp) override; - void removeDevice(INDI::BaseDevice dp) override; - void newProperty(INDI::Property property) override; - //void updateProperty(INDI::Property property) override; - void removeProperty(INDI::Property property) override {}; - //void newMessage(INDI::BaseDevice dp, int messageID) override; - void serverConnected() override; - void serverDisconnected(int exit_code) override; - - public: - StepGuiderSbigAoINDI(); - ~StepGuiderSbigAoINDI(); - - // StepGuider parts - bool Connect() override; - bool Disconnect() override; - bool HasNonGuiMove() override; - bool HasSetupDialog() const override; - void SetupDialog() override; - - private: - void ShowPropertyDialog() override; +private: + // INDI parts + static const int MaxDeviceInitWaitMilliSeconds = 2000; + static const int MaxDevicePropertiesWaitMilliSeconds = 5000; + long INDIport; + wxString INDIhost; + wxString INDIaoDeviceName; + bool modal; + bool ready; + void ClearStatus(); + void CheckState(); + + INumberVectorProperty *pulseGuideNS_prop; + INumber *pulseN_prop; + INumber *pulseS_prop; + INumberVectorProperty *pulseGuideWE_prop; + INumber *pulseW_prop; + INumber *pulseE_prop; + INumberVectorProperty *aoNS_prop; + INumber *aoN_prop; + INumber *aoS_prop; + INumberVectorProperty *aoWE_prop; + INumber *aoW_prop; + INumber *aoE_prop; + ISwitchVectorProperty *aoCenterSW_prop; + ISwitch *aoCenter_prop; + INDI::BaseDevice ao_device; + ITextVectorProperty *ao_driverInfo; + IText *ao_driverName; + IText *ao_driverExec; + IText *ao_driverVersion; + IText *ao_driverInterface; + + // StepGuider parts + static const int DefaultMaxSteps = 45; + wxString m_Name; + int m_maxSteps; + bool Connected { false }; + + bool Center() override; + STEP_RESULT Step(GUIDE_DIRECTION direction, int steps) override; + int MaxPosition(GUIDE_DIRECTION direction) const override; + bool SetMaxPosition(int steps) override; + bool IsAtLimit(GUIDE_DIRECTION direction, bool *isAtLimit) override; + + bool ST4HasGuideOutput() override; + bool ST4HostConnected() override; + bool ST4HasNonGuiMove() override; + bool ST4PulseGuideScope(int direction, int duration) override; + +protected: + // INDI parts + void newDevice(INDI::BaseDevice dp) override; + void removeDevice(INDI::BaseDevice dp) override; + void newProperty(INDI::Property property) override; + // void updateProperty(INDI::Property property) override; + void removeProperty(INDI::Property property) override {}; + // void newMessage(INDI::BaseDevice dp, int messageID) override; + void serverConnected() override; + void serverDisconnected(int exit_code) override; + +public: + StepGuiderSbigAoINDI(); + ~StepGuiderSbigAoINDI(); + + // StepGuider parts + bool Connect() override; + bool Disconnect() override; + bool HasNonGuiMove() override; + bool HasSetupDialog() const override; + void SetupDialog() override; + +private: + void ShowPropertyDialog() override; }; StepGuiderSbigAoINDI::StepGuiderSbigAoINDI() @@ -130,8 +130,8 @@ StepGuiderSbigAoINDI::StepGuiderSbigAoINDI() ClearStatus(); // load the values from the current profile - INDIhost = pConfig->Profile.GetString("/indi/INDIhost", _T("localhost")); - INDIport = pConfig->Profile.GetLong("/indi/INDIport", 7624); + INDIhost = pConfig->Profile.GetString("/indi/INDIhost", _T("localhost")); + INDIport = pConfig->Profile.GetLong("/indi/INDIport", 7624); INDIaoDeviceName = pConfig->Profile.GetString("/indi/INDIao", _T("SBIG CCD")); m_Name = INDIaoDeviceName; @@ -177,9 +177,9 @@ void StepGuiderSbigAoINDI::CheckState() { if (atof(ao_driverVersion->text) < 2.1) { - wxMessageBox(wxString::Format( - _("We need at least INDI driver %s version 2.1 to get AO support."), - ao_driverExec->text), _("Error")); + wxMessageBox( + wxString::Format(_("We need at least INDI driver %s version 2.1 to get AO support."), ao_driverExec->text), + _("Error")); } Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::CheckState is ready")); @@ -295,8 +295,7 @@ bool StepGuiderSbigAoINDI::Connect() setServer(INDIhost.mb_str(wxConvUTF8), INDIport); // define server to connect to. watchDevice(INDIaoDeviceName.mb_str(wxConvUTF8)); // Receive messages only for our device. - Debug.AddLine(wxString::Format("Connecting to INDI server %s on port %d, device %s", - INDIhost, INDIport, INDIaoDeviceName)); + Debug.AddLine(wxString::Format("Connecting to INDI server %s on port %d, device %s", INDIhost, INDIport, INDIaoDeviceName)); Debug.Write(wxString::Format("Waiting for 30s for [%s] to connect...\n", INDIaoDeviceName)); @@ -304,7 +303,10 @@ bool StepGuiderSbigAoINDI::Connect() struct ConnectInBg : public ConnectAoInBg { StepGuiderSbigAoINDI *ao; - ConnectInBg(StepGuiderSbigAoINDI *ao_) : ao(ao_) { } + ConnectInBg(StepGuiderSbigAoINDI *ao_) + : ao(ao_) + { + } bool Entry() { // Wait for driver to establish a device connection @@ -445,29 +447,29 @@ StepGuider::STEP_RESULT StepGuiderSbigAoINDI::Step(GUIDE_DIRECTION direction, in switch (direction) { - case NORTH: - aoN_prop->value = steps; - aoS_prop->value = 0; - sendNewNumber(aoNS_prop); - break; - case SOUTH: - aoN_prop->value = 0; - aoS_prop->value = steps; - sendNewNumber(aoNS_prop); - break; - case EAST: - aoW_prop->value = 0; - aoE_prop->value = steps; - sendNewNumber(aoWE_prop); - break; - case WEST: - aoW_prop->value = steps; - aoE_prop->value = 0; - sendNewNumber(aoWE_prop); - break; - default: - throw ERROR_INFO("StepGuiderSbigAO::step: invalid direction"); - break; + case NORTH: + aoN_prop->value = steps; + aoS_prop->value = 0; + sendNewNumber(aoNS_prop); + break; + case SOUTH: + aoN_prop->value = 0; + aoS_prop->value = steps; + sendNewNumber(aoNS_prop); + break; + case EAST: + aoW_prop->value = 0; + aoE_prop->value = steps; + sendNewNumber(aoWE_prop); + break; + case WEST: + aoW_prop->value = steps; + aoE_prop->value = 0; + sendNewNumber(aoWE_prop); + break; + default: + throw ERROR_INFO("StepGuiderSbigAO::step: invalid direction"); + break; } } catch (const wxString& Msg) @@ -501,25 +503,25 @@ bool StepGuiderSbigAoINDI::IsAtLimit(GUIDE_DIRECTION direction, bool *isAtLimit) { switch (direction) { - case NORTH: - *isAtLimit = aoNS_prop->np[0].value == aoNS_prop->np[0].max; - Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::IsAtLimit North")); - break; - case SOUTH: - *isAtLimit = aoNS_prop->np[1].value == aoNS_prop->np[1].max; - Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::IsAtLimit South")); - break; - case EAST: - *isAtLimit = aoWE_prop->np[0].value == aoWE_prop->np[0].max; - Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::IsAtLimit East")); - break; - case WEST: - *isAtLimit = aoWE_prop->np[1].value == aoWE_prop->np[1].max; - Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::IsAtLimit West")); - break; - default: - throw ERROR_INFO("StepGuiderSbigAoINDI::IsAtLimit: invalid direction"); - break; + case NORTH: + *isAtLimit = aoNS_prop->np[0].value == aoNS_prop->np[0].max; + Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::IsAtLimit North")); + break; + case SOUTH: + *isAtLimit = aoNS_prop->np[1].value == aoNS_prop->np[1].max; + Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::IsAtLimit South")); + break; + case EAST: + *isAtLimit = aoWE_prop->np[0].value == aoWE_prop->np[0].max; + Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::IsAtLimit East")); + break; + case WEST: + *isAtLimit = aoWE_prop->np[1].value == aoWE_prop->np[1].max; + Debug.AddLine(wxString::Format("StepGuiderSbigAoINDI::IsAtLimit West")); + break; + default: + throw ERROR_INFO("StepGuiderSbigAoINDI::IsAtLimit: invalid direction"); + break; } } catch (const wxString& Msg) @@ -575,29 +577,29 @@ bool StepGuiderSbigAoINDI::ST4PulseGuideScope(int direction, int duration) { switch (direction) { - case NORTH: - pulseN_prop->value = duration; - pulseS_prop->value = 0; - sendNewNumber(pulseGuideNS_prop); - break; - case SOUTH: - pulseN_prop->value = 0; - pulseS_prop->value = duration; - sendNewNumber(pulseGuideNS_prop); - break; - case EAST: - pulseW_prop->value = 0; - pulseE_prop->value = duration; - sendNewNumber(pulseGuideWE_prop); - break; - case WEST: - pulseW_prop->value = duration; - pulseE_prop->value = 0; - sendNewNumber(pulseGuideWE_prop); - break; - default: - throw ERROR_INFO("StepGuiderSbigAO::ST4PulseGuideScope: invalid direction"); - break; + case NORTH: + pulseN_prop->value = duration; + pulseS_prop->value = 0; + sendNewNumber(pulseGuideNS_prop); + break; + case SOUTH: + pulseN_prop->value = 0; + pulseS_prop->value = duration; + sendNewNumber(pulseGuideNS_prop); + break; + case EAST: + pulseW_prop->value = 0; + pulseE_prop->value = duration; + sendNewNumber(pulseGuideWE_prop); + break; + case WEST: + pulseW_prop->value = duration; + pulseE_prop->value = 0; + sendNewNumber(pulseGuideWE_prop); + break; + default: + throw ERROR_INFO("StepGuiderSbigAO::ST4PulseGuideScope: invalid direction"); + break; } } catch (const wxString& Msg) diff --git a/src/stepguider_sxao.cpp b/src/stepguider_sxao.cpp index 30c27ced0..d4b412dcf 100644 --- a/src/stepguider_sxao.cpp +++ b/src/stepguider_sxao.cpp @@ -40,14 +40,14 @@ class StepGuiderSxAO : public StepGuider { static const int DefaultMaxSteps = 45; - static const int DefaultTimeout = 1 * 1000; - static const int CenterTimeout = 45 * 1000; + static const int DefaultTimeout = 1 * 1000; + static const int CenterTimeout = 45 * 1000; wxString m_serialPortName; SerialPort *m_pSerialPort; int m_maxSteps; - public: +public: StepGuiderSxAO(); virtual ~StepGuiderSxAO(); @@ -56,7 +56,7 @@ class StepGuiderSxAO : public StepGuider bool HasNonGuiMove() override; - private: +private: bool Center() override; STEP_RESULT Step(GUIDE_DIRECTION direction, int steps) override; int MaxPosition(GUIDE_DIRECTION direction) const override; @@ -84,11 +84,11 @@ StepGuiderSxAO::StepGuiderSxAO() { m_Name = "SXV-AO"; -#ifdef USE_LOOPBACK_SERIAL +# ifdef USE_LOOPBACK_SERIAL m_pSerialPort = new SerialPortLoopback(); -#else +# else m_pSerialPort = SerialPort::SerialPortFactory(); -#endif +# endif m_serialPortName = pConfig->Profile.GetString("/stepguider/sxao/serialport", wxEmptyString); m_maxSteps = pConfig->Profile.GetInt("/stepguider/sxao/MaxSteps", DefaultMaxSteps); @@ -144,21 +144,24 @@ bool StepGuiderSxAO::Connect() if (version == 0) { - wxMessageBox(wxString::Format( - _("This AO device has firmware version %03u which means it needs to be flashed.\n" - "It is recommended to load firmware version 101 or earlier.\n" - "The SXV-AO Utility v104 or newer, available at http://www.sxccd.com/drivers-downloads,\n" - "contains the v101 firmware."), version), - _("Error")); + wxMessageBox( + wxString::Format(_("This AO device has firmware version %03u which means it needs to be flashed.\n" + "It is recommended to load firmware version 101 or earlier.\n" + "The SXV-AO Utility v104 or newer, available at http://www.sxccd.com/drivers-downloads,\n" + "contains the v101 firmware."), + version), + _("Error")); throw ERROR_INFO("StepGuiderSxAO::Connect: V000 means AO device needs a flash"); } else if (version >= 102 && version <= 107) { - bool confirmed = ConfirmDialog::Confirm(wxString::Format( - _("This version of AO firmware (%03u) limits the travel range of the AO, and may cause\n" - "calibration to fail. It is recommended to load firmware version 101 or earlier.\n" - "The SXV-AO Utility v104 or newer, available at http://www.sxccd.com/drivers-downloads,\n" - "contains the v101 firmware."), version) + "\n\n" + _("Would you like to proceed anyway?"), + bool confirmed = ConfirmDialog::Confirm( + wxString::Format(_("This version of AO firmware (%03u) limits the travel range of the AO, and may cause\n" + "calibration to fail. It is recommended to load firmware version 101 or earlier.\n" + "The SXV-AO Utility v104 or newer, available at http://www.sxccd.com/drivers-downloads,\n" + "contains the v101 firmware."), + version) + + "\n\n" + _("Would you like to proceed anyway?"), "/sx_ao_bad_firmware_ok"); if (!confirmed) @@ -188,15 +191,14 @@ void StepGuiderSxAO::ShowPropertyDialog() if (serialPorts.IsEmpty()) { - wxMessageBox(_("No serial ports found"),_("Error"), wxOK | wxICON_ERROR); + wxMessageBox(_("No serial ports found"), _("Error"), wxOK | wxICON_ERROR); throw ERROR_INFO("No Serial ports found"); } int resp = serialPorts.Index(m_serialPortName); - resp = wxGetSingleChoiceIndex(_("Select serial port"),_("Serial Port"), serialPorts, - NULL, wxDefaultCoord, wxDefaultCoord, true, wxCHOICE_WIDTH, wxCHOICE_HEIGHT, - resp); + resp = wxGetSingleChoiceIndex(_("Select serial port"), _("Serial Port"), serialPorts, NULL, wxDefaultCoord, + wxDefaultCoord, true, wxCHOICE_WIDTH, wxCHOICE_HEIGHT, resp); if (resp == -1) { Debug.Write("Serial port selection canceled\n"); @@ -279,7 +281,8 @@ bool StepGuiderSxAO::SendThenReceive(const unsigned char *pBuffer, unsigned int { throw ERROR_INFO("StepGuiderSxAO::SendThenReceive serial receive failed"); } - Debug.AddBytes(wxString::Format("StepGuiderSxAO::SendThenReceive received %c, sent", *receivedChar), pBuffer, bufferSize); + Debug.AddBytes( + wxString::Format("StepGuiderSxAO::SendThenReceive received %c, sent", *receivedChar), pBuffer, bufferSize); if (*receivedChar == 'W') // TODO: meaning { @@ -321,7 +324,8 @@ bool StepGuiderSxAO::SendShortCommand(unsigned char command, unsigned char *resp * is the command, the second is the direction and the remaining * 5 characters are a count. */ -bool StepGuiderSxAO::SendLongCommand(unsigned char command, unsigned char parameter, unsigned int count, unsigned char *response) +bool StepGuiderSxAO::SendLongCommand( + unsigned char command, unsigned char parameter, unsigned int count, unsigned char *response) { bool bError = false; @@ -334,13 +338,14 @@ bool StepGuiderSxAO::SendLongCommand(unsigned char command, unsigned char parame throw ERROR_INFO("StepGuiderSxAO::SendLongCommand invalid count"); } int bufsize = sizeof(cmdBuf); -#if defined (__WINDOWS__) +# if defined(__WINDOWS__) // MSVC-ism _snprintf returns a negative number if there is not enough space in the buffer - int ret = _snprintf((char *)&cmdBuf[0], bufsize, "%c%c%5.5d", command, parameter, count); -#else - // C99 snprintf returns the number of characters that the formatted string takes whether there was enough space in the buffer or not - int ret = snprintf((char *)&cmdBuf[0], bufsize, "%c%c%5.5d", command, parameter, count); -#endif + int ret = _snprintf((char *) &cmdBuf[0], bufsize, "%c%c%5.5d", command, parameter, count); +# else + // C99 snprintf returns the number of characters that the formatted string takes whether there was enough space in the + // buffer or not + int ret = snprintf((char *) &cmdBuf[0], bufsize, "%c%c%5.5d", command, parameter, count); +# endif if (ret < 0) { @@ -400,7 +405,7 @@ bool StepGuiderSxAO::FirmwareVersion(unsigned int *version) throw ERROR_INFO("StepGuiderSxAO::firmwareVersion: Receive failed"); } - for (int i=0; i<3; i++) + for (int i = 0; i < 3; i++) { unsigned char ch = buf[i]; @@ -494,21 +499,21 @@ StepGuider::STEP_RESULT StepGuiderSxAO::Step(GUIDE_DIRECTION direction, int step switch (direction) { - case NORTH: - parameter = 'N'; - break; - case SOUTH: - parameter = 'S'; - break; - case EAST: - parameter = 'T'; - break; - case WEST: - parameter = 'W'; - break; - default: - throw ERROR_INFO("StepGuiderSxAO::step: invalid direction"); - break; + case NORTH: + parameter = 'N'; + break; + case SOUTH: + parameter = 'S'; + break; + case EAST: + parameter = 'T'; + break; + case WEST: + parameter = 'W'; + break; + default: + throw ERROR_INFO("StepGuiderSxAO::step: invalid direction"); + break; } if (SendLongCommand(cmd, parameter, steps, &response)) @@ -526,7 +531,6 @@ StepGuider::STEP_RESULT StepGuiderSxAO::Step(GUIDE_DIRECTION direction, int step { throw ERROR_INFO("StepGuiderSxAO::step: response != cmd"); } - } catch (const wxString& Msg) { @@ -572,21 +576,21 @@ bool StepGuiderSxAO::IsAtLimit(GUIDE_DIRECTION direction, bool *isAtLimit) switch (direction) { - case NORTH: - *isAtLimit = (response & 0x1) == 0x1; - break; - case SOUTH: - *isAtLimit = (response & 0x2) == 0x2; - break; - case EAST: - *isAtLimit = (response & 0x4) == 0x4; - break; - case WEST: - *isAtLimit = (response & 0x8) == 0x8; - break; - default: - throw ERROR_INFO("StepGuiderSxAO::step: invalid direction"); - break; + case NORTH: + *isAtLimit = (response & 0x1) == 0x1; + break; + case SOUTH: + *isAtLimit = (response & 0x2) == 0x2; + break; + case EAST: + *isAtLimit = (response & 0x4) == 0x4; + break; + case WEST: + *isAtLimit = (response & 0x8) == 0x8; + break; + default: + throw ERROR_INFO("StepGuiderSxAO::step: invalid direction"); + break; } } catch (const wxString& Msg) @@ -625,21 +629,21 @@ bool StepGuiderSxAO::ST4PulseGuideScope(int direction, int duration) switch (direction) { - case NORTH: - parameter = 'N'; - break; - case SOUTH: - parameter = 'S'; - break; - case EAST: - parameter = 'T'; - break; - case WEST: - parameter = 'W'; - break; - default: - throw ERROR_INFO("StepGuiderSxAO::ST4PulseGuideScope(): invalid direction"); - break; + case NORTH: + parameter = 'N'; + break; + case SOUTH: + parameter = 'S'; + break; + case EAST: + parameter = 'T'; + break; + case WEST: + parameter = 'W'; + break; + default: + throw ERROR_INFO("StepGuiderSxAO::ST4PulseGuideScope(): invalid direction"); + break; } if (SendLongCommand(cmd, parameter, duration, &response)) diff --git a/src/stepguider_sxao_indi.cpp b/src/stepguider_sxao_indi.cpp index 4191b1640..a57b8756f 100644 --- a/src/stepguider_sxao_indi.cpp +++ b/src/stepguider_sxao_indi.cpp @@ -36,101 +36,101 @@ #ifdef STEPGUIDER_SXAO_INDI -#include "stepguider_sxao_indi.h" -#include -#include "config_indi.h" +# include "stepguider_sxao_indi.h" +# include +# include "config_indi.h" -#include -#include +# include +# include class StepGuiderSxAoINDI : public StepGuider, public INDI::BaseClient { - private: - // INDI parts - static const int MaxDeviceInitWaitMilliSeconds = 2000; - static const int MaxDevicePropertiesWaitMilliSeconds = 5000; - long INDIport; - wxString INDIhost; - wxString INDIaoDeviceName; - bool modal; - bool ready; - void ClearStatus(); - void CheckState(); - - INumberVectorProperty *pulseGuideNS_prop; - INumber *pulseN_prop; - INumber *pulseS_prop; - INumberVectorProperty *pulseGuideWE_prop; - INumber *pulseW_prop; - INumber *pulseE_prop; - INumberVectorProperty *aoNS_prop; - INumber *aoN_prop; - INumber *aoS_prop; - INumberVectorProperty *aoWE_prop; - INumber *aoW_prop; - INumber *aoE_prop; - ISwitchVectorProperty *aoCenterUnjam_prop; - ISwitch *aoCenter_prop; - ISwitch *aoUnjam_prop; - INDI::BaseDevice ao_device; - ITextVectorProperty *ao_port; - ITextVectorProperty *ao_driverInfo; - IText *ao_driverName; - IText *ao_driverExec; - IText *ao_driverVersion; - IText *ao_driverInterface; - ITextVectorProperty *ao_info; - IText *ao_firmware; - ILightVectorProperty *ao_limit; - ILight *ao_limit_north; - ILight *ao_limit_south; - ILight *ao_limit_east; - ILight *ao_limit_west; - - // StepGuider parts - static const int DefaultMaxSteps = 45; - wxString m_Name; - int m_maxSteps; - int SxAoVersion; - bool Connected {false}; - - bool Center() override; - STEP_RESULT Step(GUIDE_DIRECTION direction, int steps) override; - int MaxPosition(GUIDE_DIRECTION direction) const override; - bool SetMaxPosition(int steps) override; - bool IsAtLimit(GUIDE_DIRECTION direction, bool *isAtLimit) override; - - bool FirmwareVersion(int *version); - - bool ST4HasGuideOutput() override; - bool ST4HostConnected() override; - bool ST4HasNonGuiMove() override; - bool ST4PulseGuideScope(int direction, int duration) override; - - protected: - // INDI parts - void newDevice(INDI::BaseDevice dp) override; - void removeDevice(INDI::BaseDevice dp) override; - void newProperty(INDI::Property property) override; - void removeProperty(INDI::Property property) override {}; - //void updateProperty(INDI::Property property) override; - //void newMessage(INDI::BaseDevice dp, int messageID) override; - void serverConnected() override; - void serverDisconnected(int exit_code) override; - - public: - StepGuiderSxAoINDI(); - ~StepGuiderSxAoINDI(); - - // StepGuider parts - bool Connect() override; - bool Disconnect() override; - bool HasNonGuiMove() override; - bool HasSetupDialog() const override; - void SetupDialog() override; - - private: - void ShowPropertyDialog() override; +private: + // INDI parts + static const int MaxDeviceInitWaitMilliSeconds = 2000; + static const int MaxDevicePropertiesWaitMilliSeconds = 5000; + long INDIport; + wxString INDIhost; + wxString INDIaoDeviceName; + bool modal; + bool ready; + void ClearStatus(); + void CheckState(); + + INumberVectorProperty *pulseGuideNS_prop; + INumber *pulseN_prop; + INumber *pulseS_prop; + INumberVectorProperty *pulseGuideWE_prop; + INumber *pulseW_prop; + INumber *pulseE_prop; + INumberVectorProperty *aoNS_prop; + INumber *aoN_prop; + INumber *aoS_prop; + INumberVectorProperty *aoWE_prop; + INumber *aoW_prop; + INumber *aoE_prop; + ISwitchVectorProperty *aoCenterUnjam_prop; + ISwitch *aoCenter_prop; + ISwitch *aoUnjam_prop; + INDI::BaseDevice ao_device; + ITextVectorProperty *ao_port; + ITextVectorProperty *ao_driverInfo; + IText *ao_driverName; + IText *ao_driverExec; + IText *ao_driverVersion; + IText *ao_driverInterface; + ITextVectorProperty *ao_info; + IText *ao_firmware; + ILightVectorProperty *ao_limit; + ILight *ao_limit_north; + ILight *ao_limit_south; + ILight *ao_limit_east; + ILight *ao_limit_west; + + // StepGuider parts + static const int DefaultMaxSteps = 45; + wxString m_Name; + int m_maxSteps; + int SxAoVersion; + bool Connected { false }; + + bool Center() override; + STEP_RESULT Step(GUIDE_DIRECTION direction, int steps) override; + int MaxPosition(GUIDE_DIRECTION direction) const override; + bool SetMaxPosition(int steps) override; + bool IsAtLimit(GUIDE_DIRECTION direction, bool *isAtLimit) override; + + bool FirmwareVersion(int *version); + + bool ST4HasGuideOutput() override; + bool ST4HostConnected() override; + bool ST4HasNonGuiMove() override; + bool ST4PulseGuideScope(int direction, int duration) override; + +protected: + // INDI parts + void newDevice(INDI::BaseDevice dp) override; + void removeDevice(INDI::BaseDevice dp) override; + void newProperty(INDI::Property property) override; + void removeProperty(INDI::Property property) override {}; + // void updateProperty(INDI::Property property) override; + // void newMessage(INDI::BaseDevice dp, int messageID) override; + void serverConnected() override; + void serverDisconnected(int exit_code) override; + +public: + StepGuiderSxAoINDI(); + ~StepGuiderSxAoINDI(); + + // StepGuider parts + bool Connect() override; + bool Disconnect() override; + bool HasNonGuiMove() override; + bool HasSetupDialog() const override; + void SetupDialog() override; + +private: + void ShowPropertyDialog() override; }; StepGuiderSxAoINDI::StepGuiderSxAoINDI() @@ -138,8 +138,8 @@ StepGuiderSxAoINDI::StepGuiderSxAoINDI() ClearStatus(); // load the values from the current profile - INDIhost = pConfig->Profile.GetString("/indi/INDIhost", _T("localhost")); - INDIport = pConfig->Profile.GetLong("/indi/INDIport", 7624); + INDIhost = pConfig->Profile.GetString("/indi/INDIhost", _T("localhost")); + INDIport = pConfig->Profile.GetLong("/indi/INDIport", 7624); INDIaoDeviceName = pConfig->Profile.GetString("/indi/INDIao", _T("INDI SXV-AO-LF")); m_Name = INDIaoDeviceName; @@ -195,13 +195,15 @@ void StepGuiderSxAoINDI::CheckState() { if (atof(ao_driverVersion->text) < 1.12) { - wxMessageBox(wxString::Format( - _("We need at least INDI driver %s version 1.12 to get the Firmware version and the Limit switch states."), - ao_driverExec->text), _("Error")); + wxMessageBox( + wxString::Format( + _("We need at least INDI driver %s version 1.12 to get the Firmware version and the Limit switch states."), + ao_driverExec->text), + _("Error")); } else if (ao_firmware) { - if (! ready) + if (!ready) { if (FirmwareVersion(&SxAoVersion)) { @@ -209,11 +211,13 @@ void StepGuiderSxAoINDI::CheckState() } if (SxAoVersion == 0) { - wxMessageBox(wxString::Format( - _("This AO device has firmware version %03u which means it needs to be flashed.\n" - "The SXV-AO Utility v104 or newer, available at http://www.sxccd.com/drivers-downloads,\n" - "contains the firmware."), SxAoVersion), - _("Error")); + wxMessageBox( + wxString::Format( + _("This AO device has firmware version %03u which means it needs to be flashed.\n" + "The SXV-AO Utility v104 or newer, available at http://www.sxccd.com/drivers-downloads,\n" + "contains the firmware."), + SxAoVersion), + _("Error")); throw ERROR_INFO("StepGuiderSxAoINDI::CheckState: V000 means AO device needs a flash"); } Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::CheckState is ready, firmware %03u", SxAoVersion)); @@ -316,7 +320,7 @@ void StepGuiderSxAoINDI::newProperty(INDI::Property property) { aoCenterUnjam_prop = property.getSwitch(); aoCenter_prop = IUFindSwitch(aoCenterUnjam_prop, "CENTER"); - aoUnjam_prop = IUFindSwitch(aoCenterUnjam_prop, "UNJAM"); + aoUnjam_prop = IUFindSwitch(aoCenterUnjam_prop, "UNJAM"); } else if (strcmp(PropName, "INFO") == 0 && Proptype == INDI_TEXT) { @@ -328,8 +332,8 @@ void StepGuiderSxAoINDI::newProperty(INDI::Property property) ao_limit = property.getLight(); ao_limit_north = IUFindLight(ao_limit, "AT_LIMIT_N"); ao_limit_south = IUFindLight(ao_limit, "AT_LIMIT_S"); - ao_limit_east = IUFindLight(ao_limit, "AT_LIMIT_E"); - ao_limit_west = IUFindLight(ao_limit, "AT_LIMIT_W"); + ao_limit_east = IUFindLight(ao_limit, "AT_LIMIT_E"); + ao_limit_west = IUFindLight(ao_limit, "AT_LIMIT_W"); } CheckState(); @@ -348,14 +352,17 @@ bool StepGuiderSxAoINDI::Connect() setServer(INDIhost.mb_str(wxConvUTF8), INDIport); // define server to connect to. watchDevice(INDIaoDeviceName.mb_str(wxConvUTF8)); // Receive messages only for our device. Debug.AddLine(wxString::Format("Connecting to INDI server %s on port %d, device %s", INDIhost.mb_str(wxConvUTF8), INDIport, - INDIaoDeviceName.mb_str(wxConvUTF8))); + INDIaoDeviceName.mb_str(wxConvUTF8))); Debug.Write(wxString::Format("Waiting for 30s for [%s] to connect...\n", INDIaoDeviceName)); /* Wait in background for driver to establish a device connection */ struct ConnectInBg : public ConnectAoInBg { StepGuiderSxAoINDI *ao; - ConnectInBg(StepGuiderSxAoINDI *ao_) : ao(ao_) { } + ConnectInBg(StepGuiderSxAoINDI *ao_) + : ao(ao_) + { + } bool Entry() { // Wait for driver to establish a device connection @@ -497,29 +504,29 @@ StepGuider::STEP_RESULT StepGuiderSxAoINDI::Step(GUIDE_DIRECTION direction, int switch (direction) { - case NORTH: - aoN_prop->value = steps; - aoS_prop->value = 0; - sendNewNumber(aoNS_prop); - break; - case SOUTH: - aoN_prop->value = 0; - aoS_prop->value = steps; - sendNewNumber(aoNS_prop); - break; - case EAST: - aoW_prop->value = 0; - aoE_prop->value = steps; - sendNewNumber(aoWE_prop); - break; - case WEST: - aoW_prop->value = steps; - aoE_prop->value = 0; - sendNewNumber(aoWE_prop); - break; - default: - throw ERROR_INFO("StepGuiderSxAO::step: invalid direction"); - break; + case NORTH: + aoN_prop->value = steps; + aoS_prop->value = 0; + sendNewNumber(aoNS_prop); + break; + case SOUTH: + aoN_prop->value = 0; + aoS_prop->value = steps; + sendNewNumber(aoNS_prop); + break; + case EAST: + aoW_prop->value = 0; + aoE_prop->value = steps; + sendNewNumber(aoWE_prop); + break; + case WEST: + aoW_prop->value = steps; + aoE_prop->value = 0; + sendNewNumber(aoWE_prop); + break; + default: + throw ERROR_INFO("StepGuiderSxAO::step: invalid direction"); + break; } } catch (const wxString& Msg) @@ -553,25 +560,25 @@ bool StepGuiderSxAoINDI::IsAtLimit(GUIDE_DIRECTION direction, bool *isAtLimit) { switch (direction) { - case NORTH: - *isAtLimit = ao_limit_north->s == IPS_ALERT; - Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::IsAtLimit North")); - break; - case SOUTH: - *isAtLimit = ao_limit_south->s == IPS_ALERT; - Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::IsAtLimit South")); - break; - case EAST: - *isAtLimit = ao_limit_east->s == IPS_ALERT; - Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::IsAtLimit East")); - break; - case WEST: - *isAtLimit = ao_limit_west->s == IPS_ALERT; - Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::IsAtLimit West")); - break; - default: - throw ERROR_INFO("StepGuiderSxAoINDI::IsAtLimit: invalid direction"); - break; + case NORTH: + *isAtLimit = ao_limit_north->s == IPS_ALERT; + Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::IsAtLimit North")); + break; + case SOUTH: + *isAtLimit = ao_limit_south->s == IPS_ALERT; + Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::IsAtLimit South")); + break; + case EAST: + *isAtLimit = ao_limit_east->s == IPS_ALERT; + Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::IsAtLimit East")); + break; + case WEST: + *isAtLimit = ao_limit_west->s == IPS_ALERT; + Debug.AddLine(wxString::Format("StepGuiderSxAoINDI::IsAtLimit West")); + break; + default: + throw ERROR_INFO("StepGuiderSxAoINDI::IsAtLimit: invalid direction"); + break; } } catch (const wxString& Msg) @@ -663,29 +670,29 @@ bool StepGuiderSxAoINDI::ST4PulseGuideScope(int direction, int duration) { switch (direction) { - case NORTH: - pulseN_prop->value = duration; - pulseS_prop->value = 0; - sendNewNumber(pulseGuideNS_prop); - break; - case SOUTH: - pulseN_prop->value = 0; - pulseS_prop->value = duration; - sendNewNumber(pulseGuideNS_prop); - break; - case EAST: - pulseW_prop->value = 0; - pulseE_prop->value = duration; - sendNewNumber(pulseGuideWE_prop); - break; - case WEST: - pulseW_prop->value = duration; - pulseE_prop->value = 0; - sendNewNumber(pulseGuideWE_prop); - break; - default: - throw ERROR_INFO("StepGuiderSxAO::ST4PulseGuideScope: invalid direction"); - break; + case NORTH: + pulseN_prop->value = duration; + pulseS_prop->value = 0; + sendNewNumber(pulseGuideNS_prop); + break; + case SOUTH: + pulseN_prop->value = 0; + pulseS_prop->value = duration; + sendNewNumber(pulseGuideNS_prop); + break; + case EAST: + pulseW_prop->value = 0; + pulseE_prop->value = duration; + sendNewNumber(pulseGuideWE_prop); + break; + case WEST: + pulseW_prop->value = duration; + pulseE_prop->value = 0; + sendNewNumber(pulseGuideWE_prop); + break; + default: + throw ERROR_INFO("StepGuiderSxAO::ST4PulseGuideScope: invalid direction"); + break; } } catch (const wxString& Msg) diff --git a/src/stepguiders.h b/src/stepguiders.h index 41b05ff0a..09e62031e 100644 --- a/src/stepguiders.h +++ b/src/stepguiders.h @@ -33,31 +33,31 @@ * */ -#if defined (__WINDOWS__) -#define STEPGUIDER_SXAO +#if defined(__WINDOWS__) +# define STEPGUIDER_SXAO #endif -#if defined (__APPLE__) -#define STEPGUIDER_SXAO +#if defined(__APPLE__) +# define STEPGUIDER_SXAO #endif -#if defined (__linux__) || defined (__FreeBSD__) -#define STEPGUIDER_SXAO +#if defined(__linux__) || defined(__FreeBSD__) +# define STEPGUIDER_SXAO #endif -#if defined (GUIDE_INDI) -#define STEPGUIDER_SXAO_INDI -#define STEPGUIDER_SBIGAO_INDI +#if defined(GUIDE_INDI) +# define STEPGUIDER_SXAO_INDI +# define STEPGUIDER_SBIGAO_INDI #endif #ifndef STEPGUIDERS_H_INCLUDED -#define STEPGUIDERS_H_INCLUDED +# define STEPGUIDERS_H_INCLUDED -#define STEPGUIDER_SIMULATOR +# define STEPGUIDER_SIMULATOR -#include "stepguider.h" -#include "stepguider_sxao.h" -#include "stepguider_sxao_indi.h" -#include "stepguider_sbigao_indi.h" +# include "stepguider.h" +# include "stepguider_sxao.h" +# include "stepguider_sxao_indi.h" +# include "stepguider_sbigao_indi.h" #endif /* STEPGUIDERS_H_INCLUDED */ diff --git a/src/target.cpp b/src/target.cpp index a0c7330ec..2567158a7 100644 --- a/src/target.cpp +++ b/src/target.cpp @@ -49,10 +49,10 @@ wxBEGIN_EVENT_TABLE(TargetWindow, wxWindow) wxEND_EVENT_TABLE(); // clang-format on -TargetWindow::TargetWindow(wxWindow *parent) : - wxWindow(parent,wxID_ANY,wxDefaultPosition,wxDefaultSize, 0,_("Target")) +TargetWindow::TargetWindow(wxWindow *parent) + : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, _("Target")) { - //SetFont(wxFont(8,wxFONTFAMILY_DEFAULT,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL)); + // SetFont(wxFont(8,wxFONTFAMILY_DEFAULT,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL)); SetBackgroundColour(*wxBLACK); m_visible = false; @@ -64,7 +64,8 @@ TargetWindow::TargetWindow(wxWindow *parent) : pMainSizer->Add(pLeftSizer); wxString label = wxString::Format("%3d", m_pClient->m_length); - m_lengthButton = new OptionsButton(this,BUTTON_GRAPH_LENGTH,label,wxDefaultPosition,wxSize(40/*80*/,-1),wxALIGN_CENTER_HORIZONTAL); + m_lengthButton = new OptionsButton( + this, BUTTON_GRAPH_LENGTH, label, wxDefaultPosition, wxSize(40 /*80*/, -1), wxALIGN_CENTER_HORIZONTAL); m_lengthButton->SetToolTip(_("Select the number of frames of history to display")); wxBoxSizer *pZoomSizer = new wxBoxSizer(wxHORIZONTAL); @@ -78,7 +79,7 @@ TargetWindow::TargetWindow(wxWindow *parent) : pZoomSizer->Add(zoomInButton, wxSizerFlags(1).Expand()); pZoomSizer->Add(zoomOutButton, wxSizerFlags(1).Expand()); - wxButton *clearButton = new wxButton(this,BUTTON_GRAPH_CLEAR,_("Clear"),wxDefaultPosition,wxSize(80,-1)); + wxButton *clearButton = new wxButton(this, BUTTON_GRAPH_CLEAR, _("Clear"), wxDefaultPosition, wxSize(80, -1)); clearButton->SetToolTip(_("Clear graph data")); m_enableRefCircle = new wxCheckBox(this, TARGET_ENABLE_REF_CIRCLE, _("Reference Circle")); @@ -96,7 +97,8 @@ TargetWindow::TargetWindow(wxWindow *parent) : int w, h; GetTextExtent(_T("88.8"), &w, &h); - m_refCircleRadius = pFrame->MakeSpinCtrlDouble(this, TARGET_REF_CIRCLE_RADIUS, wxEmptyString, wxDefaultPosition, wxSize(w, -1)); + m_refCircleRadius = + pFrame->MakeSpinCtrlDouble(this, TARGET_REF_CIRCLE_RADIUS, wxEmptyString, wxDefaultPosition, wxSize(w, -1)); m_refCircleRadius->SetToolTip(_("Reference circle radius")); m_refCircleRadius->SetRange(0.1, 10.0); m_refCircleRadius->SetIncrement(0.1); @@ -107,11 +109,11 @@ TargetWindow::TargetWindow(wxWindow *parent) : pLeftSizer->Add(m_lengthButton, wxSizerFlags().Center().Border(wxTOP | wxRIGHT | wxLEFT, 5).Expand()); pLeftSizer->Add(pZoomSizer, wxSizerFlags().Border(wxRIGHT | wxLEFT, 5).Expand()); - pLeftSizer->Add(clearButton, wxSizerFlags().Border(wxRIGHT | wxLEFT,5).Expand()); + pLeftSizer->Add(clearButton, wxSizerFlags().Border(wxRIGHT | wxLEFT, 5).Expand()); pLeftSizer->Add(m_enableRefCircle, wxSizerFlags().Center().Border(wxALL, 3).Expand()); pLeftSizer->Add(sizer1, wxSizerFlags().Center().Border(wxRIGHT | wxLEFT, 5).Expand()); - pMainSizer->Add(m_pClient, wxSizerFlags().Border(wxALL,3).Expand().Proportion(1)); + pMainSizer->Add(m_pClient, wxSizerFlags().Border(wxALL, 3).Expand().Proportion(1)); SetSizer(pMainSizer); pMainSizer->SetSizeHints(this); @@ -164,8 +166,7 @@ void TargetWindow::OnButtonLength(wxCommandEvent& WXUNUSED(evt)) break; } - PopupMenu(menu, m_lengthButton->GetPosition().x, - m_lengthButton->GetPosition().y + m_lengthButton->GetSize().GetHeight()); + PopupMenu(menu, m_lengthButton->GetPosition().x, m_lengthButton->GetPosition().y + m_lengthButton->GetSize().GetHeight()); delete menu; } @@ -233,8 +234,8 @@ wxBEGIN_EVENT_TABLE(TargetClient, wxWindow) wxEND_EVENT_TABLE(); // clang-format on -TargetClient::TargetClient(wxWindow *parent) : - wxWindow(parent, wxID_ANY, wxDefaultPosition, wxSize(201,201), wxFULL_REPAINT_ON_RESIZE ) +TargetClient::TargetClient(wxWindow *parent) + : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxSize(201, 201), wxFULL_REPAINT_ON_RESIZE) { SetBackgroundStyle(wxBG_STYLE_PAINT); @@ -249,16 +250,14 @@ TargetClient::TargetClient(wxWindow *parent) : m_zoom = MIN_ZOOM; } -TargetClient::~TargetClient(void) -{ -} +TargetClient::~TargetClient(void) { } void TargetClient::AppendData(const GuideStepInfo& step) { - memmove(&m_history, &m_history[1], sizeof(m_history[0])*(m_maxHistorySize-1)); + memmove(&m_history, &m_history[1], sizeof(m_history[0]) * (m_maxHistorySize - 1)); - m_history[m_maxHistorySize-1].ra = step.mountOffset.X; - m_history[m_maxHistorySize-1].dec = step.mountOffset.Y; + m_history[m_maxHistorySize - 1].ra = step.mountOffset.X; + m_history[m_maxHistorySize - 1].dec = step.mountOffset.Y; if (m_nItems < m_maxHistorySize) { @@ -271,20 +270,20 @@ void TargetClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) wxAutoBufferedPaintDC dc(this); dc.SetBackground(*wxBLACK_BRUSH); - //dc.SetBackground(wxColour(10,0,0)); + // dc.SetBackground(wxColour(10,0,0)); dc.Clear(); - wxColour Grey(128,128,128); - wxPen GreySolidPen = wxPen(Grey,1, wxPENSTYLE_SOLID); - wxPen GreyDashPen = wxPen(Grey,1, wxPENSTYLE_DOT); + wxColour Grey(128, 128, 128); + wxPen GreySolidPen = wxPen(Grey, 1, wxPENSTYLE_SOLID); + wxPen GreyDashPen = wxPen(Grey, 1, wxPENSTYLE_DOT); - dc.SetTextForeground(wxColour(200,200,200)); - dc.SetFont(wxFont(8,wxFONTFAMILY_DEFAULT,wxFONTSTYLE_NORMAL,wxFONTWEIGHT_NORMAL)); + dc.SetTextForeground(wxColour(200, 200, 200)); + dc.SetFont(wxFont(8, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL)); dc.SetPen(GreySolidPen); dc.SetBrush(*wxTRANSPARENT_BRUSH); wxSize size = GetClientSize(); - wxPoint center(size.x/2, size.y/2); + wxPoint center(size.x / 2, size.y / 2); int radius_max = ((size.x < size.y ? size.x : size.y) - 6) / 2; int leftEdge = center.x - radius_max; @@ -300,29 +299,29 @@ void TargetClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) // Draw reference circle if (m_refCircleRadius > 0.0) { - wxDCBrushChanger b(dc, wxBrush(wxColor(55,55,55))); + wxDCBrushChanger b(dc, wxBrush(wxColor(55, 55, 55))); wxDCPenChanger p(dc, *wxTRANSPARENT_PEN); dc.DrawCircle(center, m_refCircleRadius * scale * m_zoom / sampling); } // Draw circles - for (int i = 1 ; i <= 4 ; i++) + for (int i = 1; i <= 4; i++) { int rr = radius_max * i / 4; dc.DrawCircle(center, rr); - wxString l = wxString::Format(_T("%g%s"), i/2.0 / m_zoom, sampling != 1.0 ? "''" : ""); + wxString l = wxString::Format(_T("%g%s"), i / 2.0 / m_zoom, sampling != 1.0 ? "''" : ""); wxSize sl = dc.GetTextExtent(l); dc.DrawText(l, center.x - sl.x - 1, center.y - rr - sl.y); } // Draw axes - dc.DrawLine(3, center.y , size.x - 3, center.y); + dc.DrawLine(3, center.y, size.x - 3, center.y); dc.DrawLine(center.x, 3, center.x, size.y - 3); double r = radius_max / (2 / m_zoom); int g = size.x / 100; - for (double x = 0 ; x < size.x ; x += r/4) + for (double x = 0; x < size.x; x += r / 4) { if (x != radius_max && x != r) { @@ -330,7 +329,7 @@ void TargetClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) dc.DrawLine(center.x - x, center.y - g, center.x - x, center.y + g); } } - for (double y = 0 ; y < size.y ; y += r/4) + for (double y = 0; y < size.y; y += r / 4) { if (y != radius_max && y != r) { @@ -365,15 +364,15 @@ void TargetClient::OnPaint(wxPaintEvent& WXUNUSED(evt)) GuideParity raParity = pMount ? pMount->RAParity() : GUIDE_PARITY_UNKNOWN; if (raParity == GUIDE_PARITY_EVEN) - dc.DrawText(_("SkyE"), size.x - d_width * 5, center.y + 5); // sky E = mount E + dc.DrawText(_("SkyE"), size.x - d_width * 5, center.y + 5); // sky E = mount E else if (raParity == GUIDE_PARITY_ODD) - dc.DrawText(_("SkyE"), leftEdge, center.y + 5); // sky E = mount W + dc.DrawText(_("SkyE"), leftEdge, center.y + 5); // sky E = mount W GuideParity decParity = pMount ? pMount->DecParity() : GUIDE_PARITY_UNKNOWN; if (decParity == GUIDE_PARITY_EVEN) - dc.DrawText(_("SkyN"), center.x + 5, center.y + 5 - radius_max); // sky N = mount N + dc.DrawText(_("SkyN"), center.x + 5, center.y + 5 - radius_max); // sky N = mount N else if (decParity == GUIDE_PARITY_ODD) - dc.DrawText(_("SkyN"), center.x + 5, center.y + 5 + radius_max); // sky N = mount S + dc.DrawText(_("SkyN"), center.x + 5, center.y + 5 + radius_max); // sky N = mount S dc.SetPen(wxPen(wxColour(127, 127, 255), 1, wxPENSTYLE_SOLID)); for (unsigned int i = startPoint; i < m_maxHistorySize; i++) diff --git a/src/target.h b/src/target.h index d95ebc222..848d51174 100644 --- a/src/target.h +++ b/src/target.h @@ -54,8 +54,8 @@ class TargetClient : public wxWindow double dec; } m_history[m_maxHistorySize]; - unsigned int m_nItems; // # of items in the history - unsigned int m_length; // # of items to display + unsigned int m_nItems; // # of items in the history + unsigned int m_length; // # of items to display double m_zoom; double m_refCircleRadius; diff --git a/src/testguide.cpp b/src/testguide.cpp index e856d726a..0953b2f6d 100644 --- a/src/testguide.cpp +++ b/src/testguide.cpp @@ -42,6 +42,7 @@ class TestGuideDialog : public wxDialog wxChoice *ditherTypeChoice; wxSpinCtrlDouble *ditherScaleSpinCtrl; wxCheckBox *raOnlyCheckBox; + public: TestGuideDialog(); ~TestGuideDialog(); @@ -102,11 +103,13 @@ wxSizer *TestGuideDialog::InitMountControls() wxButton *btn = new wxButton(this, ID_RESET, _("Reset")); sz1->Add(btn, wxSizerFlags().Left().Border(wxRIGHT, 10).Align(wxALIGN_CENTER_VERTICAL)); - btn->SetToolTip(_("Reset the manual guide pulse duration to the default value. The default value is the calibration step size.")); + btn->SetToolTip( + _("Reset the manual guide pulse duration to the default value. The default value is the calibration step size.")); wxSizer *sz2 = new wxBoxSizer(wxHORIZONTAL); - sz2->Add(new wxStaticText(this, wxID_ANY, _("Dither")), wxSizerFlags().Right().Border(wxRIGHT, 5).Align(wxALIGN_CENTER_VERTICAL)); + sz2->Add(new wxStaticText(this, wxID_ANY, _("Dither")), + wxSizerFlags().Right().Border(wxRIGHT, 5).Align(wxALIGN_CENTER_VERTICAL)); wxArrayString choices; choices.Add(_("MOVE1 (+/- 0.5)")); choices.Add(_("MOVE2 (+/- 1.0)")); @@ -115,24 +118,30 @@ wxSizer *TestGuideDialog::InitMountControls() choices.Add(_("MOVE5 (+/- 5.0)")); ditherTypeChoice = new wxChoice(this, ID_DITHERTYPE, wxDefaultPosition, wxDefaultSize, choices); ditherTypeChoice->Select(pConfig->Profile.GetInt("/ManualGuide/DitherType", 4) - 1); - ditherTypeChoice->SetToolTip(_("Select the dither amount type. Imaging applications have the option of sending each of these dither amounts to PHD.")); + ditherTypeChoice->SetToolTip(_( + "Select the dither amount type. Imaging applications have the option of sending each of these dither amounts to PHD.")); sz2->Add(ditherTypeChoice, wxSizerFlags().Left().Border(wxRIGHT, 10).Align(wxALIGN_CENTER_VERTICAL)); - sz2->Add(new wxStaticText(this, wxID_ANY, _("Scale")), wxSizerFlags().Right().Border(wxRIGHT, 5).Align(wxALIGN_CENTER_VERTICAL)); + sz2->Add( + new wxStaticText(this, wxID_ANY, _("Scale")), wxSizerFlags().Right().Border(wxRIGHT, 5).Align(wxALIGN_CENTER_VERTICAL)); ditherScaleSpinCtrl = pFrame->MakeSpinCtrlDouble(this, ID_DITHERSCALE, wxEmptyString, wxDefaultPosition, wxSize(StringWidth(GetParent(), "000.0"), -1), wxSP_ARROW_KEYS | wxALIGN_RIGHT, 0.1, 100.0, 1.0, 1.0); ditherScaleSpinCtrl->SetDigits(1); ditherScaleSpinCtrl->SetValue(pFrame->GetDitherScaleFactor()); - ditherScaleSpinCtrl->SetToolTip(_("Scale factor for dithering. The dither amount type is multiplied by this value to get the actual dither amount. Changing the value here affects both manual dithering and dithering from imaging applications connected to PHD.")); + ditherScaleSpinCtrl->SetToolTip( + _("Scale factor for dithering. The dither amount type is multiplied by this value to get the actual dither amount. " + "Changing the value here affects both manual dithering and dithering from imaging applications connected to PHD.")); sz2->Add(ditherScaleSpinCtrl, wxSizerFlags().Left().Border(wxRIGHT, 10).Align(wxALIGN_CENTER_VERTICAL)); raOnlyCheckBox = new wxCheckBox(this, ID_RAONLY, _("RA Only")); sz2->Add(raOnlyCheckBox, wxSizerFlags().Left().Border(wxRIGHT, 10).Align(wxALIGN_CENTER_VERTICAL)); raOnlyCheckBox->SetValue(pFrame->GetDitherRaOnly()); - raOnlyCheckBox->SetToolTip(_("Dither on RA axis only. Changing the value here affects both manual dithering and dithering from imaging applications connected to PHD.")); + raOnlyCheckBox->SetToolTip(_("Dither on RA axis only. Changing the value here affects both manual dithering and dithering " + "from imaging applications connected to PHD.")); btn = new wxButton(this, ID_DITHER, _("Dither")); - btn->SetToolTip(_("Move the guider lock position a random amount on each axis, up to the maximum value determined by the dither type and the dither scale factor.")); + btn->SetToolTip(_("Move the guider lock position a random amount on each axis, up to the maximum value determined by the " + "dither type and the dither scale factor.")); sz2->Add(btn, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); wxSizer *sz3 = new wxBoxSizer(wxVERTICAL); @@ -144,14 +153,14 @@ wxSizer *TestGuideDialog::InitMountControls() return sz3; } -TestGuideDialog::TestGuideDialog() : - wxDialog(pFrame, wxID_ANY, _("Manual Guide"), wxPoint(-1,-1), wxSize(300,300)) +TestGuideDialog::TestGuideDialog() + : wxDialog(pFrame, wxID_ANY, _("Manual Guide"), wxPoint(-1, -1), wxSize(300, 300)) { wxBoxSizer *pOuterSizer = new wxBoxSizer(wxVERTICAL); wxStaticBoxSizer *pWrapperSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Mount")); - wxGridSizer *sizer = new wxGridSizer(3,3,0,0); - static wxString AoLabels[] = {_("Up"), _("Down"), _("Right"), _("Left") }; - static wxString ScopeLabels[] = {_("North"), _("South"), _("East"), _("West") }; + wxGridSizer *sizer = new wxGridSizer(3, 3, 0, 0); + static wxString AoLabels[] = { _("Up"), _("Down"), _("Right"), _("Left") }; + static wxString ScopeLabels[] = { _("North"), _("South"), _("East"), _("West") }; bool usingAo = pSecondaryMount && pSecondaryMount->IsConnected(); @@ -169,51 +178,51 @@ TestGuideDialog::TestGuideDialog() : // Build the buttons for the primary mount - NButton1 = new wxButton(this, MGUIDE1_UP, pLabels[0], wxPoint(-1,-1),wxSize(-1,-1)); - SButton1 = new wxButton(this, MGUIDE1_DOWN, pLabels[1], wxPoint(-1,-1),wxSize(-1,-1)); - EButton1 = new wxButton(this, MGUIDE1_RIGHT, pLabels[2], wxPoint(-1,-1),wxSize(-1,-1)); - WButton1 = new wxButton(this, MGUIDE1_LEFT, pLabels[3], wxPoint(-1,-1),wxSize(-1,-1)); + NButton1 = new wxButton(this, MGUIDE1_UP, pLabels[0], wxPoint(-1, -1), wxSize(-1, -1)); + SButton1 = new wxButton(this, MGUIDE1_DOWN, pLabels[1], wxPoint(-1, -1), wxSize(-1, -1)); + EButton1 = new wxButton(this, MGUIDE1_RIGHT, pLabels[2], wxPoint(-1, -1), wxSize(-1, -1)); + WButton1 = new wxButton(this, MGUIDE1_LEFT, pLabels[3], wxPoint(-1, -1), wxSize(-1, -1)); sizer->AddStretchSpacer(); - sizer->Add(NButton1,wxSizerFlags().Expand().Border(wxALL,6)); + sizer->Add(NButton1, wxSizerFlags().Expand().Border(wxALL, 6)); sizer->AddStretchSpacer(); - sizer->Add(WButton1,wxSizerFlags().Expand().Border(wxALL,6)); + sizer->Add(WButton1, wxSizerFlags().Expand().Border(wxALL, 6)); sizer->AddStretchSpacer(); - sizer->Add(EButton1,wxSizerFlags().Expand().Border(wxALL,6)); + sizer->Add(EButton1, wxSizerFlags().Expand().Border(wxALL, 6)); sizer->AddStretchSpacer(); - sizer->Add(SButton1,wxSizerFlags().Expand().Border(wxALL,6)); + sizer->Add(SButton1, wxSizerFlags().Expand().Border(wxALL, 6)); pWrapperSizer->Add(sizer, wxSizerFlags().Center()); if (!usingAo) { pWrapperSizer->Add(InitMountControls()); } - pOuterSizer->Add(pWrapperSizer,wxSizerFlags().Border(wxALL,3).Center().Expand()); + pOuterSizer->Add(pWrapperSizer, wxSizerFlags().Border(wxALL, 3).Center().Expand()); if (usingAo) { pWrapperSizer = new wxStaticBoxSizer(wxVERTICAL, this, _("Mount")); - sizer = new wxGridSizer(3,3,0,0); + sizer = new wxGridSizer(3, 3, 0, 0); pLabels = ScopeLabels; - NButton2 = new wxButton(this, MGUIDE2_UP, pLabels[0], wxPoint(-1,-1),wxSize(-1,-1)); - SButton2 = new wxButton(this, MGUIDE2_DOWN, pLabels[1], wxPoint(-1,-1),wxSize(-1,-1)); - EButton2 = new wxButton(this, MGUIDE2_RIGHT, pLabels[2], wxPoint(-1,-1),wxSize(-1,-1)); - WButton2 = new wxButton(this, MGUIDE2_LEFT, pLabels[3], wxPoint(-1,-1),wxSize(-1,-1)); + NButton2 = new wxButton(this, MGUIDE2_UP, pLabels[0], wxPoint(-1, -1), wxSize(-1, -1)); + SButton2 = new wxButton(this, MGUIDE2_DOWN, pLabels[1], wxPoint(-1, -1), wxSize(-1, -1)); + EButton2 = new wxButton(this, MGUIDE2_RIGHT, pLabels[2], wxPoint(-1, -1), wxSize(-1, -1)); + WButton2 = new wxButton(this, MGUIDE2_LEFT, pLabels[3], wxPoint(-1, -1), wxSize(-1, -1)); sizer->AddStretchSpacer(); - sizer->Add(NButton2,wxSizerFlags().Expand().Border(wxALL,6)); + sizer->Add(NButton2, wxSizerFlags().Expand().Border(wxALL, 6)); sizer->AddStretchSpacer(); - sizer->Add(WButton2,wxSizerFlags().Expand().Border(wxALL,6)); + sizer->Add(WButton2, wxSizerFlags().Expand().Border(wxALL, 6)); sizer->AddStretchSpacer(); - sizer->Add(EButton2,wxSizerFlags().Expand().Border(wxALL,6)); + sizer->Add(EButton2, wxSizerFlags().Expand().Border(wxALL, 6)); sizer->AddStretchSpacer(); - sizer->Add(SButton2,wxSizerFlags().Expand().Border(wxALL,6)); + sizer->Add(SButton2, wxSizerFlags().Expand().Border(wxALL, 6)); pWrapperSizer->Add(sizer, wxSizerFlags().Center()); pWrapperSizer->Add(InitMountControls()); - pOuterSizer->Add(pWrapperSizer,wxSizerFlags().Border(wxALL,3).Center().Expand()); + pOuterSizer->Add(pWrapperSizer, wxSizerFlags().Border(wxALL, 3).Center().Expand()); } pOuterSizer->AddSpacer(30); @@ -279,36 +288,36 @@ inline static void ManualMove(Mount *mount, GUIDE_DIRECTION dir, int dur) } } -void TestGuideDialog::OnButton(wxCommandEvent &evt) +void TestGuideDialog::OnButton(wxCommandEvent& evt) { int duration = (int) floor(pulseDurationSpinCtrl->GetValue()); switch (evt.GetId()) { - case MGUIDE1_UP: - ManualMove(pMount, UP, duration); - break; - case MGUIDE1_DOWN: - ManualMove(pMount, DOWN, duration); - break; - case MGUIDE1_RIGHT: - ManualMove(pMount, RIGHT, duration); - break; - case MGUIDE1_LEFT: - ManualMove(pMount, LEFT, duration); - break; - case MGUIDE2_UP: - ManualMove(pSecondaryMount, UP, duration); - break; - case MGUIDE2_DOWN: - ManualMove(pSecondaryMount, DOWN, duration); - break; - case MGUIDE2_RIGHT: - ManualMove(pSecondaryMount, RIGHT, duration); - break; - case MGUIDE2_LEFT: - ManualMove(pSecondaryMount, LEFT, duration); - break; + case MGUIDE1_UP: + ManualMove(pMount, UP, duration); + break; + case MGUIDE1_DOWN: + ManualMove(pMount, DOWN, duration); + break; + case MGUIDE1_RIGHT: + ManualMove(pMount, RIGHT, duration); + break; + case MGUIDE1_LEFT: + ManualMove(pMount, LEFT, duration); + break; + case MGUIDE2_UP: + ManualMove(pSecondaryMount, UP, duration); + break; + case MGUIDE2_DOWN: + ManualMove(pSecondaryMount, DOWN, duration); + break; + case MGUIDE2_RIGHT: + ManualMove(pSecondaryMount, RIGHT, duration); + break; + case MGUIDE2_LEFT: + ManualMove(pSecondaryMount, LEFT, duration); + break; } } diff --git a/src/testguide.h b/src/testguide.h index 0c321d885..5dd6b6662 100644 --- a/src/testguide.h +++ b/src/testguide.h @@ -43,4 +43,4 @@ class TestGuide static void ManualGuideUpdateControls(); }; -#endif //TESTGUIDE_H_INCLUDED +#endif // TESTGUIDE_H_INCLUDED diff --git a/src/usImage.cpp b/src/usImage.cpp index 414d537ef..5dd5ed840 100644 --- a/src/usImage.cpp +++ b/src/usImage.cpp @@ -37,65 +37,73 @@ #include -class HistogramBuilder { - public: - int *histo; - unsigned short MinADU, MaxADU; - int pixCount; - - HistogramBuilder() { - histo = new int[65536]; - MinADU = 0; - MaxADU = 0; - pixCount = 0; - } +class HistogramBuilder +{ +public: + int *histo; + unsigned short MinADU, MaxADU; + int pixCount; - ~HistogramBuilder() { - delete[] histo; - } + HistogramBuilder() + { + histo = new int[65536]; + MinADU = 0; + MaxADU = 0; + pixCount = 0; + } - unsigned short median() const - { - int pixelLeft = pixCount / 2; + ~HistogramBuilder() { delete[] histo; } - for (int i = MinADU; i < MaxADU; ++i) { - if (histo[i] > pixelLeft) { - return i; - } - pixelLeft -= histo[i]; + unsigned short median() const + { + int pixelLeft = pixCount / 2; + + for (int i = MinADU; i < MaxADU; ++i) + { + if (histo[i] > pixelLeft) + { + return i; } - return MaxADU; + pixelLeft -= histo[i]; } + return MaxADU; + } - void scan(const unsigned short *t, int len) + void scan(const unsigned short *t, int len) + { + if (pixCount == 0) { - if (pixCount == 0) { - unsigned short v = t[0]; - // Initialization - MinADU = t[0]; - MaxADU = t[0]; - histo[t[0]] = 0; - } + unsigned short v = t[0]; + // Initialization + MinADU = t[0]; + MaxADU = t[0]; + histo[t[0]] = 0; + } - for (int i = 0; i < len; ++i) { - unsigned short v = t[i]; - if (v < MinADU) { - for (int k = v; k < MinADU; ++k) { - histo[k] = 0; - } - MinADU = v; + for (int i = 0; i < len; ++i) + { + unsigned short v = t[i]; + if (v < MinADU) + { + for (int k = v; k < MinADU; ++k) + { + histo[k] = 0; } - if (v > MaxADU) { - for (int k = MaxADU + 1; k <= v; ++k) { - histo[k] = 0; - } - MaxADU = v; + MinADU = v; + } + if (v > MaxADU) + { + for (int k = MaxADU + 1; k <= v; ++k) + { + histo[k] = 0; } - histo[v]++; + MaxADU = v; } - - pixCount += len; + histo[v]++; } + + pixCount += len; + } }; bool usImage::Init(const wxSize& size) @@ -141,8 +149,10 @@ void usImage::CalcStats() if (!ImageData || !NPixels) return; - MinADU = 65535; MaxADU = 0; - FiltMin = 65535; FiltMax = 0; + MinADU = 65535; + MaxADU = 0; + FiltMin = 65535; + FiltMax = 0; if (Subframe.IsEmpty()) { @@ -162,8 +172,10 @@ void usImage::CalcStats() for (unsigned int i = 0; i < NPixels; i++) { unsigned short d = *src++; - if (d < FiltMin) FiltMin = d; - if (d > FiltMax) FiltMax = d; + if (d < FiltMin) + FiltMin = d; + if (d > FiltMax) + FiltMax = d; } delete[] tmpdata; @@ -202,8 +214,10 @@ void usImage::CalcStats() for (unsigned int i = 0; i < pixcnt; i++) { unsigned short d = *src++; - if (d < FiltMin) FiltMin = d; - if (d > FiltMax) FiltMax = d; + if (d < FiltMin) + FiltMin = d; + if (d > FiltMax) + FiltMax = d; } delete[] dst; @@ -215,10 +229,14 @@ static unsigned char *buildGammaLookupTable(int blevel, int wlevel, double power { unsigned char *result = new unsigned char[0x10000]; - if (blevel < 0) blevel = 0; - if (wlevel < 0) wlevel = 0; - if (blevel > 0xffff) blevel = 0xffff; - if (wlevel > 0xffff) blevel = 0xffff; + if (blevel < 0) + blevel = 0; + if (wlevel < 0) + wlevel = 0; + if (blevel > 0xffff) + blevel = 0xffff; + if (wlevel > 0xffff) + blevel = 0xffff; for (int i = 0; i <= blevel; ++i) result[i] = 0; @@ -240,7 +258,8 @@ bool usImage::CopyToImage(wxImage **rawimg, int blevel, int wlevel, double power { wxImage *img = *rawimg; - if (!img || !img->Ok() || (img->GetWidth() != Size.GetWidth()) || (img->GetHeight() != Size.GetHeight()) ) // can't reuse bitmap + if (!img || !img->Ok() || (img->GetWidth() != Size.GetWidth()) || + (img->GetHeight() != Size.GetHeight())) // can't reuse bitmap { delete img; img = new wxImage(Size.GetWidth(), Size.GetHeight(), false); @@ -251,7 +270,7 @@ bool usImage::CopyToImage(wxImage **rawimg, int blevel, int wlevel, double power unsigned char *lutTable = buildGammaLookupTable(blevel, wlevel, power); - for (unsigned int i = 0; i < NPixels; i++, RawPtr++ ) + for (unsigned int i = 0; i < NPixels; i++, RawPtr++) { unsigned short v = *RawPtr; unsigned char d = lutTable[v]; @@ -277,8 +296,8 @@ bool usImage::Save(const wxString& fname, const wxString& hdrNote) const try { - fitsfile *fptr; // FITS file pointer - int status = 0; // CFITSIO status value MUST be initialized to zero! + fitsfile *fptr; // FITS file pointer + int status = 0; // CFITSIO status value MUST be initialized to zero! PHD_fits_create_file(&fptr, fname, true, &status); @@ -337,7 +356,8 @@ bool usImage::Save(const wxString& fname, const wxString& hdrNote) const int m = (int) ra; ra -= m; ra *= 60.0; - hdr.write("OBJCTRA", wxString::Format("%02d %02d %06.3f", h, m, ra).c_str(), "Object Right Ascension in hms"); + hdr.write( + "OBJCTRA", wxString::Format("%02d %02d %06.3f", h, m, ra).c_str(), "Object Right Ascension in hms"); } { @@ -349,7 +369,8 @@ bool usImage::Save(const wxString& fname, const wxString& hdrNote) const int m = (int) dec; dec -= m; dec *= 60.0; - hdr.write("OBJCTDEC", wxString::Format("%c%d %02d %06.3f", sign < 0 ? '-' : '+', d, m, dec).c_str(), "Object Declination in dms"); + hdr.write("OBJCTDEC", wxString::Format("%c%d %02d %06.3f", sign < 0 ? '-' : '+', d, m, dec).c_str(), + "Object Declination in dms"); } } @@ -415,8 +436,8 @@ bool usImage::Load(const wxString& fname) throw ERROR_INFO("File does not exist"); } - int status = 0; // CFITSIO status value MUST be initialized to zero! - fitsfile *fptr; // FITS file pointer + int status = 0; // CFITSIO status value MUST be initialized to zero! + fitsfile *fptr; // FITS file pointer if (!PHD_fits_open_diskfile(&fptr, fname, READONLY, &status)) { int hdutype; @@ -433,7 +454,8 @@ bool usImage::Load(const wxString& fname) fits_get_img_size(fptr, 2, fsize, &status); int nhdus = 0; fits_get_num_hdus(fptr, &nhdus, &status); - if ((nhdus != 1) || (naxis != 2)) { + if ((nhdus != 1) || (naxis != 2)) + { pFrame->Alert(wxString::Format(_("Unsupported type or read error loading FITS file %s"), fname)); throw ERROR_INFO("unsupported type"); } @@ -443,7 +465,8 @@ bool usImage::Load(const wxString& fname) throw ERROR_INFO("Memory Allocation failure"); } long fpixel[3] = { 1, 1, 1 }; - if (fits_read_pix(fptr, TUSHORT, fpixel, (int)(fsize[0] * fsize[1]), nullptr, ImageData, nullptr, &status)) { // Read image + if (fits_read_pix(fptr, TUSHORT, fpixel, (int) (fsize[0] * fsize[1]), nullptr, ImageData, nullptr, &status)) + { // Read image pFrame->Alert(wxString::Format(_("Error reading data from FITS file %s"), fname)); throw ERROR_INFO("Error reading"); } @@ -461,7 +484,7 @@ bool usImage::Load(const wxString& fname) int pedestal; if (fhdr_int(fptr, "PEDESTAL", &pedestal)) - Pedestal = (unsigned short) pedestal; + Pedestal = (unsigned short) pedestal; int saturate; if (fhdr_int(fptr, "SATURATE", &saturate)) @@ -469,10 +492,14 @@ bool usImage::Load(const wxString& fname) wxRect subf; bool ok = fhdr_int(fptr, "PHDSUBFX", &subf.x); - if (ok) ok = fhdr_int(fptr, "PHDSUBFY", &subf.y); - if (ok) ok = fhdr_int(fptr, "PHDSUBFW", &subf.width); - if (ok) ok = fhdr_int(fptr, "PHDSUBFH", &subf.height); - if (ok) Subframe = subf; + if (ok) + ok = fhdr_int(fptr, "PHDSUBFY", &subf.y); + if (ok) + ok = fhdr_int(fptr, "PHDSUBFW", &subf.width); + if (ok) + ok = fhdr_int(fptr, "PHDSUBFH", &subf.height); + if (ok) + Subframe = subf; PHD_fits_close_file(fptr); @@ -516,7 +543,7 @@ bool usImage::Rotate(double theta, bool mirror) mirrored = pImg->Mirror(false); } - wxImage rotated = mirrored.Rotate(theta, wxPoint(0,0)); + wxImage rotated = mirrored.Rotate(theta, wxPoint(0, 0)); CopyFromImage(rotated); diff --git a/src/usImage.h b/src/usImage.h index 5f75ce095..839eac47f 100644 --- a/src/usImage.h +++ b/src/usImage.h @@ -38,54 +38,53 @@ class usImage { public: - unsigned short *ImageData; // Pointer to raw data - wxSize Size; // Dimensions of image - wxRect Subframe; // were the valid data is - unsigned int NPixels; - unsigned short MinADU; - unsigned short MaxADU; - unsigned short MedianADU; - unsigned short FiltMin; - unsigned short FiltMax; - wxDateTime ImgStartTime; - int ImgExpDur; // milli-seconds - int ImgStackCnt; - wxByte BitsPerPixel; - unsigned short Pedestal; - unsigned int FrameNum; + unsigned short *ImageData; // Pointer to raw data + wxSize Size; // Dimensions of image + wxRect Subframe; // were the valid data is + unsigned int NPixels; + unsigned short MinADU; + unsigned short MaxADU; + unsigned short MedianADU; + unsigned short FiltMin; + unsigned short FiltMax; + wxDateTime ImgStartTime; + int ImgExpDur; // milli-seconds + int ImgStackCnt; + wxByte BitsPerPixel; + unsigned short Pedestal; + unsigned int FrameNum; usImage() - : - ImageData(nullptr), - NPixels(0), - MinADU(0), - MaxADU(0), - MedianADU(0), - FiltMin(0), - FiltMax(0), - ImgExpDur(0), - ImgStackCnt(1), - BitsPerPixel(0), - Pedestal(0), - FrameNum(0) + : ImageData(nullptr) + , NPixels(0) + , MinADU(0) + , MaxADU(0) + , MedianADU(0) + , FiltMin(0) + , FiltMax(0) + , ImgExpDur(0) + , ImgStackCnt(1) + , BitsPerPixel(0) + , Pedestal(0) + , FrameNum(0) { } ~usImage() { delete[] ImageData; } - bool Init(const wxSize& size); - bool Init(int width, int height) { return Init(wxSize(width, height)); } - void SwapImageData(usImage& other); - void CalcStats(); - void InitImgStartTime(); - bool CopyFrom(const usImage& src); - bool CopyToImage(wxImage **img, int blevel, int wlevel, double power); - bool CopyFromImage(const wxImage& img); - bool Load(const wxString& fname); - bool Save(const wxString& fname, const wxString& hdrComment = wxEmptyString) const; - bool Rotate(double theta, bool mirror=false); - unsigned short& Pixel(int x, int y) { return ImageData[y * Size.x + x]; } + bool Init(const wxSize& size); + bool Init(int width, int height) { return Init(wxSize(width, height)); } + void SwapImageData(usImage& other); + void CalcStats(); + void InitImgStartTime(); + bool CopyFrom(const usImage& src); + bool CopyToImage(wxImage **img, int blevel, int wlevel, double power); + bool CopyFromImage(const wxImage& img); + bool Load(const wxString& fname); + bool Save(const wxString& fname, const wxString& hdrComment = wxEmptyString) const; + bool Rotate(double theta, bool mirror = false); + unsigned short& Pixel(int x, int y) { return ImageData[y * Size.x + x]; } const unsigned short& Pixel(int x, int y) const { return ImageData[y * Size.x + x]; } - void Clear(void); + void Clear(void); }; inline void usImage::Clear(void) diff --git a/src/worker_thread.cpp b/src/worker_thread.cpp index e2d0c109a..adc2465a7 100644 --- a/src/worker_thread.cpp +++ b/src/worker_thread.cpp @@ -36,10 +36,10 @@ #include "phd.h" WorkerThread::WorkerThread(MyFrame *pFrame) - : wxThread(wxTHREAD_JOINABLE), - m_interruptRequested(0), - m_killable(true), - m_skipSendExposeComplete(false) + : wxThread(wxTHREAD_JOINABLE) + , m_interruptRequested(0) + , m_killable(true) + , m_skipSendExposeComplete(false) { m_pFrame = pFrame; Debug.Write("WorkerThread constructor called\n"); @@ -85,7 +85,8 @@ void WorkerThread::EnqueueWorkerThreadTerminateRequest(void) /************* Expose **************************/ -void WorkerThread::EnqueueWorkerThreadExposeRequest(usImage *pImage, int exposureDuration, int exposureOptions, const wxRect& subframe) +void WorkerThread::EnqueueWorkerThreadExposeRequest( + usImage *pImage, int exposureDuration, int exposureOptions, const wxRect& subframe) { m_interruptRequested &= ~INT_STOP; @@ -94,19 +95,22 @@ void WorkerThread::EnqueueWorkerThreadExposeRequest(usImage *pImage, int exposur Debug.Write("Enqueuing Expose request\n"); - message.request = REQUEST_EXPOSE; - message.args.expose.pImage = pImage; + message.request = REQUEST_EXPOSE; + message.args.expose.pImage = pImage; message.args.expose.exposureDuration = exposureDuration; - message.args.expose.options = exposureOptions; - message.args.expose.subframe = subframe; - message.args.expose.pSemaphore = 0; + message.args.expose.options = exposureOptions; + message.args.expose.subframe = subframe; + message.args.expose.pSemaphore = 0; EnqueueMessage(message); } unsigned int WorkerThread::MilliSleep(int ms, unsigned int checkInterrupts) { - enum { MAX_SLEEP = 100 }; + enum + { + MAX_SLEEP = 100 + }; if (ms <= MAX_SLEEP) { @@ -119,7 +123,8 @@ unsigned int WorkerThread::MilliSleep(int ms, unsigned int checkInterrupts) wxStopWatch swatch; long elapsed = 0; - do { + do + { wxMilliSleep(wxMin((long) ms - elapsed, (long) MAX_SLEEP)); unsigned int val = thr ? (thr->m_interruptRequested & checkInterrupts) : 0; if (val) @@ -136,10 +141,9 @@ void WorkerThread::SetSkipExposeComplete() m_skipSendExposeComplete = true; } -//#define ENABLE_CAMERA_TEST +// #define ENABLE_CAMERA_TEST #ifdef ENABLE_CAMERA_TEST -static void -CameraROITest(usImage *img) +static void CameraROITest(usImage *img) { // Overlay a simulated star that wanders around and periodically disappears. // This is used for testing new cameras to ensure that they deal properly with @@ -150,11 +154,11 @@ CameraROITest(usImage *img) int Y = 150 + dy; unsigned short base = (img->BitsPerPixel == 8 ? 255 : 60000); int scale = img->BitsPerPixel == 8 ? 5 : 5 * 256; - if ((double)rand() / RAND_MAX > 0.05) + if ((double) rand() / RAND_MAX > 0.05) { for (int x = -4; x <= 4; x++) for (int y = -4; y <= 4; y++) - img->ImageData[X + x + (Y + y)*img->Size.x] = base - (x * x + y * y) * scale; + img->ImageData[X + x + (Y + y) * img->Size.x] = base - (x * x + y * y) * scale; } dx += ddx; if (dx < 0 || dx >= 48) @@ -166,7 +170,10 @@ CameraROITest(usImage *img) } } #else -# define CameraROITest(img) do { } while (false) +# define CameraROITest(img) \ + do \ + { \ + } while (false) #endif bool WorkerThread::HandleExpose(EXPOSE_REQUEST *req) @@ -183,7 +190,7 @@ bool WorkerThread::HandleExpose(EXPOSE_REQUEST *req) if (pCamera->HasNonGuiCapture()) { Debug.Write(wxString::Format("Handling exposure in thread, d=%d o=%x r=(%d,%d,%d,%d)\n", req->exposureDuration, - req->options, req->subframe.x, req->subframe.y, req->subframe.width, req->subframe.height)); + req->options, req->subframe.x, req->subframe.y, req->subframe.width, req->subframe.height)); if (GuideCamera::Capture(pCamera, req->exposureDuration, *req->pImage, req->options, req->subframe)) { @@ -193,7 +200,7 @@ bool WorkerThread::HandleExpose(EXPOSE_REQUEST *req) else { Debug.Write(wxString::Format("Handling exposure in myFrame, d=%d o=%x r=(%d,%d,%d,%d)\n", req->exposureDuration, - req->options, req->subframe.x, req->subframe.y, req->subframe.width, req->subframe.height)); + req->options, req->subframe.x, req->subframe.y, req->subframe.width, req->subframe.height)); wxSemaphore semaphore; req->pSemaphore = &semaphore; @@ -217,14 +224,14 @@ bool WorkerThread::HandleExpose(EXPOSE_REQUEST *req) switch (m_pFrame->GetNoiseReductionMethod()) { - case NR_NONE: - break; - case NR_2x2MEAN: - QuickLRecon(*req->pImage); - break; - case NR_3x3MEDIAN: - Median3(*req->pImage); - break; + case NR_NONE: + break; + case NR_2x2MEAN: + QuickLRecon(*req->pImage); + break; + case NR_3x3MEDIAN: + Median3(*req->pImage); + break; } req->pImage->CalcStats(); @@ -256,19 +263,21 @@ void WorkerThread::EnqueueWorkerThreadMoveRequest(Mount *mount, const GuiderOffs WORKER_THREAD_REQUEST message; memset(&message, 0, sizeof(message)); - Debug.Write(wxString::Format("Enqueuing Move request for %s (%.2f, %.2f)\n", mount->GetMountClassName(), ofs.cameraOfs.X, ofs.cameraOfs.Y)); + Debug.Write(wxString::Format( + "Enqueuing Move request for %s (%.2f, %.2f)\n", mount->GetMountClassName(), ofs.cameraOfs.X, ofs.cameraOfs.Y)); - message.request = REQUEST_MOVE; - message.args.move.mount = mount; - message.args.move.axisMove = false; - message.args.move.ofs = ofs; - message.args.move.moveOptions = moveOptions; - message.args.move.semaphore = nullptr; + message.request = REQUEST_MOVE; + message.args.move.mount = mount; + message.args.move.axisMove = false; + message.args.move.ofs = ofs; + message.args.move.moveOptions = moveOptions; + message.args.move.semaphore = nullptr; EnqueueMessage(message); } -void WorkerThread::EnqueueWorkerThreadAxisMove(Mount *mount, const GUIDE_DIRECTION direction, int duration, unsigned int moveOptions) +void WorkerThread::EnqueueWorkerThreadAxisMove( + Mount *mount, const GUIDE_DIRECTION direction, int duration, unsigned int moveOptions) { m_interruptRequested &= ~INT_STOP; @@ -277,13 +286,13 @@ void WorkerThread::EnqueueWorkerThreadAxisMove(Mount *mount, const GUIDE_DIRECTI Debug.Write(wxString::Format("Enqueuing Calibration Move request for direction %d\n", direction)); - message.request = REQUEST_MOVE; - message.args.move.mount = mount; - message.args.move.axisMove = true; - message.args.move.direction = direction; - message.args.move.duration = duration; - message.args.move.moveOptions = moveOptions; - message.args.move.semaphore = nullptr; + message.request = REQUEST_MOVE; + message.args.move.mount = mount; + message.args.move.axisMove = true; + message.args.move.direction = direction; + message.args.move.duration = duration; + message.args.move.moveOptions = moveOptions; + message.args.move.semaphore = nullptr; EnqueueMessage(message); } @@ -299,8 +308,7 @@ void WorkerThread::HandleMove(MOVE_REQUEST *req) if (req->axisMove) { Debug.Write(wxString::Format("Handling axis move in thread for %s dir=%d dur=%d\n", - req->mount->GetMountClassName(), - req->direction, req->duration)); + req->mount->GetMountClassName(), req->direction, req->duration)); result = req->mount->MoveAxis(req->direction, req->duration, req->moveOptions); @@ -312,8 +320,7 @@ void WorkerThread::HandleMove(MOVE_REQUEST *req) else { Debug.Write(wxString::Format("Handling offset move in thread for %s, endpoint = (%.2f, %.2f)\n", - req->mount->GetMountClassName(), - req->ofs.cameraOfs.X, req->ofs.cameraOfs.Y)); + req->mount->GetMountClassName(), req->ofs.cameraOfs.X, req->ofs.cameraOfs.Y)); result = req->mount->MoveOffset(&req->ofs, req->moveOptions); @@ -362,11 +369,10 @@ void WorkerThread::HandleMove(MOVE_REQUEST *req) } MoveCompleteEvent::MoveCompleteEvent(const MOVE_REQUEST& move) - : - wxThreadEvent(wxEVT_THREAD, MYFRAME_WORKER_THREAD_MOVE_COMPLETE), - moveOptions(move.moveOptions), - result(move.moveResult), - mount(move.mount) + : wxThreadEvent(wxEVT_THREAD, MYFRAME_WORKER_THREAD_MOVE_COMPLETE) + , moveOptions(move.moveOptions) + , result(move.moveResult) + , mount(move.mount) { } @@ -413,47 +419,45 @@ wxThread::ExitCode WorkerThread::Entry() { bool bError; - case REQUEST_TERMINATE: - Debug.Write("worker thread servicing REQUEST_TERMINATE\n"); - bDone = true; - break; - - case REQUEST_EXPOSE: - Debug.Write(wxString::Format("worker thread servicing REQUEST_EXPOSE %d\n", - message.args.expose.exposureDuration)); - bError = HandleExpose(&message.args.expose); - if (m_skipSendExposeComplete) - { - Debug.Write("worker thread skipping SendWorkerThreadExposeComplete\n"); - delete message.args.expose.pImage; // should be null though - message.args.expose.pImage = 0; - m_skipSendExposeComplete = false; - } - else - SendWorkerThreadExposeComplete(message.args.expose.pImage, bError); - break; + case REQUEST_TERMINATE: + Debug.Write("worker thread servicing REQUEST_TERMINATE\n"); + bDone = true; + break; - case REQUEST_MOVE: { - if (message.args.move.axisMove) - Debug.Write(wxString::Format("worker thread servicing REQUEST_MOVE %s dir %s(%d) %d opts 0x%x\n", - message.args.move.mount->GetMountClassName(), - message.args.move.mount->DirectionChar(message.args.move.direction), - message.args.move.direction, - message.args.move.duration, message.args.move.moveOptions)); - else - Debug.Write(wxString::Format("worker thread servicing REQUEST_MOVE %s ofs (%.2f, %.2f) opts 0x%x\n", - message.args.move.mount->GetMountClassName(), - message.args.move.ofs.cameraOfs.X, message.args.move.ofs.cameraOfs.Y, - message.args.move.moveOptions)); - - HandleMove(&message.args.move); - SendWorkerThreadMoveComplete(message.args.move); - break; + case REQUEST_EXPOSE: + Debug.Write(wxString::Format("worker thread servicing REQUEST_EXPOSE %d\n", message.args.expose.exposureDuration)); + bError = HandleExpose(&message.args.expose); + if (m_skipSendExposeComplete) + { + Debug.Write("worker thread skipping SendWorkerThreadExposeComplete\n"); + delete message.args.expose.pImage; // should be null though + message.args.expose.pImage = 0; + m_skipSendExposeComplete = false; } + else + SendWorkerThreadExposeComplete(message.args.expose.pImage, bError); + break; - default: - Debug.Write(wxString::Format("worker thread servicing unknown request %d\n", message.request)); - break; + case REQUEST_MOVE: + { + if (message.args.move.axisMove) + Debug.Write(wxString::Format("worker thread servicing REQUEST_MOVE %s dir %s(%d) %d opts 0x%x\n", + message.args.move.mount->GetMountClassName(), + message.args.move.mount->DirectionChar(message.args.move.direction), message.args.move.direction, + message.args.move.duration, message.args.move.moveOptions)); + else + Debug.Write(wxString::Format("worker thread servicing REQUEST_MOVE %s ofs (%.2f, %.2f) opts 0x%x\n", + message.args.move.mount->GetMountClassName(), message.args.move.ofs.cameraOfs.X, + message.args.move.ofs.cameraOfs.Y, message.args.move.moveOptions)); + + HandleMove(&message.args.move); + SendWorkerThreadMoveComplete(message.args.move); + break; + } + + default: + Debug.Write(wxString::Format("worker thread servicing unknown request %d\n", message.request)); + break; } Debug.Write("worker thread done servicing request\n"); @@ -463,5 +467,5 @@ wxThread::ExitCode WorkerThread::Entry() Debug.Write("WorkerThread::Entry() ends\n"); Debug.Flush(); - return (wxThread::ExitCode)0; + return (wxThread::ExitCode) 0; } diff --git a/src/worker_thread.h b/src/worker_thread.h index 26c682009..43ea2ade0 100644 --- a/src/worker_thread.h +++ b/src/worker_thread.h @@ -58,24 +58,24 @@ class MyFrame; struct EXPOSE_REQUEST { - usImage *pImage; - int exposureDuration; - int options; - wxRect subframe; - bool error; - wxSemaphore *pSemaphore; + usImage *pImage; + int exposureDuration; + int options; + wxRect subframe; + bool error; + wxSemaphore *pSemaphore; }; struct MOVE_REQUEST { - Mount *mount; - int duration; - GUIDE_DIRECTION direction; - bool axisMove; - unsigned int moveOptions; + Mount *mount; + int duration; + GUIDE_DIRECTION direction; + bool axisMove; + unsigned int moveOptions; Mount::MOVE_RESULT moveResult; - GuiderOffset ofs; - wxSemaphore *semaphore; + GuiderOffset ofs; + wxSemaphore *semaphore; }; struct MoveCompleteEvent : public wxThreadEvent @@ -92,16 +92,16 @@ class WorkerThread : public wxThread // types and routines for the server->worker message queue enum WORKER_REQUEST_TYPE { - REQUEST_NONE, // not used + REQUEST_NONE, // not used REQUEST_TERMINATE, REQUEST_EXPOSE, REQUEST_MOVE, }; /* - * this struct is passed through the message queue to the worker thread - * to request work - */ + * this struct is passed through the message queue to the worker thread + * to request work + */ struct WORKER_THREAD_REQUEST { WORKER_REQUEST_TYPE request; @@ -121,8 +121,8 @@ class WorkerThread : public wxThread bool m_skipSendExposeComplete; public: - - enum InterruptBits { + enum InterruptBits + { _BITNR_STOP, _BITNR_TERMINATE, @@ -182,6 +182,7 @@ class WorkerThread : public wxThread public: void EnqueueWorkerThreadExposeRequest(usImage *pImage, int exposureDuration, int exposureOptions, const wxRect& subframe); void SetSkipExposeComplete(); + protected: bool HandleExpose(EXPOSE_REQUEST *args); void SendWorkerThreadExposeComplete(usImage *pImage, bool bError); @@ -191,6 +192,7 @@ class WorkerThread : public wxThread public: void EnqueueWorkerThreadMoveRequest(Mount *mount, const GuiderOffset& ofs, unsigned int moveOptions); void EnqueueWorkerThreadAxisMove(Mount *mount, const GUIDE_DIRECTION direction, int duration, unsigned int moveOptions); + protected: void HandleMove(MOVE_REQUEST *args); void SendWorkerThreadMoveComplete(const MOVE_REQUEST& move); @@ -241,8 +243,10 @@ class WorkerThreadKillGuard { WorkerThread *m_thread; bool m_prev; + public: - WorkerThreadKillGuard(WorkerThread *thread = WorkerThread::This()) : m_thread(thread) + WorkerThreadKillGuard(WorkerThread *thread = WorkerThread::This()) + : m_thread(thread) { m_prev = m_thread ? m_thread->SetKillable(false) : true; } @@ -256,9 +260,12 @@ class WorkerThreadKillGuard class Watchdog : public wxStopWatch { long m_timeout_ms; + public: - Watchdog(unsigned int timeout_ms, unsigned int grace_period_ms) : m_timeout_ms(timeout_ms + grace_period_ms) - { } + Watchdog(unsigned int timeout_ms, unsigned int grace_period_ms) + : m_timeout_ms(timeout_ms + grace_period_ms) + { + } bool Expired(void) const { return Time() > m_timeout_ms; } }; diff --git a/src/wxled.h b/src/wxled.h index 6645c4d13..96c92dd87 100644 --- a/src/wxled.h +++ b/src/wxled.h @@ -17,28 +17,26 @@ class WXDLLEXPORT wxLed : public wxWindow { - public : - - wxLed (wxWindow * parent, wxWindowID id, const char * disabledColor = "000000", const wxPoint & pos = wxDefaultPosition, const wxSize & size = wxDefaultSize) ; - ~wxLed () ; - - bool Enable (bool enable = true) ; - void SetColor (const char * rgb) ; - - protected : - - char m_enabledColor [7] ; - char m_disabledColor [7] ; - char m_color [7] ; - wxBitmap * m_bitmap ; - wxMutex m_mutex ; - - void OnPaint (wxPaintEvent & event) ; - virtual void SetBitmap (const char * color) ; - - private : - - wxDECLARE_EVENT_TABLE(); -} ; +public: + wxLed(wxWindow *parent, wxWindowID id, const char *disabledColor = "000000", const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + ~wxLed(); + + bool Enable(bool enable = true); + void SetColor(const char *rgb); + +protected: + char m_enabledColor[7]; + char m_disabledColor[7]; + char m_color[7]; + wxBitmap *m_bitmap; + wxMutex m_mutex; + + void OnPaint(wxPaintEvent& event); + virtual void SetBitmap(const char *color); + +private: + wxDECLARE_EVENT_TABLE(); +}; #endif // _WX_LED_H_ diff --git a/src/zfilterfactory.cpp b/src/zfilterfactory.cpp index 47f2efe63..e37c15dfa 100644 --- a/src/zfilterfactory.cpp +++ b/src/zfilterfactory.cpp @@ -1,36 +1,36 @@ /* -* zfilterfactory.cpp -* PHD Guiding -* -* Created by Ken Self -* Copyright (c) 2018 Ken Self -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * zfilterfactory.cpp + * PHD Guiding + * + * Created by Ken Self + * Copyright (c) 2018 Ken Self + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ /* Based on mkfilter by A.J. Fisher, University of York September 1992 https://www-users.cs.york.ac.uk/~fisher/mkfilter/ @@ -47,40 +47,40 @@ #include "zfilterfactory.h" -ZFilterFactory::ZFilterFactory(FILTER_DESIGN f, int o, double p, bool mzt ) +ZFilterFactory::ZFilterFactory(FILTER_DESIGN f, int o, double p, bool mzt) { bessel_poles = { - /* table produced by /usr/fisher/bessel -- N.B. only one member of each C.Conj. pair is listed */ - std::complex( -1.00000000000e+00, 0.00000000000e+00), - std::complex( -1.10160133059e+00, 6.36009824757e-01), - std::complex( -1.32267579991e+00, 0.00000000000e+00), - std::complex( -1.04740916101e+00, 9.99264436281e-01), - std::complex( -1.37006783055e+00, 4.10249717494e-01), - std::complex( -9.95208764350e-01, 1.25710573945e+00), - std::complex( -1.50231627145e+00, 0.00000000000e+00), - std::complex( -1.38087732586e+00, 7.17909587627e-01), - std::complex( -9.57676548563e-01, 1.47112432073e+00), - std::complex( -1.57149040362e+00, 3.20896374221e-01), - std::complex( -1.38185809760e+00, 9.71471890712e-01), - std::complex( -9.30656522947e-01, 1.66186326894e+00), - std::complex( -1.68436817927e+00, 0.00000000000e+00), - std::complex( -1.61203876622e+00, 5.89244506931e-01), - std::complex( -1.37890321680e+00, 1.19156677780e+00), - std::complex( -9.09867780623e-01, 1.83645135304e+00), - std::complex( -1.75740840040e+00, 2.72867575103e-01), - std::complex( -1.63693941813e+00, 8.22795625139e-01), - std::complex( -1.37384121764e+00, 1.38835657588e+00), - std::complex( -8.92869718847e-01, 1.99832584364e+00), - std::complex( -1.85660050123e+00, 0.00000000000e+00), - std::complex( -1.80717053496e+00, 5.12383730575e-01), - std::complex( -1.65239648458e+00, 1.03138956698e+00), - std::complex( -1.36758830979e+00, 1.56773371224e+00), - std::complex( -8.78399276161e-01, 2.14980052431e+00), - std::complex( -1.92761969145e+00, 2.41623471082e-01), - std::complex( -1.84219624443e+00, 7.27257597722e-01), - std::complex( -1.66181024140e+00, 1.22110021857e+00), - std::complex( -1.36069227838e+00, 1.73350574267e+00), - std::complex( -8.65756901707e-01, 2.29260483098e+00), + /* table produced by /usr/fisher/bessel -- N.B. only one member of each C.Conj. pair is listed */ + std::complex(-1.00000000000e+00, 0.00000000000e+00), + std::complex(-1.10160133059e+00, 6.36009824757e-01), + std::complex(-1.32267579991e+00, 0.00000000000e+00), + std::complex(-1.04740916101e+00, 9.99264436281e-01), + std::complex(-1.37006783055e+00, 4.10249717494e-01), + std::complex(-9.95208764350e-01, 1.25710573945e+00), + std::complex(-1.50231627145e+00, 0.00000000000e+00), + std::complex(-1.38087732586e+00, 7.17909587627e-01), + std::complex(-9.57676548563e-01, 1.47112432073e+00), + std::complex(-1.57149040362e+00, 3.20896374221e-01), + std::complex(-1.38185809760e+00, 9.71471890712e-01), + std::complex(-9.30656522947e-01, 1.66186326894e+00), + std::complex(-1.68436817927e+00, 0.00000000000e+00), + std::complex(-1.61203876622e+00, 5.89244506931e-01), + std::complex(-1.37890321680e+00, 1.19156677780e+00), + std::complex(-9.09867780623e-01, 1.83645135304e+00), + std::complex(-1.75740840040e+00, 2.72867575103e-01), + std::complex(-1.63693941813e+00, 8.22795625139e-01), + std::complex(-1.37384121764e+00, 1.38835657588e+00), + std::complex(-8.92869718847e-01, 1.99832584364e+00), + std::complex(-1.85660050123e+00, 0.00000000000e+00), + std::complex(-1.80717053496e+00, 5.12383730575e-01), + std::complex(-1.65239648458e+00, 1.03138956698e+00), + std::complex(-1.36758830979e+00, 1.56773371224e+00), + std::complex(-8.78399276161e-01, 2.14980052431e+00), + std::complex(-1.92761969145e+00, 2.41623471082e-01), + std::complex(-1.84219624443e+00, 7.27257597722e-01), + std::complex(-1.66181024140e+00, 1.22110021857e+00), + std::complex(-1.36069227838e+00, 1.73350574267e+00), + std::complex(-8.65756901707e-01, 2.29260483098e+00), }; if (o <= 0) { @@ -106,12 +106,12 @@ ZFilterFactory::ZFilterFactory(FILTER_DESIGN f, int o, double p, bool mzt ) void ZFilterFactory::splane() // compute S-plane poles for prototype LP filter { -// Bessel filter -// - if (filt == BESSEL) // Bessel filter + // Bessel filter + // + if (filt == BESSEL) // Bessel filter { - int p = (m_order * m_order) / 4; // ptr into table - if (m_order & 1) // If order is odd + int p = (m_order * m_order) / 4; // ptr into table + if (m_order & 1) // If order is odd setpole(bessel_poles[p++]); for (int i = 0; i < m_order / 2; i++) { @@ -120,15 +120,15 @@ void ZFilterFactory::splane() // compute S-plane poles for prototype LP filter p++; } } - if (filt == BUTTERWORTH || filt == CHEBYCHEV) // Butterworth filter + if (filt == BUTTERWORTH || filt == CHEBYCHEV) // Butterworth filter { for (int i = 0; i < 2 * m_order; i++) { double theta = (m_order & 1) ? (i * M_PI) / m_order : ((i + 0.5) * M_PI) / m_order; - setpole(std::polar(1.0,theta)); + setpole(std::polar(1.0, theta)); } } - if (filt == CHEBYCHEV) // modify for Chebyshev (p. 136 DeFatta et al.) + if (filt == CHEBYCHEV) // modify for Chebyshev (p. 136 DeFatta et al.) { if (chripple >= 0.0) { @@ -140,8 +140,8 @@ void ZFilterFactory::splane() // compute S-plane poles for prototype LP filter double y = asinh(1.0 / eps) / (double) m_order; for (int i = 0; i < spoles.size(); i++) { - spoles[i].real(spoles[i].real()*sinh(y)); - spoles[i].imag(spoles[i].imag()*cosh(y)); + spoles[i].real(spoles[i].real() * sinh(y)); + spoles[i].imag(spoles[i].imag() * cosh(y)); } } } @@ -171,12 +171,12 @@ void ZFilterFactory::normalize() /* called for trad, not for -Re or -Pi */ void ZFilterFactory::zplane() { -// given S-plane poles & zeros, compute Z-plane poles & zeros -// using bilinear transform or matched z-transform + // given S-plane poles & zeros, compute Z-plane poles & zeros + // using bilinear transform or matched z-transform int i; zpoles.clear(); zzeros.clear(); - if(!isMzt) + if (!isMzt) { for (i = 0; i < spoles.size(); i++) zpoles.push_back(bilinear(spoles[i])); @@ -194,7 +194,8 @@ void ZFilterFactory::zplane() } } -void ZFilterFactory::expandpoly() // given Z-plane poles & zeros, compute top & bot polynomials in Z, and then recurrence relation +void ZFilterFactory::expandpoly() // given Z-plane poles & zeros, compute top & bot polynomials in Z, and then recurrence + // relation { std::vector> topcoeffs, botcoeffs; int i; @@ -211,10 +212,10 @@ void ZFilterFactory::expandpoly() // given Z-plane poles & zeros, compute top & dc_gain = eval(topcoeffs, z_one) / eval(botcoeffs, z_one); fc_gain = eval(topcoeffs, z_theta) / eval(botcoeffs, z_theta); hf_gain = eval(topcoeffs, z_minusone) / eval(botcoeffs, z_minusone); - for (i = topcoeffs.size()-1; i >= 0; i--) - xcoeffs.push_back( +(topcoeffs[i].real() / botcoeffs.back().real()) ); - for (i = botcoeffs.size()-1; i >= 0; i--) - ycoeffs.push_back( -(botcoeffs[i].real() / botcoeffs.back().real()) ); + for (i = topcoeffs.size() - 1; i >= 0; i--) + xcoeffs.push_back(+(topcoeffs[i].real() / botcoeffs.back().real())); + for (i = botcoeffs.size() - 1; i >= 0; i--) + ycoeffs.push_back(-(botcoeffs[i].real() / botcoeffs.back().real())); } void ZFilterFactory::expand(const std::vector>& pz, std::vector>& coeffs) @@ -226,11 +227,11 @@ void ZFilterFactory::expand(const std::vector>& pz, std::ve for (i = 0; i < pz.size(); i++) coeffs.push_back(0.0); -// coeffs now has 1 more element than pz + // coeffs now has 1 more element than pz for (i = 0; i < pz.size(); i++) multin(pz[i], coeffs); -// check computed coeffs of z^k are all real + // check computed coeffs of z^k are all real for (i = 0; i < coeffs.size(); i++) { if (fabs(coeffs[i].imag()) > EPS) @@ -245,15 +246,15 @@ void ZFilterFactory::multin(const std::complex& w, std::vector nw = -w; - for (int i = coeffs.size()-1; i >= 1; i--) + for (int i = coeffs.size() - 1; i >= 1; i--) coeffs[i] = (nw * coeffs[i]) + coeffs[i - 1]; coeffs[0] = nw * coeffs[0]; } std::complex ZFilterFactory::eval(const std::vector>& coeffs, const std::complex& z) { /* evaluate polynomial in z, substituting for z */ - std::complex sum = std::complex(0.0,0.0); - for (int i = coeffs.size()-1; i >= 0; i--) + std::complex sum = std::complex(0.0, 0.0); + for (int i = coeffs.size() - 1; i >= 0; i--) sum = (sum * z) + coeffs[i]; return sum; } diff --git a/src/zfilterfactory.h b/src/zfilterfactory.h index 300888db4..015c52fe3 100644 --- a/src/zfilterfactory.h +++ b/src/zfilterfactory.h @@ -1,36 +1,36 @@ /* -* zfilterfactory.h -* PHD Guiding -* -* Created by Ken Self -* Copyright (c) 2018 Ken Self -* All rights reserved. -* -* This source code is distributed under the following "BSD" license -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, -* this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, -* this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* Neither the name of openphdguiding.org nor the names of its -* contributors may be used to endorse or promote products derived from -* this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -* POSSIBILITY OF SUCH DAMAGE. -* -*/ + * zfilterfactory.h + * PHD Guiding + * + * Created by Ken Self + * Copyright (c) 2018 Ken Self + * All rights reserved. + * + * This source code is distributed under the following "BSD" license + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of openphdguiding.org nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ #ifndef ZFILTER_FACTORY_H_INCLUDED #define ZFILTER_FACTORY_H_INCLUDED @@ -54,8 +54,9 @@ class ZFilterFactory double corner() { return 1 / raw_alpha1; }; FILTER_DESIGN design() { return filt; } std::string getname() const; - int order() { return m_order; }; - ZFilterFactory( FILTER_DESIGN f, int o, double p, bool mzt=false ); + int order() { return m_order; }; + ZFilterFactory(FILTER_DESIGN f, int o, double p, bool mzt = false); + private: const double TWOPI = (2.0 * M_PI); const double EPS = 1e-10; @@ -100,10 +101,14 @@ inline std::string ZFilterFactory::getname() const { switch (filt) { - case BUTTERWORTH: return "Butterworth"; - case BESSEL: return "Bessel"; - case CHEBYCHEV: return "Chebychev"; - default: return "Unknown filter"; + case BUTTERWORTH: + return "Butterworth"; + case BESSEL: + return "Bessel"; + case CHEBYCHEV: + return "Chebychev"; + default: + return "Unknown filter"; } }