diff options
Diffstat (limited to 'src/laser.cpp')
| -rw-r--r-- | src/laser.cpp | 70 |
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; +} |
