summaryrefslogtreecommitdiff
path: root/src/laser.cpp
blob: f23faab5fe7d02e574d04f6506f3267a8a6fd13a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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;
}