#include <iostream>
#include <cstdio>
#include "Trigger.h"
Trigger::Trigger(double f)
: fd(-1), freq(f), fname("/tmp/trigger.dat"), running(false)
{
if (! access(fname.c_str(), F_OK) )
unlink(fname.c_str());
if ( mkfifo(fname.c_str(), 0660) )
{
perror("Could not create the fifo:\n\t");
return;
}
fd = open(fname.c_str(), O_RDWR);
if (freq <= 0)
freq = 50.;
set_freq(freq);
}
Trigger::~Trigger()
{
if (fd >= 0)
{
close(fd);
unlink(fname.c_str());
}
}
void Trigger::run()
{
char val = 'A';
running = true;
while (running)
{
loop();
write(fd, &val, sizeof(char));
test_cancel();
}
}
void Trigger::loop()
{
// volatile unsigned long iloop;
// for (iloop = 0;iloop < nloop;iloop++);
DAQpp::wait(period);
}
void Trigger::set_freq(double x)
{
DAQpp::GTimer timer;
if (x > 0.)
{
freq = x;
period = 1./freq;
}
// nloop = 100000000;
// timer.start();
// loop();
// timer.stop();
// nloop = (unsigned long)(((double)nloop) / timer() / freq);
// std::cout << "nloop " << nloop << std::endl;
}
/*
Function to enable and disable the external trigger, and the trigger
function.
*/
bool Trigger::operator()()
{
int rc=0;
char val;
if ( fdlist.fd < 0 )
return false;
while (rc == 0)
{
// we poll with a timeout to avoid hang ups
rc = poll(&fdlist, 1, 100);
if ( ! DAQpp::DAQmanager::theDAQmanager()->isRunning() )
break;
if (rc == 0)
continue;
if (rc > 0)
{
if ( fdlist.revents & (POLLNVAL | POLLERR | POLLHUP | POLLERR) )
return false;
if ( fdlist.revents & (POLLIN | POLLPRI) )
{
read(fdlist.fd, &val, sizeof(char));
return true;
}
}
else
{
std::cout << "InterruptTrigger: something happened" << std::endl;
}
}
return false;
}
void Trigger::enableInterrupts()
{
fdlist.fd = open(get_file_name().c_str(), O_RDONLY);
fdlist.events = POLLIN | POLLPRI;
// Make DAQmanager aware of this
DAQpp::DAQmanager::theDAQmanager()->set_trigger(this);
// start the thread that generates the data
start();
return;
}
void Trigger::disableInterrupts()
{
DAQpp::DAQmanager::theDAQmanager()->set_trigger(0);
running = false;
DAQpp::wait(0.001);
if (is_running())
stop();
if ( fdlist.fd >= 0 )
close(fdlist.fd);
fdlist.fd = -1;
return;
}