1/*
2 * Copyright (C) 2015 Intel 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#ifndef ACQUISITION_THREAD_HPP
18#define ACQUISITION_THREAD_HPP
19
20#include <pthread.h>
21#include "Sensor.hpp"
22
23class Sensor;
24
25/**
26 * AcquisitionThread is used for implementing sensors polling
27 *
28 * The class creates a thread to periodically poll data from a
29 * sensor and write it to a pipe. The main thread can use the
30 * pipe read endpoint to retrieve sensor events.
31 *
32 * One can also wake up the thread via the wakeup method after
33 * changing the sensor parameters.
34 *
35 * It includes support for generating a flush complete event.
36 */
37class AcquisitionThread {
38  public:
39    /**
40     * AcquisitionThread constructor
41     * @param pollFd poll file descriptor
42     * @param sensor the sensor to associate with the thread
43     */
44    AcquisitionThread(int pollFd, Sensor *sensor);
45
46    /**
47     * AcquistionThread destructor
48     */
49    ~AcquisitionThread();
50
51    /**
52     * Get sensor associated with the thread
53     * @return the associated sensor
54     */
55    Sensor * getSensor() { return sensor; }
56
57    /**
58     * Get the file descriptor of the pipe read endpoint
59     * @return the pipe read file descriptor
60     */
61    int getReadPipeFd() { return pipeFds[0]; }
62
63    /**
64     * Get the file descriptor of the pipe write endpoint
65     * @return the pipe write file descriptor
66     */
67    int getWritePipeFd() { return pipeFds[1]; }
68
69    /**
70     * Initialize the acquisition thread
71     * @return true if successful, false otherwise
72     */
73    bool init();
74
75    /**
76     * Generate a flush event and send it via the associated pipe
77     * @return true if successful, false otherwise
78     */
79    bool generateFlushCompleteEvent();
80
81    /**
82     * Wake up thread if it is sleeping
83     * @return 0 if successful, < 0 otherwise
84     */
85    int wakeup();
86
87  private:
88    static void * acquisitionRoutine(void *param);
89
90    int pollFd;
91    int pipeFds[2];
92    pthread_t pthread;
93    pthread_condattr_t pthreadCondAttr;
94    pthread_cond_t pthreadCond;
95    pthread_mutex_t pthreadMutex;
96    Sensor *sensor;
97    bool initialized;
98};
99
100#endif  // ACQUISITION_THREAD_HPP
101