void OemtabletMagnetometerAdaptor::processSample(int pathId, int fd)
{
    int x, y, z;

    if (pathId != devId) {
        sensordLogW() << "pathId != devId";
        return;
    }
    lseek(fd, 0, SEEK_SET);
    if (read(fd, buf, sizeof(buf)) <= 0) {
        sensordLogW() << "read():" << strerror(errno);
        return;
    }
    sensordLogT() << "Magnetometer output value: " << buf;

    sscanf(buf, "(%d,%d,%d)", &x, &y, &z);

    TimedXyzData* pos = magnetBuffer_->nextSlot();
    pos->x_ = x;
    pos->y_ = y;
    pos->z_ = z;
    pos->timestamp_ = Utils::getTimeStamp();

    magnetBuffer_->commit();
    magnetBuffer_->wakeUpReaders();
}
// Return the number of channels
int IioAdaptor::scanElementsEnable(int device, int enable)
{
    QString elementsPath = deviceGetPath(device) + "/scan_elements";

    QDir dir(elementsPath);
    if (!dir.exists()) {
        sensordLogW() << "Directory " << elementsPath << " doesn't exists";
        return 0;
    }

    // Find all the *_en file and write 0/1 to it
    QStringList filters;
    filters << "*_en";
    dir.setNameFilters(filters);

    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);

        if (enable) {
            QString base = fileInfo.filePath();
            // Remove the _en
            base.chop(3);

            int index = sysfsReadInt(base + "_index");
            int bytes = deviceChannelParseBytes(base + "_type");

            devices_[device].channel_bytes[index] = bytes;
        }

        sysfsWriteInt(fileInfo.filePath(), enable);
    }

    return list.size();
}
Esempio n. 3
0
void ALSAdaptorSysfs::processSample(int pathId, int fd)
{
    Q_UNUSED(pathId);

    char asciidata[6];
    __u16 idata = 0;

    int bytesRead = read(fd, &asciidata, sizeof(asciidata));
    asciidata[sizeof(asciidata)-1] = '\0';

    idata = atoi(asciidata);

    if (bytesRead <= 0) {
        sensordLogW() << "read(): " << strerror(errno);
        return;
    }

    sensordLogT() << "Ambient light value: " << idata;

    TimedUnsigned* lux = alsBuffer_->nextSlot();
    lux->value_ = idata;

    lux->timestamp_ = Utils::getTimeStamp();

    alsBuffer_->commit();
    alsBuffer_->wakeUpReaders();
}
Esempio n. 4
0
void MagnetometerAdaptor::processSample(int pathId, int fd)
{
    Q_UNUSED(pathId);

    struct ak8974_data mag_data;

    unsigned int bytesRead = read(fd, &mag_data, sizeof(mag_data));

    if (bytesRead < sizeof(mag_data)) {
        sensordLogW() << "read " << bytesRead  << " bytes out of expected " << sizeof(mag_data) << " bytes. Previous error: " << strerror(errno);
        //return;
    }

    if (!mag_data.valid) {
        // Can't trust this, printed for curiosity
        sensordLogD() << "Invalid sample received from magnetometer";
    }

    sensordLogT() << "Magnetometer reading: " << mag_data.x << ", " << mag_data.y << ", " << mag_data.z;

    CalibratedMagneticFieldData* sample = magnetometerBuffer_->nextSlot();

    sample->timestamp_ = Utils::getTimeStamp();
    sample->x_ = mag_data.x;
    sample->y_ = mag_data.y;
    sample->z_ = mag_data.z;

    magnetometerBuffer_->commit();
    magnetometerBuffer_->wakeUpReaders();
}
void SteAccelAdaptor::processSample(int pathId, int fd)
{
    Q_UNUSED(pathId);
    char buf[32];
    int x, y, z;

//    if (pathId != devId) {
//        sensordLogW () << "Wrong pathId" << pathId;
//        return;
//    }

    lseek(fd, 0, SEEK_SET);
    if (read(fd, buf, sizeof(buf)) < 0 ) {
        sensordLogW() << "Read failed";
        stopSensor();
        return;
    }
    QString line(buf);

    x = line.section(":",0,0).toInt();
    y = line.section(":",1,1).toInt();
    z = line.section(":",2,2).toInt();

    AccelerationData *d = buffer->nextSlot();

    d->timestamp_ = Utils::getTimeStamp();

    d->x_ = x * 0.1 * 9.812865328;
    d->y_ = y * 0.1 * 9.812865328;
    d->z_ = z * 0.1 * 9.812865328;
    buffer->commit();
    buffer->wakeUpReaders();
}
Esempio n. 6
0
void SensorManager::setError(SensorManagerError errorCode, const QString& errorString)
{
    sensordLogW() << "SensorManagerError: " << errorString;

    errorCode_   = errorCode;
    errorString_ = errorString;

    emit errorSignal(errorCode);
}
Esempio n. 7
0
const SensorInstanceEntry* SensorManager::getSensorInstance(const QString& id) const
{
    QMap<QString, SensorInstanceEntry>::const_iterator it(sensorInstanceMap_.find(id));
    if(it == sensorInstanceMap_.end())
    {
        sensordLogW() << "Failed to locate sensor instance: " << id;
        return NULL;
    }
    return &it.value();
}
Esempio n. 8
0
void SocketHandler::socketDisconnected()
{
    QLocalSocket* socket = (QLocalSocket*)sender();

    int sessionId = -1;
    for(QMap<int, SessionData*>::const_iterator it = m_idMap.constBegin(); it != m_idMap.constEnd(); ++it)
    {
        if(it.value()->getSocket() == socket)
            sessionId = it.key();
    }

    if (sessionId == -1) {
        sensordLogW() << "[SocketHandler]: Noticed lost session, but can't find it.";
        return;
    }

    sensordLogW() << "[SocketHandler]: Noticed lost session: " << sessionId;
    emit lostSession(sessionId);
}
Esempio n. 9
0
void SensorManager::sensorDataHandler(int)
{
    PipeData pipeData;
    read(pipefds_[0], &pipeData, sizeof(pipeData));

    if (!socketHandler_->write(pipeData.id, pipeData.buffer, pipeData.size)) {
        sensordLogW() << "Failed to write data to socket.";
    }

    free(pipeData.buffer);
}
Esempio n. 10
0
FilterBase* SensorManager::instantiateFilter(const QString& id)
{
    sensordLogD() << "Instantiating filter: " << id;

    QMap<QString, FilterFactoryMethod>::iterator it = filterFactoryMap_.find(id);
    if(it == filterFactoryMap_.end())
    {
        sensordLogW() << "Filter " << id << " not found.";
        return NULL;
    }
    return it.value()();
}
int IioAdaptor::sysfsReadInt(QString filename)
{
    QString string = sysfsReadString(filename);

    bool ok;
    int value = string.toInt(&ok);

    if (!ok) {
        sensordLogW() << "Failed to parse '" << string << "' to int from file " << filename;
    }

	return value;
}
Esempio n. 12
0
bool SensorManager::releaseSensor(const QString& id, int sessionId)
{
    sensordLogD() << "Releasing sensor '" << id << "' for session: " << sessionId;

    clearError();

    if( id.contains(';') ) // no parameter passing in release
    {
        sensordLogW() << "Invalid parameter passed to releaseSensor(): " << id;
        return false;
    }

    QMap<QString, SensorInstanceEntry>::iterator entryIt = sensorInstanceMap_.find(id);

    if ( entryIt == sensorInstanceMap_.end() )
    {
        setError( SmIdNotRegistered, QString(tr("requested sensor id '%1' not registered").arg(id)) );
        return false;
    }

    /// Remove any property requests by this session
    entryIt.value().sensor_->removeSession(sessionId);

    if (entryIt.value().sessions_.empty())
    {
        setError(SmNotInstantiated, tr("sensor has not been instantiated, no session to release"));
        return false;
    }

    bool returnValue = false;

    if(entryIt.value().sessions_.remove( sessionId ))
    {
        /** Fix for NB#242237
        if ( entryIt.value().sessions_.empty() )
        {
            removeSensor(id);
        }
        */
        returnValue = true;
    }
    else
    {
        // sessionId does not correspond to a request
        setError( SmNotInstantiated, tr("invalid sessionId, no session to release") );
    }

    socketHandler_->removeSession(sessionId);

    return returnValue;
}
Esempio n. 13
0
void signalUSR2(int param)
{
    Q_UNUSED(param);

    QStringList output;

    output.append("Flushing sensord state\n");
    output.append(QString("  Logging level: %1\n").arg(SensordLogger::getOutputLevel()));
    SensorManager::instance().printStatus(output);

    foreach (const QString& line, output) {
        sensordLogW() << line.toLocal8Bit().data();
    }
}
Esempio n. 14
0
bool MagCalibrationChain::setMatrixFromString(const QString& str)
{
    QStringList strList = str.split(',');
    if (strList.size() != 9) {
        sensordLogW() << "Invalid cell count from matrix. Expected 9, got" << strList.size();
        return false;
    }

    for (int i = 0; i < 9; ++i) {
        aconv_[i/3][i%3] = strList.at(i).toInt();
    }

    return true;
}
Esempio n. 15
0
void DeclinationFilter::loadSettings()
{
    GConfClient *client = gconf_client_get_default();
    if (! client ) {
        sensordLogW() << "Failed to initialise GConf client.";
        return;
    }
    GError *error = NULL;
    int value = gconf_client_get_int(client, declinationKey, &error);
    if ( error != NULL) {
        GError *error2 = NULL;
        value = gconf_client_get_float(client, declinationKey, &error2);
        if ( error2 != NULL) {
            sensordLogW() << "Failed to read value for " << declinationKey << " from GConf: " << error2->message;
            g_error_free(error2);
            return;
        }
        g_error_free(error);
    }

    declinationCorrection_ = value;
    sensordLogD() << "Fetched declination correction from GConf: " << declinationCorrection_;
    g_object_unref(client);
}
Esempio n. 16
0
void SensorManager::lostClient(int sessionId)
{
    for(QMap<QString, SensorInstanceEntry>::iterator it = sensorInstanceMap_.begin(); it != sensorInstanceMap_.end(); ++it) {
        if (it.value().sessions_.contains(sessionId)) {
            sensordLogD() << "[SensorManager]: Lost session " << sessionId << " detected as " << it.key();

            sensordLogD() << "[SensorManager]: Stopping sessionId " << sessionId;
            it.value().sensor_->stop(sessionId);

            sensordLogD() << "[SensorManager]: Releasing sessionId " << sessionId;
            releaseSensor(it.key(), sessionId);
            return;
        }
    }
    sensordLogW() << "[SensorManager]: Lost session " << sessionId << " detected, but not found from session list";
}
bool IioAdaptor::sysfsWriteInt(QString filename, int val)
{

    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        sensordLogW() << "Failed to open " << filename;
        return false;
    }

    QTextStream out(&file);
    out << val << "\n";

    file.close();

	return true;
}
Esempio n. 18
0
bool SessionData::write(void* source, int size, unsigned int count)
{
    if(socket && count)
    {
        sensordLogT() << "[SocketHandler]: writing " << count << " fragments to socket with payload (bytes): " << size;
        memcpy(source, &count, sizeof(unsigned int));
        int written = socket->write((const char*)source, size * count + sizeof(unsigned int));
        if(written < 0)
        {
            sensordLogW() << "[SocketHandler]: failed to write payload to the socket: " << socket->errorString();
            return false;
        }
        return true;
    }
    return false;
}
int IioAdaptor::deviceChannelParseBytes(QString filename)
{
    QString type = sysfsReadString(filename);

    if (type.compare("le:s16/16>>0") == 0) {
        return 2;
    } else if (type.compare("le:s32/32>>0") == 0) {
        return 4;
    } else if (type.compare("le:s64/64>>0") == 0) {
        return 8;
    } else {
        sensordLogW() << "ERROR: invalid type from file " << filename << ": " << type;
    }

    return 0;
}
OemtabletMagnetometerAdaptor::OemtabletMagnetometerAdaptor(const QString& id) :
    SysfsAdaptor(id, SysfsAdaptor::IntervalMode),
    devId(0)
{
    if (access(SYSFS_MAGNET_PATH, R_OK) < 0) {
        sensordLogW() << SYSFS_MAGNET_PATH << ": "<< strerror(errno);
        return;
    }
    addPath(SYSFS_MAGNET_PATH, devId);
    magnetBuffer_ = new DeviceAdaptorRingBuffer<TimedXyzData>(16);
    addAdaptedSensor("magnetometer", "ak8974 ascii", magnetBuffer_);

    setDescription("OEM tablet magnetometer");
    introduceAvailableDataRange(DataRange(-2048, 2048, 1));
    introduceAvailableInterval(DataRange(10, 556, 0));
    setDefaultInterval(500);
}
Esempio n. 21
0
bool SocketHandler::listen(const QString& serverName)
{
    if (m_server->isListening()) {
        sensordLogW() << "[SocketHandler]: Already listening";
        return false;
    }

    bool unlinkDone = false;
    while (!m_server->listen(serverName) && !unlinkDone && serverName[0] == QChar('/'))
    {
        if ( unlink(serverName.toLocal8Bit().constData()) == 0) {
            sensordLogD() << "[SocketHandler]: Unlinked stale socket" << serverName;
        } else {
            sensordLogD() << m_server->errorString();
        }
        unlinkDone = true;
    }
    return m_server->isListening();
}
Esempio n. 22
0
bool SocketHandler::removeSession(int sessionId)
{
    if (!(m_idMap.keys().contains(sessionId))) {
        sensordLogW() << "[SocketHandler]: Trying to remove nonexistent session.";
        return false;
    }

    QLocalSocket* socket = (*m_idMap.find(sessionId))->stealSocket();

    if (socket) {
        disconnect(socket, SIGNAL(readyRead()), this, SLOT(socketReadable()));
        disconnect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
        disconnect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError)));
        socket->deleteLater();
    }

    delete m_idMap.take(sessionId);

    return true;
}
Esempio n. 23
0
void GyroscopeAdaptor::processSample(int pathId, int fd)
{
    Q_UNUSED(pathId);
    short x, y, z;
    char buf[32];

    if (read(fd, buf, sizeof(buf)) <= 0) {
        sensordLogW() << "read():" << strerror(errno);
        return;
    }
    sensordLogT() << "gyroscope output value: " << buf;

    sscanf(buf, "%hd %hd %hd\n", &x, &y, &z);

    TimedXyzData* pos = gyroscopeBuffer_->nextSlot();
    pos->x_ = x;
    pos->y_ = y;
    pos->z_ = z;
    gyroscopeBuffer_->wakeUpReaders();
}
Esempio n. 24
0
bool SensorManager::write(int id, const void* source, int size)
{
    void* buffer = malloc(size);
    if(!buffer) {
        sensordLogC() << "Malloc failed!";
        return false;
    }
    PipeData pipeData;
    pipeData.id = id;
    pipeData.size = size;
    pipeData.buffer = buffer;

    memcpy(buffer, source, size);

    if (::write(pipefds_[1], &pipeData, sizeof(pipeData)) < (int)sizeof(pipeData)) {
        sensordLogW() << "Failed to write all data to pipe.";
        return false;
    }
    return true;
}
int IioAdaptor::addDevice(int device) {
    
    QDir dir(deviceGetPath(device));
    if (!dir.exists()) {
        sensordLogW() << "Directory ??? doesn't exists";
        return 1;
    }

    QStringList filters;
    filters << "*_raw";
    dir.setNameFilters(filters);

    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i) {
        QFileInfo fileInfo = list.at(i);
        addPath(fileInfo.filePath(),device*IIO_MAX_DEVICE_CHANNELS+i);
    }
    
    return 0;
}
QString IioAdaptor::sysfsReadString(QString filename)
{

    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        sensordLogW() << "Failed to open " << filename;
        return QString();
    }

    QTextStream in(&file);
    QString line = in.readLine();

    if (line.endsWith("\n")) {
        line.chop(1);
    }

    file.close();

	return line;
}
Esempio n. 27
0
void ALSAdaptorAscii::processSample(int pathId, int fd) {
    Q_UNUSED(pathId);

    if (read(fd, buf, sizeof(buf)) <= 0) {
        sensordLogW() << "read():" << strerror(errno);
        return;
    }
    buf[sizeof(buf)-1] = '\0';

    sensordLogT() << "Ambient light value: " << buf;

    __u16 idata = atoi(buf);

    TimedUnsigned* lux = alsBuffer_->nextSlot();

    lux->value_ = idata;
    lux->timestamp_ = Utils::getTimeStamp();

    alsBuffer_->commit();
    alsBuffer_->wakeUpReaders();
}
Esempio n. 28
0
ALSAdaptorAscii::ALSAdaptorAscii(const QString& id) : SysfsAdaptor(id, SysfsAdaptor::IntervalMode)
{
    memset(buf, 0x0, 16);
    alsBuffer_ = new DeviceAdaptorRingBuffer<TimedUnsigned>(1);
    setAdaptedSensor("als", "Internal ambient light sensor lux values", alsBuffer_);
    setDescription("Ambient light");

    // Get range from a file, if the path is found in configuration
    QString rangeFilePath_ = Config::configuration()->value("als/range_file_path",QVariant("")).toString();
    if (rangeFilePath_ != "") {
        QFile sysFile(rangeFilePath_);

        if (!(sysFile.open(QIODevice::ReadOnly))) {
            sensordLogW() << "Unable to config ALS range from sysfs";
        } else {
            sysFile.readLine(buf, sizeof(buf));
            int range = QString(buf).toInt();

            introduceAvailableDataRange(DataRange(0, range, 1));
            sensordLogT() << "Ambient light range: " << range;
        }
    }
}
Esempio n. 29
0
SensorManager::SensorManager()
    : errorCode_(SmNoError),
    pipeNotifier_(0)
{
    const char* SOCKET_NAME = "/var/run/sensord.sock";

    new SensorManagerAdaptor(this);

    socketHandler_ = new SocketHandler(this);
    connect(socketHandler_, SIGNAL(lostSession(int)), this, SLOT(lostClient(int)));

    Q_ASSERT(socketHandler_->listen(SOCKET_NAME));

    if (pipe(pipefds_) == -1) {
        sensordLogC() << "Failed to create pipe: " << strerror(errno);
        pipefds_[0] = pipefds_[1] = 0;
    } else {
        pipeNotifier_ = new QSocketNotifier(pipefds_[0], QSocketNotifier::Read);
        connect(pipeNotifier_, SIGNAL(activated(int)), this, SLOT(sensorDataHandler(int)));
    }

    if (chmod(SOCKET_NAME, S_IRWXU|S_IRWXG|S_IRWXO) != 0) {
        sensordLogW() << "Error setting socket permissions! " << SOCKET_NAME;
    }

#ifdef SENSORFW_MCE_WATCHER

    mceWatcher_ = new MceWatcher(this);
    connect(mceWatcher_, SIGNAL(displayStateChanged(const bool)),
            this, SLOT(displayStateChanged(const bool)));

    connect(mceWatcher_, SIGNAL(devicePSMStateChanged(const bool)),
            this, SLOT(devicePSMStateChanged(const bool)));

#endif //SENSORFW_MCE_WATCHER
}
PegatronAccelerometerAdaptor::PegatronAccelerometerAdaptor(const QString& id) :
    InputDevAdaptor(id, 1)
{
    //This was previously in the base class, but it's not
    //possible call virtual methods from base class constructor.
    //TODO: find a way to get rid of all child classes calling this
    //manually.

    sleep(5);

    if (!getInputDevices(DEVICE_MATCH_STRING)) {
        sensordLogW() << "Input device not found.";
    }

    accelerometerBuffer_ = new DeviceAdaptorRingBuffer<OrientationData>(128);
    setAdaptedSensor("accelerometer", "Internal accelerometer coordinates", accelerometerBuffer_);

    // Set Metadata
    setDescription("Input device accelerometer adaptor (Pegtron Lucid Tablet)");
    introduceAvailableDataRange(DataRange(-512, 512, 1));
    introduceAvailableInterval(DataRange(0, 0, 0));
    introduceAvailableInterval(DataRange(50, 2000, 0)); // -> [1,100] Hz
    setDefaultInterval(300);
}