summaryrefslogtreecommitdiff
path: root/src/laser.cpp
diff options
context:
space:
mode:
authorNikita Kostovsky <nikita@kostovsky.me>2025-01-14 18:04:32 +0100
committerNikita Kostovsky <nikita@kostovsky.me>2025-01-14 18:04:32 +0100
commit38acf876313c9bf28e41acd8bc29d6115c1e9285 (patch)
treedc59c6c26006f740e1990150f920f4032734fc13 /src/laser.cpp
parent201d98f63131242bb8871ed0c4a3ae9ebd4ef030 (diff)
refactoring
Diffstat (limited to 'src/laser.cpp')
-rw-r--r--src/laser.cpp70
1 files changed, 70 insertions, 0 deletions
diff --git a/src/laser.cpp b/src/laser.cpp
new file mode 100644
index 0000000..f23faab
--- /dev/null
+++ b/src/laser.cpp
@@ -0,0 +1,70 @@
+#include "laser.h"
+
+#include <filesystem>
+#include <fstream>
+#include <iostream>
+
+#include "macro.h"
+
+PwmLaser::PwmLaser(const std::string &pwmChip, const std::string &pwm)
+ : INIT_FIELD(pwmChip)
+ , INIT_FIELD(pwm)
+{}
+
+bool PwmLaser::init()
+{
+ if (m_pwmChip.empty() || m_pwm.empty()) {
+ std::cerr << __func__ << ":\tinvalid pwm config: pwmChip == '"
+ << m_pwmChip << "', pwm == '" << m_pwm << "'" << std::endl;
+ return false;
+ }
+
+ auto writeToFile = [](const auto &path, const auto &value) -> bool {
+ if (!std::filesystem::exists(path)) {
+ std::cerr << __func__ << "\tno such file: " << path << std::endl;
+
+ return false;
+ }
+
+ std::ofstream ofs(path, std::ios::out | std::ios::trunc);
+
+ if (!ofs) {
+ std::cerr << __func__ << "\tcannot open" << path << "for writing"
+ << std::endl;
+
+ return false;
+ }
+
+ ofs << value;
+
+ return true;
+ };
+
+ const std::filesystem::path pwmSystemRoot{"/sys/class/pwm"};
+ const auto pwmChipRoot = pwmSystemRoot / m_pwmChip;
+ const auto pwmExportFile = pwmChipRoot / "export";
+
+ if (!writeToFile(pwmExportFile, m_pwm))
+ return false;
+
+ const auto pwmRoot = pwmChipRoot / m_pwm;
+ const auto periodFilename = pwmRoot / "period";
+ constexpr unsigned periodHz{50'000};
+
+ if (!writeToFile(periodFilename, periodHz))
+ return false;
+
+ const auto dutyCycleFilename = pwmRoot / "duty_cycle";
+ const unsigned dutyCycle{3'000};
+
+ if (!writeToFile(dutyCycleFilename, dutyCycle))
+ return false;
+
+ const auto enableFilename = pwmRoot / "enable";
+ const int enable{1};
+
+ if (!writeToFile(enableFilename, enable))
+ return false;
+
+ return true;
+}