tx-gxx-linux/device/gxx-linux/deviceio/PinMonitor.cpp

130 lines
2.7 KiB
C++

#include "PinMonitor.h"
#include "DevUtil.h"
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/epoll.h>
#include <thread>
#include <iostream>
#include "StopWatch.h"
#include <errno.h>
#include <stdlib.h>
#include "applog.h"
#include "stringex.hpp"
static const std::string loggername = "PinMonitor";
PinMonitor::PinMonitor(unsigned int pinNum, std::function<void(int)> call_back)
: pin(pinNum)
{
LOG_INIT();
pin.setDirection(Gpio::in);
pin.setEdge(Gpio::falling);
this->call_back = call_back;
thread_monitor = std::thread(&PinMonitor::monitor, this);
//printf("PinMonitor threadid = %d \n",thread_monitor.get_id());
// int priority=sched_get_priority_max(SCHED_FIFO);
// if(priority==-1)
// {
// printf("sched_get_priority_max error \n");
// }
// thparm.sched_priority = priority;
// if(pthread_setschedparam(thread_monitor.native_handle(),SCHED_FIFO,&thparm))
// {
// printf("failed to error set pthread_setschedparam \n");
// }
}
PinMonitor::~PinMonitor()
{
bMonitor = false;
if (thread_monitor.joinable())
thread_monitor.join();
}
void PinMonitor::monitor()
{
pollfd pfd;
int ret = 0;
pfd.fd = -1;
char buf[8];
int num;
StopWatch sw;
pfd.fd = open(pin.getValuePath().c_str(), O_RDONLY);
if (pfd.fd < 0)
ret = -1;
pfd.events = POLLPRI;
num = read(pfd.fd, buf, 8); // This is to clear the avaible read
while (bMonitor)
{
ret = poll(&pfd, 1, 1000);
if (ret > 0)
{
if (pfd.revents & POLLPRI)
{
lseek(pfd.fd, 0, SEEK_SET);
num = read(pfd.fd, buf, 8);
buf[num - 1] = '\0';
ret = atoi(buf);
//LOG_TRACE("poll call");
if (call_back)
{
sw.reset();
call_back(pin.getPort());
LOG_TRACE(string_format("poll call times = %.2f \n",sw.elapsed_ms()));
}
sw.reset();
while(sw.elapsed_ms() < 10)
{
ret = poll(&pfd, 1, 1);
if (ret > 0)
{
num = read(pfd.fd, buf, 8);
buf[num - 1] = '\0';
ret = atoi(buf);
//printf("pMonitor nread = %d ret val = %d \n",num,ret);
}
}
}
}
}
close(pfd.fd);
// int n;
// int epfd = epoll_create(1);
// int fd = open(pin.getValuePath().c_str(), O_RDONLY);
// char buf[8];
// //printf("open returned %d: %s\n", fd, strerror(errno));
// if (fd > 0)
// {
// struct epoll_event ev;
// struct epoll_event events;
// ev.events = EPOLLPRI;
// ev.data.fd = fd;
// n = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
// while (bMonitor)
// {
// n = epoll_wait(epfd, &events, 1, 1000);
// if (n > 0)
// {
// n = lseek(fd, 0, SEEK_SET);
// n = read(fd, buf, 8);
// buf[n - 1] = '\0';
// auto ret = atoi(buf);
// if (call_back)
// call_back(pin.getPort());
// }
// }
// }
// close(fd);
}