diff --git a/DelayedNotifier.h b/DelayedNotifier.h index eda2dcc..f8b1f46 100644 --- a/DelayedNotifier.h +++ b/DelayedNotifier.h @@ -1,5 +1,3 @@ -// Mock device adapter for testing of device change notifications -// // Copyright (C) 2024 Board of Regents of the University of Wisconsin System // // This file is distributed under the BSD license. License text is included diff --git a/ProcessModel.h b/ProcessModel.h index 9e66e85..2419f4d 100644 --- a/ProcessModel.h +++ b/ProcessModel.h @@ -1,5 +1,3 @@ -// Mock device adapter for testing of device change notifications -// // Copyright (C) 2024 Board of Regents of the University of Wisconsin System // // This file is distributed under the BSD license. License text is included @@ -30,17 +28,20 @@ #include // Models of physical device state. SyncProcessModel and AsyncProcessModel have -// the same compile-time interface. Member functions are not thread-safe: they -// must be called with external synchronization. +// the same compile-time interface. // // SyncProcessModel issues change notifications synchronously (i.e., from the -// thread setting the value) and never becomes busy. +// thread setting the value) and never becomes busy. Its member functions are +// not thread-safe: they must be called with external synchronization. // // AsyncProcessModel separates setpoint from process variable; the latter is // slewed so that it reaches the setpoint over time (so the model is "busy" // while still slewing). Change notifications are periodically issued from a // background thread during the slewing, with the last notification always -// occuring when the PV reaches the SP. +// occuring when the PV reaches the SP. The mutating member functions +// (Setpoint(value), Halt(), and the rate/interval setters) must be called with +// external synchronization; ProcessVariable(), Setpoint(), and IsSlewing() may +// be called from any thread. template class SyncProcessModel { using ValueType = std::array; @@ -267,6 +268,7 @@ template class AsyncProcessModel { stopCv_.notify_one(); slewThread_.join(); + std::lock_guard lock(mut_); setpoint_ = procVar_; } @@ -274,8 +276,11 @@ template class AsyncProcessModel { assert(std::all_of(setpoint.cbegin(), setpoint.cend(), [](double v) { return std::isfinite(v); })); Halt(); // Cancel previous slew, if any, updating last PV - setpoint_ = setpoint; - if (procVar_ == setpoint_) { + { + std::lock_guard lock(mut_); + setpoint_ = setpoint; + } + if (procVar_ == setpoint) { return; } diff --git a/SimCam.h b/SimCam.h index dbcc36f..e236206 100644 --- a/SimCam.h +++ b/SimCam.h @@ -7,6 +7,7 @@ #include "DeviceBase.h" #include +#include #include #include #include @@ -32,18 +33,27 @@ class SimCam : public CCameraBase { static constexpr const char *modeFilaments_ = "Filaments"; static constexpr const char *modeNuclei_ = "Nuclei"; + SimHub *hub_ = nullptr; + FilamentsSpecimen filamentsSpecimen_; NucleiSpecimen nucleiSpecimen_; - std::string mode_ = modeFilaments_; - // Camera state + // Settings, which may be read by the sequence thread + mutable std::mutex settingsMutex_; + std::string mode_ = modeFilaments_; double exposure_ms_ = 100.0; unsigned roiX_ = 0; unsigned roiY_ = 0; unsigned roiWidth_ = sensorWidth_; unsigned roiHeight_ = sensorHeight_; - // Last snap (always equal to ROI width/height) + struct FrameSettings { + double exposure_ms; + unsigned roiX, roiY, roiWidth, roiHeight; + std::string mode; + }; + + // Last snap (always equal to ROI width/height of last frame) std::unique_ptr snapBuffer_; std::vector signal_; @@ -54,15 +64,23 @@ class SimCam : public CCameraBase { std::mutex seqMutex_; std::condition_variable seqStopCV_; bool seqStopRequested_ = false; + std::atomic capturing_{false}; public: explicit SimCam(std::string name) : name_(std::move(name)) {} + ~SimCam() { StopSequenceAcquisition(); } + void GetName(char *buf) const final { CDeviceUtils::CopyLimitedString(buf, name_.c_str()); } int Initialize() final { + hub_ = static_cast(GetParentHub()); + if (!hub_) { + return DEVICE_COMM_HUB_MISSING; + } + int ret = CreateProperty( MM::g_Keyword_Exposure, std::to_string(exposure_ms_).c_str(), MM::Float, false, @@ -86,19 +104,21 @@ class SimCam : public CCameraBase { ret = AddAllowedValue(MM::g_Keyword_Binning, "1"); assert(ret == DEVICE_OK); - ret = - CreateProperty("Mode", mode_.c_str(), MM::String, false, - new MM::ActionLambda([this](MM::PropertyBase *pProp, - MM::ActionType eAct) { - if (eAct == MM::BeforeGet) { - pProp->Set(mode_.c_str()); - } else if (eAct == MM::AfterSet) { - std::string value; - pProp->Get(value); - mode_ = value; - } - return DEVICE_OK; - })); + ret = CreateProperty( + "Mode", mode_.c_str(), MM::String, false, + new MM::ActionLambda( + [this](MM::PropertyBase *pProp, MM::ActionType eAct) { + if (eAct == MM::BeforeGet) { + std::lock_guard lock(settingsMutex_); + pProp->Set(mode_.c_str()); + } else if (eAct == MM::AfterSet) { + std::string value; + pProp->Get(value); + std::lock_guard lock(settingsMutex_); + mode_ = value; + } + return DEVICE_OK; + })); assert(ret == DEVICE_OK); ret = AddAllowedValue("Mode", modeFilaments_); assert(ret == DEVICE_OK); @@ -108,11 +128,17 @@ class SimCam : public CCameraBase { return DEVICE_OK; } - int Shutdown() final { return DEVICE_OK; } + int Shutdown() final { return StopSequenceAcquisition(); } bool Busy() final { return false; } - unsigned GetImageWidth() const final { return roiWidth_; } - unsigned GetImageHeight() const final { return roiHeight_; } + unsigned GetImageWidth() const final { + std::lock_guard lock(settingsMutex_); + return roiWidth_; + } + unsigned GetImageHeight() const final { + std::lock_guard lock(settingsMutex_); + return roiHeight_; + } unsigned GetImageBytesPerPixel() const final { return 2; /* for now */ } long GetImageBufferSize() const final { return GetImageBytesPerPixel() * GetImageWidth() * GetImageHeight(); @@ -121,56 +147,14 @@ class SimCam : public CCameraBase { unsigned GetBitDepth() const final { return 16; } int SnapImage() final { - const auto startTime = std::chrono::steady_clock::now(); - - auto *hub = static_cast(GetParentHub()); - const auto z = hub->GetFocusUm(); - const auto xy = hub->GetXYUm(); - - const std::size_t nPixels = roiWidth_ * roiHeight_; - snapBuffer_ = - std::unique_ptr(new std::uint16_t[nPixels]); - - const double magnification = hub->GetMagnification(); - const double na = hub->GetNA(); - // 10um is a reasonable size for a CMOS pixel side length - // and it makes pixel configuration simple. - const double umPerPx = 10.0 / magnification; - // FOV center is -stagePosition (needed for tiles to align). - const double fovCenterX = xy.first; - const double fovCenterY = -xy.second; - const double x = fovCenterX - umPerPx * (double(roiX_) - - double(sensorWidth_) / 2.0); - const double y = fovCenterY - umPerPx * (double(roiY_) - - double(sensorHeight_) / 2.0); - // Derive intensity using epi-illumination formula - const double intensity = 2800.0 * GetExposure() * GetBinning() * - GetBinning() * (na * na * na * na) / - (magnification * magnification); - const float *signal = nullptr; - if (hub->IsShutterOpen()) { - signal_.resize(nPixels); - if (mode_ == modeNuclei_) { - nucleiSpecimen_.Draw(signal_.data(), x, y, z, roiWidth_, - roiHeight_, umPerPx, na, intensity); - } else { - filamentsSpecimen_.Draw(signal_.data(), x, y, z, roiWidth_, - roiHeight_, umPerPx, na, intensity); - } - signal = signal_.data(); + if (IsCapturing()) { + return DEVICE_CAMERA_BUSY_ACQUIRING; } - // TODO: Make read noise and offset adjustable? - constexpr float readNoise = 50.0f; - constexpr float darkOffset = 100.0f; - ReadOut(signal, snapBuffer_.get(), nPixels, readNoise, darkOffset, - rng_); - - std::chrono::duration exposure(GetExposure()); - const auto finishTime = - startTime + - std::chrono::round(exposure); - std::this_thread::sleep_until(finishTime); - + const auto startTime = std::chrono::steady_clock::now(); + const FrameSettings settings = SnapshotSettings(); + GenerateFrame(settings); + std::this_thread::sleep_until(startTime + + ExposureDuration(settings.exposure_ms)); return DEVICE_OK; } @@ -186,14 +170,19 @@ class SimCam : public CCameraBase { return DEVICE_OK; } - double GetExposure() const final { return exposure_ms_; } + double GetExposure() const final { + std::lock_guard lock(settingsMutex_); + return exposure_ms_; + } void SetExposure(double exposure_ms) final { + std::lock_guard lock(settingsMutex_); exposure_ms_ = std::min(EXPOSURE_MS_MAX, std::max(EXPOSURE_MS_MIN, exposure_ms)); } int GetROI(unsigned &x, unsigned &y, unsigned &width, unsigned &height) final { + std::lock_guard lock(settingsMutex_); x = roiX_; y = roiY_; width = roiWidth_; @@ -202,12 +191,16 @@ class SimCam : public CCameraBase { } int SetROI(unsigned x, unsigned y, unsigned width, unsigned height) final { + if (IsCapturing()) { + return DEVICE_CAMERA_BUSY_ACQUIRING; + } if (width == 0 || height == 0) { return DEVICE_INVALID_INPUT_PARAM; } if (x + width > sensorWidth_ || y + height > sensorHeight_) { return DEVICE_INVALID_INPUT_PARAM; } + std::lock_guard lock(settingsMutex_); roiX_ = x; roiY_ = y; roiWidth_ = width; @@ -227,73 +220,130 @@ class SimCam : public CCameraBase { (void)interval_ms; (void)stopOnOverflow; - if (IsCapturing()) { + if (capturing_) { return DEVICE_CAMERA_BUSY_ACQUIRING; } - if (numImages < 1) { return DEVICE_INVALID_INPUT_PARAM; } - const std::size_t nImages = static_cast(numImages); - const auto interval = - std::chrono::microseconds(std::llround(exposure_ms_ * 1000.0)); - - seqStopRequested_ = false; - seqThread_ = std::thread([this, nImages, interval] { - int ret = DEVICE_OK; - ret = GetCoreCallback()->PrepareForAcq(this); - if (ret != DEVICE_OK) { - GetCoreCallback()->AcqFinished(this, ret); - return; - } - auto prevTimeTaken = std::chrono::steady_clock::duration{}; - for (std::size_t i = 0; i < nImages; ++i) { - if (i > 0) { - const auto remainingTime = interval - prevTimeTaken; - std::unique_lock lock(seqMutex_); - if (seqStopCV_.wait_for(lock, remainingTime, [&] { - return seqStopRequested_; - })) { - break; - } - } - - const auto startTime = std::chrono::steady_clock::now(); - - // This is _not_ how to implement real cameras, but for this - // simulation we can implement in terms of snaps. - SnapImage(); - ret = GetCoreCallback()->InsertImage( - this, GetImageBuffer(), GetImageWidth(), GetImageHeight(), - GetImageBytesPerPixel()); - if (ret != DEVICE_OK) { - break; - } + if (seqThread_.joinable()) { + seqThread_.join(); + } + { + std::lock_guard lock(seqMutex_); + seqStopRequested_ = false; + } + capturing_ = true; - const auto stopTime = std::chrono::steady_clock::now(); - prevTimeTaken = stopTime - startTime; - } + const std::size_t nImages = static_cast(numImages); + seqThread_ = std::thread([this, nImages] { + const int ret = RunSequence(nImages); GetCoreCallback()->AcqFinished(this, ret); + capturing_ = false; }); return DEVICE_OK; } int StopSequenceAcquisition() final { - if (IsCapturing()) { - { - std::lock_guard lock(seqMutex_); - seqStopRequested_ = true; - } - seqStopCV_.notify_one(); + { + std::lock_guard lock(seqMutex_); + seqStopRequested_ = true; + } + seqStopCV_.notify_one(); + if (seqThread_.joinable()) { seqThread_.join(); } return DEVICE_OK; } - bool IsCapturing() final { return seqThread_.joinable(); } + bool IsCapturing() final { return capturing_; } int IsExposureSequenceable(bool &yesno) const final { yesno = false; return DEVICE_OK; } + + private: + static std::chrono::steady_clock::duration + ExposureDuration(double exposure_ms) { + return std::chrono::round( + std::chrono::duration(exposure_ms)); + } + + FrameSettings SnapshotSettings() const { + std::lock_guard lock(settingsMutex_); + return {exposure_ms_, roiX_, roiY_, roiWidth_, roiHeight_, mode_}; + } + + int RunSequence(std::size_t nImages) { + int ret = GetCoreCallback()->PrepareForAcq(this); + if (ret != DEVICE_OK) { + return ret; + } + for (std::size_t i = 0; i < nImages; ++i) { + const auto startTime = std::chrono::steady_clock::now(); + const FrameSettings settings = SnapshotSettings(); + GenerateFrame(settings); + { + std::unique_lock lock(seqMutex_); + if (seqStopCV_.wait_until( + lock, + startTime + ExposureDuration(settings.exposure_ms), + [&] { return seqStopRequested_; })) { + break; + } + } + ret = GetCoreCallback()->InsertImage( + this, reinterpret_cast(snapBuffer_.get()), + settings.roiWidth, settings.roiHeight, + GetImageBytesPerPixel()); + if (ret != DEVICE_OK) { + break; + } + } + return ret; + } + + void GenerateFrame(const FrameSettings &s) { + const auto z = hub_->GetFocusUm(); + const auto xy = hub_->GetXYUm(); + + const std::size_t nPixels = std::size_t(s.roiWidth) * s.roiHeight; + snapBuffer_ = + std::unique_ptr(new std::uint16_t[nPixels]); + + const double magnification = hub_->GetMagnification(); + const double na = hub_->GetNA(); + // 10um is a reasonable size for a CMOS pixel side length + // and it makes pixel configuration simple. + const double umPerPx = 10.0 / magnification; + // FOV center is -stagePosition (needed for tiles to align). + const double fovCenterX = xy.first; + const double fovCenterY = -xy.second; + const double x = fovCenterX - umPerPx * (double(s.roiX) - + double(sensorWidth_) / 2.0); + const double y = fovCenterY - umPerPx * (double(s.roiY) - + double(sensorHeight_) / 2.0); + // Derive intensity using epi-illumination formula + const double intensity = 2800.0 * s.exposure_ms * GetBinning() * + GetBinning() * (na * na * na * na) / + (magnification * magnification); + const float *signal = nullptr; + if (hub_->IsShutterOpen()) { + signal_.resize(nPixels); + if (s.mode == modeNuclei_) { + nucleiSpecimen_.Draw(signal_.data(), x, y, z, s.roiWidth, + s.roiHeight, umPerPx, na, intensity); + } else { + filamentsSpecimen_.Draw(signal_.data(), x, y, z, s.roiWidth, + s.roiHeight, umPerPx, na, intensity); + } + signal = signal_.data(); + } + // TODO: Make read noise and offset adjustable? + constexpr float readNoise = 50.0f; + constexpr float darkOffset = 100.0f; + ReadOut(signal, snapBuffer_.get(), nPixels, readNoise, darkOffset, + rng_); + } }; diff --git a/SimFocus.h b/SimFocus.h index 38fd9aa..0c80b25 100644 --- a/SimFocus.h +++ b/SimFocus.h @@ -20,12 +20,16 @@ class SimFocus : public CStageBase> { static constexpr double umPerStep_ = 0.1; std::string name_; - ProcModel model_; + SimHub *hub_ = nullptr; DelayedNotifier delayer_; std::mutex notificationMut_; bool notificationsEnabled_ = false; + // Declared last so that it is destroyed first: its slew thread's update + // function uses the members above. + ProcModel model_; + public: explicit SimFocus(std::string name) : name_(std::move(name)), model_([this](std::array pv) { @@ -44,11 +48,18 @@ class SimFocus : public CStageBase> { this->OnStagePositionChanged(umPerStep_ * ipv); }); }) { - // Adjust default for stage-like velocity (100 um/s). - model_.ReciprocalSlewRateSeconds(0.01 * umPerStep_); + if constexpr (ProcModel::isAsync) { + // Adjust default for stage-like velocity (100 um/s). + model_.ReciprocalSlewRateSeconds(0.01 * umPerStep_); + } } int Initialize() final { + hub_ = static_cast(this->GetParentHub()); + if (!hub_) { + return DEVICE_COMM_HUB_MISSING; + } + int ret = this->CreateFloatProperty("UmPerStep", umPerStep_, true); assert(ret == DEVICE_OK); @@ -98,7 +109,7 @@ class SimFocus : public CStageBase> { })); assert(ret == DEVICE_OK); - if (ProcModel::isAsync) { + if constexpr (ProcModel::isAsync) { ret = this->CreateFloatProperty( "SlewTimePerStep_s", model_.ReciprocalSlewRateSeconds(), false, new MM::ActionLambda( @@ -158,8 +169,7 @@ class SimFocus : public CStageBase> { } (void)ret; - auto *hub = static_cast(this->GetParentHub()); - hub->SetGetFocusUmFunction([this] { + hub_->SetGetFocusUmFunction([this] { double z_um; // Technically the specimen Z may differ from the software Z um, // but we treat them as the same thing for nowa. @@ -171,8 +181,10 @@ class SimFocus : public CStageBase> { } int Shutdown() final { - auto *hub = static_cast(this->GetParentHub()); - hub->SetGetFocusUmFunction([] { return 0.0; }); + if (hub_) { + hub_->SetGetFocusUmFunction([] { return 0.0; }); + hub_ = nullptr; + } model_.Halt(); delayer_.CancelAll(); return DEVICE_OK; diff --git a/SimHub.h b/SimHub.h index 9690be2..756219b 100644 --- a/SimHub.h +++ b/SimHub.h @@ -3,12 +3,17 @@ #include "DeviceBase.h" #include +#include #include #include class SimHub : public HubBase { std::string name_; + // Held while invoking the functions, so that a peripheral's Shutdown() + // (which replaces its function) cannot return while the camera is still + // calling into it. + mutable std::mutex mut_; std::function getFocusUmFunc_ = [] { return 0.0; }; std::function()> getXYUmFunc_ = [] { return std::make_pair(0.0, 0.0); @@ -29,24 +34,48 @@ class SimHub : public HubBase { int DetectInstalledDevices() final; template void SetGetFocusUmFunction(F f) { - getFocusUmFunc_ = f; + std::lock_guard lock(mut_); + getFocusUmFunc_ = std::move(f); } - template void SetGetXYUmFunction(F f) { getXYUmFunc_ = f; } + template void SetGetXYUmFunction(F f) { + std::lock_guard lock(mut_); + getXYUmFunc_ = std::move(f); + } template void SetGetMagnificationFunction(F f) { - getMagnificationFunc_ = f; + std::lock_guard lock(mut_); + getMagnificationFunc_ = std::move(f); } - template void SetGetNAFunction(F f) { getNAFunc_ = f; } + template void SetGetNAFunction(F f) { + std::lock_guard lock(mut_); + getNAFunc_ = std::move(f); + } template void SetGetShutterOpenFunction(F f) { - getShutterOpenFunc_ = f; + std::lock_guard lock(mut_); + getShutterOpenFunc_ = std::move(f); } - double GetFocusUm() { return getFocusUmFunc_(); } - std::pair GetXYUm() { return getXYUmFunc_(); } - double GetMagnification() { return getMagnificationFunc_(); } - double GetNA() { return getNAFunc_(); } - bool IsShutterOpen() { return getShutterOpenFunc_(); } + double GetFocusUm() { + std::lock_guard lock(mut_); + return getFocusUmFunc_(); + } + std::pair GetXYUm() { + std::lock_guard lock(mut_); + return getXYUmFunc_(); + } + double GetMagnification() { + std::lock_guard lock(mut_); + return getMagnificationFunc_(); + } + double GetNA() { + std::lock_guard lock(mut_); + return getNAFunc_(); + } + bool IsShutterOpen() { + std::lock_guard lock(mut_); + return getShutterOpenFunc_(); + } }; diff --git a/SimObjectiveTurret.h b/SimObjectiveTurret.h index 869a8c0..d32c1b6 100644 --- a/SimObjectiveTurret.h +++ b/SimObjectiveTurret.h @@ -4,6 +4,7 @@ #include "SimHub.h" #include +#include #include #include #include @@ -34,6 +35,11 @@ class SimObjectiveTurret : public CStateDeviceBase { ~SimObjectiveTurret() { Shutdown(); } int Initialize() final { + hub_ = static_cast(GetParentHub()); + if (!hub_) { + return DEVICE_COMM_HUB_MISSING; + } + int ret{}; // create default positions and labels @@ -65,24 +71,22 @@ class SimObjectiveTurret : public CStateDeviceBase { if (ret != DEVICE_OK) return ret; - auto *hub = static_cast(this->GetParentHub()); - hub->SetGetMagnificationFunction([this] { - return objectives_[static_cast(state_)].magnification; + hub_->SetGetMagnificationFunction([this] { + return objectives_[static_cast(state_.load())] + .magnification; }); - hub->SetGetNAFunction([this] { - return objectives_[static_cast(state_)].na; + hub_->SetGetNAFunction([this] { + return objectives_[static_cast(state_.load())].na; }); - initialized_ = true; return DEVICE_OK; } int Shutdown() final { - if (initialized_) { - auto *hub = static_cast(this->GetParentHub()); - hub->SetGetMagnificationFunction([] { return 1.0; }); - hub->SetGetNAFunction([] { return 1.0; }); - initialized_ = false; + if (hub_) { + hub_->SetGetMagnificationFunction([] { return 1.0; }); + hub_->SetGetNAFunction([] { return 1.0; }); + hub_ = nullptr; } return DEVICE_OK; } @@ -94,12 +98,12 @@ class SimObjectiveTurret : public CStateDeviceBase { bool Busy() { return false; }; unsigned long GetNumberOfPositions() const { - return static_cast(objectives_.size()); + return static_cast(objectives_.size()); } int OnState(MM::PropertyBase *pProp, MM::ActionType eAct) { if (eAct == MM::BeforeGet) { - pProp->Set(state_); + pProp->Set(state_.load()); } else if (eAct == MM::AfterSet) { long newState; pProp->Get(newState); @@ -107,7 +111,7 @@ class SimObjectiveTurret : public CStateDeviceBase { newState < static_cast(objectives_.size())) { state_ = newState; } else { - pProp->Set(state_); + pProp->Set(state_.load()); return DEVICE_INVALID_PROPERTY_VALUE; } } @@ -115,7 +119,8 @@ class SimObjectiveTurret : public CStateDeviceBase { } private: - bool initialized_ = false; std::string name_; - long state_ = 0; + SimHub *hub_ = nullptr; + // Read by the camera thread via the hub + std::atomic state_{0}; }; diff --git a/SimShutter.h b/SimShutter.h index 857acb9..92a772c 100644 --- a/SimShutter.h +++ b/SimShutter.h @@ -10,7 +10,7 @@ class SimShutter : public CShutterBase { std::string name_; - bool initialized_ = false; + SimHub *hub_ = nullptr; // Shutter state std::atomic isOpen_{false}; @@ -32,6 +32,11 @@ class SimShutter : public CShutterBase { int Fire(double /*deltaT*/) final { return DEVICE_UNSUPPORTED_COMMAND; } int Initialize() final { + hub_ = static_cast(GetParentHub()); + if (!hub_) { + return DEVICE_COMM_HUB_MISSING; + } + isOpen_ = false; int ret = CreateIntegerProperty( @@ -56,18 +61,15 @@ class SimShutter : public CShutterBase { if (ret != DEVICE_OK) return ret; - auto *hub = static_cast(GetParentHub()); - hub->SetGetShutterOpenFunction([this] { return isOpen_.load(); }); - initialized_ = true; + hub_->SetGetShutterOpenFunction([this] { return isOpen_.load(); }); return DEVICE_OK; } int Shutdown() final { isOpen_ = false; - if (initialized_) { - auto *hub = static_cast(GetParentHub()); - hub->SetGetShutterOpenFunction([] { return true; }); - initialized_ = false; + if (hub_) { + hub_->SetGetShutterOpenFunction([] { return true; }); + hub_ = nullptr; } return DEVICE_OK; } diff --git a/SimXY.h b/SimXY.h index 6ef5b6d..1df2265 100644 --- a/SimXY.h +++ b/SimXY.h @@ -20,12 +20,16 @@ class SimXY : public CXYStageBase> { // readout). X and Y use the same step size. static constexpr double umPerStep_ = 0.1; std::string name_; - ProcModel model_; + SimHub *hub_ = nullptr; DelayedNotifier delayer_; std::mutex notificationMut_; bool notificationsEnabled_ = false; + // Declared last so that it is destroyed first: its slew thread's update + // function uses the members above. + ProcModel model_; + public: explicit SimXY(std::string name) : name_(std::move(name)), model_([this](std::array pv) { @@ -50,11 +54,18 @@ class SimXY : public CXYStageBase> { umPerStep_ * iy); }); }) { - // Adjust default for stage-like velocity (100 um/s). - model_.ReciprocalSlewRateSeconds(umPerStep_ / 100.0); + if constexpr (ProcModel::isAsync) { + // Adjust default for stage-like velocity (100 um/s). + model_.ReciprocalSlewRateSeconds(umPerStep_ / 100.0); + } } int Initialize() final { + hub_ = static_cast(this->GetParentHub()); + if (!hub_) { + return DEVICE_COMM_HUB_MISSING; + } + int ret = this->CreateFloatProperty("UmPerStep", umPerStep_, true); assert(ret == DEVICE_OK); @@ -84,7 +95,7 @@ class SimXY : public CXYStageBase> { ret = this->AddAllowedValue("NotificationsEnabled", "Yes"); assert(ret == DEVICE_OK); - if (ProcModel::isAsync) { + if constexpr (ProcModel::isAsync) { ret = this->CreateFloatProperty( "SlewTimePerStep_s", model_.ReciprocalSlewRateSeconds(), false, new MM::ActionLambda( @@ -144,8 +155,7 @@ class SimXY : public CXYStageBase> { } (void)ret; - auto *hub = static_cast(this->GetParentHub()); - hub->SetGetXYUmFunction([this] { + hub_->SetGetXYUmFunction([this] { // We do _not_ call GetPositionUm() here, because those um coords // may be flipped wrt the specimen due to TransposeMirrorX/Y. // Instead, we use a pure scaling of the steps here. @@ -162,8 +172,10 @@ class SimXY : public CXYStageBase> { } int Shutdown() final { - auto *hub = static_cast(this->GetParentHub()); - hub->SetGetXYUmFunction([] { return std::make_pair(0.0, 0.0); }); + if (hub_) { + hub_->SetGetXYUmFunction([] { return std::make_pair(0.0, 0.0); }); + hub_ = nullptr; + } model_.Halt(); delayer_.CancelAll(); return DEVICE_OK; diff --git a/Specimen.h b/Specimen.h index 9fd89f9..c767665 100644 --- a/Specimen.h +++ b/Specimen.h @@ -43,8 +43,8 @@ void RenderSpecimenImage(float *signal, double x_um, double y_um, double z_um, BLPath origin_marker; origin_marker.moveTo(0.0, 0.0); - origin_marker.lineTo(50.0, 50.0); - origin_marker.addCircle(BLCircle(0.0, 0.0, 50.0)); + origin_marker.lineTo(12.5, 12.5); + origin_marker.addCircle(BLCircle(0.0, 0.0, 12.5)); ctx.strokePath(origin_marker, BLRgba32(0xaaaaaaaa)); drawContent(ctx);