xref: /openbmc/phosphor-led-sysfs/sysfs.cpp (revision ebc30b7f)
1 /**
2  * Copyright © 2019 IBM Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "sysfs.hpp"
18 
19 #include <fstream>
20 #include <iostream>
21 #include <string>
22 
23 namespace fs = std::filesystem;
24 
25 namespace phosphor
26 {
27 namespace led
28 {
29 
30 constexpr char SysfsLed::BRIGHTNESS[];
31 constexpr char SysfsLed::MAX_BRIGHTNESS[];
32 constexpr char SysfsLed::TRIGGER[];
33 constexpr char SysfsLed::DELAY_ON[];
34 constexpr char SysfsLed::DELAY_OFF[];
35 
36 template <typename T>
37 T get_sysfs_attr(const fs::path& path);
38 
39 template <>
40 std::string get_sysfs_attr(const fs::path& path)
41 {
42     std::string content;
43     std::ifstream file(path);
44     file >> content;
45     return content;
46 }
47 
48 template <>
49 unsigned long get_sysfs_attr(const fs::path& path)
50 {
51     std::string content = get_sysfs_attr<std::string>(std::move(path));
52     return std::strtoul(content.c_str(), nullptr, 0);
53 }
54 
55 template <typename T>
56 void set_sysfs_attr(const fs::path& path, const T& value)
57 {
58     std::ofstream file(path);
59     file << value;
60 }
61 
62 unsigned long SysfsLed::getBrightness()
63 {
64     return get_sysfs_attr<unsigned long>(root / BRIGHTNESS);
65 }
66 
67 void SysfsLed::setBrightness(unsigned long brightness)
68 {
69     set_sysfs_attr<unsigned long>(root / BRIGHTNESS, brightness);
70 }
71 
72 unsigned long SysfsLed::getMaxBrightness()
73 {
74     return get_sysfs_attr<unsigned long>(root / MAX_BRIGHTNESS);
75 }
76 
77 std::string SysfsLed::getTrigger()
78 {
79     return get_sysfs_attr<std::string>(root / TRIGGER);
80 }
81 
82 void SysfsLed::setTrigger(const std::string& trigger)
83 {
84     set_sysfs_attr<std::string>(root / TRIGGER, trigger);
85 }
86 
87 unsigned long SysfsLed::getDelayOn()
88 {
89     return get_sysfs_attr<unsigned long>(root / DELAY_ON);
90 }
91 
92 void SysfsLed::setDelayOn(unsigned long ms)
93 {
94     set_sysfs_attr<unsigned long>(root / DELAY_ON, ms);
95 }
96 
97 unsigned long SysfsLed::getDelayOff()
98 {
99     return get_sysfs_attr<unsigned long>(root / DELAY_OFF);
100 }
101 
102 void SysfsLed::setDelayOff(unsigned long ms)
103 {
104     set_sysfs_attr<unsigned long>(root / DELAY_OFF, ms);
105 }
106 } // namespace led
107 } // namespace phosphor
108