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 <cutils/properties.h>
20 #include "SensorIIODev.h"
23 static const std::string IIO_DIR = "/sys/bus/iio/devices";
24 static const int DEF_BUFFER_LEN = 2;
25 static const int DEF_HYST_VALUE = 0;
27 SensorIIODev::SensorIIODev(const std::string& dev_name, const std::string& units,
28 const std::string& exponent,
29 const std::string& channel_prefix, int retry_cnt)
32 unit_expo_str(exponent),
34 device_name(dev_name),
35 channel_prefix_str(channel_prefix),
38 retry_count(retry_cnt),
40 sample_delay_min_ms(0)
42 ALOGV("%s", __func__);
45 SensorIIODev::SensorIIODev(const std::string& dev_name, const std::string& units,
46 const std::string& exponent,
47 const std::string& channel_prefix)
50 unit_expo_str(exponent),
52 device_name(dev_name),
53 channel_prefix_str(channel_prefix),
60 ALOGV("%s", __func__);
63 int SensorIIODev::discover()
69 // Allow overriding sample_delay_min_ms via properties using
70 // the IIO device name. e.g.:
71 // ro.sys.sensors_accel_3d_samp_min_ms = 16
72 char sampmin[PROPERTY_VALUE_MAX];
73 std::string pn = "ro.sys.sensors_" + device_name + "_samp_min_ms";
74 property_get(pn.c_str(), sampmin, "");
76 sample_delay_min_ms = strtol(sampmin, NULL, 10);
78 ALOGD(">>%s discover", __func__);
79 for (cnt = 0; cnt < retry_count; cnt++) {
80 status = ParseIIODirectory(device_name);
82 std::stringstream filename;
84 filename << "/dev/iio:device" << device_number;
85 mDevPath = filename.str();
86 ALOGV("mDevPath %s", mDevPath.c_str());
91 ALOGE("Sensor IIO Init failed, retry left:%d\n", retry_count-cnt);
95 // Device not enumerated yet, wait and retry
101 int SensorIIODev::AllocateRxBuffer()
103 ALOGV(">>%s Allocate:%d", __func__, datum_size * buffer_len);
104 raw_buffer = new unsigned char[datum_size * buffer_len];
106 ALOGE("AllocateRxBuffer: Failed\n");
112 int SensorIIODev::FreeRxBuffer()
114 ALOGV(">>%s", __func__);
120 int SensorIIODev::enable(int enabled)
124 ALOGD(">>%s enabled:%d", __func__, enabled);
126 if (mEnabled == enabled) {
130 // QUIRK: some sensor hubs need to be turned on and off and on
131 // before sending any information. So we turn it on and off first
132 // before enabling again later in this function.
136 if (ReadHIDExponentValue(&unit_expo_value) < 0)
138 if (ReadHIDMeasurmentUnit(&units_value) < 0)
140 if (SetDataReadyTrigger(GetDeviceNumber(), true) < 0)
142 if (EnableBuffer(1) < 0)
144 if (DeviceActivate(GetDeviceNumber(), 1) < 0)
146 if (DeviceSetSensitivity(GetDeviceNumber(), DEF_HYST_VALUE) < 0)
148 if (AllocateRxBuffer() < 0)
154 if (SetDataReadyTrigger(GetDeviceNumber(), false) < 0)
156 if (EnableBuffer(0) < 0)
158 if (DeviceActivate(GetDeviceNumber(), 0) < 0)
160 if (DeviceSetSensitivity(GetDeviceNumber(), 0))
162 if (FreeRxBuffer() < 0)
169 ALOGE("SesnorIIO: Enable failed\n");
173 int SensorIIODev::setDelay(int64_t delay_ns){
174 int ms = nsToMs(delay_ns);
177 ALOGV(">>%s %ld", __func__, delay_ns);
178 if (IsDeviceInitialized() == false){
179 ALOGE("Device was not initialized \n");
183 if ((r = SetSampleDelay(GetDeviceNumber(), ms)) < 0)
186 ALOGV("<<%s", __func__);
190 int SensorIIODev::setInitialState(){
191 mHasPendingEvent = false;
195 long SensorIIODev::GetUnitValue()
200 long SensorIIODev::GetExponentValue()
202 return unit_expo_value;
205 bool SensorIIODev::IsDeviceInitialized(){
209 int SensorIIODev::GetDeviceNumber(){
210 return device_number;
213 int SensorIIODev::GetDir(const std::string& dir, std::vector < std::string >& files){
217 if ((dp = opendir(dir.c_str())) == NULL){
218 ALOGE("Error opening directory %s\n", (char*)dir.c_str());
221 while ((dirp = readdir(dp)) != NULL){
222 files.push_back(std::string(dirp->d_name));
228 void SensorIIODev::ListFiles(const std::string& dir){
229 std::vector < std::string > files = std::vector < std::string > ();
233 for (unsigned int i = 0; i < files.size(); i++){
234 ALOGV("File List.. %s\n", (char*)files[i].c_str());
238 // This function returns a device number for IIO device
239 // For example if the device is "iio:device1", this will return 1
240 int SensorIIODev::FindDeviceNumberFromName(const std::string& name, const std::string&
243 std::vector < std::string > files = std::vector < std::string > ();
244 std::string device_name;
246 GetDir(std::string(IIO_DIR), files);
248 for (unsigned int i = 0; i < files.size(); i++){
249 std::stringstream ss;
250 if ((files[i] == ".") || (files[i] == "..") || files[i].length() <=
254 if (files[i].compare(0, prefix.length(), prefix) == 0){
255 sscanf(files[i].c_str() + prefix.length(), "%d", &dev_number);
257 ss << IIO_DIR << "/" << prefix << dev_number;
258 std::ifstream ifs(ss.str().c_str(), std::ifstream::in);
266 std::ifstream ifn((ss.str() + "/" + "name").c_str(), std::ifstream::in);
273 std::getline(ifn, device_name);
274 if (name.compare(device_name) == 0){
275 ALOGV("matched %s\n", device_name.c_str());
286 int SensorIIODev::SetUpTrigger(int dev_num){
287 std::stringstream trigger_name;
290 trigger_name << device_name << "-dev" << dev_num;
291 if (trigger_name.str().length()){
292 ALOGV("trigger_name %s\n", (char*)trigger_name.str().c_str());
293 trigger_num = FindDeviceNumberFromName(trigger_name.str(), "trigger");
294 if (trigger_num < 0){
295 ALOGE("Failed to find trigger\n");
300 ALOGE("trigger_name not found \n");
306 // Setup buffer length in terms of datum size
307 int SensorIIODev::SetUpBufferLen(int len){
308 std::stringstream filename;
309 std::stringstream len_str;
311 ALOGV("%s: len:%d", __func__, len);
313 filename << buffer_dir_name.str() << "/" << "length";
317 int ret = path_ops.write(filename.str(), len_str.str());
319 ALOGE("Write Error %s", filename.str().c_str());
327 int SensorIIODev::EnableBuffer(int status){
328 std::stringstream filename;
329 std::stringstream status_str;
331 ALOGV("%s: len:%d", __func__, status);
333 filename << buffer_dir_name.str() << "/" << "enable";
335 status_str << status;
336 int ret = path_ops.write(filename.str(), status_str.str());
338 ALOGE("Write Error %s", filename.str().c_str());
341 enable_buffer = status;
345 int SensorIIODev::EnableChannels(){
349 std::string dir = std::string(IIO_DIR);
350 std::vector < std::string > files = std::vector < std::string > ();
351 const std::string FORMAT_SCAN_ELEMENTS_DIR = "/scan_elements";
352 unsigned char signchar, bits_used, total_bits, shift, unused;
353 SensorIIOChannel iio_channel;
355 ALOGV(">>%s", __func__);
356 scan_el_dir.str(std::string());
357 scan_el_dir << dev_device_name.str() << FORMAT_SCAN_ELEMENTS_DIR;
358 GetDir(scan_el_dir.str(), files);
360 for (unsigned int i = 0; i < files.size(); i++){
361 int len = files[i].length();
362 if (len > 3 && files[i].compare(len - 3, 3, "_en") == 0){
363 std::stringstream filename, file_type;
366 filename << scan_el_dir.str() << "/" << files[i];
367 ret = path_ops.write(filename.str(), "1");
369 ALOGE("Channel Enable Error %s:%d", filename.str().c_str(), ret);
375 int SensorIIODev::BuildChannelList(){
379 std::string dir = std::string(IIO_DIR);
380 std::vector < std::string > files = std::vector < std::string > ();
381 const std::string FORMAT_SCAN_ELEMENTS_DIR = "/scan_elements";
382 unsigned char signchar, bits_used, total_bits, shift, unused;
383 SensorIIOChannel iio_channel;
384 std::string type_name;
386 ALOGV(">>%s", __func__);
387 scan_el_dir.str(std::string());
388 scan_el_dir << dev_device_name.str() << FORMAT_SCAN_ELEMENTS_DIR;
389 GetDir(scan_el_dir.str(), files);
391 // File ending with _en will specify a channel
392 // it contains the count. If we add all these count
393 // those many channels present
395 for (unsigned int i = 0; i < files.size(); i++){
396 int len = files[i].length();
397 // At the least the length should be more than 3 for "_en"
398 if (len > 3 && files[i].compare(len - 3, 3, "_en") == 0){
399 std::stringstream filename, file_type;
400 filename << scan_el_dir.str() << "/" << files[i];
401 std::ifstream ifs(filename.str().c_str(), std::ifstream::in);
407 count = ifs.get() - '0';
412 iio_channel.enabled = 1;
413 iio_channel.scale = 1.0;
414 iio_channel.offset = 0;
416 iio_channel.name = files[i].substr(0, files[i].length() - 3);
418 ALOGV("IIO channel name:%s\n", (char*)iio_channel.name.c_str());
419 file_type << scan_el_dir.str() << "/" << iio_channel.name <<
422 std::ifstream its(file_type.str().c_str(), std::ifstream::in);
427 std::getline(its, type_name);
428 sscanf(type_name.c_str(), "%c%c%c%c%u/%u>>%u", (unsigned char*) &unused,
429 (unsigned char*) &unused, (unsigned char*) &unused, (unsigned
430 char*) &signchar, (unsigned int*) &bits_used, (unsigned int*)
431 &total_bits, (unsigned int*) &shift);
434 // Buggy sscanf on some platforms
435 if (total_bits == 0 || bits_used == 0){
436 if (!strcmp(type_name.c_str(), "le:s16/32")){
440 else if (!strcmp(type_name.c_str(), "le:s16/16")){
450 iio_channel.bytes = total_bits / 8;
451 iio_channel.real_bytes = bits_used / 8;
452 iio_channel.shift = shift;
453 iio_channel.is_signed = signchar;
456 info_array.push_back(iio_channel);
459 ALOGV("<<%s", __func__);
463 int SensorIIODev::GetSizeFromChannels(){
465 for (unsigned int i = 0; i < info_array.size(); i++){
466 SensorIIOChannel channel = info_array[i];
467 size += channel.bytes;
469 ALOGD("%s:%d:%d", __func__, info_array.size(), size);
473 int SensorIIODev::GetChannelBytesUsedSize(unsigned int channel_no){
474 if (channel_no < info_array.size()){
475 SensorIIOChannel channel = info_array[channel_no];
476 return channel.real_bytes;
482 int SensorIIODev::ParseIIODirectory(const std::string& name){
487 ALOGV(">>%s", __func__);
489 dev_device_name.str(std::string());
490 buffer_dir_name.str(std::string());
492 device_number = dev_num = FindDeviceNumberFromName(name, "iio:device");
494 ALOGE("Failed to find device %s\n", (char*)name.c_str());
498 // Construct device directory Eg. /sys/devices/iio:device0
499 dev_device_name << IIO_DIR << "/" << "iio:device" << dev_num;
501 // Construct device directory Eg. /sys/devices/iio:device0:buffer0
502 buffer_dir_name << dev_device_name.str() << "/" << "buffer";
505 ret = SetUpTrigger(dev_num);
507 ALOGE("ParseIIODirectory Failed due to Trigger\n");
511 // Setup buffer len. This is in the datum units, not an absolute number
512 SetUpBufferLen(DEF_BUFFER_LEN);
514 // Set up channel masks
515 ret = EnableChannels();
517 ALOGE("ParseIIODirectory Failed due Enable Channels failed\n");
518 if (ret == -EACCES) {
519 // EACCES means the nodes do not have current owner.
520 // Need to retry, or else sensors won't power on.
521 // Other errors can be ignored, as these nodes are
522 // set once, and will return error when set again.
527 // Parse the channels and build a list
528 ret = BuildChannelList();
530 ALOGE("ParseIIODirectory Failed due BuildChannelList\n");
534 datum_size = GetSizeFromChannels();
535 ALOGV("Datum Size %d", datum_size);
536 ALOGV("<<%s", __func__);
541 int SensorIIODev::SetDataReadyTrigger(int dev_num, bool status){
542 std::stringstream filename;
543 std::stringstream trigger_name;
546 ALOGV("%s: status:%d", __func__, status);
548 filename << dev_device_name.str() << "/trigger/current_trigger";
549 trigger_name << device_name << "-dev" << dev_num;
554 ret = path_ops.write(filename.str(), trigger_name.str());
556 ret = path_ops.write(filename.str(), " ");
558 ALOGE("Write Error %s:%d", filename.str().c_str(), ret);
559 // Ignore error, as this may be due to
560 // Trigger was active during resume
566 int SensorIIODev::DeviceActivate(int dev_num, int state){
567 std::stringstream filename;
568 std::stringstream activate_str;
570 ALOGV("%s: Device Activate:%d", __func__, rate);
574 // Set sensitivity in absolute terms
575 int SensorIIODev::DeviceSetSensitivity(int dev_num, int value){
576 std::stringstream filename;
577 std::stringstream sensitivity_str;
579 ALOGV("%s: Sensitivity :%d", __func__, value);
581 filename << IIO_DIR << "/" << "iio:device" << dev_num << "/" << channel_prefix_str << "hysteresis";
584 sensitivity_str << value;
585 int ret = path_ops.write(filename.str(), sensitivity_str.str());
587 ALOGE("Write Error %s", filename.str().c_str());
588 // Don't bail out as this field may be absent
593 // Set the sample period delay: units ms
594 int SensorIIODev::SetSampleDelay(int dev_num, int period){
595 std::stringstream filename;
596 std::stringstream sample_rate_str;
598 ALOGV("%s: sample_rate:%d", __func__, rate);
600 if (sample_delay_min_ms && period < sample_delay_min_ms)
601 period = sample_delay_min_ms;
603 filename << IIO_DIR << "/" << "iio:device" << dev_num << "/" << channel_prefix_str << "sampling_frequency";
605 ALOGE("%s: Invalid_rate:%d", __func__, period);
608 sample_rate_str << 1000/period;
609 int ret = path_ops.write(filename.str(), sample_rate_str.str());
611 ALOGE("Write Error %s", filename.str().c_str());
612 // Don't bail out as this field may be absent
617 int SensorIIODev::readEvents(sensors_event_t *data, int count){
619 int numEventReceived;
630 if (mHasPendingEvent){
631 mHasPendingEvent = false;
632 mPendingEvent.timestamp = getTimestamp();
633 *data = mPendingEvent;
636 read_size = read(mFd, raw_buffer, datum_size);
637 numEventReceived = 0;
638 if(read_size != datum_size) {
639 ALOGE("read() error (or short count) from IIO device: %d\n", errno);
641 if (processEvent(raw_buffer, datum_size) >= 0) {
642 mPendingEvent.timestamp = getTimestamp();
643 *data = mPendingEvent;
647 return numEventReceived;
650 int SensorIIODev::ReadHIDMeasurmentUnit(long *unit){
651 std::stringstream filename;
653 std::string long_str;
655 filename << IIO_DIR << "/" << "iio:device" << device_number << "/" << unit_str;
657 std::ifstream its(filename.str().c_str(), std::ifstream::in);
659 ALOGE("%s: Can't Open :%s",
660 __func__, filename.str().c_str());
664 std::getline(its, long_str);
667 if (long_str.length() > 0){
668 *unit = atol(long_str.c_str());
671 ALOGE("ReadHIDMeasurmentUnit failed");
675 int SensorIIODev::ReadHIDExponentValue(long *exponent){
676 std::stringstream filename;
678 std::string long_str;
680 filename << IIO_DIR << "/" << "iio:device" << device_number << "/" << unit_expo_str;
682 std::ifstream its(filename.str().c_str(), std::ifstream::in);
684 ALOGE("%s: Can't Open :%s",
685 __func__, filename.str().c_str());
689 std::getline(its, long_str);
692 if (long_str.length() > 0){
693 *exponent = atol(long_str.c_str());
696 ALOGE("ReadHIDExponentValue failed");