2 * Copyright (C) 2010-2012 Intel Corporation
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <cutils/log.h>
19 #include "SensorIIODev.h"
22 static const std::string IIO_DIR = "/sys/bus/iio/devices";
23 static const int DEF_BUFFER_LEN = 2;
24 static const int DEF_HYST_VALUE = 0;
26 SensorIIODev::SensorIIODev(const std::string& dev_name, const std::string& units,
27 const std::string& exponent,
28 const std::string& channel_prefix, int retry_cnt)
31 unit_expo_str(exponent),
33 device_name(dev_name),
34 channel_prefix_str(channel_prefix),
37 retry_count(retry_cnt),
41 ALOGV("%s", __func__);
44 SensorIIODev::SensorIIODev(const std::string& dev_name, const std::string& units,
45 const std::string& exponent,
46 const std::string& channel_prefix)
49 unit_expo_str(exponent),
51 device_name(dev_name),
52 channel_prefix_str(channel_prefix),
59 ALOGV("%s", __func__);
62 int SensorIIODev::discover()
68 ALOGD(">>%s discover", __func__);
69 for (cnt = 0; cnt < retry_count; cnt++) {
70 status = ParseIIODirectory(device_name);
72 std::stringstream filename;
74 filename << "/dev/iio:device" << device_number;
75 mDevPath = filename.str();
76 ALOGV("mDevPath %s", mDevPath.c_str());
81 ALOGE("Sensor IIO Init failed, retry left:%d\n", retry_count-cnt);
85 // Device not enumerated yet, wait and retry
91 int SensorIIODev::AllocateRxBuffer()
93 ALOGV(">>%s Allocate:%d", __func__, datum_size * buffer_len);
94 raw_buffer = new unsigned char[datum_size * buffer_len];
96 ALOGE("AllocateRxBuffer: Failed\n");
102 int SensorIIODev::FreeRxBuffer()
104 ALOGV(">>%s", __func__);
110 int SensorIIODev::enable(int enabled)
114 ALOGD(">>%s enabled:%d", __func__, enabled);
116 if (mEnabled == enabled) {
120 // QUIRK: some sensor hubs need to be turned on and off and on
121 // before sending any information. So we turn it on and off first
122 // before enabling again later in this function.
126 if (ReadHIDExponentValue(&unit_expo_value) < 0)
128 if (ReadHIDMeasurmentUnit(&units_value) < 0)
130 if (SetDataReadyTrigger(GetDeviceNumber(), true) < 0)
132 if (EnableBuffer(1) < 0)
134 if (DeviceActivate(GetDeviceNumber(), 1) < 0)
136 if (DeviceSetSensitivity(GetDeviceNumber(), DEF_HYST_VALUE) < 0)
138 if (AllocateRxBuffer() < 0)
144 if (SetDataReadyTrigger(GetDeviceNumber(), false) < 0)
146 if (EnableBuffer(0) < 0)
148 if (DeviceActivate(GetDeviceNumber(), 0) < 0)
150 if (DeviceSetSensitivity(GetDeviceNumber(), 0))
152 if (FreeRxBuffer() < 0)
159 ALOGE("SesnorIIO: Enable failed\n");
163 int SensorIIODev::setDelay(int64_t delay_ns){
164 int ms = nsToMs(delay_ns);
167 ALOGV(">>%s %ld", __func__, delay_ns);
168 if (IsDeviceInitialized() == false){
169 ALOGE("Device was not initialized \n");
173 if ((r = SetSampleDelay(GetDeviceNumber(), ms)) < 0)
176 ALOGV("<<%s", __func__);
180 int SensorIIODev::setInitialState(){
181 mHasPendingEvent = false;
185 long SensorIIODev::GetUnitValue()
190 long SensorIIODev::GetExponentValue()
192 return unit_expo_value;
195 bool SensorIIODev::IsDeviceInitialized(){
199 int SensorIIODev::GetDeviceNumber(){
200 return device_number;
203 int SensorIIODev::GetDir(const std::string& dir, std::vector < std::string >& files){
207 if ((dp = opendir(dir.c_str())) == NULL){
208 ALOGE("Error opening directory %s\n", (char*)dir.c_str());
211 while ((dirp = readdir(dp)) != NULL){
212 files.push_back(std::string(dirp->d_name));
218 void SensorIIODev::ListFiles(const std::string& dir){
219 std::vector < std::string > files = std::vector < std::string > ();
223 for (unsigned int i = 0; i < files.size(); i++){
224 ALOGV("File List.. %s\n", (char*)files[i].c_str());
228 // This function returns a device number for IIO device
229 // For example if the device is "iio:device1", this will return 1
230 int SensorIIODev::FindDeviceNumberFromName(const std::string& name, const std::string&
233 std::vector < std::string > files = std::vector < std::string > ();
234 std::string device_name;
236 GetDir(std::string(IIO_DIR), files);
238 for (unsigned int i = 0; i < files.size(); i++){
239 std::stringstream ss;
240 if ((files[i] == ".") || (files[i] == "..") || files[i].length() <=
244 if (files[i].compare(0, prefix.length(), prefix) == 0){
245 sscanf(files[i].c_str() + prefix.length(), "%d", &dev_number);
247 ss << IIO_DIR << "/" << prefix << dev_number;
248 std::ifstream ifs(ss.str().c_str(), std::ifstream::in);
256 std::ifstream ifn((ss.str() + "/" + "name").c_str(), std::ifstream::in);
263 std::getline(ifn, device_name);
264 if (name.compare(device_name) == 0){
265 ALOGV("matched %s\n", device_name.c_str());
276 int SensorIIODev::SetUpTrigger(int dev_num){
277 std::stringstream trigger_name;
280 trigger_name << device_name << "-dev" << dev_num;
281 if (trigger_name.str().length()){
282 ALOGV("trigger_name %s\n", (char*)trigger_name.str().c_str());
283 trigger_num = FindDeviceNumberFromName(trigger_name.str(), "trigger");
284 if (trigger_num < 0){
285 ALOGE("Failed to find trigger\n");
290 ALOGE("trigger_name not found \n");
296 // Setup buffer length in terms of datum size
297 int SensorIIODev::SetUpBufferLen(int len){
298 std::stringstream filename;
299 std::stringstream len_str;
301 ALOGV("%s: len:%d", __func__, len);
303 filename << buffer_dir_name.str() << "/" << "length";
307 int ret = path_ops.write(filename.str(), len_str.str());
309 ALOGE("Write Error %s", filename.str().c_str());
317 int SensorIIODev::EnableBuffer(int status){
318 std::stringstream filename;
319 std::stringstream status_str;
321 ALOGV("%s: len:%d", __func__, status);
323 filename << buffer_dir_name.str() << "/" << "enable";
325 status_str << status;
326 int ret = path_ops.write(filename.str(), status_str.str());
328 ALOGE("Write Error %s", filename.str().c_str());
331 enable_buffer = status;
335 int SensorIIODev::EnableChannels(){
339 std::string dir = std::string(IIO_DIR);
340 std::vector < std::string > files = std::vector < std::string > ();
341 const std::string FORMAT_SCAN_ELEMENTS_DIR = "/scan_elements";
342 unsigned char signchar, bits_used, total_bits, shift, unused;
343 SensorIIOChannel iio_channel;
345 ALOGV(">>%s", __func__);
346 scan_el_dir.str(std::string());
347 scan_el_dir << dev_device_name.str() << FORMAT_SCAN_ELEMENTS_DIR;
348 GetDir(scan_el_dir.str(), files);
350 for (unsigned int i = 0; i < files.size(); i++){
351 int len = files[i].length();
352 if (len > 3 && files[i].compare(len - 3, 3, "_en") == 0){
353 std::stringstream filename, file_type;
356 filename << scan_el_dir.str() << "/" << files[i];
357 ret = path_ops.write(filename.str(), "1");
359 ALOGE("Channel Enable Error %s:%d", filename.str().c_str(), ret);
365 int SensorIIODev::BuildChannelList(){
369 std::string dir = std::string(IIO_DIR);
370 std::vector < std::string > files = std::vector < std::string > ();
371 const std::string FORMAT_SCAN_ELEMENTS_DIR = "/scan_elements";
372 unsigned char signchar, bits_used, total_bits, shift, unused;
373 SensorIIOChannel iio_channel;
374 std::string type_name;
376 ALOGV(">>%s", __func__);
377 scan_el_dir.str(std::string());
378 scan_el_dir << dev_device_name.str() << FORMAT_SCAN_ELEMENTS_DIR;
379 GetDir(scan_el_dir.str(), files);
381 // File ending with _en will specify a channel
382 // it contains the count. If we add all these count
383 // those many channels present
384 for (unsigned int i = 0; i < files.size(); i++){
385 int len = files[i].length();
386 // At the least the length should be more than 3 for "_en"
387 if (len > 3 && files[i].compare(len - 3, 3, "_en") == 0){
388 std::stringstream filename, file_type;
389 filename << scan_el_dir.str() << "/" << files[i];
390 std::ifstream ifs(filename.str().c_str(), std::ifstream::in);
396 count = ifs.get() - '0';
401 iio_channel.enabled = 1;
402 iio_channel.scale = 1.0;
403 iio_channel.offset = 0;
405 iio_channel.name = files[i].substr(0, files[i].length() - 3);
407 ALOGV("IIO channel name:%s\n", (char*)iio_channel.name.c_str());
408 file_type << scan_el_dir.str() << "/" << iio_channel.name <<
411 std::ifstream its(file_type.str().c_str(), std::ifstream::in);
416 std::getline(its, type_name);
417 sscanf(type_name.c_str(), "%c%c%c%c%u/%u>>%u", (unsigned char*) &unused,
418 (unsigned char*) &unused, (unsigned char*) &unused, (unsigned
419 char*) &signchar, (unsigned int*) &bits_used, (unsigned int*)
420 &total_bits, (unsigned int*) &shift);
423 // Buggy sscanf on some platforms
424 if (total_bits == 0 || bits_used == 0){
425 if (!strcmp(type_name.c_str(), "le:s16/32")){
429 else if (!strcmp(type_name.c_str(), "le:s16/16")){
439 iio_channel.bytes = total_bits / 8;
440 iio_channel.real_bytes = bits_used / 8;
441 iio_channel.shift = shift;
442 iio_channel.is_signed = signchar;
445 info_array.push_back(iio_channel);
448 ALOGV("<<%s", __func__);
452 int SensorIIODev::GetSizeFromChannels(){
454 for (unsigned int i = 0; i < info_array.size(); i++){
455 SensorIIOChannel channel = info_array[i];
456 size += channel.bytes;
458 ALOGD("%s:%d:%d", __func__, info_array.size(), size);
462 int SensorIIODev::GetChannelBytesUsedSize(unsigned int channel_no){
463 if (channel_no < info_array.size()){
464 SensorIIOChannel channel = info_array[channel_no];
465 return channel.real_bytes;
471 int SensorIIODev::ParseIIODirectory(const std::string& name){
476 ALOGV(">>%s", __func__);
478 dev_device_name.str(std::string());
479 buffer_dir_name.str(std::string());
481 device_number = dev_num = FindDeviceNumberFromName(name, "iio:device");
483 ALOGE("Failed to find device %s\n", (char*)name.c_str());
487 // Construct device directory Eg. /sys/devices/iio:device0
488 dev_device_name << IIO_DIR << "/" << "iio:device" << dev_num;
490 // Construct device directory Eg. /sys/devices/iio:device0:buffer0
491 buffer_dir_name << dev_device_name.str() << "/" << "buffer";
494 ret = SetUpTrigger(dev_num);
496 ALOGE("ParseIIODirectory Failed due to Trigger\n");
500 // Setup buffer len. This is in the datum units, not an absolute number
501 SetUpBufferLen(DEF_BUFFER_LEN);
503 // Set up channel masks
504 ret = EnableChannels();
506 ALOGE("ParseIIODirectory Failed due Enable Channels failed\n");
507 if (ret == -EACCES) {
508 // EACCES means the nodes do not have current owner.
509 // Need to retry, or else sensors won't power on.
510 // Other errors can be ignored, as these nodes are
511 // set once, and will return error when set again.
516 // Parse the channels and build a list
517 ret = BuildChannelList();
519 ALOGE("ParseIIODirectory Failed due BuildChannelList\n");
523 datum_size = GetSizeFromChannels();
524 ALOGV("Datum Size %d", datum_size);
525 ALOGV("<<%s", __func__);
530 int SensorIIODev::SetDataReadyTrigger(int dev_num, bool status){
531 std::stringstream filename;
532 std::stringstream trigger_name;
535 ALOGV("%s: status:%d", __func__, status);
537 filename << dev_device_name.str() << "/trigger/current_trigger";
538 trigger_name << device_name << "-dev" << dev_num;
543 ret = path_ops.write(filename.str(), trigger_name.str());
545 ret = path_ops.write(filename.str(), " ");
547 ALOGE("Write Error %s:%d", filename.str().c_str(), ret);
548 // Ignore error, as this may be due to
549 // Trigger was active during resume
555 int SensorIIODev::DeviceActivate(int dev_num, int state){
556 std::stringstream filename;
557 std::stringstream activate_str;
559 ALOGV("%s: Device Activate:%d", __func__, rate);
563 // Set sensitivity in absolute terms
564 int SensorIIODev::DeviceSetSensitivity(int dev_num, int value){
565 std::stringstream filename;
566 std::stringstream sensitivity_str;
568 ALOGV("%s: Sensitivity :%d", __func__, value);
570 filename << IIO_DIR << "/" << "iio:device" << dev_num << "/" << channel_prefix_str << "hysteresis";
573 sensitivity_str << value;
574 int ret = path_ops.write(filename.str(), sensitivity_str.str());
576 ALOGE("Write Error %s", filename.str().c_str());
577 // Don't bail out as this field may be absent
582 // Set the sample period delay: units ms
583 int SensorIIODev::SetSampleDelay(int dev_num, int period){
584 std::stringstream filename;
585 std::stringstream sample_rate_str;
587 ALOGV("%s: sample_rate:%d", __func__, rate);
589 filename << IIO_DIR << "/" << "iio:device" << dev_num << "/" << channel_prefix_str << "sampling_frequency";
591 ALOGE("%s: Invalid_rate:%d", __func__, period);
594 sample_rate_str << 1000/period;
595 int ret = path_ops.write(filename.str(), sample_rate_str.str());
597 ALOGE("Write Error %s", filename.str().c_str());
598 // Don't bail out as this field may be absent
603 int SensorIIODev::readEvents(sensors_event_t *data, int count){
605 int numEventReceived;
616 if (mHasPendingEvent){
617 mHasPendingEvent = false;
618 mPendingEvent.timestamp = getTimestamp();
619 *data = mPendingEvent;
622 read_size = read(mFd, raw_buffer, datum_size * buffer_len);
623 numEventReceived = 0;
624 if (processEvent(raw_buffer, datum_size) >= 0){
625 mPendingEvent.timestamp = getTimestamp();
626 mPendingEvent.timestamp = getTimestamp();
627 *data = mPendingEvent;
630 return numEventReceived;
633 int SensorIIODev::ReadHIDMeasurmentUnit(long *unit){
634 std::stringstream filename;
636 std::string long_str;
638 filename << IIO_DIR << "/" << "iio:device" << device_number << "/" << unit_str;
640 std::ifstream its(filename.str().c_str(), std::ifstream::in);
642 ALOGE("%s: Can't Open :%s",
643 __func__, filename.str().c_str());
647 std::getline(its, long_str);
650 if (long_str.length() > 0){
651 *unit = atol(long_str.c_str());
654 ALOGE("ReadHIDMeasurmentUnit failed");
658 int SensorIIODev::ReadHIDExponentValue(long *exponent){
659 std::stringstream filename;
661 std::string long_str;
663 filename << IIO_DIR << "/" << "iio:device" << device_number << "/" << unit_expo_str;
665 std::ifstream its(filename.str().c_str(), std::ifstream::in);
667 ALOGE("%s: Can't Open :%s",
668 __func__, filename.str().c_str());
672 std::getline(its, long_str);
675 if (long_str.length() > 0){
676 *exponent = atol(long_str.c_str());
679 ALOGE("ReadHIDExponentValue failed");