blob: 0292082a454782991e65fd545dbc4c46a63503fd [file] [log] [blame]
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "led_driver_sysfs.h"
#include <fcntl.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <base/logging.h>
namespace android {
namespace {
const char kSysfsLedPathPrefix[] = "/sys/class/leds/";
const char kMaxBrightnessFilename[] = "max_brightness";
const char kBrightnessFilename[] = "brightness";
} // namespace
LedDriverSysfs::LedDriverSysfs(std::string* prefix)
: fd_(-1), prefix_(prefix) {}
LedDriverSysfs::~LedDriverSysfs() {
if (fd_ >= 0) {
close(fd_);
}
}
bool LedDriverSysfs::Init(const std::string& name) {
LOG(INFO) << "Opening " << name;
// If a custom prefix was defined, use it.
std::string path = prefix_ ? *prefix_ + name : kSysfsLedPathPrefix + name;
int fd = open(path.c_str(), O_RDONLY);
if (fd < 0) {
PLOG(WARNING) << "Failed to open " << path;
return false;
}
fd_ = fd;
return true;
}
bool LedDriverSysfs::SetBrightness(uint32_t val) {
return WriteToFile(kBrightnessFilename, std::to_string(val));
}
bool LedDriverSysfs::GetBrightness(uint32_t* val) {
std::string str_val;
if (!ReadFromFile(kBrightnessFilename, &str_val))
return false;
*val = std::stoi(str_val);
return true;
}
bool LedDriverSysfs::GetMaxBrightness(uint32_t* val) {
std::string str_val;
if (!ReadFromFile(kMaxBrightnessFilename, &str_val))
return false;
*val = std::stoi(str_val);
return true;
}
bool LedDriverSysfs::ReadFromFile(const std::string& file, std::string* value) {
int fd = openat(fd_, file.c_str(), O_RDONLY);
if (fd < 0)
return false;
char tmp_buf[16] = "";
ssize_t bytes = read(fd, tmp_buf, sizeof(tmp_buf));
close(fd);
if (bytes < 0)
return false;
value->assign(tmp_buf, bytes);
return true;
}
bool LedDriverSysfs::WriteToFile(const std::string& file,
const std::string& value) {
int fd = openat(fd_, file.c_str(), O_RDWR);
if (fd < 0)
return false;
ssize_t bytes = write(fd, value.c_str(), value.size());
close(fd);
if (bytes < 0)
return false;
if ((size_t)bytes != value.size())
return false;
return true;
}
} // namespace android