#include "laser.h" #include #include #include #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; }