file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
adegirmenci/HBL-ICEbot/LabJackWidget/labjackwidget.cpp
#include "labjackwidget.h" #include "ui_labjackwidget.h" LabJackWidget::LabJackWidget(QWidget *parent) : QWidget(parent), ui(new Ui::LabJackWidget) { ui->setupUi(this); m_worker = new LabJackThread; m_worker->moveToThread(&m_thread); connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater); m_thread.start(); // connect widget signals to worker slots connect(this, SIGNAL(connectLabJack()), m_worker, SLOT(connectLabJack())); connect(this, SIGNAL(initializeLabJack(uint, QVector<ushort>, QVector<QString>)), m_worker, SLOT(initializeLabJack(uint, QVector<ushort>, QVector<QString>))); connect(this, SIGNAL(disconnectLabJack()), m_worker, SLOT(disconnectLabJack())); connect(this, SIGNAL(startAcquisition()), m_worker, SLOT(startAcquisition())); connect(this, SIGNAL(stopAcquisition()), m_worker, SLOT(stopAcquisition())); // connect worker signals to widget slots connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int))); // QCustomPlot // include this section to fully disable antialiasing for higher performance: ui->plotWidget->setNotAntialiasedElements(QCP::aeAll); QFont font; font.setStyleStrategy(QFont::NoAntialias); ui->plotWidget->xAxis->setTickLabelFont(font); ui->plotWidget->yAxis->setTickLabelFont(font); ui->plotWidget->legend->setFont(font); ui->plotWidget->addGraph(); // blue line ui->plotWidget->graph(0)->setPen(QPen(Qt::blue)); //ui->plotWidget->graph(0)->setBrush(QBrush(QColor(240, 255, 200))); ui->plotWidget->graph(0)->setAntialiasedFill(false); ui->plotWidget->xAxis->setTickLabelType(QCPAxis::ltDateTime); ui->plotWidget->xAxis->setDateTimeFormat("hh:mm:ss"); ui->plotWidget->xAxis->setAutoTickStep(false); ui->plotWidget->xAxis->setTickStep(2); ui->plotWidget->axisRect()->setupFullAxesBox(); // make left and bottom axes transfer their ranges to right and top axes: connect(ui->plotWidget->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->plotWidget->xAxis2, SLOT(setRange(QCPRange))); connect(ui->plotWidget->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->plotWidget->yAxis2, SLOT(setRange(QCPRange))); // setup a timer that repeatedly calls MainWindow::realtimeDataSlot: connect(m_worker, SIGNAL(logData(qint64,std::vector<double>)), this, SLOT(addDataToPlot(qint64,std::vector<double>))); // Heart Rate Widget connect(m_worker, SIGNAL(logData(qint64,std::vector<double>)), ui->HRwidget, SLOT(receiveECG(qint64,std::vector<double>))); // qDebug() << "LabJack Widget Thread ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; m_hrWidget = ui->HRwidget; } LabJackWidget::~LabJackWidget() { m_thread.quit(); m_thread.wait(); qDebug() << "LabJack thread quit."; delete ui; } void LabJackWidget::addDataToPlot(qint64 timeStamp, std::vector<double> data) { //TODO : automatically add more lines depending on the size of 'data' double key = timeStamp/1000.0; static double lastPointKey = 0; if( (key - lastPointKey) > 0.010) // at most add point every 10 ms { // add data to lines: ui->plotWidget->graph(0)->addData(key, data[0]); // remove data of lines that's outside visible range: ui->plotWidget->graph(0)->removeDataBefore(key-8); // rescale value (vertical) axis to fit the current data: ui->plotWidget->graph(0)->rescaleValueAxis(); lastPointKey = key; // make key axis range scroll with the data (at a constant range size of 8): ui->plotWidget->xAxis->setRange(key+0.25, 8, Qt::AlignRight); ui->plotWidget->replot(); } } void LabJackWidget::workerStatusChanged(int status) { switch(status) { case LABJACK_CONNECT_BEGIN: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Connecting."); ui->initializeLJbutton->setEnabled(true); ui->startRecordButton->setEnabled(false); ui->stopRecordButton->setEnabled(false); break; case LABJACK_CONNECT_FAILED: ui->connectButton->setEnabled(true); ui->disconnectButton->setEnabled(false); ui->samplesPsecSpinBox->setEnabled(true); ui->statusLineEdit->setText("Connection failed."); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(false); ui->stopRecordButton->setEnabled(false); break; case LABJACK_CONNECTED: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Connected."); ui->initializeLJbutton->setEnabled(true); ui->startRecordButton->setEnabled(false); ui->stopRecordButton->setEnabled(false); break; case LABJACK_INITIALIZE_BEGIN: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Initializing."); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(true); ui->stopRecordButton->setEnabled(false); break; case LABJACK_INITIALIZE_FAILED: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Initialization failed."); ui->initializeLJbutton->setEnabled(true); ui->startRecordButton->setEnabled(false); ui->stopRecordButton->setEnabled(false); break; case LABJACK_INITIALIZED: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Initialized."); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(true); ui->stopRecordButton->setEnabled(false); break; case LABJACK_LOOP_STARTED: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Acquiring."); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(false); ui->stopRecordButton->setEnabled(true); break; case LABJACK_LOOP_STOPPED: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Acquisition stopped."); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(true); ui->stopRecordButton->setEnabled(false); break; case LABJACK_EPOCH_SET: ui->statusLineEdit->setText("Epoch set."); break; case LABJACK_EPOCH_SET_FAILED: ui->statusLineEdit->setText("Epoch set failed."); break; case LABJACK_DISCONNECTED: ui->connectButton->setEnabled(true); ui->disconnectButton->setEnabled(false); ui->samplesPsecSpinBox->setEnabled(true); ui->statusLineEdit->setText("Disconnected."); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(false); ui->stopRecordButton->setEnabled(false); break; case LABJACK_DISCONNECT_FAILED: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Disconnection failed."); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(true); ui->stopRecordButton->setEnabled(false); break; default: ui->statusLineEdit->setText("Unknown state."); break; } } void LabJackWidget::on_connectButton_clicked() { emit connectLabJack(); } void LabJackWidget::on_disconnectButton_clicked() { emit disconnectLabJack(); } void LabJackWidget::on_initializeLJbutton_clicked() { int samplesPsec = ui->samplesPsecSpinBox->value(); QVector<ushort> channelIdx; QVector<QString> channelNames; // TODO: figure out which channels are desired by the user channelIdx.push_back(0); channelNames.push_back("ECG"); emit initializeLabJack(samplesPsec,channelIdx,channelNames); } void LabJackWidget::on_startRecordButton_clicked() { emit startAcquisition(); } void LabJackWidget::on_stopRecordButton_clicked() { emit stopAcquisition(); }
8,745
C++
37.026087
127
0.67673
adegirmenci/HBL-ICEbot/LabJackWidget/labjackwidget.h
#ifndef LABJACKWIDGET_H #define LABJACKWIDGET_H #include <QWidget> #include <QThread> #include "labjackthread.h" #include "HeartRateWidget/heartratewidget.h" namespace Ui { class LabJackWidget; } class LabJackWidget : public QWidget { Q_OBJECT public: explicit LabJackWidget(QWidget *parent = 0); ~LabJackWidget(); LabJackThread *m_worker; HeartRateWidget *m_hrWidget; signals: void connectLabJack(); // open connection void initializeLabJack(const uint samplesPerSec, const QVector<ushort> channelIdx, const QVector<QString> channelNames); // initialize settings void startAcquisition(); // start timer void stopAcquisition(); // stop timer void disconnectLabJack(); // disconnect private slots: void workerStatusChanged(int status); void addDataToPlot(qint64 timeStamp, std::vector<double> data); void on_connectButton_clicked(); void on_disconnectButton_clicked(); void on_initializeLJbutton_clicked(); void on_startRecordButton_clicked(); void on_stopRecordButton_clicked(); private: Ui::LabJackWidget *ui; QThread m_thread; // LabJack Thread will live in here }; #endif // LABJACKWIDGET_H
1,188
C
20.618181
147
0.727273
adegirmenci/HBL-ICEbot/LabJackWidget/labjackthread.cpp
#include "labjackthread.h" LabJackThread::LabJackThread(QObject *parent) : QObject(parent) { qRegisterMetaType< QVector<ushort> >("QVector<ushort>"); qRegisterMetaType< QVector<QString> >("QVector<QString>"); qRegisterMetaType< std::vector<double> >("std::vector<double>"); m_isEpochSet = false; m_isReady = false; m_keepAcquiring = false; m_abort = false; m_mutex = new QMutex(QMutex::Recursive); m_lngErrorcode = 0; m_lngHandle = 0; m_i = 0; m_k = 0; m_lngIOType = 0; m_lngChannel = 0; m_dblValue = 0; m_dblCommBacklog = 0; m_dblUDBacklog = 0; m_numChannels = 1; m_channelNames.push_back(tr("ECG")); m_scanRate = 1000; //scan rate = sample rate / #channels m_delayms = 1000; // 1 seconds per 1000 samples m_numScans = 2*m_scanRate*m_delayms/1000; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000). //m_adblData = (double *)calloc( m_numScans, sizeof(double)); //Max buffer size (#channels*numScansRequested) //m_padblData = (long)&m_adblData[0]; } LabJackThread::~LabJackThread() { disconnectLabJack(); m_mutex->lock(); m_abort = true; qDebug() << "Ending LabJackThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; m_mutex->unlock(); delete m_mutex; emit finished(); } void LabJackThread::connectLabJack() { QMutexLocker locker(m_mutex); // lock mutex bool success = true; emit statusChanged(LABJACK_CONNECT_BEGIN); //Open the first found LabJack U6. m_lngErrorcode = OpenLabJack(LJ_dtU6, LJ_ctUSB, "1", 1, &m_lngHandle); success = ErrorHandler(m_lngErrorcode, __LINE__, 0); //Read and display the hardware version of this U6. m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_CONFIG, LJ_chHARDWARE_VERSION, &m_dblValue, 0); success = success && ErrorHandler(m_lngErrorcode, __LINE__, 0); emit logEventWithMessage(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_CONNECTED, QString("U6 Hardware Version = %1\n") .arg(QString::number(m_dblValue,'f',3)) ); qDebug() << "U6 Hardware Version = " << m_dblValue; //Read and display the firmware version of this U6. m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, &m_dblValue, 0); success = success && ErrorHandler(m_lngErrorcode, __LINE__, 0); emit logEventWithMessage(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_CONNECTED, QString("U6 Firmware Version = %1\n") .arg(QString::number(m_dblValue,'f',3)) ); qDebug() << "U6 Firmware Version = " << m_dblValue; if(success) emit statusChanged(LABJACK_CONNECTED); else emit statusChanged(LABJACK_CONNECT_FAILED); //ResetLabJack(m_lngHandle); } void LabJackThread::initializeLabJack(const uint samplesPerSec, const QVector<ushort> channelIdx, const QVector<QString> channelNames) { QMutexLocker locker(m_mutex); emit statusChanged(LABJACK_INITIALIZE_BEGIN); m_scanRate = samplesPerSec; qDebug() << "LabJack samples per sec: " << m_scanRate; m_numChannels = channelIdx.size(); if(m_numChannels < 1) qDebug() << "LabJack should have at least one channel enabled!"; m_channelNames = channelNames; m_numScans = 2*m_scanRate*m_delayms/1000; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000). m_adblData = (double *)calloc( m_numChannels*m_numScans, sizeof(double)); //Max buffer size (#channels*numScansRequested) m_padblData = (long)&m_adblData[0]; bool success = true; //Configure the stream: //Configure resolution of the analog inputs (pass a non-zero value for quick sampling). //See section 2.6 / 3.1 for more information. m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chAIN_RESOLUTION, 0, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); // Configure the analog input range on channel 0 for bipolar + -10 volts. m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_AIN_RANGE, 0, LJ_rgBIP10V, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); // Configure the analog input resolution on channel 0 to index 3, 17bit resolution, 0.08 ms/sample m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chAIN_RESOLUTION, 3, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); // //Set the scan rate. // m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_SCAN_FREQUENCY, m_scanRate, 0, 0); // ErrorHandler(m_lngErrorcode, __LINE__, 0); // //Give the driver a 5 second buffer (scanRate * 1 channels * 5 seconds). // m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_BUFFER_SIZE, m_scanRate * 1 * 5, 0, 0); // ErrorHandler(m_lngErrorcode, __LINE__, 0); // //Configure reads to retrieve whatever data is available without waiting (wait mode LJ_swNONE). // m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_WAIT_MODE, LJ_swNONE, 0, 0); // ErrorHandler(m_lngErrorcode, __LINE__, 0); // //Define the scan list as AIN0. // m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioCLEAR_STREAM_CHANNELS, 0, 0, 0, 0); // ErrorHandler(m_lngErrorcode, __LINE__, 0); // m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioADD_STREAM_CHANNEL, 0, 0, 0, 0); // first method for single ended reading - AIN0 // ErrorHandler(m_lngErrorcode, __LINE__, 0); //Request AIN0. m_lngErrorcode = AddRequest (m_lngHandle, LJ_ioGET_AIN, 2, 0, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); //Execute the list of requests. m_lngErrorcode = GoOne(m_lngHandle); success = ErrorHandler(m_lngErrorcode, __LINE__, 0); //Get all the results just to check for errors. m_lngErrorcode = GetFirstResult(m_lngHandle, &m_lngIOType, &m_lngChannel, &m_dblValue, 0, 0); success = success && ErrorHandler(m_lngErrorcode, __LINE__, 0); m_lngGetNextIteration = 0; //Used by the error handling function. while (m_lngErrorcode < LJE_MIN_GROUP_ERROR) { m_lngErrorcode = GetNextResult(m_lngHandle, &m_lngIOType, &m_lngChannel, &m_dblValue, 0, 0); if (m_lngErrorcode != LJE_NO_MORE_DATA_AVAILABLE) { success = success && ErrorHandler(m_lngErrorcode, __LINE__, m_lngGetNextIteration); } m_lngGetNextIteration++; } m_isReady = success; if(success) emit statusChanged(LABJACK_INITIALIZED); else emit statusChanged(LABJACK_INITIALIZE_FAILED); } void LabJackThread::startAcquisition() { QMutexLocker locker(m_mutex); if(m_isReady && !m_keepAcquiring) // ready to read data { //Start the stream. // m_lngErrorcode = eGet(m_lngHandle, LJ_ioSTART_STREAM, 0, &m_dblValue, 0); // ErrorHandler(m_lngErrorcode, __LINE__, 0); m_keepAcquiring = true; m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), this, SLOT(ReadStream())); //m_timer->start(m_delayms); m_timer->start(1); if(m_timer->isActive()) { qDebug() << "Timer started."; emit statusChanged(LABJACK_LOOP_STARTED); emit logEvent(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_LOOP_STARTED); } else { qDebug() << "Timer is not active."; emit statusChanged(LABJACK_LOOP_STOPPED); emit logError(SRC_LABJACK, LOG_ERROR, QTime::currentTime(), LJE_TIMER_INVALID_MODE, QString("Timer is not active.")); } } else { qDebug() << "LabJack is not ready."; emit statusChanged(LABJACK_INITIALIZE_FAILED); emit logError(SRC_LABJACK, LOG_ERROR, QTime::currentTime(), LJE_DEVICE_NOT_OPEN, QString("LabJack is not ready.")); } } void LabJackThread::stopAcquisition() { QMutexLocker locker(m_mutex); if(m_keepAcquiring) { m_keepAcquiring = false; m_timer->stop(); disconnect(m_timer, SIGNAL(timeout()), 0, 0); delete m_timer; emit logEvent(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_LOOP_STOPPED); emit statusChanged(LABJACK_LOOP_STOPPED); // m_lngErrorcode = eGet(m_lngHandle, LJ_ioSTOP_STREAM, 0, 0, 0); // ErrorHandler(m_lngErrorcode, __LINE__, 0); qDebug() << "Timer stopped."; } else { qDebug() << "Timer already stopped."; } } void LabJackThread::disconnectLabJack() { QMutexLocker locker(m_mutex); stopAcquisition(); if(m_lngHandle != 0) {// Reset LabJack //m_lngErrorcode = ResetLabJack(m_lngHandle); //ErrorHandler(m_lngErrorcode, __LINE__, 0); } emit statusChanged(LABJACK_DISCONNECTED); } void LabJackThread::setEpoch(const QDateTime &epoch) { QMutexLocker locker(m_mutex); if(!m_keepAcquiring) { m_epoch = epoch; m_isEpochSet = true; emit logEventWithMessage(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_EPOCH_SET, m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz")); } else emit logEvent(SRC_LABJACK, LOG_INFO, QTime::currentTime(), LABJACK_EPOCH_SET_FAILED); } void LabJackThread::ReadStream() { QMutexLocker locker(m_mutex); if(m_isReady) { // for (m_k = 0; m_k < m_numScans; m_k++) // { // m_adblData[m_k] = 9999.0; // } //Read the data. We will request twice the number we expect, to //make sure we get everything that is available. //Note that the array we pass must be sized to hold enough SAMPLES, and //the Value we pass specifies the number of SCANS to read. // m_numScansRequested = m_numScans; // m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_STREAM_DATA, LJ_chALL_CHANNELS, // &m_numScansRequested, m_padblData); std::vector<double> newData; newData.resize(m_numChannels, 99.0); m_lngErrorcode = eGet (m_lngHandle, LJ_ioGET_AIN, 0, &newData[0], 0); // single read ErrorHandler(m_lngErrorcode, __LINE__, 0); // emit logData(QTime::currentTime(), m_adblData[0]); emit logData(QDateTime::currentMSecsSinceEpoch(), newData); } } bool LabJackThread::ErrorHandler(LJ_ERROR lngErrorcode, long lngLineNumber, long lngIteration) { char err[255]; if (lngErrorcode != LJE_NOERROR) { ErrorToString(lngErrorcode, err); QString msg = QString("Error string = ").append(err); msg.append(QString(" Source line number = %1. ").arg(lngLineNumber)); msg.append(QString("Iteration = %1").arg(lngIteration)); if (lngErrorcode > LJE_MIN_GROUP_ERROR) { qDebug() << "FATAL ERROR!" << msg; logError(SRC_LABJACK, LOG_FATAL, QTime::currentTime(), lngErrorcode, msg); } else { qDebug() << msg; logError(SRC_LABJACK, LOG_ERROR, QTime::currentTime(), lngErrorcode, msg); } return false; // there was an error } else return true; // no errors - success }
11,392
C++
33.524242
134
0.617363
adegirmenci/HBL-ICEbot/LabJackWidget/labjackthread.h
#ifndef LABJACKTHREAD_H #define LABJACKTHREAD_H #include <QObject> #include <QMutex> #include <QMutexLocker> #include <QThread> #include <QString> #include <QTime> #include <QDateTime> #include <QTimer> #include <QDebug> #include <QSharedPointer> #include <vector> #include <memory> #include "../icebot_definitions.h" #include "LabJackLibs/LabJackUD.h" Q_DECLARE_METATYPE( QVector<ushort> ) Q_DECLARE_METATYPE( QVector<QString> ) Q_DECLARE_METATYPE( std::vector<double> ) class LabJackThread : public QObject { Q_OBJECT public: explicit LabJackThread(QObject *parent = 0); ~LabJackThread(); signals: void statusChanged(int status); //void EM_Ready(bool status); // tells the widget that the EM tracker is ready void logData(qint64 timeStamp, std::vector<double> data); void logEvent(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int eventID); // LABJACK_EVENT_IDS void logEventWithMessage(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int eventID, // LABJACK_EVENT_IDS QString &message); void logError(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int errorCode, // LJ_ERROR QString message); //void sendDataToGUI(int sensorID, const QString &output); void finished(); // emit upon termination public slots: void connectLabJack(); // open connection void initializeLabJack(const uint samplesPerSec, const QVector<ushort> channelIdx, const QVector<QString> channelNames); // initialize settings void startAcquisition(); // start timer void stopAcquisition(); // stop timer void disconnectLabJack(); // disconnect void setEpoch(const QDateTime &epoch); private slots: void ReadStream(); private: // Instead of using "m_mutex.lock()" // use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex *m_mutex; // Timer for calling acquireData every xxx msecs QTimer *m_timer; // Epoch for time stamps // During initializeLabJack(), check 'isEpochSet' flag // If Epoch is set externally from MainWindow, the flag will be true // Otherwise, Epoch will be set internally QDateTime m_epoch; bool m_isEpochSet; // Flag to indicate if LabJack is ready // True if InitializeLabJack was successful bool m_isReady; // Flag to tell that we are still acquiring data bool m_keepAcquiring; // Flag to abort actions (e.g. initialize, acquire, etc.) bool m_abort; // LabJack specific variables LJ_ERROR m_lngErrorcode; LJ_HANDLE m_lngHandle; long m_lngGetNextIteration; unsigned long long int m_i, m_k; long m_lngIOType, m_lngChannel; double m_dblValue, m_dblCommBacklog, m_dblUDBacklog; double m_scanRate; //scan rate = sample rate / #channels int m_delayms; unsigned int m_numChannels; QVector<QString> m_channelNames; double m_numScans; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000). double m_numScansRequested; double *m_adblData; long m_padblData; // LabJack specific variables \\ bool ErrorHandler(LJ_ERROR lngErrorcode, long lngLineNumber, long lngIteration); }; #endif // LABJACKTHREAD_H
3,489
C
29.884955
147
0.665807
adegirmenci/HBL-ICEbot/LabJackWidget/LabJackLibs/LabJackUD.h
#ifndef LJHEADER_H #define LJHEADER_H // The version of this driver. Call GetDriverVersion() to determine the version of the DLL you have. // It should match this number, otherwise your .h and DLL's are from different versions. #define DRIVER_VERSION 3.46 #define LJ_HANDLE long #define LJ_ERROR long #ifdef __cplusplus extern "C" { #endif // ************************************************** // Functions // ************************************************** // The S form of these functions (the ones with S at the end) take strings instead of numerics for places where constants // would normally be used. This allows languages that can't include this header file to still use defined constants rather // than hard coded numbers. // The Ptr form of these functions (the ones with Ptr at the end) take a void * instead of a long for the x1 parameter. // This allows the x1 parameter to be 64-bit pointer address safe, and is required in 64-bit applications when passing an // pointer/array to x1. void _stdcall Close(); // Closes all LabJack device handles. LJ_ERROR _stdcall ListAll(long DeviceType, long ConnectionType, long *pNumFound, long *pSerialNumbers, long *pIDs, double *pAddresses); LJ_ERROR _stdcall ListAllS(const char *pDeviceType, const char *pConnectionType, long *pNumFound, long *pSerialNumbers, long *pIDs, double *pAddresses); // Returns all the devices found of a given device type and connection type. pSerialNumbers, pIDs and // pAddresses must be arrays of the given type at least 128 elements in size. pNumFound is a single element and will tell you how many // of those 128 elements have valid data (and therefore the number of units found. With pAddresses you'll probably want // to use the DoubleToStringAddress() function below to convert. LJ_ERROR _stdcall OpenLabJack(long DeviceType, long ConnectionType, const char *pAddress, long FirstFound, LJ_HANDLE *pHandle); LJ_ERROR _stdcall OpenLabJackS(const char *pDeviceType, const char *pConnectionType, const char *pAddress, long FirstFound, LJ_HANDLE *pHandle); // Must be called before working with a device. // DeviceType = The type of LabJack device to open (see device types constants). // ConnectionType = How to connect to the device, USB or Ethernet presently. // Ethernet only currently supported on the UE9. // Address = Either the ID or serial number (if USB), or the IP address. Note this is a string for either. // FirstFound = If true, then ignore Address and find the first available LabJack. // pHandle = The handle to use for subsequent functions on this device, or 0 if failed. // // This function returns 0 if success and a handle to the open labjack, or an errorcode if failed. LJ_ERROR _stdcall AddRequest(LJ_HANDLE Handle, long IOType, long Channel, double Value, long x1, double UserData); LJ_ERROR _stdcall AddRequestS(LJ_HANDLE Handle, const char *pIOType, long Channel, double Value, long x1, double UserData); LJ_ERROR _stdcall AddRequestSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double Value, long x1, double UserData); LJ_ERROR _stdcall AddRequestPtr(LJ_HANDLE Handle, long IOType, long Channel, double Value, void *x1, double UserData); // Function to add to the list of things to do with the next call to Go/GoOne(). // Handle: A handle returned by OpenLabJack(). // IOType: The type of data request (see IO type constants). // Channel: The channel # on the particular IOType. // Value: For output channels, the value to set to. // X1: Optional parameters used by some IOTypes. // UserData: Data that is kept with the request and returned with the GetFirst and GetNextResult() functions. // Returns 0 if success, errorcode if not (most likely handle not found). // NOTE: When you call AddRequest on a particular Handle, all previous data is erased and cannot be retrieved // by GetResult() until read again. This is on a device by device basis, so you can call AddRequest() with a different // handle while a device is busy performing its I/O. // The long version is used by languages that can't cast a pointer into a double and should only be used in such situations. LJ_ERROR _stdcall Go(void); // Called once AddRequest has specified all the items to do. This function actually does all those things on all devices. // takes no parameters. Returns 0 if success, errorcode if not (currently never returns an error, as errors in reading // individual items are returned when GetResult() is called. LJ_ERROR _stdcall GoOne(LJ_HANDLE Handle); // Same as above, but only does requests on the given handle. LJ_ERROR _stdcall eGet(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, long x1); LJ_ERROR _stdcall eGetPtr(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, void *x1); LJ_ERROR _stdcall eGetS(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, long x1); LJ_ERROR _stdcall eGetSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, long x1); LJ_ERROR _stdcall ePut(LJ_HANDLE Handle, long IOType, long Channel, double Value, long x1); LJ_ERROR _stdcall ePutS(LJ_HANDLE Handle, const char *pIOType, long Channel, double Value, long x1); LJ_ERROR _stdcall ePutSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double Value, long x1); LJ_ERROR _stdcall eGet_DblArray(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, double *x1); LJ_ERROR _stdcall eGet_U8Array(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, unsigned char *x1); LJ_ERROR _stdcall eGetS_DblArray(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, double *x1); LJ_ERROR _stdcall eGetS_U8Array(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, unsigned char *x1); LJ_ERROR _stdcall eGetSS_DblArray(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, double *x1); LJ_ERROR _stdcall eGetSS_U8Array(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, unsigned char *x1); // These functions do AddRequest, Go, and GetResult in one step. The Get versions are designed for inputs or retrieving parameters // as it takes a pointer to a double where the result is placed, but can be used for outputs if pValue is preset to the // desired value. This is also useful for things like StreamRead where a value is required to be input and a value is // returned. The Put versions are designed for outputs or setting configuration parameters and won't return anything but the error code. // Internally, all the put versions do is call the get function with a pointer set for you. // You can repetitively call Go() and GoOne() along with GetResult() to repeat the same requests. Once you call AddRequest() // once on a particular device, it will clear out the requests on that particular device. // NOTE: Be careful when using multiple devices and Go(): AddRequest() only clears out the request list on the device handle // provided. If, for example, you perform run two requests, one on each of two different devices, and then add a new request on // one device but not the other and then call Go(), the original request on the second device will be performed again. LJ_ERROR _stdcall GetResult(LJ_HANDLE Handle, long IOType, long Channel, double *pValue); LJ_ERROR _stdcall GetResultS(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue); LJ_ERROR _stdcall GetResultSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue); // Called to retrieve data and error codes for the things done in Go(). Typically this should be called // for each element passed with AddRequest, but outputs can be skipped if errorcodes not needed. // Handle, IOType, Channel: these should match the parameters passed in AddRequest to retrieve the result for // that particular item. // pValue = Value retrieved for that item. // Returns 0 if success, LJE_NODATA if no data available for the particular Handle, IOType, and Channel specified, // or the error code for the particular action performed. // The long version is used by languages that can't cast a pointer into a double and should only be used in such situations. LJ_ERROR _stdcall GetFirstResult(LJ_HANDLE Handle, long *pIOType, long *pChannel, double *pValue, long *px1, double *pUserData); LJ_ERROR _stdcall GetNextResult(LJ_HANDLE Handle, long *pIOType, long *pChannel, double *pValue, long *px1, double *pUserData); // These GetResult() type functions are designed for situations when you want to get all the results in order. Call GetFirstResult() // first to get the first result avialable for the given handle and the error code. Then call GetNextResult() repeditively for // subsequent requests. When either function returns LJE_NO_MORE_DATA_AVAILABLE, you're done. Note that x1 and UserData are always // returned as well. You can therefore use UserData as space for your own tracking information, or whatever else you may need. // Here's a sample of how a loop might work: // err = GetFirstResult(..) // while (!err) // { // process result... // err = GetNextResult(..) // } LJ_ERROR _stdcall eAIN(LJ_HANDLE Handle, long ChannelP, long ChannelN, double *Voltage, long Range, long Resolution, long Settling, long Binary, long Reserved1, long Reserved2); LJ_ERROR _stdcall eDAC(LJ_HANDLE Handle, long Channel, double Voltage, long Binary, long Reserved1, long Reserved2); LJ_ERROR _stdcall eDI(LJ_HANDLE Handle, long Channel, long *State); LJ_ERROR _stdcall eDO(LJ_HANDLE Handle, long Channel, long State); LJ_ERROR _stdcall eAddGoGet(LJ_HANDLE Handle, long NumRequests, long *aIOTypes, long *aChannels, double *aValues, long *ax1s, long *aRequestErrors, long *GoError, long *aResultErrors); LJ_ERROR _stdcall eTCConfig(LJ_HANDLE Handle, long *aEnableTimers, long *aEnableCounters, long TCPinOffset, long TimerClockBaseIndex, long TimerClockDivisor, long *aTimerModes, double *aTimerValues, long Reserved1, long Reserved2); LJ_ERROR _stdcall eTCValues(LJ_HANDLE Handle, long *aReadTimers, long *aUpdateResetTimers, long *aReadCounters, long *aResetCounters, double *aTimerValues, double *aCounterValues, long Reserved1, long Reserved2); LJ_ERROR _stdcall eModbus(LJ_HANDLE Handle, long readwrite, long addr, long size, unsigned char *value); // Prototypes for beta version of easy functions to make simple tasks easier. // ************************************************* // NOTE: This driver is completely thread safe. With some very minor exceptions, you can call all these functions from // multiple threads at the same time and the driver will keep everything straight. Because of this, you must call Add...(), // Go...() and Get...() from the same thread for a particular set of requests. Internally the list of things to do and // results are split by thread. This allows you to use multiple threads to make requests without accidently getting // data from one thread into another. If you are Adding requests and then getting NO_DATA_AVAILABlE or similar error when // Getting the results, then chances are you are running in different threads and don't realize this. // SubNote: The driver tracks which thread a request is made in by the thread ID. If you kill a thread and then create a new one // it is possible for the new thread to have the same ID. Its not really a problem if you call AddRequest first, but if you // did GetFirstResult on a new thread you may actually get data from the thread that already ended. // SubNote: As mentioned, the list of requests and results is kept on a thread by thread basis. Since the driver can't tell // when a thread has ended, the results are kept in memory for that thread even though the thread is done (thus the reason for the // above mentioned subnote). This is not a problem in general as the driver will clean it all up when its unloaded. When it can // be a problem is in situations where you are creating and destorying threads continuously. This will result in the slow consumption // of memory as requests on old threads are left behind. Since each request only uses 44 bytes and as mentioned the ID's will // eventually get recycled, it won't be a huge memory loss, but it will be there. In general, even without this issue, we strongly // recommend against creating and destroying a lot of threads. Its terribly slow and inefficient. Use thread pools and other // techniques to keep new thread creation to a minimum. This is what is done internally, // ************************************************** // NOTE: Continuing on the thread safety issue, the one big exception to the thread safety of this driver is in the use of // the windows TerminateThread() function. As it warns in the MSDN documentation, using TerminateThread() will kill the thread // without releasing any resources, and more importantly, releasing any synchronization objects. If you TerminateThread() on a // thread that is currently in the middle of a call to this driver, you will more than likely leave a synchronization object open // on the particular device and you will no longer be able to access the device from you application until you restart. On some // devices, it can be worse. On devices that have interprocess synchonization, such as the U12, calling TerminateThread() may // kill all access to the device through this driver no matter which process is using it and even if you restart your application. // Just avoid using TerminateThread()! All device calls have a timeout, which defaults to 1 second, but is changeable. Make sure // when you are waiting for the driver that you wait at least as long as the timeout for it to finish. // ************************************************** LJ_ERROR _stdcall ResetLabJack(LJ_HANDLE Handle); // Error functions: LJ_ERROR _stdcall GetNextError(LJ_HANDLE Handle, long *pIOType, long *pChannel); // Instead of having to check every GetResult for errors, you can instead repetitively call GetNextError to retrieve all the errors // from a particular Go. This includes eGet, ePut, etc if you want to use the same error handling routine. This function will // return an error with each call along with the IOType and channel that caused the error. If there are no errors or no errors left // it will return LJE_NOERROR. LJ_ERROR _stdcall GetStreamError(LJ_HANDLE Handle); // This function allows you to quickly determine if there is a stream error on a particular device. It only applies when // stream is running. This is especially useful if you are using a StreamCallback function, which will pass -1 in as scansavailable // if there is an error. // Useful functions: // Some config functions require IP address in a double instead of a string. Here are some helpful functions: LJ_ERROR _stdcall DoubleToStringAddress(double Number, char *pString, long HexDot); // Takes the given IP address in number notation (32 bit), and puts it into the String. String should be // preallocated to at least 16 bytes (255.255.255.255\0). LJ_ERROR _stdcall StringToDoubleAddress(const char *pString, double *pNumber, long HexDot); // Does the opposite, takes an IP address in dot notation and puts it into the given double. long _stdcall StringToConstant(const char *pString); // Converts the given string to the appropriate constant. Used internally by the S functions, but could be useful if // you wanted to use the GetFirst/Next functions and couldn't use this header. Then you could do a comparison on the // returned values: // // if (IOType == StringToConstant("LJ_ioGET_AIN")) // // This function returns LJ_INVALID_CONSTANT if an invalid constant. void _stdcall ErrorToString(LJ_ERROR ErrorCode, char *pString); // Returns a string describing the given error code or an empty string if not found. pString must be at least 256 chars in length. double _stdcall GetDriverVersion(void); // Returns the version number of this driver, the resultant number should match the number at the top of this header file. unsigned long _stdcall GetThreadID(void); // Returns the ID of the current thread. LJ_ERROR _stdcall TCVoltsToTemp( long TCType, double TCVolts, double CJTempK, double *pTCTempK); // Utility function to convert voltage readings from thermocouples to temperatures. Use the LJ_tt constants // to specify a thermocouple type. Types B, E, J, K, N, R, S and T are supported. TC voltes is the // measured voltage. CJTempK is the cold junction temperature in kelvin and the output is placed into pTCTempK. // ************************************************** // Constants // ************************************************** // Device types: const long LJ_dtUE9 = 9; const long LJ_dtU3 = 3; const long LJ_dtU6 = 6; const long LJ_dtSMB = 1000; // Connection types: const long LJ_ctUSB = 1; // UE9 + U3 + U6 const long LJ_ctETHERNET = 2; // UE9 only const long LJ_ctETHERNET_MB = 3; // Modbus over Ethernet. UE9 only. const long LJ_ctETHERNET_DATA_ONLY = 4; // Opens data port but not stream port. UE9 only. // Raw connection types are used to open a device but not communicate with it // should only be used if the normal connection types fail and for testing. // If a device is opened with the raw connection types, only LJ_ioRAW_OUT // and LJ_ioRAW_IN io types should be used. const long LJ_ctUSB_RAW = 101; // UE9 + U3 + U6 const long LJ_ctETHERNET_RAW = 102; // UE9 only // IO types: const long LJ_ioGET_AIN = 10; // UE9 + U3 + U6. This is single ended version. const long LJ_ioGET_AIN_DIFF = 15; // U3/U6 only. Put negative channel in x1. If 32 is passed as x1, Vref will be added to the result. const long LJ_ioGET_AIN_ADVANCED = 16; // For testing purposes. const long LJ_ioPUT_AIN_RANGE = 2000; // UE9 + U6 const long LJ_ioGET_AIN_RANGE = 2001; // UE9 only // Sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15. const long LJ_ioPUT_ANALOG_ENABLE_BIT = 2013; // U3 only const long LJ_ioGET_ANALOG_ENABLE_BIT = 2014; // U3 only // Sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting // bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double // for the value. The first bit of the int that the double represents will be the setting // for the pin number sent into the channel variable. const long LJ_ioPUT_ANALOG_ENABLE_PORT = 2015; // U3 only const long LJ_ioGET_ANALOG_ENABLE_PORT = 2016; // U3 only const long LJ_ioPUT_DAC = 20; // UE9 + U3 + U6 const long LJ_ioPUT_DAC_ENABLE = 2002; // UE9 + U3 (U3 on Channel 1 only) const long LJ_ioGET_DAC_ENABLE = 2003; // UE9 + U3 (U3 on Channel 1 only) const long LJ_ioGET_DIGITAL_BIT = 30; // UE9 + U3 + U6. Changes direction of bit to input as well. const long LJ_ioGET_DIGITAL_BIT_DIR = 31; // UE9 + U3 + U6 const long LJ_ioGET_DIGITAL_BIT_STATE = 32; // UE9 + U3 + U6. Does not change direction of bit, allowing readback of output. // Channel is starting bit #, x1 is number of bits to read. const long LJ_ioGET_DIGITAL_PORT = 35; // UE9 + U3 + U6 // changes direction of bits to input as well. const long LJ_ioGET_DIGITAL_PORT_DIR = 36; // UE9 + U3 + U6 const long LJ_ioGET_DIGITAL_PORT_STATE = 37; //UE9 + U3 + U6 // does not change direction of bits, allowing readback of output. // Digital put commands will set the specified digital line(s) to output. const long LJ_ioPUT_DIGITAL_BIT = 40; // UE9 + U3 + U6 // Channel is starting bit #, value is output value, x1 is bits to write. const long LJ_ioPUT_DIGITAL_PORT = 45; // UE9 + U3 + U6 // Used to create a pause between two events in a U3 low-level feedback // command. For example, to create a 100 ms positive pulse on FIO0, add a // request to set FIO0 high, add a request for a wait of 100000, add a // request to set FIO0 low, then Go. Channel is ignored. Value is // microseconds to wait and should range from 0 to 8388480. The actual // resolution of the wait is 128 microseconds. On U3 hardware version // 1.20 the resolution and delay times are doubled. const long LJ_ioPUT_WAIT = 70; // U3 + U6 // Counter. Input only. const long LJ_ioGET_COUNTER = 50; // UE9 + U3 + U6 const long LJ_ioPUT_COUNTER_ENABLE = 2008; // UE9 + U3 + U6 const long LJ_ioGET_COUNTER_ENABLE = 2009; // UE9 + U3 + U6 // This will cause the designated counter to reset. If you want to reset the counter with // every read, you have to use this command every time. const long LJ_ioPUT_COUNTER_RESET = 2012; // UE9 + U3 + U6 // On UE9: timer only used for input. Output Timers don't use these. Only Channel used. // On U3/U6: Channel used (0 or 1). const long LJ_ioGET_TIMER = 60; // UE9 + U3 + U6 const long LJ_ioPUT_TIMER_VALUE = 2006; // UE9 + U3 + U6. Value gets new value. const long LJ_ioPUT_TIMER_MODE = 2004; // UE9 + U3 + U6. On both Value gets new mode. const long LJ_ioGET_TIMER_MODE = 2005; // UE9 + U3 + U6 // IOType for use with SHT sensor. For LJ_ioSHT_GET_READING, a channel of LJ_chSHT_TEMP (5000) will // read temperature, and LJ_chSHT_RH (5001) will read humidity. const long LJ_ioSHT_GET_READING = 500; // UE9 + U3 + U6 // Uses settings from LJ_chSPI special channels (set with LJ_ioPUT_CONFIG) to communcaite with // something using an SPI interface. The value parameter is the number of bytes to transfer // and x1 is the address of the buffer. The data from the buffer will be sent, then overwritten // with the data read. The channel parameter is ignored. const long LJ_ioSPI_COMMUNICATION = 503; // UE9 + U3 + U6 const long LJ_ioI2C_COMMUNICATION = 504; // UE9 + U3 + U6 const long LJ_ioASYNCH_COMMUNICATION = 505; // UE9 + U3 + U6 const long LJ_ioTDAC_COMMUNICATION = 506; // UE9 + U3 + U6 // Sets the original configuration. // On U3: This means sending the following to the ConfigIO and TimerClockConfig low level // functions. // // ConfigIO // Byte # // 6 WriteMask 15 Write all parameters. // 8 TimerCounterConfig 0 No timers/counters. Offset=0. // 9 DAC1Enable 0 DAC1 disabled. // 10 FIOAnalog 0 FIO all digital. // 11 EIOAnalog 0 EIO all digital. // // // TimerClockConfig // Byte # // 8 TimerClockConfig 130 Set clock to 48 MHz. (24 MHz for U3 hardware version 1.20 or less) // 9 TimerClockDivisor 0 Divisor = 0. // // On UE9/U6: This means disabling all timers and counters, setting the TimerClockConfig to // default (750 kHZ for UE9, 48 MHz for U6) and the offset to 0 (U6). // const long LJ_ioPIN_CONFIGURATION_RESET = 2017; // UE9 + U3 + U6 // The raw in/out are unusual, channel number corresponds to the particular comm port, which // depends on the device. For example, on the UE9, 0 is main comm port, and 1 is the streaming comm. // Make sure and pass a porter to a char buffer in x1, and the number of bytes desired in value. A call // to GetResult will return the number of bytes actually read/written. The max you can send out in one call // is 512 bytes to the UE9 and 16384 bytes to the U3. const long LJ_ioRAW_OUT = 100; // UE9 + U3 + U6 const long LJ_ioRAW_IN = 101; // UE9 + U3 + U6 const long LJ_ioRAWMB_OUT = 104; // UE9 Only. Used with LJ_ctETHERNET_MB to send raw modbus commands to the modbus TCP/IP Socket. const long LJ_ioRAWMB_IN = 105; // UE9 only. Used with LJ_ctETHERNET_MB to receive raw modbus responses from the modbus TCP/IP Socket. // Sets the default power up settings based on the current settings of the device AS THIS DLL KNOWS. This last part // basically means that you should set all parameters directly through this driver before calling this. This writes // to flash which has a limited lifetime, so do not do this too often. Rated endurance is 20,000 writes. const long LJ_ioSET_DEFAULTS = 103; // U3 + U6 // Requests to create the list of channels to stream. Usually you will use the CLEAR_STREAM_CHANNELS request first, which // will clear any existing channels, then use ADD_STREAM_CHANNEL multiple times to add your desired channels. Note that // you can do CLEAR, and then all your ADDs in a single Go() as long as you add the requests in order. const long LJ_ioADD_STREAM_CHANNEL = 200; // UE9 + U3 + U6 // Put negative channel in x1. If 32 is passed as x1, Vref will be added to the result. const long LJ_ioADD_STREAM_CHANNEL_DIFF = 206; // U3 + U6 const long LJ_ioCLEAR_STREAM_CHANNELS = 201; // UE9 + U3 + U6 const long LJ_ioSTART_STREAM = 202; // UE9 + U3 + U6 const long LJ_ioSTOP_STREAM = 203; // UE9 + U3 + U6 const long LJ_ioADD_STREAM_DAC = 207; //UE9 only // Get stream data has several options. If you just want to get a single channel's data (if streaming multiple channels), you // can pass in the desired channel #, then the number of data points desired in Value, and a pointer to an array to put the // data into as X1. This array needs to be an array of doubles. Therefore, the array needs to be 8 * number of // requested data points in byte length. What is returned depends on the StreamWaitMode. If None, this function will only return // data available at the time of the call. You therefore must call GetResult() for this function to retrieve the actually number // of points retreived. If Pump or Sleep, it will return only when the appropriate number of points have been read or no // new points arrive within 100ms. Since there is this timeout, you still need to use GetResult() to determine if the timeout // occured. If AllOrNone, you again need to check GetResult. // // You can also retreive the entire scan by passing LJ_chALL_CHANNELS. In this case, the Value determines the number of SCANS // returned, and therefore, the array must be 8 * number of scans requested * number of channels in each scan. Likewise // GetResult() will return the number of scans, not the number of data points returned. // // Note: data is stored interleaved across all streaming channels. In other words, if you are streaming two channels, 0 and 1, // and you request LJ_chALL_CHANNELS, you will get, Channel0, Channel1, Channel0, Channel1, etc. Once you have requested the // data, any data returned is removed from the internal buffer, and the next request will give new data. // // Note: if reading the data channel by channel and not using LJ_chALL_CHANNELS, the data is not removed from the internal buffer // until the data from the last channel in the scan is requested. This means that if you are streaming three channels, 0, 1 and 2, // and you request data from channel 0, then channel 1, then channel 0 again, the request for channel 0 the second time will // return the exact same data. Also note, that the amount of data that will be returned for each channel request will be // the same until you've read the last channel in the scan, at which point your next block may be a different size. // // Note: although more convenient, requesting individual channels is slightly slower then using LJ_chALL_CHANNELS. Since you // are probably going to have to split the data out anyway, we have saved you the trouble with this option. // // Note: if you are only scanning one channel, the Channel parameter is ignored. const long LJ_ioGET_STREAM_DATA = 204; // UE9 + U3 + U6 // Since this driver has to start a thread to poll the hardware in stream mode, we give you the option of having this thread // call a user defined function after a block of data has been read. To use, pass a pointer to the following function type as // Channel. Pass 0 to turn this feature off. X1 is a user definable value that is passed when the callback function is called. // Value is the number of scans before the callback occurs. If 0, then the default is used, which varies depending on the // device and scan rate but typically results in the callback being called about every 10ms. /* example: void StreamCallback(long ScansAvailable, long UserValue) { ... do stuff when a callback occurs (retrieve data for example) } ... tStreamCallback pCallback = StreamCallback; AddRequest(Handle,LJ_ioSET_STREAM_CALLBACK,(long)pCallback,0,0,0); ... */ // NOTE: the callback function is called from a secondary worker thread that has no message pump. Do not directly update any // windows controls from your callback as there is no message pump to do so. On the same note, the driver stream buffer is locked // during the callback function. This means that while your callback function is running, you cannot do a GetStreamData or any // other stream function from a DIFFERENT thread. You can of course do getstreamdata from the callback function. You don't really // have to worry about this much as any other thread trying to do GetStreamData or other function will simply stall until your // callback is complete and the lock released. Where you will run into trouble is if your callback function waits on another thread // that is trying to do a stream function. Note this applies on a device by device basis. typedef void (*tStreamCallback)(long ScansAvailable, long UserValue); const long LJ_ioSET_STREAM_CALLBACK = 205; // UE9 + U3 + U6 const long LJ_ioSET_STREAM_CALLBACK_PTR = 260; // UE9 + U3 + U6. This is for 64-bit compatibility. The tStreamCallback function is passed as X1 and channel is the User Variable. // Channel = 0 buzz for a count, Channel = 1 buzz continuous. // Value is the Period. // X1 is the toggle count when channel = 0. const long LJ_ioBUZZER = 300; // U3 only // There are a number of things that happen asynchronously inside the UD driver and so don't directly associate with a Add, Go, or // Get function. To allow the UD to tell your code when these events occur, you can pass it a callback function that will // be called whenever this occurs. For an example of how to use the callback, look at the StreamCallback above. Like the // streamcallback, the function may be called from any thread, maybe one with a message pump, maybe not, so you should make // your function fast and don't do anything with windows or on screen controls. typedef void (*tEventCallback)(long EventCode, long Data1, long Data2, long Data3, long UserValue); // Pass pointer to function as Channel, and userdata as x1. Value not used, but should be set to 0 for forward // compatibility. If more events are required with future LabJacks, we may use this to allow you to specify which // events you wish to receive notifcation of and 0 will mean All. const long LJ_ioSET_EVENT_CALLBACK = 400; // UE9 + U3 + U6 // These are the possible EventCodes that will be passed: const long LJ_ecDISCONNECT = 1; // Called when the device is unplugged from USB. No Data is passed. const long LJ_ecRECONNECT = 2; // Called when the device is reconnected to USB. No Data is passed. const long LJ_ecSTREAMERROR = 4; // Called when a stream error occurs. Data1 is errorcode, Data2 and Data3 are not used. // Future events will be power of 2. // Config iotypes: const long LJ_ioPUT_CONFIG = 1000; // UE9 + U3 + U6 const long LJ_ioGET_CONFIG = 1001; // UE9 + U3 + U6 // Channel numbers used for CONFIG types: const long LJ_chLOCALID = 0; // UE9 + U3 + U6 const long LJ_chHARDWARE_VERSION = 10; // UE9 + U3 + U6 (Read Only) const long LJ_chSERIAL_NUMBER = 12; // UE9 + U3 + U6 (Read Only) const long LJ_chFIRMWARE_VERSION = 11; // UE9 + U3 + U6 (Read Only) const long LJ_chBOOTLOADER_VERSION = 15; // UE9 + U3 + U6 (Read Only) const long LJ_chPRODUCTID = 8; // UE9 + U3 + U6 (Read Only) // UE9 specific: const long LJ_chCOMM_POWER_LEVEL = 1; // UE9 const long LJ_chIP_ADDRESS = 2; // UE9 const long LJ_chGATEWAY = 3; // UE9 const long LJ_chSUBNET = 4; // UE9 const long LJ_chPORTA = 5; // UE9 const long LJ_chPORTB = 6; // UE9 const long LJ_chDHCP = 7; // UE9 const long LJ_chMACADDRESS = 9; // UE9 const long LJ_chCOMM_FIRMWARE_VERSION = 11; // UE9 const long LJ_chCONTROL_POWER_LEVEL = 13; // UE9 const long LJ_chCONTROL_FIRMWARE_VERSION = 14; // UE9 (Read Only) const long LJ_chCONTROL_BOOTLOADER_VERSION = 15; // UE9 (Read Only) const long LJ_chCONTROL_RESET_SOURCE = 16; // UE9 (Read Only) const long LJ_chUE9_PRO = 19; // UE9 (Read Only) const long LJ_chLED_STATE = 17; // U3 + U6. Sets the state of the LED. Value = LED state. const long LJ_chSDA_SCL = 18; // U3 + U6. Enable/disable SDA/SCL as digital I/O. const long LJ_chU3HV = 22; // U3 only (Read Only). Value will be 1 for a U3-HV and 0 for a U3-LV or a U3 with hardware version < 1.30. const long LJ_chU6_PRO = 23; // U6 only. // Driver related: // Number of milliseconds that the driver will wait for communication to complete. const long LJ_chCOMMUNICATION_TIMEOUT = 20; const long LJ_chSTREAM_COMMUNICATION_TIMEOUT = 21; // Used to access calibration and user data. The address of an array is passed in as x1. // For the UE9, a 1024-element buffer of bytes is passed for user data and a 128-element // buffer of doubles is passed for cal constants. // For the U3/U3-LV, a 256-element buffer of bytes is passed for user data and a 12-element // buffer of doubles is passed for cal constants. // For the U3-HV, a 256-element buffer of bytes is passed for user data and a 20-element // buffer of doubles is passed for cal constants. // For the U6, a 256-element buffer of bytes is passed for user data and a 64-element // buffer of doubles is passed for cal constants. // The layout of cal constants are defined in the users guide for each device. // When the LJ_chCAL_CONSTANTS special channel is used with PUT_CONFIG, a // special value (0x4C6C) must be passed in to the Value parameter. This makes it // more difficult to accidently erase the cal constants. In all other cases the Value // parameter is ignored. const long LJ_chCAL_CONSTANTS = 400; // UE9 + U3 + U6 const long LJ_chUSER_MEM = 402; // UE9 + U3 + U6 // Used to write and read the USB descriptor strings. This is generally for OEMs // who wish to change the strings. // Pass the address of an array in x1. Value parameter is ignored. // The array should be 128 elements of bytes. The first 64 bytes are for the // iManufacturer string, and the 2nd 64 bytes are for the iProduct string. // The first byte of each 64 byte block (bytes 0 and 64) contains the number // of bytes in the string. The second byte (bytes 1 and 65) is the USB spec // value for a string descriptor (0x03). Bytes 2-63 and 66-127 contain unicode // encoded strings (up to 31 characters each). const long LJ_chUSB_STRINGS = 404; // U3 + U6 // Timer/counter related: const long LJ_chNUMBER_TIMERS_ENABLED = 1000; // UE9 + U3 + U6 const long LJ_chTIMER_CLOCK_BASE = 1001; // UE9 + U3 + U6 const long LJ_chTIMER_CLOCK_DIVISOR = 1002; // UE9 + U3 + U6 const long LJ_chTIMER_COUNTER_PIN_OFFSET = 1003; // U3 + U6 // AIn related: const long LJ_chAIN_RESOLUTION = 2000; // UE9 + U3 + U6 const long LJ_chAIN_SETTLING_TIME = 2001; // UE9 + U3 + U6 const long LJ_chAIN_BINARY = 2002; // UE9 + U3 + U6 // DAC related: const long LJ_chDAC_BINARY = 3000; // UE9 + U3 // SHT related: // LJ_chSHT_TEMP and LJ_chSHT_RH are used with LJ_ioSHT_GET_READING to read those values. // The LJ_chSHT_DATA_CHANNEL and LJ_chSHT_SCK_CHANNEL constants use the passed value // to set the appropriate channel for the data and SCK lines for the SHT sensor. // Default digital channels are FIO0 for the data channel and FIO1 for the clock channel. const long LJ_chSHT_TEMP = 5000; // UE9 + U3 + U6 const long LJ_chSHT_RH = 5001; // UE9 + U3 + U6 const long LJ_chSHT_DATA_CHANNEL = 5002; // UE9 + U3 + U6. Default is FIO0 const long LJ_chSHT_CLOCK_CHANNEL = 5003; // UE9 + U3 + U6. Default is FIO1 // SPI related: const long LJ_chSPI_AUTO_CS = 5100; // UE9 + U3 + U6 const long LJ_chSPI_DISABLE_DIR_CONFIG = 5101; // UE9 + U3 + U6 const long LJ_chSPI_MODE = 5102; // UE9 + U3 + U6 const long LJ_chSPI_CLOCK_FACTOR = 5103; // UE9 + U3 + U6 const long LJ_chSPI_MOSI_PIN_NUM = 5104; // UE9 + U3 + U6 const long LJ_chSPI_MISO_PIN_NUM = 5105; // UE9 + U3 + U6 const long LJ_chSPI_CLK_PIN_NUM = 5106; // UE9 + U3 + U6 const long LJ_chSPI_CS_PIN_NUM = 5107; // UE9 + U3 + U6 // I2C related: // Used with LJ_ioPUT_CONFIG const long LJ_chI2C_ADDRESS_BYTE = 5108; // UE9 + U3 + U6 const long LJ_chI2C_SCL_PIN_NUM = 5109; // UE9 + U3 + U6 const long LJ_chI2C_SDA_PIN_NUM = 5110; // UE9 + U3 + U6 const long LJ_chI2C_OPTIONS = 5111; // UE9 + U3 + U6 const long LJ_chI2C_SPEED_ADJUST = 5112; // UE9 + U3 + U6 // Used with LJ_ioI2C_COMMUNICATION: const long LJ_chI2C_READ = 5113; // UE9 + U3 + U6 const long LJ_chI2C_WRITE = 5114; // UE9 + U3 + U6 const long LJ_chI2C_GET_ACKS = 5115; // UE9 + U3 + U6 const long LJ_chI2C_WRITE_READ = 5130; // UE9 + U3 + U6 // ASYNCH related: // Used with LJ_ioASYNCH_COMMUNICATION const long LJ_chASYNCH_RX = 5117; // UE9 + U3 + U6 const long LJ_chASYNCH_TX = 5118; // UE9 + U3 + U6 const long LJ_chASYNCH_FLUSH = 5128; // UE9 + U3 + U6 const long LJ_chASYNCH_ENABLE = 5129; // UE9 + U3 + U6 // Used with LJ_ioPUT_CONFIG and LJ_ioGET_CONFIG const long LJ_chASYNCH_BAUDFACTOR = 5127; // UE9 + U3 + U6 // LJ TickDAC related: const long LJ_chTDAC_SCL_PIN_NUM = 5119; // UE9 + U3 + U6: Used with LJ_ioPUT_CONFIG. // Used with LJ_ioTDAC_COMMUNICATION const long LJ_chTDAC_SERIAL_NUMBER = 5120; // UE9 + U3 + U6: Read only. const long LJ_chTDAC_READ_USER_MEM = 5121; // UE9 + U3 + U6 const long LJ_chTDAC_WRITE_USER_MEM = 5122; // UE9 + U3 + U6 const long LJ_chTDAC_READ_CAL_CONSTANTS = 5123; // UE9 + U3 + U6 const long LJ_chTDAC_WRITE_CAL_CONSTANTS = 5124; // UE9 + U3 + U6 const long LJ_chTDAC_UPDATE_DACA = 5125; // UE9 + U3 + U6 const long LJ_chTDAC_UPDATE_DACB = 5126; // UE9 + U3 + U6 // Stream related. Note: Putting to any of these values will stop any running streams. const long LJ_chSTREAM_SCAN_FREQUENCY = 4000; // UE9 + U3 + U6 const long LJ_chSTREAM_BUFFER_SIZE = 4001; const long LJ_chSTREAM_CLOCK_OUTPUT = 4002; // UE9 only const long LJ_chSTREAM_EXTERNAL_TRIGGER = 4003; // UE9 only const long LJ_chSTREAM_WAIT_MODE = 4004; const long LJ_chSTREAM_DISABLE_AUTORECOVERY = 4005; // U3 + U6 const long LJ_chSTREAM_SAMPLES_PER_PACKET = 4108; // UE9 + U3 + U6. Read only for UE9. const long LJ_chSTREAM_READS_PER_SECOND = 4109; const long LJ_chAIN_STREAM_SETTLING_TIME = 4110; // U6 only // Read only stream related const long LJ_chSTREAM_BACKLOG_COMM = 4105; // UE9 + U3 + U6 const long LJ_chSTREAM_BACKLOG_CONTROL = 4106; // UE9 only const long LJ_chSTREAM_BACKLOG_UD = 4107; // Special channel numbers const long LJ_chALL_CHANNELS = -1; const long LJ_INVALID_CONSTANT = -999; //Thermocouple Type constants. const long LJ_ttB = 6001; const long LJ_ttE = 6002; const long LJ_ttJ = 6003; const long LJ_ttK = 6004; const long LJ_ttN = 6005; const long LJ_ttR = 6006; const long LJ_ttS = 6007; const long LJ_ttT = 6008; // Other constants: // Ranges (not all are supported by all devices): const long LJ_rgBIP20V = 1; // -20V to +20V const long LJ_rgBIP10V = 2; // -10V to +10V const long LJ_rgBIP5V = 3; // -5V to +5V const long LJ_rgBIP4V = 4; // -4V to +4V const long LJ_rgBIP2P5V = 5; // -2.5V to +2.5V const long LJ_rgBIP2V = 6; // -2V to +2V const long LJ_rgBIP1P25V = 7; // -1.25V to +1.25V const long LJ_rgBIP1V = 8; // -1V to +1V const long LJ_rgBIPP625V = 9; // -0.625V to +0.625V const long LJ_rgBIPP1V = 10; // -0.1V to +0.1V const long LJ_rgBIPP01V = 11; // -0.01V to +0.01V const long LJ_rgUNI20V = 101; // 0V to +20V const long LJ_rgUNI10V = 102; // 0V to +10V const long LJ_rgUNI5V = 103; // 0V to +5V const long LJ_rgUNI4V = 104; // 0V to +4V const long LJ_rgUNI2P5V = 105; // 0V to +2.5V const long LJ_rgUNI2V = 106; // 0V to +2V const long LJ_rgUNI1P25V = 107; // 0V to +1.25V const long LJ_rgUNI1V = 108; // 0V to +1V const long LJ_rgUNIP625V = 109; // 0V to +0.625V const long LJ_rgUNIP5V = 110; // 0V to +0.500V const long LJ_rgUNIP25V = 112; // 0V to +0.25V const long LJ_rgUNIP3125V = 111; // 0V to +0.3125V const long LJ_rgUNIP025V = 113; // 0V to +0.025V const long LJ_rgUNIP0025V = 114; // 0V to +0.0025V // Timer modes: const long LJ_tmPWM16 = 0; // 16 bit PWM const long LJ_tmPWM8 = 1; // 8 bit PWM const long LJ_tmRISINGEDGES32 = 2; // 32-bit rising to rising edge measurement const long LJ_tmFALLINGEDGES32 = 3; // 32-bit falling to falling edge measurement const long LJ_tmDUTYCYCLE = 4; // Duty cycle measurement const long LJ_tmFIRMCOUNTER = 5; // Firmware based rising edge counter const long LJ_tmFIRMCOUNTERDEBOUNCE = 6; // Firmware counter with debounce const long LJ_tmFREQOUT = 7; // Frequency output const long LJ_tmQUAD = 8; // Quadrature const long LJ_tmTIMERSTOP = 9; // Stops another timer after n pulses const long LJ_tmSYSTIMERLOW = 10; // Read lower 32-bits of system timer const long LJ_tmSYSTIMERHIGH = 11; // Read upper 32-bits of system timer const long LJ_tmRISINGEDGES16 = 12; // 16-bit rising to rising edge measurement const long LJ_tmFALLINGEDGES16 = 13; // 16-bit falling to falling edge measurement const long LJ_tmLINETOLINE = 14; // Line to Line measurement // Timer clocks: const long LJ_tc750KHZ = 0; // UE9: 750 kHz const long LJ_tcSYS = 1; // UE9 + U3 + U6: System clock const long LJ_tc2MHZ = 10; // U3: Hardware Version 1.20 or lower const long LJ_tc6MHZ = 11; // U3: Hardware Version 1.20 or lower const long LJ_tc24MHZ = 12; // U3: Hardware Version 1.20 or lower const long LJ_tc500KHZ_DIV = 13; // U3: Hardware Version 1.20 or lower const long LJ_tc2MHZ_DIV = 14; // U3: Hardware Version 1.20 or lower const long LJ_tc6MHZ_DIV = 15; // U3: Hardware Version 1.20 or lower const long LJ_tc24MHZ_DIV = 16; // U3: Hardware Version 1.20 or lower const long LJ_tc4MHZ = 20; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc12MHZ = 21; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc48MHZ = 22; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc1MHZ_DIV = 23; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc4MHZ_DIV = 24; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc12MHZ_DIV = 25; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc48MHZ_DIV = 26; // U3: Hardware Version 1.21 or higher, + U6 // Stream wait modes: const long LJ_swNONE = 1; // No wait, return whatever is available. const long LJ_swALL_OR_NONE = 2; // No wait, but if all points requested aren't available, return none. const long LJ_swPUMP = 11; // Wait and pump the message pump. Preferred when called from primary thread (if you don't know // if you are in the primary thread of your app then you probably are. Do not use in worker // secondary threads (i.e. ones without a message pump). const long LJ_swSLEEP = 12; // Wait by sleeping (don't do this in the primary thread of your app, or it will temporarily // hang). This is usually used in worker secondary threads. // BETA CONSTANTS: // Please note that specific usage of these constants and their values might change. // SWDT: // Sets parameters used to control the software watchdog option. The device is only // communicated with and updated when LJ_ioSWDT_CONFIG is used with LJ_chSWDT_ENABLE // or LJ_chSWDT_DISABLE. Thus, to change a value, you must use LJ_io_PUT_CONFIG // with the appropriate channel constant so set the value inside the driver, then call // LJ_ioSWDT_CONFIG to enable that change. const long LJ_ioSWDT_CONFIG = 507; // UE9 + U3 + U6: Use with LJ_chSWDT_ENABLE or LJ_chSWDT_DISABLE. const long LJ_ioSWDT_STROKE = 508; // UE9 only: Used when SWDT_STRICT_ENABLE is turned on to renew the watchdog. const long LJ_chSWDT_ENABLE = 5200; // UE9 + U3 + U6: Used with LJ_ioSWDT_CONFIG to enable watchdog. Value paramter is number of seconds to trigger. const long LJ_chSWDT_DISABLE = 5201; // UE9 + U3 + U6: Used with LJ_ioSWDT_CONFIG to disable watchdog. // Used with LJ_io_PUT_CONFIG const long LJ_chSWDT_RESET_DEVICE = 5202; // U3 + U6: Reset U3 on watchdog reset. Write only. const long LJ_chSWDT_RESET_COMM = 5203; // UE9 only: Reset Comm on watchdog reset. Write only. const long LJ_chSWDT_RESET_CONTROL = 5204; // UE9 only: Reset Control on watchdog trigger. Write only. const long LJ_chSWDT_UPDATE_DIOA = 5205; // UE9 + U3 + U6: Update DIO0 settings after reset. Write only. const long LJ_chSWDT_UPDATE_DIOB = 5206; // UE9 only: Update DIO1 settings after reset. Write only. const long LJ_chSWDT_DIOA_CHANNEL = 5207; // UE9 + U3 + U6: DIO0 channel to be set after reset. Write only. const long LJ_chSWDT_DIOA_STATE = 5208; // UE9 + U3 + U6: DIO0 state to be set after reset. Write only. const long LJ_chSWDT_DIOB_CHANNEL = 5209; // UE9: DIO1 channel to be set after reset. Write only. const long LJ_chSWDT_DIOB_STATE = 5210; // UE9: DIO1 state to be set after reset. Write only. const long LJ_chSWDT_UPDATE_DAC0 = 5211; // UE9 only: Update DAC0 settings after reset. Write only. const long LJ_chSWDT_UPDATE_DAC1 = 5212; // UE9 only: Update DAC1 settings after reset. Write only. const long LJ_chSWDT_DAC0 = 5213; // UE9 only: Voltage to set DAC0 at on watchdog reset. Write only. const long LJ_chSWDT_DAC1 = 5214; // UE9 only: Voltage to set DAC1 at on watchdog reset. Write only. const long LJ_chSWDT_DAC_ENABLE = 5215; // UE9 only: Enable DACs on watchdog reset. Default is true. Both DACs are enabled or disabled togeather. Write only. const long LJ_chSWDT_STRICT_ENABLE = 5216; // UE9 only: Watchdog will only renew with LJ_ioSWDT_STROKE command. const long LJ_chSWDT_INITIAL_ROLL_TIME = 5217; // UE9 only: Watchdog timer for the first cycle when powered on, after watchdog triggers a reset the normal value is used. Set to 0 to disable. // END BETA CONSTANTS // Error codes: These will always be in the range of -1000 to 3999 for labView compatibility (+6000). const LJ_ERROR LJE_NOERROR = 0; const LJ_ERROR LJE_COMMAND_LIST_ERROR = 1; const LJ_ERROR LJE_INVALID_CHANNEL_NUMBER = 2; // Cccurs when a channel that doesn't exist is specified (i.e. DAC #2 on a UE9), or data from streaming is requested on a channel that isn't streaming. const LJ_ERROR LJE_INVALID_RAW_INOUT_PARAMETER = 3; const LJ_ERROR LJE_UNABLE_TO_START_STREAM = 4; const LJ_ERROR LJE_UNABLE_TO_STOP_STREAM = 5; const LJ_ERROR LJE_NOTHING_TO_STREAM = 6; const LJ_ERROR LJE_UNABLE_TO_CONFIG_STREAM = 7; const LJ_ERROR LJE_BUFFER_OVERRUN = 8; // Cccurs when stream buffer overruns (this is the driver buffer not the hardware buffer). Stream is stopped. const LJ_ERROR LJE_STREAM_NOT_RUNNING = 9; const LJ_ERROR LJE_INVALID_PARAMETER = 10; const LJ_ERROR LJE_INVALID_STREAM_FREQUENCY = 11; const LJ_ERROR LJE_INVALID_AIN_RANGE = 12; const LJ_ERROR LJE_STREAM_CHECKSUM_ERROR = 13; // Occurs when a stream packet fails checksum. Stream is stopped. const LJ_ERROR LJE_STREAM_COMMAND_ERROR = 14; // Occurs when a stream packet has invalid command values. Stream is stopped. const LJ_ERROR LJE_STREAM_ORDER_ERROR = 15; // Occurs when a stream packet is received out of order (typically one is missing). Stream is stopped. const LJ_ERROR LJE_AD_PIN_CONFIGURATION_ERROR = 16; // Occurs when an analog or digital request was made on a pin that isn't configured for that type of request. const LJ_ERROR LJE_REQUEST_NOT_PROCESSED = 17; // When a LJE_AD_PIN_CONFIGURATION_ERROR occurs, all other IO requests after the request that caused the error won't be processed. Those requests will return this error. // U3 & U6 Specific Errors const LJ_ERROR LJE_SCRATCH_ERROR = 19; const LJ_ERROR LJE_DATA_BUFFER_OVERFLOW = 20; const LJ_ERROR LJE_ADC0_BUFFER_OVERFLOW = 21; const LJ_ERROR LJE_FUNCTION_INVALID = 22; const LJ_ERROR LJE_SWDT_TIME_INVALID = 23; const LJ_ERROR LJE_FLASH_ERROR = 24; const LJ_ERROR LJE_STREAM_IS_ACTIVE = 25; const LJ_ERROR LJE_STREAM_TABLE_INVALID = 26; const LJ_ERROR LJE_STREAM_CONFIG_INVALID = 27; const LJ_ERROR LJE_STREAM_BAD_TRIGGER_SOURCE = 28; const LJ_ERROR LJE_STREAM_INVALID_TRIGGER = 30; const LJ_ERROR LJE_STREAM_ADC0_BUFFER_OVERFLOW = 31; const LJ_ERROR LJE_STREAM_SAMPLE_NUM_INVALID = 33; const LJ_ERROR LJE_STREAM_BIPOLAR_GAIN_INVALID = 34; const LJ_ERROR LJE_STREAM_SCAN_RATE_INVALID = 35; const LJ_ERROR LJE_TIMER_INVALID_MODE = 36; const LJ_ERROR LJE_TIMER_QUADRATURE_AB_ERROR = 37; const LJ_ERROR LJE_TIMER_QUAD_PULSE_SEQUENCE = 38; const LJ_ERROR LJE_TIMER_BAD_CLOCK_SOURCE = 39; const LJ_ERROR LJE_TIMER_STREAM_ACTIVE = 40; const LJ_ERROR LJE_TIMER_PWMSTOP_MODULE_ERROR = 41; const LJ_ERROR LJE_TIMER_SEQUENCE_ERROR = 42; const LJ_ERROR LJE_TIMER_SHARING_ERROR = 43; const LJ_ERROR LJE_TIMER_LINE_SEQUENCE_ERROR = 44; const LJ_ERROR LJE_EXT_OSC_NOT_STABLE = 45; const LJ_ERROR LJE_INVALID_POWER_SETTING = 46; const LJ_ERROR LJE_PLL_NOT_LOCKED = 47; const LJ_ERROR LJE_INVALID_PIN = 48; const LJ_ERROR LJE_IOTYPE_SYNCH_ERROR = 49; const LJ_ERROR LJE_INVALID_OFFSET = 50; const LJ_ERROR LJE_FEEDBACK_IOTYPE_NOT_VALID = 51; const LJ_ERROR LJE_CANT_CONFIGURE_PIN_FOR_ANALOG = 67; const LJ_ERROR LJE_CANT_CONFIGURE_PIN_FOR_DIGITAL = 68; const LJ_ERROR LJE_TC_PIN_OFFSET_MUST_BE_4_TO_8 = 70; const LJ_ERROR LJE_INVALID_DIFFERENTIAL_CHANNEL = 71; const LJ_ERROR LJE_DSP_SIGNAL_OUT_OF_RANGE = 72; // Other errors const LJ_ERROR LJE_SHT_CRC = 52; const LJ_ERROR LJE_SHT_MEASREADY = 53; const LJ_ERROR LJE_SHT_ACK = 54; const LJ_ERROR LJE_SHT_SERIAL_RESET = 55; const LJ_ERROR LJE_SHT_COMMUNICATION = 56; const LJ_ERROR LJE_AIN_WHILE_STREAMING = 57; const LJ_ERROR LJE_STREAM_TIMEOUT = 58; const LJ_ERROR LJE_STREAM_CONTROL_BUFFER_OVERFLOW = 59; const LJ_ERROR LJE_STREAM_SCAN_OVERLAP = 60; const LJ_ERROR LJE_FIRMWARE_VERSION_IOTYPE = 61; const LJ_ERROR LJE_FIRMWARE_VERSION_CHANNEL = 62; const LJ_ERROR LJE_FIRMWARE_VERSION_VALUE = 63; const LJ_ERROR LJE_HARDWARE_VERSION_IOTYPE = 64; const LJ_ERROR LJE_HARDWARE_VERSION_CHANNEL = 65; const LJ_ERROR LJE_HARDWARE_VERSION_VALUE = 66; const LJ_ERROR LJE_LJTDAC_ACK_ERROR = 69; const LJ_ERROR LJE_STREAM_INVALID_CONNECTION = 73; const LJ_ERROR LJE_MIN_GROUP_ERROR = 1000; // All errors above this number will stop all requests, below this number are request level errors. const LJ_ERROR LJE_UNKNOWN_ERROR = 1001; // Occurs when an unknown error occurs that is caught, but still unknown. const LJ_ERROR LJE_INVALID_DEVICE_TYPE = 1002; // Occurs when devicetype is not a valid device type. const LJ_ERROR LJE_INVALID_HANDLE = 1003; // Occurs when invalid handle used. const LJ_ERROR LJE_DEVICE_NOT_OPEN = 1004; // Occurs when Open() fails and AppendRead called despite. const LJ_ERROR LJE_NO_DATA_AVAILABLE = 1005; // This is cause when GetResult() called without calling Go/GoOne(), or when GetResult() passed a channel that wasn't read. const LJ_ERROR LJE_NO_MORE_DATA_AVAILABLE = 1006; const LJ_ERROR LJE_LABJACK_NOT_FOUND = 1007; // Occurs when the LabJack is not found at the given id or address. const LJ_ERROR LJE_COMM_FAILURE = 1008; // Occurs when unable to send or receive the correct number of bytes. const LJ_ERROR LJE_CHECKSUM_ERROR = 1009; const LJ_ERROR LJE_DEVICE_ALREADY_OPEN = 1010; // Occurs when LabJack is already open via USB in another program or process. const LJ_ERROR LJE_COMM_TIMEOUT = 1011; const LJ_ERROR LJE_USB_DRIVER_NOT_FOUND = 1012; const LJ_ERROR LJE_INVALID_CONNECTION_TYPE = 1013; const LJ_ERROR LJE_INVALID_MODE = 1014; const LJ_ERROR LJE_DEVICE_NOT_CONNECTED = 1015; // Occurs when a LabJack that was opened is no longer connected to the system. // These errors aren't actually generated by the UD, but could be handy in your code to indicate an event as an error code without // conflicting with LabJack error codes. const LJ_ERROR LJE_DISCONNECT = 2000; const LJ_ERROR LJE_RECONNECT = 2001; // and an area for your own codes. This area won't ever be used for LabJack codes. const LJ_ERROR LJE_MIN_USER_ERROR = 3000; const LJ_ERROR LJE_MAX_USER_ERROR = 3999; // Warning are negative const LJ_ERROR LJE_DEVICE_NOT_CALIBRATED = -1; // Defaults used instead const LJ_ERROR LJE_UNABLE_TO_READ_CALDATA = -2; // Defaults used instead /* Version History: 2.02: ain_binary fixed for non-streaming. Adjusted for new streaming usb firmware (64-byte packets). New streaming errors- stop the stream and error is returned with next GetData. Fixed resolution setting while streaming (was fixed to 12, now follows poll setting). 2.03: Added callback option for streaming. 2.04: Changed warnings to be negative. Renamed POWER_LEVEL to COMM_POWER_LEVEL. 2.05: Updated timer/counter stuff. Added CounterReset, TimerClockDivisor. 2.06: Fixed problem when unplugging USB UE9 and plugging it into a different USB port. Renamed LJ_chCOUNTERTIMER_CLOCK to LJ_chTIMER_CLOCK_CONFIG. 2.08: Fixed two UE9 USB unplug issue. Driver now uses high temp calibration for Control power level zero. Added new timer modes to header. Fixed LJ_tcSYS constant in header. 2.09: New timer constants for new modes. Timer/counter update bits auto-setting updated. put_counter_reset will execute with the next go, not only with the next read. 2.10: Timer/counter update bits auto-setting updated again. Fixed MIO bits as outputs. listall(). Fixed control power level and reset source. Added ioDIGITAL_PORT_IN and ioDIGITAL_PORT_OUT. 2.11: Fixed problem with ListAll when performed without prior opening of devices. 2.12: Added initial raw U3 support. 2.13: Fixed issues with streaming backlog and applying cals to extended channels. 2.14: Fixed issue with U3 raw support. 2.15: Fixed driver issue with stream clock output and stream external triggering. 2.16: Fixed problem with listall after changing local id. 2.17: Fixed issues with streaming backlog and applying cals to extended channels. Fixed problem with usb reset. Added timer mode 6 to header file. 2.18: Fixed issue with rollover on counter/timer. Fixed reset issues. 2.21: UE9 changed to use feedbackalt instead of feedback. Allows for multiple internal channels to be called from same call to feedback. Fixed internal channel numbers 14/128 and 15/136 and extended channels to return proper values. 2.22: Fixed problem with ioGET_TIMER when passed as a string. Added support for make unlimited number of requests for analog input channels for a single call to a go function. 2.23: 2.24: Fixed bug sometimes causing errors when a pointer was passed into the Raw io functions that caused a communication error. 2.25: Improved U3 support. 2.26: Fixed U3 bugs with timer/counter values, DAC rounding and set analog enabled port functions. 2.46: Various U3 fixes and support added. 2.47: Fixed threading issue. 2.48: Added LJ_ioPUT_WAIT. 2.56: Fixed bug with EAIN. 2.57: Added Thermocouple conversion functions. 2.58: Added SWDT functionality for UE9 (BETA). 2.59: Fixed bug causing some U3 timer values to report incorrectly. Added support for OEMs to change USB string descriptors on the U3. 2.60: Added beta support for timer values for U3s with hardware version >= 1.21. 2.61: Fixed bug causing U3 streaming to sometimes hang. 2.62: Added ability to open devices over USB using the serial number. 2.63: Added new stream error codes and fixed bug with opening multiple U3s. 2.64: Fixed bug when streaming with differential channels on U3. 2.65: Improved eAin to work properly with special all special channels. 2.66: LJ_chSTREAM_ENABLE_AUTORECOVER renamed to LJ_chSTREAM_DISABLE_AUTORECOVERY. 2.67: Fixed bug with eTCConfig and eTCValues on U3. 2.68: Added internal function for factory use. 2.69: Added Ethernet support for ListAll() for UE9. 2.70: Added I2C support for U3 and UE9. 2.72: Fixed problem with using trigger mode when streaming. 2.73: Added detection for reads from Timers/Counters that weren't enabled on UE9. 2.74: Fixed bug that sometimes occurs when requesting version numbers. 2.75: Fixed issue with reopening U3 after a device reset. 2.76: Fixed bug with the proper range not always being used when streaming on a UE9. Fixed bug with UE9 Ethernet ListAll() returning wrong values for IP addresses. 2.77: Fixed bug with special channel readings while streaming. Added Asynch support for U3. 2.78: Fixed bug when doing SPI communication with an odd number of bytes. 2.79: LJ_chI2C_WRITE_READ support. 3.00: Added support for U3-HV and U3-LV. 3.01: Fixed bug with U3-HV applying wrong calibration constants when streaming. 3.02: Fixed bugs with U3-HV and U3-LV and a delay with StopStream. 3.03: Added initial support for U6. 3.04: Fixed bug with Asynch communication on U3-HVs and U3-LVs. 3.05: Fixed calibration bug with eAIN on the U3-HV and U3-LV. 3.06: Fixed bug with SWDT functionality for U3. 3.10: Added support for new USB driver that works with 64-bit OS versions. 3.11: Fixed a memory leak when devices were kept open via USB. 3.12: Fixed various U6 bugs. 3.13: Added LJE_DEVICE_ALREADY_OPEN error to occur when another program/process has the LabJack open. 3.14: Various minor bug fixes. 3.15: Added full support for Asynch communication on the U6. 3.16: Fixed bug causing a delay when the LabJackUD driver was unloaded in a program. 3.17: Added support for SWDT settings for initial roll time and strict mode. 3.18: Fixed a bug with negative timer values when using ETCConfig with LJ_tmQUAD on the U3 and U6. Fixed bug causing a delay when stream on U3/U6 was stopped. 3.19: Fixed bug that caused LJ_ioPUT_TIMER_VALUE to corrupt other results when done in the same Go or GoOne call. 3.22: Fixed bug in the U6 and U3 that caused excessive delays when com buffer started to fill. 3.23: Added GetThreadID function. 3.26: Fixed bug with U6 reading channels 200-224 not returning proper values. 3.27: Fixed bug with setting calibration constants for LJTickDAC. 3.28: Fixed bug with U3s reading internal temperature using LJ_ioGET_AIN_DIFF. Added LJ_ctETHERNET_DATA_ONLY support. 3.32: Various bug fixes. 3.38: Added AddRequestPtr, ePutPtr and LJ_ioSET_STREAM_CALLBACK_PTR for better 64-bit compatibility. 3.40: Added LJ_chSTREAM_COMMUNICATION_TIMEOUT support for U3/U6. 3.41: Fixed compatibility for Ptr functions and raw read/write support. 3.42: Fixed error in values of streaming extended channels on U6. 3.43: Fixed bug with eAin high resolution readings on Pro devices. Fixed bug with IC2 and *Ptr functions. 3.44: Changed eAddGoGet() to return LJE_COMMAND_LIST_ERROR if an error is detected. Error arrays are also defaulted to zero. 3.45: Fixed a bug which would sometimes cause a critcal error if the LabJackUD.dll was unloaded after streaming. 3.46: Updated internal reconnect routine to help prevent deadlocks. Fixed a bug when disabling UE9 DACs. Added the ability to set multiple timer values in a single Go/GoOne call for the U6. Updated LJ_chASYNCH_TX's result so the Value is the number of bytes in the RX buffer. Fixed LJ_chCAL_CONSTANTS, LJ_chUSER_MEM, LJ_chUSB_STRINGS and LJ_ioSPI_COMMUNICATION functionality when using Array and Ptr functions. Fixed writing calibration constants, LJ_chCAL_CONSTANTS, for the U3 and U6. Fixed eTCValues U6 bug. */ // Depreciated constants: const long LJ_ioANALOG_INPUT = 10; const long LJ_ioANALOG_OUTPUT = 20; // UE9 + U3 const long LJ_ioDIGITAL_BIT_IN = 30; // UE9 + U3 const long LJ_ioDIGITAL_PORT_IN = 35; // UE9 + U3 const long LJ_ioDIGITAL_BIT_OUT = 40; // UE9 + U3 const long LJ_ioDIGITAL_PORT_OUT = 45; // UE9 + U3 const long LJ_ioCOUNTER = 50; // UE9 + U3 const long LJ_ioTIMER = 60; // UE9 + U3 const long LJ_ioPUT_COUNTER_MODE = 2010; // UE9 const long LJ_ioGET_COUNTER_MODE = 2011; // UE9 const long LJ_ioGET_TIMER_VALUE = 2007; // UE9 const long LJ_ioCYCLE_PORT = 102; // UE9 const long LJ_chTIMER_CLOCK_CONFIG = 1001; // UE9 + U3 const long LJ_ioPUT_CAL_CONSTANTS = 400; const long LJ_ioGET_CAL_CONSTANTS = 401; const long LJ_ioPUT_USER_MEM = 402; const long LJ_ioGET_USER_MEM = 403; const long LJ_ioPUT_USB_STRINGS = 404; const long LJ_ioGET_USB_STRINGS = 405; const long LJ_ioSHT_DATA_CHANNEL = 501; // UE9 + U3 const long LJ_ioSHT_CLOCK_CHANNEL = 502; // UE9 + U3 const long LJ_chI2C_ADDRESS = 5108; // UE9 + U3 const long LJ_chASYNCH_CONFIG = 5116; // UE9 + U3 const long LJ_rgUNIP500V = 110; // 0V to +0.500V const long LJ_ioENABLE_POS_PULLDOWN = 2018; // U6 const long LJ_ioENABLE_NEG_PULLDOWN = 2019; // U6 const long LJ_rgAUTO = 0; const long LJ_chSWDT_UDPATE_DIOA = 5205; #ifdef __cplusplus } // extern C #endif #endif
60,335
C
57.921875
231
0.732195
adegirmenci/HBL-ICEbot/LabJackWidget/LabJackLibs/LabJackM.h
/** * Name: LabJackM.h * Desc: Header file describing C-style exposed * API functions for the LabJackM Library * Auth: LabJack Corp. **/ #ifndef LAB_JACK_M_HEADER #define LAB_JACK_M_HEADER #define LJM_VERSION 1.0806 // Format: xx.yyzz // xx is the major version (left of the decimal). // yy is the minor version (the two places to the right of the decimal). // zz is the revision version (the two places to the right of the minor // version). /****************************************************************************** * How To Use This Library: * * See the LJM User's Guide: labjack.com/support/ljm/users-guide * * Check out the example files for examples of workflow * * To write/read other Modbus addresses, check out labjack.com/support/modbus * *****************************************************************************/ #define LJM_ERROR_CODE static const int #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 #define LJM_ERROR_RETURN int __stdcall #define LJM_VOID_RETURN void __stdcall #define LJM_ERROR_STRING const char * __stdcall #define LJM_DOUBLE_RETURN double __stdcall #else #define LJM_ERROR_RETURN int #define LJM_VOID_RETURN void #define LJM_ERROR_STRING const char * #define LJM_DOUBLE_RETURN double #endif /************* * Constants * *************/ // Read/Write direction constants: static const int LJM_READ = 0; static const int LJM_WRITE = 1; // Data Types: // These do automatic endianness conversion, if needed by the local machine's // processor. static const int LJM_UINT16 = 0; // C type of unsigned short static const int LJM_UINT32 = 1; // C type of unsigned int static const int LJM_INT32 = 2; // C type of int static const int LJM_FLOAT32 = 3; // C type of float // Advanced users data types: // These do not do any endianness conversion. static const int LJM_BYTE = 99; // Contiguous bytes. If the number of LJM_BYTEs is // odd, the last, (least significant) byte is 0x00. // For example, for 3 LJM_BYTES of values // [0x01, 0x02, 0x03], LJM sends the contiguous byte // array [0x01, 0x02, 0x03, 0x00] static const int LJM_STRING = 98; // Same as LJM_BYTE, but LJM automatically appends // a null-terminator. static const unsigned int LJM_STRING_MAX_SIZE = 49; // Max LJM_STRING size not including the automatic null-terminator // Max LJM_STRING size with the null-terminator enum { LJM_STRING_ALLOCATION_SIZE = 50 }; // LJM_NamesToAddresses uses this when a register name is not found static const int LJM_INVALID_NAME_ADDRESS = -1; enum { LJM_MAX_NAME_SIZE = 256 }; // 18 = 6 * 2 (number of byte chars) + 5 (number of colons) + 1 (null-terminator) enum { LJM_MAC_STRING_SIZE = 18 }; // 16 is INET_ADDRSTRLEN enum { LJM_IPv4_STRING_SIZE = 16 }; static const int LJM_BYTES_PER_REGISTER = 2; // Device types: static const int LJM_dtANY = 0; static const int LJM_dtT7 = 7; static const int LJM_dtDIGIT = 200; // Connection types: static const int LJM_ctANY = 0; static const int LJM_ctUSB = 1; static const int LJM_ctTCP = 2; static const int LJM_ctETHERNET = 3; static const int LJM_ctWIFI = 4; // TCP/Ethernet constants: static const int LJM_NO_IP_ADDRESS = 0; static const int LJM_NO_PORT = 0; static const int LJM_DEFAULT_PORT = 502; // Identifier types: static const char * const LJM_DEMO_MODE = "-2"; static const int LJM_idANY = 0; // LJM_AddressesToMBFB Constants enum { LJM_DEFAULT_FEEDBACK_ALLOCATION_SIZE = 62 }; static const int LJM_USE_DEFAULT_MAXBYTESPERMBFB = 0; // LJM_MBFBComm Constants; static const int LJM_DEFAULT_UNIT_ID = 1; // LJM_ListAll Constants enum { LJM_LIST_ALL_SIZE = 128 }; // Please note that some devices must append 2 bytes to certain packets. // Please check the docs for the device you are using. static const int LJM_MAX_USB_PACKET_NUM_BYTES = 64; static const int LJM_MAX_TCP_PACKET_NUM_BYTES_T7 = 1040; // Deprecated static const int LJM_MAX_ETHERNET_PACKET_NUM_BYTES_T7 = 1040; static const int LJM_MAX_WIFI_PACKET_NUM_BYTES_T7 = 500; // Timeout Constants. Times in milliseconds. static const int LJM_NO_TIMEOUT = 0; static const int LJM_DEFAULT_USB_SEND_RECEIVE_TIMEOUT_MS = 2600; static const int LJM_DEFAULT_ETHERNET_OPEN_TIMEOUT_MS = 1000; static const int LJM_DEFAULT_ETHERNET_SEND_RECEIVE_TIMEOUT_MS = 2600; static const int LJM_DEFAULT_WIFI_OPEN_TIMEOUT_MS = 1000; static const int LJM_DEFAULT_WIFI_SEND_RECEIVE_TIMEOUT_MS = 4000; // Stream Constants static const int LJM_DUMMY_VALUE = -9999; static const int LJM_SCAN_NOT_READ = -8888; static const int LJM_GND = 199; /***************************************************************************** * Return Values * * Success: * * Constant: LJME_NOERROR * * Description: The function executed without error. * * Range: 0 * * * * Warnings: * * Prefix: LJME_ * * Description: Some or all outputs might be valid. * * Range: 200-399 * * * * Modbus Errors: * * Prefix: LJME_MBE * * Description: Errors corresponding to official Modbus errors which are * * returned from the device. * * Note: To find the original Modbus error in base 10, subtract 1200. * * Ranges: 1200-1216 * * * * Library Errors: * * Prefix: LJME_ * * Description: Errors where all outputs are null, invalid, 0, or 9999. * * Range: 1220-1399 * * * * Device Errors: * * Description: Errors returned from the firmware on the device. * * Range: 2000-2999 * * * * User Area: * * Description: Errors defined by users. * * Range: 3900-3999 * * */ // Success LJM_ERROR_CODE LJME_NOERROR = 0; // Warnings: LJM_ERROR_CODE LJME_WARNINGS_BEGIN = 200; LJM_ERROR_CODE LJME_WARNINGS_END = 399; LJM_ERROR_CODE LJME_FRAMES_OMITTED_DUE_TO_PACKET_SIZE = 201; // Functions: // LJM_AddressesToMBFB: // Problem: This indicates that the length (in bytes) of the Feedback // command being created was greater than the value passed as // MaxBytesPerMBFB. As a result, the command returned is a valid // Feedback command that includes some of the frames originally // specified, but not all of them. You can check the NumFrames // pointer to find out how many frames were included. // Solutions: // 1) Pass a larger value for MaxBytesPerMBFB and make sure // aMBFBCommand has memory allocated of size MaxBytesPerMBFB. // The default size for MaxBytesPerMBFB is 64. // 2) Split the command into multiple commands. // Any other function that creates a Feedback command: // Problem: The Feedback command being created was too large for // the device to handle on this connection type. // Solution: Split the command into multiple commands. LJM_ERROR_CODE LJME_DEBUG_LOG_FAILURE = 202; LJM_ERROR_CODE LJME_USING_DEFAULT_CALIBRATION = 203; // Problem: LJM has detected the device has one or more invalid calibration // constants and is using the default calibration constants. Readings may // inaccurate. // Solution: Contact LabJack support. LJM_ERROR_CODE LJME_DEBUG_LOG_FILE_NOT_OPEN = 204; // Modbus Errors: LJM_ERROR_CODE LJME_MODBUS_ERRORS_BEGIN = 1200; LJM_ERROR_CODE LJME_MODBUS_ERRORS_END = 1216; LJM_ERROR_CODE LJME_MBE1_ILLEGAL_FUNCTION = 1201; LJM_ERROR_CODE LJME_MBE2_ILLEGAL_DATA_ADDRESS = 1202; LJM_ERROR_CODE LJME_MBE3_ILLEGAL_DATA_VALUE = 1203; LJM_ERROR_CODE LJME_MBE4_SLAVE_DEVICE_FAILURE = 1204; LJM_ERROR_CODE LJME_MBE5_ACKNOWLEDGE = 1205; LJM_ERROR_CODE LJME_MBE6_SLAVE_DEVICE_BUSY = 1206; LJM_ERROR_CODE LJME_MBE8_MEMORY_PARITY_ERROR = 1208; LJM_ERROR_CODE LJME_MBE10_GATEWAY_PATH_UNAVAILABLE = 1210; LJM_ERROR_CODE LJME_MBE11_GATEWAY_TARGET_NO_RESPONSE = 1211; // Library Errors: LJM_ERROR_CODE LJME_LIBRARY_ERRORS_BEGIN = 1220; LJM_ERROR_CODE LJME_LIBRARY_ERRORS_END = 1399; LJM_ERROR_CODE LJME_UNKNOWN_ERROR = 1221; LJM_ERROR_CODE LJME_INVALID_DEVICE_TYPE = 1222; LJM_ERROR_CODE LJME_INVALID_HANDLE = 1223; LJM_ERROR_CODE LJME_DEVICE_NOT_OPEN = 1224; LJM_ERROR_CODE LJME_STREAM_NOT_INITIALIZED = 1225; LJM_ERROR_CODE LJME_DEVICE_DISCONNECTED = 1226; LJM_ERROR_CODE LJME_DEVICE_NOT_FOUND = 1227; LJM_ERROR_CODE LJME_DEVICE_ALREADY_OPEN = 1229; LJM_ERROR_CODE LJME_COULD_NOT_CLAIM_DEVICE = 1230; LJM_ERROR_CODE LJME_CANNOT_CONNECT = 1231; LJM_ERROR_CODE LJME_SOCKET_LEVEL_ERROR = 1233; LJM_ERROR_CODE LJME_CANNOT_OPEN_DEVICE = 1236; LJM_ERROR_CODE LJME_CANNOT_DISCONNECT = 1237; LJM_ERROR_CODE LJME_WINSOCK_FAILURE = 1238; LJM_ERROR_CODE LJME_RECONNECT_FAILED = 1239; LJM_ERROR_CODE LJME_U3_CANNOT_BE_OPENED_BY_LJM = 1243; LJM_ERROR_CODE LJME_U6_CANNOT_BE_OPENED_BY_LJM = 1246; LJM_ERROR_CODE LJME_UE9_CANNOT_BE_OPENED_BY_LJM = 1249; LJM_ERROR_CODE LJME_INVALID_ADDRESS = 1250; LJM_ERROR_CODE LJME_INVALID_CONNECTION_TYPE = 1251; LJM_ERROR_CODE LJME_INVALID_DIRECTION = 1252; LJM_ERROR_CODE LJME_INVALID_FUNCTION = 1253; // Function: LJM_MBFBComm // Problem: The aMBFB buffer passed as an input parameter // did not have a function number corresponding to Feedback. // Solution: Make sure the 8th byte of your buffer is 76 (base 10). // (For example, aMBFB[7] == 76 should evaluate to true.) LJM_ERROR_CODE LJME_INVALID_NUM_REGISTERS = 1254; LJM_ERROR_CODE LJME_INVALID_PARAMETER = 1255; LJM_ERROR_CODE LJME_INVALID_PROTOCOL_ID = 1256; // Problem: The Protocol ID was not in the proper range. LJM_ERROR_CODE LJME_INVALID_TRANSACTION_ID = 1257; // Problem: The Transaction ID was not in the proper range. LJM_ERROR_CODE LJME_INVALID_VALUE_TYPE = 1259; LJM_ERROR_CODE LJME_MEMORY_ALLOCATION_FAILURE = 1260; // Problem: A memory allocation attempt has failed, probably due to a // lack of available memory. LJM_ERROR_CODE LJME_NO_COMMAND_BYTES_SENT = 1261; // Problem: No bytes could be sent to the device. // Possibilities: // * The device was previously connected, but was suddenly // disconnected. LJM_ERROR_CODE LJME_INCORRECT_NUM_COMMAND_BYTES_SENT = 1262; // Problem: The expected number of bytes could not be sent to the device. // Possibilities: // * The device was disconnected while bytes were being sent. LJM_ERROR_CODE LJME_NO_RESPONSE_BYTES_RECEIVED = 1263; // Problem: No bytes could be received from the device. // Possibilities: // * The device was previously connected, but was suddenly // disconnected. // * The timeout length was too short for the device to respond. LJM_ERROR_CODE LJME_INCORRECT_NUM_RESPONSE_BYTES_RECEIVED = 1264; // Problem: The expected number of bytes could not be received from the // device. // Possibilities: // * The device was previously connected, but was suddenly // disconnected. // * The device needs a firmware update. LJM_ERROR_CODE LJME_MIXED_FORMAT_IP_ADDRESS = 1265; // Functions: LJM_OpenS and LJM_Open // Problem: The string passed as an identifier contained an IP address // that was ambiguous. // Solution: Make sure the IP address is in either decimal format // (i.e. "192.168.1.25") or hex format (i.e. "0xC0.A8.0.19"). LJM_ERROR_CODE LJME_UNKNOWN_IDENTIFIER = 1266; LJM_ERROR_CODE LJME_NOT_IMPLEMENTED = 1267; LJM_ERROR_CODE LJME_INVALID_INDEX = 1268; // Problem: An error internal to the LabJackM Library has occurred. // Solution: Please report this error to LabJack. LJM_ERROR_CODE LJME_INVALID_LENGTH = 1269; LJM_ERROR_CODE LJME_ERROR_BIT_SET = 1270; LJM_ERROR_CODE LJME_INVALID_MAXBYTESPERMBFB = 1271; // Functions: // LJM_AddressesToMBFB: // Problem: This indicates the MaxBytesPerMBFB value was // insufficient for any Feedback command. // Solution: Pass a larger value for MaxBytesPerMBFB and make sure // aMBFBCommand has memory allocated of size MaxBytesPerMBFB. // The default size for MaxBytesPerMBFB is 64. LJM_ERROR_CODE LJME_NULL_POINTER = 1272; // Problem: The Library has received an invalid pointer. // Solution: Make sure that any functions that have pointers in their // parameter list are valid pointers that point to allocated memory. LJM_ERROR_CODE LJME_NULL_OBJ = 1273; // Functions: // LJM_OpenS and LJM_Open: // Problem: The Library failed to parse the input parameters. // Solution: Check the validity of your inputs and if the problem // persists, please contact LabJack support. LJM_ERROR_CODE LJME_RESERVED_NAME = 1274; // LJM_OpenS and LJM_Open: // Problem: The string passed as Identifier was a reserved name. // Solution: Use a different name for your device. You can also connect // by passing the device's serial number or IP address, if // applicable. LJM_ERROR_CODE LJME_UNPARSABLE_DEVICE_TYPE = 1275; // LJM_OpenS: // Problem: This Library could not parse the DeviceType. // Solution: Check the LJM_OpenS documentation and make sure the // DeviceType does not contain any unusual characters. LJM_ERROR_CODE LJME_UNPARSABLE_CONNECTION_TYPE = 1276; // LJM_OpenS: // Problem: This Library could not parse the ConnectionType. // Solution: Check the LJM_OpenS documentation and make sure the // ConnectionType does not contain any unusual characters. LJM_ERROR_CODE LJME_UNPARSABLE_IDENTIFIER = 1277; // LJM_OpenS and LJM_Open: // Problem: This Library could not parse the Identifier. // Solution: Check the LJM_OpenS documentation and make sure the // Identifier does not contain any unusual characters. LJM_ERROR_CODE LJME_PACKET_SIZE_TOO_LARGE = 1278; // Problems: The packet being sent to the device contained too many bytes. // Note: Some LabJack devices need two bytes appended to any Modbus packets // sent to a device. The packet size plus these two appended bytes // could have exceeded the packet size limit. // Solution: Send a smaller packet, i.e. break your packet up into multiple // packets. LJM_ERROR_CODE LJME_TRANSACTION_ID_ERR = 1279; // Problem: LJM received an unexpected Modbus Transaction ID. LJM_ERROR_CODE LJME_PROTOCOL_ID_ERR = 1280; // Problem: LJM received an unexpected Modbus Protocol ID. LJM_ERROR_CODE LJME_LENGTH_ERR = 1281; // Problem: LJM received a packet with an unexpected Modbus Length. LJM_ERROR_CODE LJME_UNIT_ID_ERR = 1282; // Problem: LJM received a packet with an unexpected Modbus Unit ID. LJM_ERROR_CODE LJME_FUNCTION_ERR = 1283; // Problem: LJM received a packet with an unexpected Modbus Function. LJM_ERROR_CODE LJME_STARTING_REG_ERR = 1284; // Problem: LJM received a packet with an unexpected Modbus address. LJM_ERROR_CODE LJME_NUM_REGS_ERR = 1285; // Problem: LJM received a packet with an unexpected Modbus number of // registers. LJM_ERROR_CODE LJME_NUM_BYTES_ERR = 1286; // Problem: LJM received a packet with an unexpected Modbus number of bytes. LJM_ERROR_CODE LJME_CONFIG_FILE_NOT_FOUND = 1289; LJM_ERROR_CODE LJME_CONFIG_PARSING_ERROR = 1290; LJM_ERROR_CODE LJME_INVALID_NUM_VALUES = 1291; LJM_ERROR_CODE LJME_CONSTANTS_FILE_NOT_FOUND = 1292; LJM_ERROR_CODE LJME_INVALID_CONSTANTS_FILE = 1293; LJM_ERROR_CODE LJME_INVALID_NAME = 1294; // Problem: LJM received a name that was not found/matched in the constants // file or was otherwise an invalid name. // Solution: Use LJM_ErrorToString to find the invalid name(s). LJM_ERROR_CODE LJME_OVERSPECIFIED_PORT = 1296; // Functions: LJM_Open, LJM_OpenS // Problem: LJM received an Identifier that specified a port/pipe, but // connection type was not specified. LJM_ERROR_CODE LJME_INTENT_NOT_READY = 1297; // Please contact LabJack support if the problem is not apparent. LJM_ERROR_CODE LJME_ATTR_LOAD_COMM_FAILURE = 1298; /** * Name: LJME_ATTR_LOAD_COMM_FAILURE * Functions: LJM_Open, LJM_OpenS * Desc: Indicates that a device was found and opened, but communication with * that device failed, so the device was closed. The handle returned is * not a valid handle. This communication failure can mean the device is * in a non-responsive state or has out-of-date firmware. * Solutions: a) Power your device off, then back on, i.e. unplug it then plug * it back in. * b) Make sure your device(s) have up-to-date firmware. **/ LJM_ERROR_CODE LJME_INVALID_CONFIG_NAME = 1299; // Functions: LJM_WriteLibraryConfigS, LJM_WriteLibraryConfigStringS, // LJM_ReadLibraryConfigS, LJM_ReadLibraryConfigStringS // Problem: An unknown string has been passed in as Parameter. // Solution: Please check the documentation in this header file for the // configuration parameter you are trying to read or write. Not all // config parameters can be read, nor can all config parameters be // written. LJM_ERROR_CODE LJME_ERROR_RETRIEVAL_FAILURE = 1300; // Problem: A device has reported an error and LJM failed to to retrieve the // error code from the device. // Solution: Please make sure the device has current firmware and that this // is a current of LJM. If the problem persists, please contact LabJack // support. LJM_ERROR_CODE LJME_LJM_BUFFER_FULL = 1301; LJM_ERROR_CODE LJME_COULD_NOT_START_STREAM = 1302; LJM_ERROR_CODE LJME_STREAM_NOT_RUNNING = 1303; LJM_ERROR_CODE LJME_UNABLE_TO_STOP_STREAM = 1304; LJM_ERROR_CODE LJME_INVALID_VALUE = 1305; LJM_ERROR_CODE LJME_SYNCHRONIZATION_TIMEOUT = 1306; LJM_ERROR_CODE LJME_OLD_FIRMWARE = 1307; LJM_ERROR_CODE LJME_CANNOT_READ_OUT_ONLY_STREAM = 1308; LJM_ERROR_CODE LJME_NO_SCANS_RETURNED = 1309; LJM_ERROR_CODE LJME_TEMPERATURE_OUT_OF_RANGE = 1310; LJM_ERROR_CODE LJME_VOLTAGE_OUT_OF_RANGE = 1311; /******************************* * Device Management Functions * *******************************/ /** * Name: LJM_ListAll, LJM_ListAllS * Desc: Scans for LabJack devices, returning arrays describing the devices * found, allowing LJM_dtANY and LJM_ctANY to be used * Para: DeviceType, filters which devices will be returned (LJM_dtT7, * LJM_dtDIGIT, etc.). LJM_dtANY is allowed. * ConnectionType, filters by connection type (LJM_ctUSB or LJM_ctTCP). * LJM_ctANY is allowed. * NumFound, a pointer that returns the number of devices found * aDeviceTypes, an array that must be preallocated to size * LJM_LIST_ALL_SIZE, returns the device type for each of the * NumFound devices * aConnectionTypes, an array that must be preallocated to size * LJM_LIST_ALL_SIZE, returns the connect type for each of the * NumFound devices * aSerialNumbers, an array that must be preallocated to size * LJM_LIST_ALL_SIZE, returns the serial number for each of the * NumFound devices * aIPAddresses, an array that must be preallocated to size * LJM_LIST_ALL_SIZE, returns the IPAddresses for each of the * NumFound devices, but only if ConnectionType is TCP-based. For * each corresponding device for which aConnectionTypes[i] is not * TCP-based, aIPAddresses[i] will be LJM_NO_IP_ADDRESS. * Note: These functions only show what devices could be opened. To actually * open a device, use LJM_Open or LJM_OpenS. * Note: These functions will ignore NULL pointers, except for NumFound. **/ LJM_ERROR_RETURN LJM_ListAll(int DeviceType, int ConnectionType, int * NumFound, int * aDeviceTypes, int * aConnectionTypes, int * aSerialNumbers, int * aIPAddresses); LJM_ERROR_RETURN LJM_ListAllS(const char * DeviceType, const char * ConnectionType, int * NumFound, int * aDeviceTypes, int * aConnectionTypes, int * aSerialNumbers, int * aIPAddresses); /** * Name: LJM_ListAllExtended * Desc: Advanced version of LJM_ListAll that performs an additional query of * arbitrary registers on the device. * Para: DeviceType, filters which devices will be returned (LJM_dtT7, * LJM_dtDIGIT, etc.). LJM_dtANY is allowed. * ConnectionType, filters by connection type (LJM_ctUSB or LJM_ctTCP). * LJM_ctANY is allowed. * NumAddresses, the number of addresses to query. Also the size of * aAddresses and aNumRegs. * aAddresses, the addresses to query for each device that is found. * aNumRegs, the number of registers to query for each address. * Each aNumRegs[i] corresponds to aAddresses[i]. * MaxNumFound, the maximum number of devices to find. Also the size of * aDeviceTypes, aConnectionTypes, aSerialNumbers, and aIPAddresses. * NumFound, a pointer that returns the number of devices found * aDeviceTypes, an array that must be preallocated to size * MaxNumFound, returns the device type for each of the * NumFound devices * aConnectionTypes, an array that must be preallocated to size * MaxNumFound, returns the connect type for each of the * NumFound devices * aSerialNumbers, an array that must be preallocated to size * MaxNumFound, returns the serial number for each of the * NumFound devices * aIPAddresses, an array that must be preallocated to size * MaxNumFound, returns the IPAddresses for each of the * NumFound devices, but only if ConnectionType is TCP-based. For * each corresponding device for which aConnectionTypes[i] is not * TCP-based, aIPAddresses[i] will be LJM_NO_IP_ADDRESS. * aBytes, an array that must be preallocated to size: * MaxNumFound * <the sum of aNumRegs> * LJM_BYTES_PER_REGISTER, * which will contain the query bytes sequentially. A device * represented by index i would have an aBytes index of: * (i * <the sum of aNumRegs> * LJM_BYTES_PER_REGISTER). * Note: These functions only show what devices could be opened. To actually * open a device, use LJM_Open or LJM_OpenS. * Note: These functions will ignore NULL pointers, except for NumFound and * aBytes. * * * TODO: Define error behavior * * **/ LJM_ERROR_RETURN LJM_ListAllExtended(int DeviceType, int ConnectionType, int NumAddresses, const int * aAddresses, const int * aNumRegs, int MaxNumFound, int * NumFound, int * aDeviceTypes, int * aConnectionTypes, int * aSerialNumbers, int * aIPAddresses, unsigned char * aBytes); /** * Name: LJM_OpenS * Desc: Opens a LabJack device. * Para: DeviceType, a string containing the type of the device to be connected, * optionally prepended by "LJM_dt". Possible values include "ANY", * "T7", and "DIGIT". * ConnectionType, a string containing the type of the connection desired, * optionally prepended by "LJM_ct". Possible values include "ANY", * "USB", "TCP", "ETHERNET", and "WIFI". * Identifier, a string identifying the device to be connected or * "LJM_idANY"/"ANY". This can be a serial number, IP address, or * device name. Device names may not contain periods. * Handle, the new handle that represents a device connection upon success * Retr: LJME_NOERROR, if a device was successfully opened. * LJME_ATTR_LOAD_COMM_FAILURE, if a device was found, but there was a * communication failure. * Note: Input parameters are not case-sensitive. * Note: Empty strings passed to DeviceType, ConnectionType, or Identifier * indicate the same thing as LJM_dtANY, LJM_ctANY, or LJM_idANY, * respectively. **/ LJM_ERROR_RETURN LJM_OpenS(const char * DeviceType, const char * ConnectionType, const char * Identifier, int * Handle); /** * Name: LJM_Open * Desc: See the description for LJM_OpenS. The only difference between * LJM_Open and LJM_OpenS is the first two parameters. * Para: DeviceType, a constant corresponding to the type of device to open, * such as LJM_dtT7, or LJM_dtANY. * ConnectionType, a constant corresponding to the type of connection to * open, such as LJM_ctUSB, or LJM_ctANY. **/ LJM_ERROR_RETURN LJM_Open(int DeviceType, int ConnectionType, const char * Identifier, int * Handle); /** * Name: LJM_GetHandleInfo * Desc: Takes a device handle as input and returns details about that device. * Para: Handle, a valid handle to an open device. * DeviceType, the output device type corresponding to a constant such as * LJM_dtT7. * ConnectionType, the output device type corresponding to a constant * such as LJM_ctUSB. * SerialNumber, the output serial number of the device. * IPAddress, the output integer representation of the device's IP * address when ConnectionType is TCP-based. If ConnectionType is not * TCP-based, this will be LJM_NO_IP_ADDRESS. Note that this can be * converted to a human-readable string with the LJM_NumberToIP * function. * Port, the output port if the device connection is TCP-based, or the pipe * if the device connection is USB-based. * MaxBytesPerMB, the maximum packet size in number of bytes that can be * sent to or received from this device. Note that this can change * depending on connection type and device type. * Note: This function returns device information loaded during an open call * and therefore does not initiate communications with the device. In * other words, it is fast but will not represent changes to serial * number or IP address since the device was opened. * Warn: This function ignores null pointers **/ LJM_ERROR_RETURN LJM_GetHandleInfo(int Handle, int * DeviceType, int * ConnectionType, int * SerialNumber, int * IPAddress, int * Port, int * MaxBytesPerMB); /** * Name: LJM_Close * Desc: Closes the connection to the device. * Para: Handle, a valid handle to an open device. **/ LJM_ERROR_RETURN LJM_Close(int Handle); /** * Name: LJM_CloseAll * Desc: Closes all connections to all devices **/ LJM_ERROR_RETURN LJM_CloseAll(); /****************************** * Easy Read/Write Functions * ******************************/ // Easy Functions: All type, either reading or writing, single address /** * Name: LJM_eReadAddress, LJM_eReadName * LJM_eWriteAddress, LJM_eWriteName * Desc: Creates and sends a Modbus operation, then receives and parses the * response. * Para: Handle, a valid handle to an open device * (Address), an address to read/write * (Type), the type corresponding to Address * (Name), a name to read/write * Value, a value to write or read * Note: These functions may take liberties in deciding what kind of Modbus * operation to create. For more control of what kind of packets may be * sent/received, please see the LJM_WriteLibraryConfigS function. **/ LJM_ERROR_RETURN LJM_eWriteAddress(int Handle, int Address, int Type, double Value); LJM_ERROR_RETURN LJM_eReadAddress(int Handle, int Address, int Type, double * Value); LJM_ERROR_RETURN LJM_eWriteName(int Handle, const char * Name, double Value); LJM_ERROR_RETURN LJM_eReadName(int Handle, const char * Name, double * Value); // Easy Functions: All type, either reading or writing, multiple addresses /** * Name: LJM_eReadAddresses, LJM_eReadNames * LJM_eWriteAddresses, LJM_eWriteNames * Desc: Creates and sends a Modbus operation, then receives and parses the * response. * Para: Handle, a valid handle to an open device. * NumFrames, the total number of reads/writes to perform. * (aAddresses), an array of size NumFrames of the addresses to * read/write for each frame. * (aTypes), an array of size NumFrames of the data types corresponding * to each address in aAddresses. * (aNames), an array of size NumFrames of the names to read/write for * each frame. * aValues, an array of size NumFrames that represents the values to * write from or read to. * ErrorAddress, a pointer to an integer, which in the case of a relevant * error, gets updated to contain the device-reported address that * caused an error. * Note: Reads/writes are compressed into arrays for consecutive addresses that * line up, based on type. See the LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES * configuration. * Note: These functions may take liberties in deciding what kind of Modbus * operation to create. For more control of what kind of packets may be * sent/received, please see the LJM_WriteLibraryConfigS function. **/ LJM_ERROR_RETURN LJM_eReadAddresses(int Handle, int NumFrames, const int * aAddresses, const int * aTypes, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eReadNames(int Handle, int NumFrames, const char ** aNames, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eWriteAddresses(int Handle, int NumFrames, const int * aAddresses, const int * aTypes, const double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eWriteNames(int Handle, int NumFrames, const char ** aNames, const double * aValues, int * ErrorAddress); // Easy Functions: All type, reading and writing, multiple values to one address /** * Name: LJM_eReadAddressArray, LJM_eReadNameArray * LJM_eWriteAddressArray, LJM_eWriteNameArray * Desc: Performs a Modbus operation to either read or write an array. * Para: Handle, a valid handle to an open device. * (Address), the address to read an array from or write an array to. * (Type), the data type of Address. * (Name), the register name to read an array from or write an array to. * NumValues, the size of the array to read or write. * aValues, an array of size NumValues that represents the values to * write from or read to. * ErrorAddress, a pointer to an integer, which in the case of a relevant * error, gets updated to contain the device-reported address that * caused an error. * Note: These functions may take liberties in deciding what kind of Modbus * operation to create. For more control of what kind of packets may be * sent/received, please see the LJM_WriteLibraryConfigS function. **/ LJM_ERROR_RETURN LJM_eReadAddressArray(int Handle, int Address, int Type, int NumValues, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eReadNameArray(int Handle, const char * Name, int NumValues, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eWriteAddressArray(int Handle, int Address, int Type, int NumValues, const double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eWriteNameArray(int Handle, const char * Name, int NumValues, const double * aValues, int * ErrorAddress); // Easy Functions: All type, reading and writing, multiple addresses with // multiple values for each /** * Name: LJM_eAddresses, LJM_eNames * Desc: Performs Modbus operations that write/read data. * Para: Handle, a valid handle to an open device. * NumFrames, the total number of reads/writes frames to perform. * (aAddresses), an array of size NumFrames of the addresses to * read/write for each frame. * (aTypes), an array of size NumFrames of the data types corresponding * to each address in aAddresses. * (aNames), an array of size NumFrames of the names to read/write for * each frame. * aWrites, an array of size NumFrames of the direction/access type * (LJM_READ or LJM_WRITE) for each frame. * aNumValues, an array of size NumFrames giving the number of values to * read/write for each frame. * aValues, an array that represents the values to write or read. The * size of this array must be the sum of aNumValues. * ErrorAddress, a pointer to an integer, which in the case of a relevant * error, gets updated to contain the device-reported address that * caused an error. * Note: Reads/writes are compressed into arrays for consecutive addresses that * line up, based on type. See the LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES * configuration. * Note: These functions may take liberties in deciding what kind of Modbus * operation to create. For more control of what kind of packets may be * sent/received, please see the LJM_WriteLibraryConfigS function. **/ LJM_ERROR_RETURN LJM_eAddresses(int Handle, int NumFrames, const int * aAddresses, const int * aTypes, const int * aWrites, const int * aNumValues, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eNames(int Handle, int NumFrames, const char ** aNames, const int * aWrites, const int * aNumValues, double * aValues, int * ErrorAddress); /** * Name: LJM_eReadNameString, LJM_eReadAddressString * Desc: Reads a 50-byte string from a device. * Para: Handle, a valid handle to an open device. * (Name), the name of the registers to read, which must be of type * LJM_STRING. * (Address), the address of the registers to read an LJM_STRING from. * String, A string that is updated to contain the result of the read. * Must be allocated to size LJM_STRING_ALLOCATION_SIZE or * greater prior to calling this function. * Note: This is a convenience function for LJM_eNames/LJM_eAddressess. * Note: LJM_eReadNameString checks to make sure that Name is in the constants * file and describes registers that have a data type of LJM_STRING, * but LJM_eReadAddressString does not perform any data type checking. **/ LJM_ERROR_RETURN LJM_eReadNameString(int Handle, const char * Name, char * String); LJM_ERROR_RETURN LJM_eReadAddressString(int Handle, int Address, char * String); /** * Name: LJM_eWriteNameString, LJM_eWriteAddressString * Desc: Writes a 50-byte string to a device. * Para: Handle, a valid handle to an open device. * (Name), the name of the registers to write to, which must be of type * LJM_STRING * (Address), the address of the registers to write an LJM_STRING to * String, The string to write. Must null-terminate at length * LJM_STRING_ALLOCATION_SIZE or less. * Note: This is a convenience function for LJM_eNames/LJM_eAddressess * Note: LJM_eWriteNameString checks to make sure that Name is in the constants * file and describes registers that have a data type of LJM_STRING, * but LJM_eWriteAddressString does not perform any data type checking. **/ LJM_ERROR_RETURN LJM_eWriteNameString(int Handle, const char * Name, const char * String); LJM_ERROR_RETURN LJM_eWriteAddressString(int Handle, int Address, const char * String); /********************* * Stream Functions * *********************/ /** * Name: LJM_eStreamStart * Desc: Initializes a stream object and begins streaming. This includes * creating a buffer in LJM that collects data from the device. * Para: Handle, a valid handle to an open device. * ScansPerRead, Number of scans returned by each call to the * LJM_eStreamRead function. This is not tied to the maximum packet * size for the device. * NumAddresses, The size of aScanList. The number of addresses to scan. * aScanList, Array of Modbus addresses to collect samples from, per scan. * ScanRate, intput/output pointer. Sets the desired number of scans per * second. Upon successful return of this function, gets updated to * the actual scan rate that the device will scan at. * Note: Address configuration such as range, resolution, and differential * voltages are handled by writing to the device. * Note: Check your device's documentation for which addresses are valid for * aScanList. **/ LJM_ERROR_RETURN LJM_eStreamStart(int Handle, int ScansPerRead, int NumAddresses, const int * aScanList, double * ScanRate); /** * Name: LJM_eStreamRead * Desc: Returns data from an initialized and running LJM stream buffer. Waits * for data to become available, if necessary. * Para: Handle, a valid handle to an open device. * aData, Output data array. Returns all addresses interleaved. Must be * large enough to hold (ScansPerRead * NumAddresses) values. * ScansPerRead and NumAddresses are set when stream is set up with * LJM_eStreamStart. The data returned is removed from the LJM stream * buffer. * DeviceScanBacklog, The number of scans left in the device buffer, as * measured from when data was last collected from the device. This * should usually be near zero and not growing for healthy streams. * LJMScanBacklog, The number of scans left in the LJM buffer, as * measured from after the data returned from this function is * removed from the LJM buffer. This should usually be near zero and * not growing for healthy streams. * Note: Returns LJME_NO_SCANS_RETURNED if LJM_STREAM_SCANS_RETURN is * LJM_STREAM_SCANS_RETURN_ALL_OR_NONE. **/ LJM_ERROR_RETURN LJM_eStreamRead(int Handle, double * aData, int * DeviceScanBacklog, int * LJMScanBacklog); /** * Name: LJM_SetStreamCallback * Desc: Sets a callback that is called by LJM when the stream has collected * ScansPerRead scans. * Para: Handle, a valid handle to an open device. * Callback, the callback function for LJM's stream thread to call * when stream data is ready, which should call LJM_eStreamRead to * acquire data. * Arg, the user-defined argument that is passed to Callback when it is * invoked. * Note: LJM_SetStreamCallback should be called after LJM_eStreamStart. * Note: LJM_eStreamStop may be called at any time when using * LJM_SetStreamCallback, but the Callback function should not try to * stop stream. If the Callback function detects that stream needs to be * stopped, it should signal to a different thread that stream should be * stopped. * Note: To disable the previous callback for stream reading, pass 0 or NULL as * Callback. **/ typedef void (*LJM_StreamReadCallback)(void *); LJM_ERROR_RETURN LJM_SetStreamCallback(int Handle, LJM_StreamReadCallback Callback, void * Arg); /** * Name: LJM_eStreamStop * Desc: Stops LJM from streaming any more data from the device, while leaving * any collected data in the LJM buffer to be read. Stops the device from * streaming. * Para: Handle, a valid handle to an open device. **/ LJM_ERROR_RETURN LJM_eStreamStop(int Handle); /*************************************** * Byte-oriented Read/Write Functions * ***************************************/ /** * Name: LJM_WriteRaw * Desc: Sends an unaltered data packet to a device. * Para: Handle, a valid handle to an open device. * Data, the byte array packet to send. * NumBytes, the size of Data. **/ LJM_ERROR_RETURN LJM_WriteRaw(int Handle, const unsigned char * Data, int NumBytes); /** * Name: LJM_ReadRaw * Desc: Reads an unaltered data packet from a device. * Para: Handle, a valid handle to an open device. * Data, the allocated byte array to receive the data packet. * NumBytes, the number of bytes to receive. **/ LJM_ERROR_RETURN LJM_ReadRaw(int Handle, unsigned char * Data, int NumBytes); /** * Name: LJM_AddressesToMBFB * Desc: Takes in arrays that together represent operations to be performed on a * device and outputs a byte array representing a valid Feedback command, * which can be used as input to the LJM_MBFBComm function. * Para: MaxBytesPerMBFB, the maximum number of bytes that the Feedback command * is allowed to consist of. It is highly recommended to pass the size * of the aMBFBCommand buffer as MaxBytesPerMBFB to prevent buffer * overflow. See LJM_DEFAULT_FEEDBACK_ALLOCATION_SIZE. * aAddresses, an array of size NumFrames representing the register * addresses to read from or write to for each frame. * aTypes, an array of size NumFrames representing the data types to read * or write. See the Data Type constants in this header file. * aWrites, an array of size NumFrames of the direction/access type * (LJM_READ or LJM_WRITE) for each frame. * aNumValues, an array of size NumFrames giving the number of values to * read/write for each frame. * aValues, for every entry in aWrites[i] that is LJM_WRITE, this contains * aNumValues[i] values to write and for every entry in aWrites that * is LJM_READ, this contains aNumValues[i] values that can later be * updated in the LJM_UpdateValues function. aValues values must be * in the same order as the rest of the arrays. For example, if aWrite is * {LJM_WRITE, LJM_READ, LJM_WRITE}, * and aNumValues is * {1, 4, 2} * aValues would have one value to be written, then 4 blank/garbage * values to later be updated, and then 2 values to be written. * NumFrames, A pointer to the number of frames being created, which is * also the size of aAddresses, aTypes, aWrites, and aNumValues. Once * this function returns, NumFrames will be updated to the number of * frames aMBFBCommand contains. * aMBFBCommand, the output parameter that contains the valid Feedback * command. Transaction ID and Unit ID will be blanks that * LJM_MBFBComm will fill in. * Warn: aMBFBCommand must be an allocated array of size large enough to hold * the Feedback command (including its frames). You can use * MaxBytesPerMBFB to limit the size of the Feedback command. * Note: If this function returns LJME_FRAMES_OMITTED_DUE_TO_PACKET_SIZE, * aMBFBCommand is still valid, but does not contain all of the frames * that were intended and NumFrames is updated to contain the number of * frames that were included. **/ LJM_ERROR_RETURN LJM_AddressesToMBFB(int MaxBytesPerMBFB, const int * aAddresses, const int * aTypes, const int * aWrites, const int * aNumValues, const double * aValues, int * NumFrames, unsigned char * aMBFBCommand); /** * Name: LJM_MBFBComm * Desc: Sends a Feedback command and receives a Feedback response, parsing the * response for obvious errors. This function adds its own Transaction ID * to the command. The Feedback response may be parsed with the * LJM_UpdateValues function. * Para: Handle, a valid handle to an open device. * UnitID, the ID of the specific unit that the Feedback command should * be sent to. Use LJM_DEFAULT_UNIT_ID unless the device * documentation instructs otherwise. * aMBFB, both an input parameter and an output parameter. As an input * parameter, it is a valid Feedback command. As an output parameter, * it is a Feedback response, which may be an error response. * ErrorAddress, a pointer to an integer, which in the case of a relevant * error, gets updated to contain the device-reported * address that caused an error. * Note: aMBFB must be an allocated array of size large enough to hold the * Feedback response. **/ LJM_ERROR_RETURN LJM_MBFBComm(int Handle, unsigned char UnitID, unsigned char * aMBFB, int * ErrorAddress); /** * Name: LJM_UpdateValues * Desc: Takes a Feedback response named aMBFBResponse from a device and the * arrays corresponding to the Feedback command for which aMBFBResponse * is a response and updates the aValues array based on the read data in * aMBFBResponse. * Para: aMBFBResponse, a valid Feedback response. * aTypes, an array of size NumFrames representing the data types to read * or write. See the Data Type constants in this header file. * aWrites, the array of constants from LabJackM.h - either LJM_WRITE or * LJM_READ. * aNumValues, the array representing how many values were read or written. * NumFrames, the number of frames in aTypes, aWrites, and aNumValues. * aValues, for every entry in aWrites[i] that is LJM_WRITE, this contains * aNumValues[i] values that were written and for every entry in * aWrites that is LJM_READ, this contains aNumValues[i] values * that will now be updated. aValues values must be in the same * order as the rest of the arrays. For example, if aWrite is * {LJM_WRITE, LJM_READ, LJM_WRITE}, * and aNumValues is * {1, 4, 2} * LJM_UpdateValues would skip one value, then update 4 values with * the data in aMBFBResponse, then do nothing with the last 2 values. **/ LJM_ERROR_RETURN LJM_UpdateValues(unsigned char * aMBFBResponse, const int * aTypes, const int * aWrites, const int * aNumValues, int NumFrames, double * aValues); /**************************** * Constants File Functions * ****************************/ /** * Name: LJM_NamesToAddresses * Desc: Takes a list of Modbus register names as input and produces two lists * as output - the corresponding Modbus addresses and types. These two * lists can serve as input to functions that have Address/aAddresses and * Type/aTypes as input parameters. * Para: NumFrames, the number of names in aNames and the allocated size of * aAddresses and aTypes. * aNames, an array of null-terminated C-string register identifiers. * These register identifiers can be register names or register * alternate names. * aAddresses, output parameter containing the addresses described by * aNames in the same order, must be allocated to the size NumFrames * before calling LJM_NamesToAddresses. * aTypes, output parameter containing the types described by aNames in * the same order, must be allocated to the size NumFrames before * calling LJM_NamesToAddresses. * Note: For each register identifier in aNames that is invalid, the * corresponding aAddresses value will be set to LJM_INVALID_NAME_ADDRESS. **/ LJM_ERROR_RETURN LJM_NamesToAddresses(int NumFrames, const char ** aNames, int * aAddresses, int * aTypes); /** * Name: LJM_NameToAddress * Desc: Takes a Modbus register name as input and produces the corresponding * Modbus address and type. These two values can serve as input to * functions that have Address/aAddresses and Type/aTypes as input * parameters. * Para: Name, a null-terminated C-string register identifier. These register * identifiers can be register names or register alternate names. * Address, output parameter containing the address described by Name. * Type, output parameter containing the type described by Names. * Note: If Name is not a valid register identifier, Address will be set to * LJM_INVALID_NAME_ADDRESS. **/ LJM_ERROR_RETURN LJM_NameToAddress(const char * Name, int * Address, int * Type); /** * Name: LJM_AddressesToTypes * Desc: Retrieves multiple data types for given Modbus register addresses. * Para: NumAddresses, the number of addresses to convert to data types. * aAddresses, an array of size NumAddresses of Modbus register addresses. * aType, a pre-allocated array of size NumAddresses which gets updated * to the data type for each corresponding entry in Addresses. * Note: For each aAddresses[i] that is not found, the corresponding entry * aTypes[i] will be set to LJM_INVALID_NAME_ADDRESS and this function * will return LJME_INVALID_ADDRESS. **/ LJM_ERROR_RETURN LJM_AddressesToTypes(int NumAddresses, int * aAddresses, int * aTypes); /** * Name: LJM_AddressToType * Desc: Retrieves the data type for a given Modbus register address. * Para: Address, the Modbus register address to look up. * Type, an integer pointer which gets updated to the data type of * Address. **/ LJM_ERROR_RETURN LJM_AddressToType(int Address, int * Type); /** * Name: LJM_LookupConstantValue * Desc: Takes a register name or other scope and a constant name, and returns * the constant value. * Para: Scope, the register name or other scope to search within. Must be of * size LJM_MAX_NAME_SIZE or less. * ConstantName, the name of the constant to search for. Must be of size * LJM_MAX_NAME_SIZE or less. * ConstantValue, the returned value of ConstantName within the scope * of Scope, if found. **/ LJM_ERROR_RETURN LJM_LookupConstantValue(const char * Scope, const char * ConstantName, double * ConstantValue); /** * Name: LJM_LookupConstantName * Desc: Takes a register name or other scope and a value, and returns the * name of that value, if found within the given scope. * Para: Scope, the register name or other scope to search within. Must be of * size LJM_MAX_NAME_SIZE or less. * ConstantValue, the constant value to search for. * ConstantName, a pointer to a char array allocated to size * LJM_MAX_NAME_SIZE, used to return the null-terminated constant * name. **/ LJM_ERROR_RETURN LJM_LookupConstantName(const char * Scope, double ConstantValue, char * ConstantName); /** * Name: LJM_ErrorToString * Desc: Gets the name of an error code. * Para: ErrorCode, the error code to look up. * ErrorString, a pointer to a char array allocated to size * LJM_MAX_NAME_SIZE, used to return the null-terminated error name. * Note: If the constants file that has been loaded does not contain * ErrorCode, this returns a null-terminated message saying so. * If the constants file could not be opened, this returns a * null-terminated string saying so and where that constants file was * expected to be. **/ LJM_VOID_RETURN LJM_ErrorToString(int ErrorCode, char * ErrorString); /** * Name: LJM_LoadConstants * Desc: Manually loads or reloads the constants files associated with * the LJM_ErrorToString and LJM_NamesToAddresses functions. * Note: This step is handled automatically. This function does not need to be * called before either LJM_ErrorToString or LJM_NamesToAddresses. **/ LJM_VOID_RETURN LJM_LoadConstants(); /** * Name: LJM_LoadConstantsFromFile * Desc: Alias for executing: * LJM_WriteLibraryConfigStringS(LJM_CONSTANTS_FILE, FileName) * Para: FileName, the absolute or relative file path string to pass to * LJM_WriteLibraryConfigStringS as the String parameter. Must * null-terminate. **/ LJM_ERROR_RETURN LJM_LoadConstantsFromFile(const char * FileName); /** * Name: LJM_LoadConstantsFromString * Desc: Parses JsonString as the constants file and loads it. * Para: JsonString, A JSON string containing a "registers" array and/or an "errors" * array. * Note: If the JSON string does not contain a "registers" array, the Modbus-related * constants are not affected. Similarly, if the JSON string does not contain * an "errors" array, the errorcode-related constants are not affected. **/ LJM_ERROR_RETURN LJM_LoadConstantsFromString(const char * JsonString); /****************************** * Type Conversion Functions * ******************************/ // Thermocouple conversion // Thermocouple Type constants static const long LJM_ttB = 6001; static const long LJM_ttE = 6002; static const long LJM_ttJ = 6003; static const long LJM_ttK = 6004; static const long LJM_ttN = 6005; static const long LJM_ttR = 6006; static const long LJM_ttS = 6007; static const long LJM_ttT = 6008; static const long LJM_ttC = 6009; /** * Desc: Converts thermocouple voltage to temperature. * Para: TCType, the thermocouple type. See "Thermocouple Type constants". * TCVolts, the voltage reported by the thermocouple. * CJTempK, the cold junction temperature in degrees Kelvin. * pTCTempK, outputs the calculated temperature in degrees Kelvin. **/ LJM_ERROR_RETURN LJM_TCVoltsToTemp(int TCType, double TCVolts, double CJTempK, double * pTCTempK); /** * Name: LJM_TYPE#BitsToByteArray * Desc: Converts an array of values from C-types to bytes, performing automatic * endian conversions if necessary. * Para: aTYPE#Bits (such as aFLOAT32), the array of values to be converted. * RegisterOffset, the register offset to put the converted values in aBytes. * The actual offset depends on how many bits the type is. * NumTYPE#Bits (such as NumFLOAT32), the number of values to convert. * aBytes, the converted values in byte form. **/ /** * Name: LJM_ByteArrayToTYPE#Bits * Desc: Converts an array of values from bytes to C-types, performing automatic * endian conversions if necessary. * Para: aBytes, the bytes to be converted. * RegisterOffset, the register offset to get the values from in aBytes. * The actual offset depends on how many bits the type is. * NumTYPE#Bits (such as NumFLOAT32), the number of values to convert. * aTYPE#Bits (such as aFLOAT32), the converted values in C-type form. **/ // Single precision float, 32 bits // (the C type "float") LJM_VOID_RETURN LJM_FLOAT32ToByteArray(const float * aFLOAT32, int RegisterOffset, int NumFLOAT32, unsigned char * aBytes); LJM_VOID_RETURN LJM_ByteArrayToFLOAT32(const unsigned char * aBytes, int RegisterOffset, int NumFLOAT32, float * aFLOAT32); // Unsigned 16 bit integer // (the C type "unsigned short" or similar) LJM_VOID_RETURN LJM_UINT16ToByteArray(const unsigned short * aUINT16, int RegisterOffset, int NumUINT16, unsigned char * aBytes); LJM_VOID_RETURN LJM_ByteArrayToUINT16(const unsigned char * aBytes, int RegisterOffset, int NumUINT16, unsigned short * aUINT16); // Unsigned 32 bit integer // (the C type "unsigned int" or similar) LJM_VOID_RETURN LJM_UINT32ToByteArray(const unsigned int * aUINT32, int RegisterOffset, int NumUINT32, unsigned char * aBytes); LJM_VOID_RETURN LJM_ByteArrayToUINT32(const unsigned char * aBytes, int RegisterOffset, int NumUINT32, unsigned int * aUINT32); // Signed 32 bit integer // (the C type "int" or similar) LJM_VOID_RETURN LJM_INT32ToByteArray(const int * aINT32, int RegisterOffset, int NumINT32, unsigned char * aBytes); LJM_VOID_RETURN LJM_ByteArrayToINT32(const unsigned char * aBytes, int RegisterOffset, int NumINT32, int * aINT32); /** * Name: LJM_NumberToIP * Desc: Takes an integer representing an IPv4 address and outputs the corresponding * decimal-dot IPv4 address as a null-terminated string. * Para: Number, the numerical representation of an IP address to be converted to * a string representation. * IPv4String, a char array that must be allocated to size LJM_IPv4_STRING_SIZE * which will be set to contain the null-terminated string representation * of the IP address after the completion of this function. * Retr: LJME_NOERROR for no detected errors, * LJME_NULL_POINTER if IPv4String is NULL. **/ LJM_ERROR_RETURN LJM_NumberToIP(unsigned int Number, char * IPv4String); /** * Name: LJM_IPToNumber * Desc: Takes a decimal-dot IPv4 string representing an IPv4 address and outputs the * corresponding integer version of the address. * Para: IPv4String, the string representation of the IP address to be converted to * a numerical representation. * Number, the output parameter that will be updated to contain the numerical * representation of IPv4String after the completion of this function. * Retr: LJME_NOERROR for no detected errors, * LJME_NULL_POINTER if IPv4String or Number is NULL, * LJME_INVALID_PARAMETER if IPv4String could not be parsed as a IPv4 address. **/ LJM_ERROR_RETURN LJM_IPToNumber(const char * IPv4String, unsigned int * Number); /** * Name: LJM_NumberToMAC * Desc: Takes an integer representing a MAC address and outputs the corresponding * hex-colon MAC address as a string. * Para: Number, the numerical representation of a MAC address to be converted to * a string representation. * MACString, a char array that must be allocated to size LJM_MAC_STRING_SIZE * which will be set to contain the string representation of the MAC * address after the completion of this function. * Retr: LJME_NOERROR for no detected errors, * LJME_NULL_POINTER if MACString is NULL. **/ LJM_ERROR_RETURN LJM_NumberToMAC(unsigned long long Number, char * MACString); /** * Name: LJM_MACToNumber * Desc: Takes a hex-colon string representing a MAC address and outputs the * corresponding integer version of the address. * Para: MACString, the string representation of the MAC address to be converted to * a numerical representation. * Number, the output parameter that will be updated to contain the numerical * representation of MACString after the completion of this function. * Retr: LJME_NOERROR for no detected errors, * LJME_NULL_POINTER if MACString or Number is NULL, * LJME_INVALID_PARAMETER if MACString could not be parsed as a MAC address. **/ LJM_ERROR_RETURN LJM_MACToNumber(const char * MACString, unsigned long long * Number); /********************** * LJM Configuration * **********************/ // Config Parameters /** * Desc: The maximum number of milliseconds that LJM will wait for a packet to * be sent and also for a packet to be received before timing out. In * other words, LJM can wait this long for a command to be sent, then * wait this long again for the response to be received. **/ static const char * const LJM_USB_SEND_RECEIVE_TIMEOUT_MS = "LJM_USB_SEND_RECEIVE_TIMEOUT_MS"; static const char * const LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS = "LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS"; static const char * const LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS = "LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS"; /** * Desc: Sets LJM_USB_SEND_RECEIVE_TIMEOUT_MS, LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS, * and LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS. * Note: Write-only. May not be read. **/ static const char * const LJM_SEND_RECEIVE_TIMEOUT_MS = "LJM_SEND_RECEIVE_TIMEOUT_MS"; /** * Name: LJM_ETHERNET_OPEN_TIMEOUT_MS * Desc: The maximum number of milliseconds that LJM will wait for a device * being opened via TCP to respond before timing out. **/ static const char * const LJM_ETHERNET_OPEN_TIMEOUT_MS = "LJM_ETHERNET_OPEN_TIMEOUT_MS"; /** * Name: LJM_WIFI_OPEN_TIMEOUT_MS * Desc: The maximum number of milliseconds that LJM will wait for a device * being opened via TCP to respond before timing out. **/ static const char * const LJM_WIFI_OPEN_TIMEOUT_MS = "LJM_WIFI_OPEN_TIMEOUT_MS"; /** * Name: LJM_OPEN_TCP_DEVICE_TIMEOUT_MS * Desc: Sets both LJM_ETHERNET_OPEN_TIMEOUT_MS and LJM_WIFI_OPEN_TIMEOUT_MS. * Note: Write-only. May not be read. **/ static const char * const LJM_OPEN_TCP_DEVICE_TIMEOUT_MS = "LJM_OPEN_TCP_DEVICE_TIMEOUT_MS"; /** * Name: LJM_DEBUG_LOG_MODE * Desc: Any of the following modes: * Vals: 1 (default) - Never logs anything, regardless of LJM_DEBUG_LOG_LEVEL. * 2 - Log continuously to the log file according to LJM_DEBUG_LOG_LEVEL (see LJM_DEBUG_LOG_FILE). * 3 - Continuously stores a finite number of log messages, writes them to file upon error. **/ static const char * const LJM_DEBUG_LOG_MODE = "LJM_DEBUG_LOG_MODE"; enum { LJM_DEBUG_LOG_MODE_NEVER = 1, LJM_DEBUG_LOG_MODE_CONTINUOUS = 2, LJM_DEBUG_LOG_MODE_ON_ERROR = 3 }; /** * Name: LJM_DEBUG_LOG_LEVEL * Desc: The level of priority that LJM will log. Levels that are lower than * the current LJM_DEBUG_LOG_LEVEL are not logged. For example, if log * priority is set to LJM_WARNING, messages with priority level * LJM_WARNING and greater are logged to the debug file. * Vals: See below. * Note: LJM_PACKET is the default value. **/ static const char * const LJM_DEBUG_LOG_LEVEL = "LJM_DEBUG_LOG_LEVEL"; enum { LJM_STREAM_PACKET = 1, LJM_TRACE = 2, LJM_DEBUG = 4, LJM_INFO = 6, LJM_PACKET = 7, LJM_WARNING = 8, LJM_USER = 9, LJM_ERROR = 10, LJM_FATAL = 12 }; /** * Name: LJM_DEBUG_LOG_BUFFER_MAX_SIZE * Desc: The number of log messages LJM's logger buffer can hold. **/ static const char * const LJM_DEBUG_LOG_BUFFER_MAX_SIZE = "LJM_DEBUG_LOG_BUFFER_MAX_SIZE"; /** * Name: LJM_DEBUG_LOG_SLEEP_TIME_MS * Desc: The number of milliseconds the logger thread will sleep for between * flushing the messages in the logger buffer to the log file. * Note: See also LJM_DEBUG_LOG_BUFFER_MAX_SIZE **/ static const char * const LJM_DEBUG_LOG_SLEEP_TIME_MS = "LJM_DEBUG_LOG_SLEEP_TIME_MS"; /** * Name: LJM_LIBRARY_VERSION * Desc: Returns the current version of LJM. This will match LJM_VERSION (at * the top of this header file) if you are using the executable LJM that * corresponds to this header file. **/ static const char * const LJM_LIBRARY_VERSION = "LJM_LIBRARY_VERSION"; /** * Name: LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS * Desc: A mode that sets whether or not LJM will automatically send/receive * multiple Feedback commands when the desired operations would exceed * the maximum packet length. This mode is relevant to Easy functions * such as LJM_eReadNames. * Vals: 0 - Disable * Anything else - Enable (default) **/ static const char * const LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS = "LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS"; /** * Name: LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES * Desc: A mode that sets whether or not LJM will automatically condense * single address reads/writes into array reads/writes, which minimizes * packet size. This mode is relevant to Easy functions such as * LJM_eReadNames. * Vals: 0 - Disable * Anything else - Enable (default) **/ static const char * const LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES = "LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES"; /** * Name: LJM_AUTO_RECONNECT_STICKY_CONNECTION * Desc: Sets whether or not LJM attempts to reconnect disrupted / disconnected * connections according to same connection type as the original handle. * Vals: 0 - Disable * 1 - Enable (default) **/ static const char * const LJM_AUTO_RECONNECT_STICKY_CONNECTION = "LJM_AUTO_RECONNECT_STICKY_CONNECTION"; /** * Name: LJM_AUTO_RECONNECT_STICKY_SERIAL * Desc: Sets whether or not LJM attempts to reconnect disrupted / disconnected * connections according to same serial number as the original handle. * Vals: 0 - Disable * 1 - Enable (default) **/ static const char * const LJM_AUTO_RECONNECT_STICKY_SERIAL = "LJM_AUTO_RECONNECT_STICKY_SERIAL"; /** * Name: LJM_OPEN_MODE * Desc: Specifies the mode of interaction LJM will use when communicating with * opened devices. * Vals: See following values. * Note: See LJM_KEEP_OPEN and LJM_OPEN_MODE. **/ static const char * const LJM_OPEN_MODE = "LJM_OPEN_MODE"; enum { /** * Name: LJM_KEEP_OPEN * Desc: A LJM_OPEN_MODE that claims ownership of each opened device until * the device is explicitly closed. In this mode, LJM maintains a * connection to each opened device at all times. * Note: This is a somewhat faster mode, but it is not multi-process friendly. * If there is another process trying to access a device that is opened * with LJM using this mode, it will not be able to. **/ LJM_KEEP_OPEN = 1, /** * THIS MODE IS NOT YET IMPLEMENTED * Name: LJM_KEEP_OPEN * Desc: A multi-process friendly LJM_OPEN_MODE that does not claim ownership * of any opened devices except when the device is being communicated * with. In this mode, LJM will automatically close connection(s) to * devices that are not actively sending/receiving communications and * automatically reopen connection(s) when needed. * Note: This mode is slightly slower, but allows other processes/programs to * access a LJM-opened device without needing to close the device with * LJM first. * When using LJM_KEEP_OPEN mode, LJM_Close or LJM_CloseAll still need * to be called (to clean up memory). **/ LJM_OPEN_CLOSE = 2 }; /** * Name: LJM_MODBUS_MAP_CONSTANTS_FILE * Desc: Specifies absolute or relative path of the constants file to use for * functions that use the LJM Name functionality, such as * LJM_NamesToAddresses and LJM_eReadName. **/ static const char * const LJM_MODBUS_MAP_CONSTANTS_FILE = "LJM_MODBUS_MAP_CONSTANTS_FILE"; /** * Name: LJM_ERROR_CONSTANTS_FILE * Desc: Specifies absolute or relative path of the constants file to use for * LJM_ErrorToString. **/ static const char * const LJM_ERROR_CONSTANTS_FILE = "LJM_ERROR_CONSTANTS_FILE"; /** * Name: LJM_DEBUG_LOG_FILE * Desc: Describes the absolute or relative path of the file to output log * messages to. * Note: See LJM_DEBUG_LOG_MODE and LJM_DEBUG_LOG_LEVEL. **/ static const char * const LJM_DEBUG_LOG_FILE = "LJM_DEBUG_LOG_FILE"; /** * Name: LJM_CONSTANTS_FILE * Desc: Sets LJM_MODBUS_MAP_CONSTANTS_FILE and LJM_ERROR_CONSTANTS_FILE at the same * time, as an absolute or relative file path. * Note: Cannot be read, since LJM_MODBUS_MAP_CONSTANTS_FILE and * LJM_ERROR_CONSTANTS_FILE can be different files. **/ static const char * const LJM_CONSTANTS_FILE = "LJM_CONSTANTS_FILE"; /** * Name: LJM_DEBUG_LOG_FILE_MAX_SIZE * Desc: The maximum size of the log file in number of characters. * Note: This is an approximate limit. **/ static const char * const LJM_DEBUG_LOG_FILE_MAX_SIZE = "LJM_DEBUG_LOG_FILE_MAX_SIZE"; /** * Name: LJM_STREAM_AIN_BINARY * Desc: Sets whether data returned from LJM_eStreamRead will be * calibrated or uncalibrated. * Vals: 0 - Calibrated floating point AIN data (default) * 1 - Uncalibrated binary AIN data **/ static const char * const LJM_STREAM_AIN_BINARY = "LJM_STREAM_AIN_BINARY"; /** * Name: LJM_STREAM_SCANS_RETURN * Desc: Sets how LJM_eStreamRead will return data. * Note: Does not affect currently running or already initialized streams. **/ static const char * const LJM_STREAM_SCANS_RETURN = "LJM_STREAM_SCANS_RETURN"; enum { /** * Name: LJM_STREAM_SCANS_RETURN_ALL * Desc: A mode that will cause LJM_eStreamRead to sleep until the full * ScansPerRead scans are collected by LJM. * Note: ScansPerRead is a parameter of LJM_eStreamStart. * Note: This mode may not be apporpriate for stream types that are not * consistently timed, such as gate stream mode or external clock stream * mode. **/ LJM_STREAM_SCANS_RETURN_ALL = 1, /** * Name: LJM_STREAM_SCANS_RETURN_ALL_OR_NONE * Desc: A mode that will cause LJM_eStreamRead to never sleep, and instead * either: * consume ScansPerRead scans and return LJME_NOERROR, or * consume no scans and return LJME_NO_SCANS_RETURNED. * LJM_eStreamRead will consume ScansPerRead if the LJM handle has * received ScansPerRead or more scans, otherwise it will consume none. * Note: ScansPerRead is a parameter of LJM_eStreamStart. **/ LJM_STREAM_SCANS_RETURN_ALL_OR_NONE = 2 /** * Name: LJM_STREAM_SCANS_RETURN_AVAILABLE * Desc: A mode that will cause LJM_eStreamRead to never sleep, and always * consume the number of scans that the LJM handle has received, up to * a maximum of ScansPerRead. Fills the excess scan places in aData * not read, if any, with LJM_SCAN_NOT_READ. * Note: ScansPerRead is a parameter of LJM_eStreamStart. * TODO: LJM_STREAM_SCANS_RETURN_AVAILABLE is not currently implemented. **/ // LJM_STREAM_SCANS_RETURN_AVAILABLE = 3 }; /** * Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE * Desc: Sets how stream should time out. * Note: Does not affect currently running or already initialized streams. **/ static const char * const LJM_STREAM_RECEIVE_TIMEOUT_MODE = "LJM_STREAM_RECEIVE_TIMEOUT_MODE"; enum { /** * Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE_CALCULATED * Desc: Calculates how long the stream timeout should be, according to the * scan rate reported by the device. * Note: This is the default LJM_STREAM_RECEIVE_TIMEOUT_MODE. **/ LJM_STREAM_RECEIVE_TIMEOUT_MODE_CALCULATED = 1, /** * Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL * Desc: Manually sets how long the stream timeout should be. * Note: The actual stream timeout value is set via * LJM_STREAM_RECEIVE_TIMEOUT_MS. **/ LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL = 2 }; /** * Name: LJM_STREAM_RECEIVE_TIMEOUT_MS * Desc: Manually sets the stream receive timeout in milliseconds. Writing to * this configuration sets LJM_STREAM_RECEIVE_TIMEOUT_MODE to be * LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL. * Note: 0 is never timeout. * Note: Only affects currently running or already initialized streams if those * streams were initialized with a LJM_STREAM_RECEIVE_TIMEOUT_MODE of * LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL. **/ static const char * const LJM_STREAM_RECEIVE_TIMEOUT_MS = "LJM_STREAM_RECEIVE_TIMEOUT_MS"; /** * Name: LJM_STREAM_TRANSFERS_PER_SECOND * Desc: Sets/gets the number of times per second stream threads attempt to * read from the stream. * Note: Does not affect currently running or already initialized streams. **/ static const char * const LJM_STREAM_TRANSFERS_PER_SECOND = "LJM_STREAM_TRANSFERS_PER_SECOND"; /** * Name: LJM_RETRY_ON_TRANSACTION_ID_MISMATCH * Desc: Sets/gets whether or not LJM will automatically retry an operation if * an LJME_TRANSACTION_ID_ERR occurs. * Vals: 0 - Disable * 1 - Enable (default) **/ static const char * const LJM_RETRY_ON_TRANSACTION_ID_MISMATCH = "LJM_RETRY_ON_TRANSACTION_ID_MISMATCH"; /** * Name: LJM_OLD_FIRMWARE_CHECK * Desc: Sets/gets whether or not LJM will check the constants file (see * LJM_CONSTANTS_FILE) to make sure the firmware of the current device is * compatible with the Modbus register(s) being read from or written to, * when applicable. When device firmware is lower than fwmin for the * register(s) being read/written, LJM will return LJME_OLD_FIRMWARE and * not perform the Modbus operation(s). * Vals: 0 - Disable * 1 - Enable (default) * Note: When enabled, LJM will perform a check that is linear in size * proportional to the number of register entries in the constants file * for each address/name being read/written. **/ static const char * const LJM_OLD_FIRMWARE_CHECK = "LJM_OLD_FIRMWARE_CHECK"; /** * Name: LJM_ZERO_LENGTH_ARRAY_MODE * Desc: Determines the behavior of array read/write functions when the array * size is 0. **/ static const char * const LJM_ZERO_LENGTH_ARRAY_MODE = "LJM_ZERO_LENGTH_ARRAY_MODE"; enum { /** * Name: LJM_ZERO_LENGTH_ARRAY_ERROR * Desc: Sets LJM to return an error when an array of size 0 is detected. **/ LJM_ZERO_LENGTH_ARRAY_ERROR = 1, /** * Name: LJM_ZERO_LENGTH_ARRAY_IGNORE_OPERATION * Desc: Sets LJM to ignore the operation when all arrays in the * operation are of size 0. **/ LJM_ZERO_LENGTH_ARRAY_IGNORE_OPERATION = 2 }; // Config functions /** * Name: LJM_WriteLibraryConfigS * Desc: Writes/sets a library configuration/setting. * Para: Parameter, the name of the configuration setting. Not * case-sensitive. Must null-terminate. * Value, the config value to apply to Parameter. * Retr: LJM_NOERROR for success, * LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown. * Note: See "Config Parameters" for valid Parameters and "Config Values" for * valid Values. **/ LJM_ERROR_RETURN LJM_WriteLibraryConfigS(const char * Parameter, double Value); /** * Name: LJM_WriteLibraryConfigStringS * Desc: Writes/sets a library configuration/setting. * Para: Parameter, the name of the configuration setting. Not * case-sensitive. Must null-terminate. * String, the config value string to apply to Parameter. Must * null-terminate. Must not be of size greater than * LJM_MAX_NAME_SIZE, including null-terminator. * Retr: LJM_NOERROR for success, * LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown * Note: See "Config Parameters" for valid Parameters and "Config Values" for * valid Values. **/ LJM_ERROR_RETURN LJM_WriteLibraryConfigStringS(const char * Parameter, const char * String); /** * Name: LJM_ReadLibraryConfigS * Desc: Reads a configuration/setting from the library. * Para: Parameter, the name of the configuration setting. Not * case-sensitive. Must null-terminate. * Value, return value representing the config value. * Retr: LJM_NOERROR for success, * LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown. * Note: See "Config Parameters" for valid Parameters and "Config Values" for * valid Values. **/ LJM_ERROR_RETURN LJM_ReadLibraryConfigS(const char * Parameter, double * Value); /** * Name: LJM_ReadLibraryConfigStringS * Desc: Reads a configuration/setting from the library. * Para: Parameter, the name of the configuration setting. Not * case-sensitive. Must null-terminate. * string, return value representing the config string. Must be * pre-allocated to size LJM_MAX_NAME_SIZE. * Retr: LJM_NOERROR for success, * LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown. * Note: See "Config Parameters" for valid Parameters and "Config Values" for * valid Values. **/ LJM_ERROR_RETURN LJM_ReadLibraryConfigStringS(const char * Parameter, char * String); /** * Desc: Load all the configuration values in a specified file. * Para: FileName, a relative or absolute file location. "default" maps to the * default configuration file ljm_startup_config.json in the * constants file location. Must null-terminate. **/ LJM_ERROR_RETURN LJM_LoadConfigurationFile(const char * FileName); /****************** * Log Functions * ******************/ /** * Name: LJM_Log * Desc: Sends a message of the specified level to the LJM debug logger. * Para: Level, the level to output the message at. See LJM_DEBUG_LOG_LEVEL. * String, the debug message to be written to the log file. * Note: By default, LJM_DEBUG_LOG_MODE is to never log, so LJM does not output * any log messages, even from this function. * Note: For more information on the LJM debug logger, see LJM_DEBUG_LOG_MODE, * LJM_DEBUG_LOG_LEVEL, LJM_DEBUG_LOG_BUFFER_MAX_SIZE, * LJM_DEBUG_LOG_SLEEP_TIME_MS, LJM_DEBUG_LOG_FILE, * LJM_DEBUG_LOG_FILE_MAX_SIZE **/ LJM_ERROR_RETURN LJM_Log(int Level, const char * String); /** * Name: LJM_ResetLog * Desc: Clears all characters from the debug log file. * Note: See the LJM configuration properties for Log-related properties. **/ LJM_ERROR_RETURN LJM_ResetLog(); #ifdef __cplusplus } #endif #endif // #define LAB_JACK_M_HEADER
76,915
C
43.980117
129
0.680894
adegirmenci/HBL-ICEbot/LabJackWidget/LabJackLibs/64bit/LabJackUD.h
#ifndef LJHEADER_H #define LJHEADER_H // The version of this driver. Call GetDriverVersion() to determine the version of the DLL you have. // It should match this number, otherwise your .h and DLL's are from different versions. #define DRIVER_VERSION 3.46 #define LJ_HANDLE long #define LJ_ERROR long #ifdef __cplusplus extern "C" { #endif // ************************************************** // Functions // ************************************************** // The S form of these functions (the ones with S at the end) take strings instead of numerics for places where constants // would normally be used. This allows languages that can't include this header file to still use defined constants rather // than hard coded numbers. // The Ptr form of these functions (the ones with Ptr at the end) take a void * instead of a long for the x1 parameter. // This allows the x1 parameter to be 64-bit pointer address safe, and is required in 64-bit applications when passing an // pointer/array to x1. void _stdcall Close(); // Closes all LabJack device handles. LJ_ERROR _stdcall ListAll(long DeviceType, long ConnectionType, long *pNumFound, long *pSerialNumbers, long *pIDs, double *pAddresses); LJ_ERROR _stdcall ListAllS(const char *pDeviceType, const char *pConnectionType, long *pNumFound, long *pSerialNumbers, long *pIDs, double *pAddresses); // Returns all the devices found of a given device type and connection type. pSerialNumbers, pIDs and // pAddresses must be arrays of the given type at least 128 elements in size. pNumFound is a single element and will tell you how many // of those 128 elements have valid data (and therefore the number of units found. With pAddresses you'll probably want // to use the DoubleToStringAddress() function below to convert. LJ_ERROR _stdcall OpenLabJack(long DeviceType, long ConnectionType, const char *pAddress, long FirstFound, LJ_HANDLE *pHandle); LJ_ERROR _stdcall OpenLabJackS(const char *pDeviceType, const char *pConnectionType, const char *pAddress, long FirstFound, LJ_HANDLE *pHandle); // Must be called before working with a device. // DeviceType = The type of LabJack device to open (see device types constants). // ConnectionType = How to connect to the device, USB or Ethernet presently. // Ethernet only currently supported on the UE9. // Address = Either the ID or serial number (if USB), or the IP address. Note this is a string for either. // FirstFound = If true, then ignore Address and find the first available LabJack. // pHandle = The handle to use for subsequent functions on this device, or 0 if failed. // // This function returns 0 if success and a handle to the open labjack, or an errorcode if failed. LJ_ERROR _stdcall AddRequest(LJ_HANDLE Handle, long IOType, long Channel, double Value, long x1, double UserData); LJ_ERROR _stdcall AddRequestS(LJ_HANDLE Handle, const char *pIOType, long Channel, double Value, long x1, double UserData); LJ_ERROR _stdcall AddRequestSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double Value, long x1, double UserData); LJ_ERROR _stdcall AddRequestPtr(LJ_HANDLE Handle, long IOType, long Channel, double Value, void *x1, double UserData); // Function to add to the list of things to do with the next call to Go/GoOne(). // Handle: A handle returned by OpenLabJack(). // IOType: The type of data request (see IO type constants). // Channel: The channel # on the particular IOType. // Value: For output channels, the value to set to. // X1: Optional parameters used by some IOTypes. // UserData: Data that is kept with the request and returned with the GetFirst and GetNextResult() functions. // Returns 0 if success, errorcode if not (most likely handle not found). // NOTE: When you call AddRequest on a particular Handle, all previous data is erased and cannot be retrieved // by GetResult() until read again. This is on a device by device basis, so you can call AddRequest() with a different // handle while a device is busy performing its I/O. // The long version is used by languages that can't cast a pointer into a double and should only be used in such situations. LJ_ERROR _stdcall Go(void); // Called once AddRequest has specified all the items to do. This function actually does all those things on all devices. // takes no parameters. Returns 0 if success, errorcode if not (currently never returns an error, as errors in reading // individual items are returned when GetResult() is called. LJ_ERROR _stdcall GoOne(LJ_HANDLE Handle); // Same as above, but only does requests on the given handle. LJ_ERROR _stdcall eGet(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, long x1); LJ_ERROR _stdcall eGetPtr(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, void *x1); LJ_ERROR _stdcall eGetS(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, long x1); LJ_ERROR _stdcall eGetSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, long x1); LJ_ERROR _stdcall ePut(LJ_HANDLE Handle, long IOType, long Channel, double Value, long x1); LJ_ERROR _stdcall ePutS(LJ_HANDLE Handle, const char *pIOType, long Channel, double Value, long x1); LJ_ERROR _stdcall ePutSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double Value, long x1); LJ_ERROR _stdcall eGet_DblArray(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, double *x1); LJ_ERROR _stdcall eGet_U8Array(LJ_HANDLE Handle, long IOType, long Channel, double *pValue, unsigned char *x1); LJ_ERROR _stdcall eGetS_DblArray(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, double *x1); LJ_ERROR _stdcall eGetS_U8Array(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue, unsigned char *x1); LJ_ERROR _stdcall eGetSS_DblArray(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, double *x1); LJ_ERROR _stdcall eGetSS_U8Array(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue, unsigned char *x1); // These functions do AddRequest, Go, and GetResult in one step. The Get versions are designed for inputs or retrieving parameters // as it takes a pointer to a double where the result is placed, but can be used for outputs if pValue is preset to the // desired value. This is also useful for things like StreamRead where a value is required to be input and a value is // returned. The Put versions are designed for outputs or setting configuration parameters and won't return anything but the error code. // Internally, all the put versions do is call the get function with a pointer set for you. // You can repetitively call Go() and GoOne() along with GetResult() to repeat the same requests. Once you call AddRequest() // once on a particular device, it will clear out the requests on that particular device. // NOTE: Be careful when using multiple devices and Go(): AddRequest() only clears out the request list on the device handle // provided. If, for example, you perform run two requests, one on each of two different devices, and then add a new request on // one device but not the other and then call Go(), the original request on the second device will be performed again. LJ_ERROR _stdcall GetResult(LJ_HANDLE Handle, long IOType, long Channel, double *pValue); LJ_ERROR _stdcall GetResultS(LJ_HANDLE Handle, const char *pIOType, long Channel, double *pValue); LJ_ERROR _stdcall GetResultSS(LJ_HANDLE Handle, const char *pIOType, const char *pChannel, double *pValue); // Called to retrieve data and error codes for the things done in Go(). Typically this should be called // for each element passed with AddRequest, but outputs can be skipped if errorcodes not needed. // Handle, IOType, Channel: these should match the parameters passed in AddRequest to retrieve the result for // that particular item. // pValue = Value retrieved for that item. // Returns 0 if success, LJE_NODATA if no data available for the particular Handle, IOType, and Channel specified, // or the error code for the particular action performed. // The long version is used by languages that can't cast a pointer into a double and should only be used in such situations. LJ_ERROR _stdcall GetFirstResult(LJ_HANDLE Handle, long *pIOType, long *pChannel, double *pValue, long *px1, double *pUserData); LJ_ERROR _stdcall GetNextResult(LJ_HANDLE Handle, long *pIOType, long *pChannel, double *pValue, long *px1, double *pUserData); // These GetResult() type functions are designed for situations when you want to get all the results in order. Call GetFirstResult() // first to get the first result avialable for the given handle and the error code. Then call GetNextResult() repeditively for // subsequent requests. When either function returns LJE_NO_MORE_DATA_AVAILABLE, you're done. Note that x1 and UserData are always // returned as well. You can therefore use UserData as space for your own tracking information, or whatever else you may need. // Here's a sample of how a loop might work: // err = GetFirstResult(..) // while (!err) // { // process result... // err = GetNextResult(..) // } LJ_ERROR _stdcall eAIN(LJ_HANDLE Handle, long ChannelP, long ChannelN, double *Voltage, long Range, long Resolution, long Settling, long Binary, long Reserved1, long Reserved2); LJ_ERROR _stdcall eDAC(LJ_HANDLE Handle, long Channel, double Voltage, long Binary, long Reserved1, long Reserved2); LJ_ERROR _stdcall eDI(LJ_HANDLE Handle, long Channel, long *State); LJ_ERROR _stdcall eDO(LJ_HANDLE Handle, long Channel, long State); LJ_ERROR _stdcall eAddGoGet(LJ_HANDLE Handle, long NumRequests, long *aIOTypes, long *aChannels, double *aValues, long *ax1s, long *aRequestErrors, long *GoError, long *aResultErrors); LJ_ERROR _stdcall eTCConfig(LJ_HANDLE Handle, long *aEnableTimers, long *aEnableCounters, long TCPinOffset, long TimerClockBaseIndex, long TimerClockDivisor, long *aTimerModes, double *aTimerValues, long Reserved1, long Reserved2); LJ_ERROR _stdcall eTCValues(LJ_HANDLE Handle, long *aReadTimers, long *aUpdateResetTimers, long *aReadCounters, long *aResetCounters, double *aTimerValues, double *aCounterValues, long Reserved1, long Reserved2); LJ_ERROR _stdcall eModbus(LJ_HANDLE Handle, long readwrite, long addr, long size, unsigned char *value); // Prototypes for beta version of easy functions to make simple tasks easier. // ************************************************* // NOTE: This driver is completely thread safe. With some very minor exceptions, you can call all these functions from // multiple threads at the same time and the driver will keep everything straight. Because of this, you must call Add...(), // Go...() and Get...() from the same thread for a particular set of requests. Internally the list of things to do and // results are split by thread. This allows you to use multiple threads to make requests without accidently getting // data from one thread into another. If you are Adding requests and then getting NO_DATA_AVAILABlE or similar error when // Getting the results, then chances are you are running in different threads and don't realize this. // SubNote: The driver tracks which thread a request is made in by the thread ID. If you kill a thread and then create a new one // it is possible for the new thread to have the same ID. Its not really a problem if you call AddRequest first, but if you // did GetFirstResult on a new thread you may actually get data from the thread that already ended. // SubNote: As mentioned, the list of requests and results is kept on a thread by thread basis. Since the driver can't tell // when a thread has ended, the results are kept in memory for that thread even though the thread is done (thus the reason for the // above mentioned subnote). This is not a problem in general as the driver will clean it all up when its unloaded. When it can // be a problem is in situations where you are creating and destorying threads continuously. This will result in the slow consumption // of memory as requests on old threads are left behind. Since each request only uses 44 bytes and as mentioned the ID's will // eventually get recycled, it won't be a huge memory loss, but it will be there. In general, even without this issue, we strongly // recommend against creating and destroying a lot of threads. Its terribly slow and inefficient. Use thread pools and other // techniques to keep new thread creation to a minimum. This is what is done internally, // ************************************************** // NOTE: Continuing on the thread safety issue, the one big exception to the thread safety of this driver is in the use of // the windows TerminateThread() function. As it warns in the MSDN documentation, using TerminateThread() will kill the thread // without releasing any resources, and more importantly, releasing any synchronization objects. If you TerminateThread() on a // thread that is currently in the middle of a call to this driver, you will more than likely leave a synchronization object open // on the particular device and you will no longer be able to access the device from you application until you restart. On some // devices, it can be worse. On devices that have interprocess synchonization, such as the U12, calling TerminateThread() may // kill all access to the device through this driver no matter which process is using it and even if you restart your application. // Just avoid using TerminateThread()! All device calls have a timeout, which defaults to 1 second, but is changeable. Make sure // when you are waiting for the driver that you wait at least as long as the timeout for it to finish. // ************************************************** LJ_ERROR _stdcall ResetLabJack(LJ_HANDLE Handle); // Error functions: LJ_ERROR _stdcall GetNextError(LJ_HANDLE Handle, long *pIOType, long *pChannel); // Instead of having to check every GetResult for errors, you can instead repetitively call GetNextError to retrieve all the errors // from a particular Go. This includes eGet, ePut, etc if you want to use the same error handling routine. This function will // return an error with each call along with the IOType and channel that caused the error. If there are no errors or no errors left // it will return LJE_NOERROR. LJ_ERROR _stdcall GetStreamError(LJ_HANDLE Handle); // This function allows you to quickly determine if there is a stream error on a particular device. It only applies when // stream is running. This is especially useful if you are using a StreamCallback function, which will pass -1 in as scansavailable // if there is an error. // Useful functions: // Some config functions require IP address in a double instead of a string. Here are some helpful functions: LJ_ERROR _stdcall DoubleToStringAddress(double Number, char *pString, long HexDot); // Takes the given IP address in number notation (32 bit), and puts it into the String. String should be // preallocated to at least 16 bytes (255.255.255.255\0). LJ_ERROR _stdcall StringToDoubleAddress(const char *pString, double *pNumber, long HexDot); // Does the opposite, takes an IP address in dot notation and puts it into the given double. long _stdcall StringToConstant(const char *pString); // Converts the given string to the appropriate constant. Used internally by the S functions, but could be useful if // you wanted to use the GetFirst/Next functions and couldn't use this header. Then you could do a comparison on the // returned values: // // if (IOType == StringToConstant("LJ_ioGET_AIN")) // // This function returns LJ_INVALID_CONSTANT if an invalid constant. void _stdcall ErrorToString(LJ_ERROR ErrorCode, char *pString); // Returns a string describing the given error code or an empty string if not found. pString must be at least 256 chars in length. double _stdcall GetDriverVersion(void); // Returns the version number of this driver, the resultant number should match the number at the top of this header file. unsigned long _stdcall GetThreadID(void); // Returns the ID of the current thread. LJ_ERROR _stdcall TCVoltsToTemp( long TCType, double TCVolts, double CJTempK, double *pTCTempK); // Utility function to convert voltage readings from thermocouples to temperatures. Use the LJ_tt constants // to specify a thermocouple type. Types B, E, J, K, N, R, S and T are supported. TC voltes is the // measured voltage. CJTempK is the cold junction temperature in kelvin and the output is placed into pTCTempK. // ************************************************** // Constants // ************************************************** // Device types: const long LJ_dtUE9 = 9; const long LJ_dtU3 = 3; const long LJ_dtU6 = 6; const long LJ_dtSMB = 1000; // Connection types: const long LJ_ctUSB = 1; // UE9 + U3 + U6 const long LJ_ctETHERNET = 2; // UE9 only const long LJ_ctETHERNET_MB = 3; // Modbus over Ethernet. UE9 only. const long LJ_ctETHERNET_DATA_ONLY = 4; // Opens data port but not stream port. UE9 only. // Raw connection types are used to open a device but not communicate with it // should only be used if the normal connection types fail and for testing. // If a device is opened with the raw connection types, only LJ_ioRAW_OUT // and LJ_ioRAW_IN io types should be used. const long LJ_ctUSB_RAW = 101; // UE9 + U3 + U6 const long LJ_ctETHERNET_RAW = 102; // UE9 only // IO types: const long LJ_ioGET_AIN = 10; // UE9 + U3 + U6. This is single ended version. const long LJ_ioGET_AIN_DIFF = 15; // U3/U6 only. Put negative channel in x1. If 32 is passed as x1, Vref will be added to the result. const long LJ_ioGET_AIN_ADVANCED = 16; // For testing purposes. const long LJ_ioPUT_AIN_RANGE = 2000; // UE9 + U6 const long LJ_ioGET_AIN_RANGE = 2001; // UE9 only // Sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15. const long LJ_ioPUT_ANALOG_ENABLE_BIT = 2013; // U3 only const long LJ_ioGET_ANALOG_ENABLE_BIT = 2014; // U3 only // Sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting // bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double // for the value. The first bit of the int that the double represents will be the setting // for the pin number sent into the channel variable. const long LJ_ioPUT_ANALOG_ENABLE_PORT = 2015; // U3 only const long LJ_ioGET_ANALOG_ENABLE_PORT = 2016; // U3 only const long LJ_ioPUT_DAC = 20; // UE9 + U3 + U6 const long LJ_ioPUT_DAC_ENABLE = 2002; // UE9 + U3 (U3 on Channel 1 only) const long LJ_ioGET_DAC_ENABLE = 2003; // UE9 + U3 (U3 on Channel 1 only) const long LJ_ioGET_DIGITAL_BIT = 30; // UE9 + U3 + U6. Changes direction of bit to input as well. const long LJ_ioGET_DIGITAL_BIT_DIR = 31; // UE9 + U3 + U6 const long LJ_ioGET_DIGITAL_BIT_STATE = 32; // UE9 + U3 + U6. Does not change direction of bit, allowing readback of output. // Channel is starting bit #, x1 is number of bits to read. const long LJ_ioGET_DIGITAL_PORT = 35; // UE9 + U3 + U6 // changes direction of bits to input as well. const long LJ_ioGET_DIGITAL_PORT_DIR = 36; // UE9 + U3 + U6 const long LJ_ioGET_DIGITAL_PORT_STATE = 37; //UE9 + U3 + U6 // does not change direction of bits, allowing readback of output. // Digital put commands will set the specified digital line(s) to output. const long LJ_ioPUT_DIGITAL_BIT = 40; // UE9 + U3 + U6 // Channel is starting bit #, value is output value, x1 is bits to write. const long LJ_ioPUT_DIGITAL_PORT = 45; // UE9 + U3 + U6 // Used to create a pause between two events in a U3 low-level feedback // command. For example, to create a 100 ms positive pulse on FIO0, add a // request to set FIO0 high, add a request for a wait of 100000, add a // request to set FIO0 low, then Go. Channel is ignored. Value is // microseconds to wait and should range from 0 to 8388480. The actual // resolution of the wait is 128 microseconds. On U3 hardware version // 1.20 the resolution and delay times are doubled. const long LJ_ioPUT_WAIT = 70; // U3 + U6 // Counter. Input only. const long LJ_ioGET_COUNTER = 50; // UE9 + U3 + U6 const long LJ_ioPUT_COUNTER_ENABLE = 2008; // UE9 + U3 + U6 const long LJ_ioGET_COUNTER_ENABLE = 2009; // UE9 + U3 + U6 // This will cause the designated counter to reset. If you want to reset the counter with // every read, you have to use this command every time. const long LJ_ioPUT_COUNTER_RESET = 2012; // UE9 + U3 + U6 // On UE9: timer only used for input. Output Timers don't use these. Only Channel used. // On U3/U6: Channel used (0 or 1). const long LJ_ioGET_TIMER = 60; // UE9 + U3 + U6 const long LJ_ioPUT_TIMER_VALUE = 2006; // UE9 + U3 + U6. Value gets new value. const long LJ_ioPUT_TIMER_MODE = 2004; // UE9 + U3 + U6. On both Value gets new mode. const long LJ_ioGET_TIMER_MODE = 2005; // UE9 + U3 + U6 // IOType for use with SHT sensor. For LJ_ioSHT_GET_READING, a channel of LJ_chSHT_TEMP (5000) will // read temperature, and LJ_chSHT_RH (5001) will read humidity. const long LJ_ioSHT_GET_READING = 500; // UE9 + U3 + U6 // Uses settings from LJ_chSPI special channels (set with LJ_ioPUT_CONFIG) to communcaite with // something using an SPI interface. The value parameter is the number of bytes to transfer // and x1 is the address of the buffer. The data from the buffer will be sent, then overwritten // with the data read. The channel parameter is ignored. const long LJ_ioSPI_COMMUNICATION = 503; // UE9 + U3 + U6 const long LJ_ioI2C_COMMUNICATION = 504; // UE9 + U3 + U6 const long LJ_ioASYNCH_COMMUNICATION = 505; // UE9 + U3 + U6 const long LJ_ioTDAC_COMMUNICATION = 506; // UE9 + U3 + U6 // Sets the original configuration. // On U3: This means sending the following to the ConfigIO and TimerClockConfig low level // functions. // // ConfigIO // Byte # // 6 WriteMask 15 Write all parameters. // 8 TimerCounterConfig 0 No timers/counters. Offset=0. // 9 DAC1Enable 0 DAC1 disabled. // 10 FIOAnalog 0 FIO all digital. // 11 EIOAnalog 0 EIO all digital. // // // TimerClockConfig // Byte # // 8 TimerClockConfig 130 Set clock to 48 MHz. (24 MHz for U3 hardware version 1.20 or less) // 9 TimerClockDivisor 0 Divisor = 0. // // On UE9/U6: This means disabling all timers and counters, setting the TimerClockConfig to // default (750 kHZ for UE9, 48 MHz for U6) and the offset to 0 (U6). // const long LJ_ioPIN_CONFIGURATION_RESET = 2017; // UE9 + U3 + U6 // The raw in/out are unusual, channel number corresponds to the particular comm port, which // depends on the device. For example, on the UE9, 0 is main comm port, and 1 is the streaming comm. // Make sure and pass a porter to a char buffer in x1, and the number of bytes desired in value. A call // to GetResult will return the number of bytes actually read/written. The max you can send out in one call // is 512 bytes to the UE9 and 16384 bytes to the U3. const long LJ_ioRAW_OUT = 100; // UE9 + U3 + U6 const long LJ_ioRAW_IN = 101; // UE9 + U3 + U6 const long LJ_ioRAWMB_OUT = 104; // UE9 Only. Used with LJ_ctETHERNET_MB to send raw modbus commands to the modbus TCP/IP Socket. const long LJ_ioRAWMB_IN = 105; // UE9 only. Used with LJ_ctETHERNET_MB to receive raw modbus responses from the modbus TCP/IP Socket. // Sets the default power up settings based on the current settings of the device AS THIS DLL KNOWS. This last part // basically means that you should set all parameters directly through this driver before calling this. This writes // to flash which has a limited lifetime, so do not do this too often. Rated endurance is 20,000 writes. const long LJ_ioSET_DEFAULTS = 103; // U3 + U6 // Requests to create the list of channels to stream. Usually you will use the CLEAR_STREAM_CHANNELS request first, which // will clear any existing channels, then use ADD_STREAM_CHANNEL multiple times to add your desired channels. Note that // you can do CLEAR, and then all your ADDs in a single Go() as long as you add the requests in order. const long LJ_ioADD_STREAM_CHANNEL = 200; // UE9 + U3 + U6 // Put negative channel in x1. If 32 is passed as x1, Vref will be added to the result. const long LJ_ioADD_STREAM_CHANNEL_DIFF = 206; // U3 + U6 const long LJ_ioCLEAR_STREAM_CHANNELS = 201; // UE9 + U3 + U6 const long LJ_ioSTART_STREAM = 202; // UE9 + U3 + U6 const long LJ_ioSTOP_STREAM = 203; // UE9 + U3 + U6 const long LJ_ioADD_STREAM_DAC = 207; //UE9 only // Get stream data has several options. If you just want to get a single channel's data (if streaming multiple channels), you // can pass in the desired channel #, then the number of data points desired in Value, and a pointer to an array to put the // data into as X1. This array needs to be an array of doubles. Therefore, the array needs to be 8 * number of // requested data points in byte length. What is returned depends on the StreamWaitMode. If None, this function will only return // data available at the time of the call. You therefore must call GetResult() for this function to retrieve the actually number // of points retreived. If Pump or Sleep, it will return only when the appropriate number of points have been read or no // new points arrive within 100ms. Since there is this timeout, you still need to use GetResult() to determine if the timeout // occured. If AllOrNone, you again need to check GetResult. // // You can also retreive the entire scan by passing LJ_chALL_CHANNELS. In this case, the Value determines the number of SCANS // returned, and therefore, the array must be 8 * number of scans requested * number of channels in each scan. Likewise // GetResult() will return the number of scans, not the number of data points returned. // // Note: data is stored interleaved across all streaming channels. In other words, if you are streaming two channels, 0 and 1, // and you request LJ_chALL_CHANNELS, you will get, Channel0, Channel1, Channel0, Channel1, etc. Once you have requested the // data, any data returned is removed from the internal buffer, and the next request will give new data. // // Note: if reading the data channel by channel and not using LJ_chALL_CHANNELS, the data is not removed from the internal buffer // until the data from the last channel in the scan is requested. This means that if you are streaming three channels, 0, 1 and 2, // and you request data from channel 0, then channel 1, then channel 0 again, the request for channel 0 the second time will // return the exact same data. Also note, that the amount of data that will be returned for each channel request will be // the same until you've read the last channel in the scan, at which point your next block may be a different size. // // Note: although more convenient, requesting individual channels is slightly slower then using LJ_chALL_CHANNELS. Since you // are probably going to have to split the data out anyway, we have saved you the trouble with this option. // // Note: if you are only scanning one channel, the Channel parameter is ignored. const long LJ_ioGET_STREAM_DATA = 204; // UE9 + U3 + U6 // Since this driver has to start a thread to poll the hardware in stream mode, we give you the option of having this thread // call a user defined function after a block of data has been read. To use, pass a pointer to the following function type as // Channel. Pass 0 to turn this feature off. X1 is a user definable value that is passed when the callback function is called. // Value is the number of scans before the callback occurs. If 0, then the default is used, which varies depending on the // device and scan rate but typically results in the callback being called about every 10ms. /* example: void StreamCallback(long ScansAvailable, long UserValue) { ... do stuff when a callback occurs (retrieve data for example) } ... tStreamCallback pCallback = StreamCallback; AddRequest(Handle,LJ_ioSET_STREAM_CALLBACK,(long)pCallback,0,0,0); ... */ // NOTE: the callback function is called from a secondary worker thread that has no message pump. Do not directly update any // windows controls from your callback as there is no message pump to do so. On the same note, the driver stream buffer is locked // during the callback function. This means that while your callback function is running, you cannot do a GetStreamData or any // other stream function from a DIFFERENT thread. You can of course do getstreamdata from the callback function. You don't really // have to worry about this much as any other thread trying to do GetStreamData or other function will simply stall until your // callback is complete and the lock released. Where you will run into trouble is if your callback function waits on another thread // that is trying to do a stream function. Note this applies on a device by device basis. typedef void (*tStreamCallback)(long ScansAvailable, long UserValue); const long LJ_ioSET_STREAM_CALLBACK = 205; // UE9 + U3 + U6 const long LJ_ioSET_STREAM_CALLBACK_PTR = 260; // UE9 + U3 + U6. This is for 64-bit compatibility. The tStreamCallback function is passed as X1 and channel is the User Variable. // Channel = 0 buzz for a count, Channel = 1 buzz continuous. // Value is the Period. // X1 is the toggle count when channel = 0. const long LJ_ioBUZZER = 300; // U3 only // There are a number of things that happen asynchronously inside the UD driver and so don't directly associate with a Add, Go, or // Get function. To allow the UD to tell your code when these events occur, you can pass it a callback function that will // be called whenever this occurs. For an example of how to use the callback, look at the StreamCallback above. Like the // streamcallback, the function may be called from any thread, maybe one with a message pump, maybe not, so you should make // your function fast and don't do anything with windows or on screen controls. typedef void (*tEventCallback)(long EventCode, long Data1, long Data2, long Data3, long UserValue); // Pass pointer to function as Channel, and userdata as x1. Value not used, but should be set to 0 for forward // compatibility. If more events are required with future LabJacks, we may use this to allow you to specify which // events you wish to receive notifcation of and 0 will mean All. const long LJ_ioSET_EVENT_CALLBACK = 400; // UE9 + U3 + U6 // These are the possible EventCodes that will be passed: const long LJ_ecDISCONNECT = 1; // Called when the device is unplugged from USB. No Data is passed. const long LJ_ecRECONNECT = 2; // Called when the device is reconnected to USB. No Data is passed. const long LJ_ecSTREAMERROR = 4; // Called when a stream error occurs. Data1 is errorcode, Data2 and Data3 are not used. // Future events will be power of 2. // Config iotypes: const long LJ_ioPUT_CONFIG = 1000; // UE9 + U3 + U6 const long LJ_ioGET_CONFIG = 1001; // UE9 + U3 + U6 // Channel numbers used for CONFIG types: const long LJ_chLOCALID = 0; // UE9 + U3 + U6 const long LJ_chHARDWARE_VERSION = 10; // UE9 + U3 + U6 (Read Only) const long LJ_chSERIAL_NUMBER = 12; // UE9 + U3 + U6 (Read Only) const long LJ_chFIRMWARE_VERSION = 11; // UE9 + U3 + U6 (Read Only) const long LJ_chBOOTLOADER_VERSION = 15; // UE9 + U3 + U6 (Read Only) const long LJ_chPRODUCTID = 8; // UE9 + U3 + U6 (Read Only) // UE9 specific: const long LJ_chCOMM_POWER_LEVEL = 1; // UE9 const long LJ_chIP_ADDRESS = 2; // UE9 const long LJ_chGATEWAY = 3; // UE9 const long LJ_chSUBNET = 4; // UE9 const long LJ_chPORTA = 5; // UE9 const long LJ_chPORTB = 6; // UE9 const long LJ_chDHCP = 7; // UE9 const long LJ_chMACADDRESS = 9; // UE9 const long LJ_chCOMM_FIRMWARE_VERSION = 11; // UE9 const long LJ_chCONTROL_POWER_LEVEL = 13; // UE9 const long LJ_chCONTROL_FIRMWARE_VERSION = 14; // UE9 (Read Only) const long LJ_chCONTROL_BOOTLOADER_VERSION = 15; // UE9 (Read Only) const long LJ_chCONTROL_RESET_SOURCE = 16; // UE9 (Read Only) const long LJ_chUE9_PRO = 19; // UE9 (Read Only) const long LJ_chLED_STATE = 17; // U3 + U6. Sets the state of the LED. Value = LED state. const long LJ_chSDA_SCL = 18; // U3 + U6. Enable/disable SDA/SCL as digital I/O. const long LJ_chU3HV = 22; // U3 only (Read Only). Value will be 1 for a U3-HV and 0 for a U3-LV or a U3 with hardware version < 1.30. const long LJ_chU6_PRO = 23; // U6 only. // Driver related: // Number of milliseconds that the driver will wait for communication to complete. const long LJ_chCOMMUNICATION_TIMEOUT = 20; const long LJ_chSTREAM_COMMUNICATION_TIMEOUT = 21; // Used to access calibration and user data. The address of an array is passed in as x1. // For the UE9, a 1024-element buffer of bytes is passed for user data and a 128-element // buffer of doubles is passed for cal constants. // For the U3/U3-LV, a 256-element buffer of bytes is passed for user data and a 12-element // buffer of doubles is passed for cal constants. // For the U3-HV, a 256-element buffer of bytes is passed for user data and a 20-element // buffer of doubles is passed for cal constants. // For the U6, a 256-element buffer of bytes is passed for user data and a 64-element // buffer of doubles is passed for cal constants. // The layout of cal constants are defined in the users guide for each device. // When the LJ_chCAL_CONSTANTS special channel is used with PUT_CONFIG, a // special value (0x4C6C) must be passed in to the Value parameter. This makes it // more difficult to accidently erase the cal constants. In all other cases the Value // parameter is ignored. const long LJ_chCAL_CONSTANTS = 400; // UE9 + U3 + U6 const long LJ_chUSER_MEM = 402; // UE9 + U3 + U6 // Used to write and read the USB descriptor strings. This is generally for OEMs // who wish to change the strings. // Pass the address of an array in x1. Value parameter is ignored. // The array should be 128 elements of bytes. The first 64 bytes are for the // iManufacturer string, and the 2nd 64 bytes are for the iProduct string. // The first byte of each 64 byte block (bytes 0 and 64) contains the number // of bytes in the string. The second byte (bytes 1 and 65) is the USB spec // value for a string descriptor (0x03). Bytes 2-63 and 66-127 contain unicode // encoded strings (up to 31 characters each). const long LJ_chUSB_STRINGS = 404; // U3 + U6 // Timer/counter related: const long LJ_chNUMBER_TIMERS_ENABLED = 1000; // UE9 + U3 + U6 const long LJ_chTIMER_CLOCK_BASE = 1001; // UE9 + U3 + U6 const long LJ_chTIMER_CLOCK_DIVISOR = 1002; // UE9 + U3 + U6 const long LJ_chTIMER_COUNTER_PIN_OFFSET = 1003; // U3 + U6 // AIn related: const long LJ_chAIN_RESOLUTION = 2000; // UE9 + U3 + U6 const long LJ_chAIN_SETTLING_TIME = 2001; // UE9 + U3 + U6 const long LJ_chAIN_BINARY = 2002; // UE9 + U3 + U6 // DAC related: const long LJ_chDAC_BINARY = 3000; // UE9 + U3 // SHT related: // LJ_chSHT_TEMP and LJ_chSHT_RH are used with LJ_ioSHT_GET_READING to read those values. // The LJ_chSHT_DATA_CHANNEL and LJ_chSHT_SCK_CHANNEL constants use the passed value // to set the appropriate channel for the data and SCK lines for the SHT sensor. // Default digital channels are FIO0 for the data channel and FIO1 for the clock channel. const long LJ_chSHT_TEMP = 5000; // UE9 + U3 + U6 const long LJ_chSHT_RH = 5001; // UE9 + U3 + U6 const long LJ_chSHT_DATA_CHANNEL = 5002; // UE9 + U3 + U6. Default is FIO0 const long LJ_chSHT_CLOCK_CHANNEL = 5003; // UE9 + U3 + U6. Default is FIO1 // SPI related: const long LJ_chSPI_AUTO_CS = 5100; // UE9 + U3 + U6 const long LJ_chSPI_DISABLE_DIR_CONFIG = 5101; // UE9 + U3 + U6 const long LJ_chSPI_MODE = 5102; // UE9 + U3 + U6 const long LJ_chSPI_CLOCK_FACTOR = 5103; // UE9 + U3 + U6 const long LJ_chSPI_MOSI_PIN_NUM = 5104; // UE9 + U3 + U6 const long LJ_chSPI_MISO_PIN_NUM = 5105; // UE9 + U3 + U6 const long LJ_chSPI_CLK_PIN_NUM = 5106; // UE9 + U3 + U6 const long LJ_chSPI_CS_PIN_NUM = 5107; // UE9 + U3 + U6 // I2C related: // Used with LJ_ioPUT_CONFIG const long LJ_chI2C_ADDRESS_BYTE = 5108; // UE9 + U3 + U6 const long LJ_chI2C_SCL_PIN_NUM = 5109; // UE9 + U3 + U6 const long LJ_chI2C_SDA_PIN_NUM = 5110; // UE9 + U3 + U6 const long LJ_chI2C_OPTIONS = 5111; // UE9 + U3 + U6 const long LJ_chI2C_SPEED_ADJUST = 5112; // UE9 + U3 + U6 // Used with LJ_ioI2C_COMMUNICATION: const long LJ_chI2C_READ = 5113; // UE9 + U3 + U6 const long LJ_chI2C_WRITE = 5114; // UE9 + U3 + U6 const long LJ_chI2C_GET_ACKS = 5115; // UE9 + U3 + U6 const long LJ_chI2C_WRITE_READ = 5130; // UE9 + U3 + U6 // ASYNCH related: // Used with LJ_ioASYNCH_COMMUNICATION const long LJ_chASYNCH_RX = 5117; // UE9 + U3 + U6 const long LJ_chASYNCH_TX = 5118; // UE9 + U3 + U6 const long LJ_chASYNCH_FLUSH = 5128; // UE9 + U3 + U6 const long LJ_chASYNCH_ENABLE = 5129; // UE9 + U3 + U6 // Used with LJ_ioPUT_CONFIG and LJ_ioGET_CONFIG const long LJ_chASYNCH_BAUDFACTOR = 5127; // UE9 + U3 + U6 // LJ TickDAC related: const long LJ_chTDAC_SCL_PIN_NUM = 5119; // UE9 + U3 + U6: Used with LJ_ioPUT_CONFIG. // Used with LJ_ioTDAC_COMMUNICATION const long LJ_chTDAC_SERIAL_NUMBER = 5120; // UE9 + U3 + U6: Read only. const long LJ_chTDAC_READ_USER_MEM = 5121; // UE9 + U3 + U6 const long LJ_chTDAC_WRITE_USER_MEM = 5122; // UE9 + U3 + U6 const long LJ_chTDAC_READ_CAL_CONSTANTS = 5123; // UE9 + U3 + U6 const long LJ_chTDAC_WRITE_CAL_CONSTANTS = 5124; // UE9 + U3 + U6 const long LJ_chTDAC_UPDATE_DACA = 5125; // UE9 + U3 + U6 const long LJ_chTDAC_UPDATE_DACB = 5126; // UE9 + U3 + U6 // Stream related. Note: Putting to any of these values will stop any running streams. const long LJ_chSTREAM_SCAN_FREQUENCY = 4000; // UE9 + U3 + U6 const long LJ_chSTREAM_BUFFER_SIZE = 4001; const long LJ_chSTREAM_CLOCK_OUTPUT = 4002; // UE9 only const long LJ_chSTREAM_EXTERNAL_TRIGGER = 4003; // UE9 only const long LJ_chSTREAM_WAIT_MODE = 4004; const long LJ_chSTREAM_DISABLE_AUTORECOVERY = 4005; // U3 + U6 const long LJ_chSTREAM_SAMPLES_PER_PACKET = 4108; // UE9 + U3 + U6. Read only for UE9. const long LJ_chSTREAM_READS_PER_SECOND = 4109; const long LJ_chAIN_STREAM_SETTLING_TIME = 4110; // U6 only // Read only stream related const long LJ_chSTREAM_BACKLOG_COMM = 4105; // UE9 + U3 + U6 const long LJ_chSTREAM_BACKLOG_CONTROL = 4106; // UE9 only const long LJ_chSTREAM_BACKLOG_UD = 4107; // Special channel numbers const long LJ_chALL_CHANNELS = -1; const long LJ_INVALID_CONSTANT = -999; //Thermocouple Type constants. const long LJ_ttB = 6001; const long LJ_ttE = 6002; const long LJ_ttJ = 6003; const long LJ_ttK = 6004; const long LJ_ttN = 6005; const long LJ_ttR = 6006; const long LJ_ttS = 6007; const long LJ_ttT = 6008; // Other constants: // Ranges (not all are supported by all devices): const long LJ_rgBIP20V = 1; // -20V to +20V const long LJ_rgBIP10V = 2; // -10V to +10V const long LJ_rgBIP5V = 3; // -5V to +5V const long LJ_rgBIP4V = 4; // -4V to +4V const long LJ_rgBIP2P5V = 5; // -2.5V to +2.5V const long LJ_rgBIP2V = 6; // -2V to +2V const long LJ_rgBIP1P25V = 7; // -1.25V to +1.25V const long LJ_rgBIP1V = 8; // -1V to +1V const long LJ_rgBIPP625V = 9; // -0.625V to +0.625V const long LJ_rgBIPP1V = 10; // -0.1V to +0.1V const long LJ_rgBIPP01V = 11; // -0.01V to +0.01V const long LJ_rgUNI20V = 101; // 0V to +20V const long LJ_rgUNI10V = 102; // 0V to +10V const long LJ_rgUNI5V = 103; // 0V to +5V const long LJ_rgUNI4V = 104; // 0V to +4V const long LJ_rgUNI2P5V = 105; // 0V to +2.5V const long LJ_rgUNI2V = 106; // 0V to +2V const long LJ_rgUNI1P25V = 107; // 0V to +1.25V const long LJ_rgUNI1V = 108; // 0V to +1V const long LJ_rgUNIP625V = 109; // 0V to +0.625V const long LJ_rgUNIP5V = 110; // 0V to +0.500V const long LJ_rgUNIP25V = 112; // 0V to +0.25V const long LJ_rgUNIP3125V = 111; // 0V to +0.3125V const long LJ_rgUNIP025V = 113; // 0V to +0.025V const long LJ_rgUNIP0025V = 114; // 0V to +0.0025V // Timer modes: const long LJ_tmPWM16 = 0; // 16 bit PWM const long LJ_tmPWM8 = 1; // 8 bit PWM const long LJ_tmRISINGEDGES32 = 2; // 32-bit rising to rising edge measurement const long LJ_tmFALLINGEDGES32 = 3; // 32-bit falling to falling edge measurement const long LJ_tmDUTYCYCLE = 4; // Duty cycle measurement const long LJ_tmFIRMCOUNTER = 5; // Firmware based rising edge counter const long LJ_tmFIRMCOUNTERDEBOUNCE = 6; // Firmware counter with debounce const long LJ_tmFREQOUT = 7; // Frequency output const long LJ_tmQUAD = 8; // Quadrature const long LJ_tmTIMERSTOP = 9; // Stops another timer after n pulses const long LJ_tmSYSTIMERLOW = 10; // Read lower 32-bits of system timer const long LJ_tmSYSTIMERHIGH = 11; // Read upper 32-bits of system timer const long LJ_tmRISINGEDGES16 = 12; // 16-bit rising to rising edge measurement const long LJ_tmFALLINGEDGES16 = 13; // 16-bit falling to falling edge measurement const long LJ_tmLINETOLINE = 14; // Line to Line measurement // Timer clocks: const long LJ_tc750KHZ = 0; // UE9: 750 kHz const long LJ_tcSYS = 1; // UE9 + U3 + U6: System clock const long LJ_tc2MHZ = 10; // U3: Hardware Version 1.20 or lower const long LJ_tc6MHZ = 11; // U3: Hardware Version 1.20 or lower const long LJ_tc24MHZ = 12; // U3: Hardware Version 1.20 or lower const long LJ_tc500KHZ_DIV = 13; // U3: Hardware Version 1.20 or lower const long LJ_tc2MHZ_DIV = 14; // U3: Hardware Version 1.20 or lower const long LJ_tc6MHZ_DIV = 15; // U3: Hardware Version 1.20 or lower const long LJ_tc24MHZ_DIV = 16; // U3: Hardware Version 1.20 or lower const long LJ_tc4MHZ = 20; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc12MHZ = 21; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc48MHZ = 22; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc1MHZ_DIV = 23; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc4MHZ_DIV = 24; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc12MHZ_DIV = 25; // U3: Hardware Version 1.21 or higher, + U6 const long LJ_tc48MHZ_DIV = 26; // U3: Hardware Version 1.21 or higher, + U6 // Stream wait modes: const long LJ_swNONE = 1; // No wait, return whatever is available. const long LJ_swALL_OR_NONE = 2; // No wait, but if all points requested aren't available, return none. const long LJ_swPUMP = 11; // Wait and pump the message pump. Preferred when called from primary thread (if you don't know // if you are in the primary thread of your app then you probably are. Do not use in worker // secondary threads (i.e. ones without a message pump). const long LJ_swSLEEP = 12; // Wait by sleeping (don't do this in the primary thread of your app, or it will temporarily // hang). This is usually used in worker secondary threads. // BETA CONSTANTS: // Please note that specific usage of these constants and their values might change. // SWDT: // Sets parameters used to control the software watchdog option. The device is only // communicated with and updated when LJ_ioSWDT_CONFIG is used with LJ_chSWDT_ENABLE // or LJ_chSWDT_DISABLE. Thus, to change a value, you must use LJ_io_PUT_CONFIG // with the appropriate channel constant so set the value inside the driver, then call // LJ_ioSWDT_CONFIG to enable that change. const long LJ_ioSWDT_CONFIG = 507; // UE9 + U3 + U6: Use with LJ_chSWDT_ENABLE or LJ_chSWDT_DISABLE. const long LJ_ioSWDT_STROKE = 508; // UE9 only: Used when SWDT_STRICT_ENABLE is turned on to renew the watchdog. const long LJ_chSWDT_ENABLE = 5200; // UE9 + U3 + U6: Used with LJ_ioSWDT_CONFIG to enable watchdog. Value paramter is number of seconds to trigger. const long LJ_chSWDT_DISABLE = 5201; // UE9 + U3 + U6: Used with LJ_ioSWDT_CONFIG to disable watchdog. // Used with LJ_io_PUT_CONFIG const long LJ_chSWDT_RESET_DEVICE = 5202; // U3 + U6: Reset U3 on watchdog reset. Write only. const long LJ_chSWDT_RESET_COMM = 5203; // UE9 only: Reset Comm on watchdog reset. Write only. const long LJ_chSWDT_RESET_CONTROL = 5204; // UE9 only: Reset Control on watchdog trigger. Write only. const long LJ_chSWDT_UPDATE_DIOA = 5205; // UE9 + U3 + U6: Update DIO0 settings after reset. Write only. const long LJ_chSWDT_UPDATE_DIOB = 5206; // UE9 only: Update DIO1 settings after reset. Write only. const long LJ_chSWDT_DIOA_CHANNEL = 5207; // UE9 + U3 + U6: DIO0 channel to be set after reset. Write only. const long LJ_chSWDT_DIOA_STATE = 5208; // UE9 + U3 + U6: DIO0 state to be set after reset. Write only. const long LJ_chSWDT_DIOB_CHANNEL = 5209; // UE9: DIO1 channel to be set after reset. Write only. const long LJ_chSWDT_DIOB_STATE = 5210; // UE9: DIO1 state to be set after reset. Write only. const long LJ_chSWDT_UPDATE_DAC0 = 5211; // UE9 only: Update DAC0 settings after reset. Write only. const long LJ_chSWDT_UPDATE_DAC1 = 5212; // UE9 only: Update DAC1 settings after reset. Write only. const long LJ_chSWDT_DAC0 = 5213; // UE9 only: Voltage to set DAC0 at on watchdog reset. Write only. const long LJ_chSWDT_DAC1 = 5214; // UE9 only: Voltage to set DAC1 at on watchdog reset. Write only. const long LJ_chSWDT_DAC_ENABLE = 5215; // UE9 only: Enable DACs on watchdog reset. Default is true. Both DACs are enabled or disabled togeather. Write only. const long LJ_chSWDT_STRICT_ENABLE = 5216; // UE9 only: Watchdog will only renew with LJ_ioSWDT_STROKE command. const long LJ_chSWDT_INITIAL_ROLL_TIME = 5217; // UE9 only: Watchdog timer for the first cycle when powered on, after watchdog triggers a reset the normal value is used. Set to 0 to disable. // END BETA CONSTANTS // Error codes: These will always be in the range of -1000 to 3999 for labView compatibility (+6000). const LJ_ERROR LJE_NOERROR = 0; const LJ_ERROR LJE_COMMAND_LIST_ERROR = 1; const LJ_ERROR LJE_INVALID_CHANNEL_NUMBER = 2; // Cccurs when a channel that doesn't exist is specified (i.e. DAC #2 on a UE9), or data from streaming is requested on a channel that isn't streaming. const LJ_ERROR LJE_INVALID_RAW_INOUT_PARAMETER = 3; const LJ_ERROR LJE_UNABLE_TO_START_STREAM = 4; const LJ_ERROR LJE_UNABLE_TO_STOP_STREAM = 5; const LJ_ERROR LJE_NOTHING_TO_STREAM = 6; const LJ_ERROR LJE_UNABLE_TO_CONFIG_STREAM = 7; const LJ_ERROR LJE_BUFFER_OVERRUN = 8; // Cccurs when stream buffer overruns (this is the driver buffer not the hardware buffer). Stream is stopped. const LJ_ERROR LJE_STREAM_NOT_RUNNING = 9; const LJ_ERROR LJE_INVALID_PARAMETER = 10; const LJ_ERROR LJE_INVALID_STREAM_FREQUENCY = 11; const LJ_ERROR LJE_INVALID_AIN_RANGE = 12; const LJ_ERROR LJE_STREAM_CHECKSUM_ERROR = 13; // Occurs when a stream packet fails checksum. Stream is stopped. const LJ_ERROR LJE_STREAM_COMMAND_ERROR = 14; // Occurs when a stream packet has invalid command values. Stream is stopped. const LJ_ERROR LJE_STREAM_ORDER_ERROR = 15; // Occurs when a stream packet is received out of order (typically one is missing). Stream is stopped. const LJ_ERROR LJE_AD_PIN_CONFIGURATION_ERROR = 16; // Occurs when an analog or digital request was made on a pin that isn't configured for that type of request. const LJ_ERROR LJE_REQUEST_NOT_PROCESSED = 17; // When a LJE_AD_PIN_CONFIGURATION_ERROR occurs, all other IO requests after the request that caused the error won't be processed. Those requests will return this error. // U3 & U6 Specific Errors const LJ_ERROR LJE_SCRATCH_ERROR = 19; const LJ_ERROR LJE_DATA_BUFFER_OVERFLOW = 20; const LJ_ERROR LJE_ADC0_BUFFER_OVERFLOW = 21; const LJ_ERROR LJE_FUNCTION_INVALID = 22; const LJ_ERROR LJE_SWDT_TIME_INVALID = 23; const LJ_ERROR LJE_FLASH_ERROR = 24; const LJ_ERROR LJE_STREAM_IS_ACTIVE = 25; const LJ_ERROR LJE_STREAM_TABLE_INVALID = 26; const LJ_ERROR LJE_STREAM_CONFIG_INVALID = 27; const LJ_ERROR LJE_STREAM_BAD_TRIGGER_SOURCE = 28; const LJ_ERROR LJE_STREAM_INVALID_TRIGGER = 30; const LJ_ERROR LJE_STREAM_ADC0_BUFFER_OVERFLOW = 31; const LJ_ERROR LJE_STREAM_SAMPLE_NUM_INVALID = 33; const LJ_ERROR LJE_STREAM_BIPOLAR_GAIN_INVALID = 34; const LJ_ERROR LJE_STREAM_SCAN_RATE_INVALID = 35; const LJ_ERROR LJE_TIMER_INVALID_MODE = 36; const LJ_ERROR LJE_TIMER_QUADRATURE_AB_ERROR = 37; const LJ_ERROR LJE_TIMER_QUAD_PULSE_SEQUENCE = 38; const LJ_ERROR LJE_TIMER_BAD_CLOCK_SOURCE = 39; const LJ_ERROR LJE_TIMER_STREAM_ACTIVE = 40; const LJ_ERROR LJE_TIMER_PWMSTOP_MODULE_ERROR = 41; const LJ_ERROR LJE_TIMER_SEQUENCE_ERROR = 42; const LJ_ERROR LJE_TIMER_SHARING_ERROR = 43; const LJ_ERROR LJE_TIMER_LINE_SEQUENCE_ERROR = 44; const LJ_ERROR LJE_EXT_OSC_NOT_STABLE = 45; const LJ_ERROR LJE_INVALID_POWER_SETTING = 46; const LJ_ERROR LJE_PLL_NOT_LOCKED = 47; const LJ_ERROR LJE_INVALID_PIN = 48; const LJ_ERROR LJE_IOTYPE_SYNCH_ERROR = 49; const LJ_ERROR LJE_INVALID_OFFSET = 50; const LJ_ERROR LJE_FEEDBACK_IOTYPE_NOT_VALID = 51; const LJ_ERROR LJE_CANT_CONFIGURE_PIN_FOR_ANALOG = 67; const LJ_ERROR LJE_CANT_CONFIGURE_PIN_FOR_DIGITAL = 68; const LJ_ERROR LJE_TC_PIN_OFFSET_MUST_BE_4_TO_8 = 70; const LJ_ERROR LJE_INVALID_DIFFERENTIAL_CHANNEL = 71; const LJ_ERROR LJE_DSP_SIGNAL_OUT_OF_RANGE = 72; // Other errors const LJ_ERROR LJE_SHT_CRC = 52; const LJ_ERROR LJE_SHT_MEASREADY = 53; const LJ_ERROR LJE_SHT_ACK = 54; const LJ_ERROR LJE_SHT_SERIAL_RESET = 55; const LJ_ERROR LJE_SHT_COMMUNICATION = 56; const LJ_ERROR LJE_AIN_WHILE_STREAMING = 57; const LJ_ERROR LJE_STREAM_TIMEOUT = 58; const LJ_ERROR LJE_STREAM_CONTROL_BUFFER_OVERFLOW = 59; const LJ_ERROR LJE_STREAM_SCAN_OVERLAP = 60; const LJ_ERROR LJE_FIRMWARE_VERSION_IOTYPE = 61; const LJ_ERROR LJE_FIRMWARE_VERSION_CHANNEL = 62; const LJ_ERROR LJE_FIRMWARE_VERSION_VALUE = 63; const LJ_ERROR LJE_HARDWARE_VERSION_IOTYPE = 64; const LJ_ERROR LJE_HARDWARE_VERSION_CHANNEL = 65; const LJ_ERROR LJE_HARDWARE_VERSION_VALUE = 66; const LJ_ERROR LJE_LJTDAC_ACK_ERROR = 69; const LJ_ERROR LJE_STREAM_INVALID_CONNECTION = 73; const LJ_ERROR LJE_MIN_GROUP_ERROR = 1000; // All errors above this number will stop all requests, below this number are request level errors. const LJ_ERROR LJE_UNKNOWN_ERROR = 1001; // Occurs when an unknown error occurs that is caught, but still unknown. const LJ_ERROR LJE_INVALID_DEVICE_TYPE = 1002; // Occurs when devicetype is not a valid device type. const LJ_ERROR LJE_INVALID_HANDLE = 1003; // Occurs when invalid handle used. const LJ_ERROR LJE_DEVICE_NOT_OPEN = 1004; // Occurs when Open() fails and AppendRead called despite. const LJ_ERROR LJE_NO_DATA_AVAILABLE = 1005; // This is cause when GetResult() called without calling Go/GoOne(), or when GetResult() passed a channel that wasn't read. const LJ_ERROR LJE_NO_MORE_DATA_AVAILABLE = 1006; const LJ_ERROR LJE_LABJACK_NOT_FOUND = 1007; // Occurs when the LabJack is not found at the given id or address. const LJ_ERROR LJE_COMM_FAILURE = 1008; // Occurs when unable to send or receive the correct number of bytes. const LJ_ERROR LJE_CHECKSUM_ERROR = 1009; const LJ_ERROR LJE_DEVICE_ALREADY_OPEN = 1010; // Occurs when LabJack is already open via USB in another program or process. const LJ_ERROR LJE_COMM_TIMEOUT = 1011; const LJ_ERROR LJE_USB_DRIVER_NOT_FOUND = 1012; const LJ_ERROR LJE_INVALID_CONNECTION_TYPE = 1013; const LJ_ERROR LJE_INVALID_MODE = 1014; const LJ_ERROR LJE_DEVICE_NOT_CONNECTED = 1015; // Occurs when a LabJack that was opened is no longer connected to the system. // These errors aren't actually generated by the UD, but could be handy in your code to indicate an event as an error code without // conflicting with LabJack error codes. const LJ_ERROR LJE_DISCONNECT = 2000; const LJ_ERROR LJE_RECONNECT = 2001; // and an area for your own codes. This area won't ever be used for LabJack codes. const LJ_ERROR LJE_MIN_USER_ERROR = 3000; const LJ_ERROR LJE_MAX_USER_ERROR = 3999; // Warning are negative const LJ_ERROR LJE_DEVICE_NOT_CALIBRATED = -1; // Defaults used instead const LJ_ERROR LJE_UNABLE_TO_READ_CALDATA = -2; // Defaults used instead /* Version History: 2.02: ain_binary fixed for non-streaming. Adjusted for new streaming usb firmware (64-byte packets). New streaming errors- stop the stream and error is returned with next GetData. Fixed resolution setting while streaming (was fixed to 12, now follows poll setting). 2.03: Added callback option for streaming. 2.04: Changed warnings to be negative. Renamed POWER_LEVEL to COMM_POWER_LEVEL. 2.05: Updated timer/counter stuff. Added CounterReset, TimerClockDivisor. 2.06: Fixed problem when unplugging USB UE9 and plugging it into a different USB port. Renamed LJ_chCOUNTERTIMER_CLOCK to LJ_chTIMER_CLOCK_CONFIG. 2.08: Fixed two UE9 USB unplug issue. Driver now uses high temp calibration for Control power level zero. Added new timer modes to header. Fixed LJ_tcSYS constant in header. 2.09: New timer constants for new modes. Timer/counter update bits auto-setting updated. put_counter_reset will execute with the next go, not only with the next read. 2.10: Timer/counter update bits auto-setting updated again. Fixed MIO bits as outputs. listall(). Fixed control power level and reset source. Added ioDIGITAL_PORT_IN and ioDIGITAL_PORT_OUT. 2.11: Fixed problem with ListAll when performed without prior opening of devices. 2.12: Added initial raw U3 support. 2.13: Fixed issues with streaming backlog and applying cals to extended channels. 2.14: Fixed issue with U3 raw support. 2.15: Fixed driver issue with stream clock output and stream external triggering. 2.16: Fixed problem with listall after changing local id. 2.17: Fixed issues with streaming backlog and applying cals to extended channels. Fixed problem with usb reset. Added timer mode 6 to header file. 2.18: Fixed issue with rollover on counter/timer. Fixed reset issues. 2.21: UE9 changed to use feedbackalt instead of feedback. Allows for multiple internal channels to be called from same call to feedback. Fixed internal channel numbers 14/128 and 15/136 and extended channels to return proper values. 2.22: Fixed problem with ioGET_TIMER when passed as a string. Added support for make unlimited number of requests for analog input channels for a single call to a go function. 2.23: 2.24: Fixed bug sometimes causing errors when a pointer was passed into the Raw io functions that caused a communication error. 2.25: Improved U3 support. 2.26: Fixed U3 bugs with timer/counter values, DAC rounding and set analog enabled port functions. 2.46: Various U3 fixes and support added. 2.47: Fixed threading issue. 2.48: Added LJ_ioPUT_WAIT. 2.56: Fixed bug with EAIN. 2.57: Added Thermocouple conversion functions. 2.58: Added SWDT functionality for UE9 (BETA). 2.59: Fixed bug causing some U3 timer values to report incorrectly. Added support for OEMs to change USB string descriptors on the U3. 2.60: Added beta support for timer values for U3s with hardware version >= 1.21. 2.61: Fixed bug causing U3 streaming to sometimes hang. 2.62: Added ability to open devices over USB using the serial number. 2.63: Added new stream error codes and fixed bug with opening multiple U3s. 2.64: Fixed bug when streaming with differential channels on U3. 2.65: Improved eAin to work properly with special all special channels. 2.66: LJ_chSTREAM_ENABLE_AUTORECOVER renamed to LJ_chSTREAM_DISABLE_AUTORECOVERY. 2.67: Fixed bug with eTCConfig and eTCValues on U3. 2.68: Added internal function for factory use. 2.69: Added Ethernet support for ListAll() for UE9. 2.70: Added I2C support for U3 and UE9. 2.72: Fixed problem with using trigger mode when streaming. 2.73: Added detection for reads from Timers/Counters that weren't enabled on UE9. 2.74: Fixed bug that sometimes occurs when requesting version numbers. 2.75: Fixed issue with reopening U3 after a device reset. 2.76: Fixed bug with the proper range not always being used when streaming on a UE9. Fixed bug with UE9 Ethernet ListAll() returning wrong values for IP addresses. 2.77: Fixed bug with special channel readings while streaming. Added Asynch support for U3. 2.78: Fixed bug when doing SPI communication with an odd number of bytes. 2.79: LJ_chI2C_WRITE_READ support. 3.00: Added support for U3-HV and U3-LV. 3.01: Fixed bug with U3-HV applying wrong calibration constants when streaming. 3.02: Fixed bugs with U3-HV and U3-LV and a delay with StopStream. 3.03: Added initial support for U6. 3.04: Fixed bug with Asynch communication on U3-HVs and U3-LVs. 3.05: Fixed calibration bug with eAIN on the U3-HV and U3-LV. 3.06: Fixed bug with SWDT functionality for U3. 3.10: Added support for new USB driver that works with 64-bit OS versions. 3.11: Fixed a memory leak when devices were kept open via USB. 3.12: Fixed various U6 bugs. 3.13: Added LJE_DEVICE_ALREADY_OPEN error to occur when another program/process has the LabJack open. 3.14: Various minor bug fixes. 3.15: Added full support for Asynch communication on the U6. 3.16: Fixed bug causing a delay when the LabJackUD driver was unloaded in a program. 3.17: Added support for SWDT settings for initial roll time and strict mode. 3.18: Fixed a bug with negative timer values when using ETCConfig with LJ_tmQUAD on the U3 and U6. Fixed bug causing a delay when stream on U3/U6 was stopped. 3.19: Fixed bug that caused LJ_ioPUT_TIMER_VALUE to corrupt other results when done in the same Go or GoOne call. 3.22: Fixed bug in the U6 and U3 that caused excessive delays when com buffer started to fill. 3.23: Added GetThreadID function. 3.26: Fixed bug with U6 reading channels 200-224 not returning proper values. 3.27: Fixed bug with setting calibration constants for LJTickDAC. 3.28: Fixed bug with U3s reading internal temperature using LJ_ioGET_AIN_DIFF. Added LJ_ctETHERNET_DATA_ONLY support. 3.32: Various bug fixes. 3.38: Added AddRequestPtr, ePutPtr and LJ_ioSET_STREAM_CALLBACK_PTR for better 64-bit compatibility. 3.40: Added LJ_chSTREAM_COMMUNICATION_TIMEOUT support for U3/U6. 3.41: Fixed compatibility for Ptr functions and raw read/write support. 3.42: Fixed error in values of streaming extended channels on U6. 3.43: Fixed bug with eAin high resolution readings on Pro devices. Fixed bug with IC2 and *Ptr functions. 3.44: Changed eAddGoGet() to return LJE_COMMAND_LIST_ERROR if an error is detected. Error arrays are also defaulted to zero. 3.45: Fixed a bug which would sometimes cause a critcal error if the LabJackUD.dll was unloaded after streaming. 3.46: Updated internal reconnect routine to help prevent deadlocks. Fixed a bug when disabling UE9 DACs. Added the ability to set multiple timer values in a single Go/GoOne call for the U6. Updated LJ_chASYNCH_TX's result so the Value is the number of bytes in the RX buffer. Fixed LJ_chCAL_CONSTANTS, LJ_chUSER_MEM, LJ_chUSB_STRINGS and LJ_ioSPI_COMMUNICATION functionality when using Array and Ptr functions. Fixed writing calibration constants, LJ_chCAL_CONSTANTS, for the U3 and U6. Fixed eTCValues U6 bug. */ // Depreciated constants: const long LJ_ioANALOG_INPUT = 10; const long LJ_ioANALOG_OUTPUT = 20; // UE9 + U3 const long LJ_ioDIGITAL_BIT_IN = 30; // UE9 + U3 const long LJ_ioDIGITAL_PORT_IN = 35; // UE9 + U3 const long LJ_ioDIGITAL_BIT_OUT = 40; // UE9 + U3 const long LJ_ioDIGITAL_PORT_OUT = 45; // UE9 + U3 const long LJ_ioCOUNTER = 50; // UE9 + U3 const long LJ_ioTIMER = 60; // UE9 + U3 const long LJ_ioPUT_COUNTER_MODE = 2010; // UE9 const long LJ_ioGET_COUNTER_MODE = 2011; // UE9 const long LJ_ioGET_TIMER_VALUE = 2007; // UE9 const long LJ_ioCYCLE_PORT = 102; // UE9 const long LJ_chTIMER_CLOCK_CONFIG = 1001; // UE9 + U3 const long LJ_ioPUT_CAL_CONSTANTS = 400; const long LJ_ioGET_CAL_CONSTANTS = 401; const long LJ_ioPUT_USER_MEM = 402; const long LJ_ioGET_USER_MEM = 403; const long LJ_ioPUT_USB_STRINGS = 404; const long LJ_ioGET_USB_STRINGS = 405; const long LJ_ioSHT_DATA_CHANNEL = 501; // UE9 + U3 const long LJ_ioSHT_CLOCK_CHANNEL = 502; // UE9 + U3 const long LJ_chI2C_ADDRESS = 5108; // UE9 + U3 const long LJ_chASYNCH_CONFIG = 5116; // UE9 + U3 const long LJ_rgUNIP500V = 110; // 0V to +0.500V const long LJ_ioENABLE_POS_PULLDOWN = 2018; // U6 const long LJ_ioENABLE_NEG_PULLDOWN = 2019; // U6 const long LJ_rgAUTO = 0; const long LJ_chSWDT_UDPATE_DIOA = 5205; #ifdef __cplusplus } // extern C #endif #endif
60,335
C
57.921875
231
0.732195
adegirmenci/HBL-ICEbot/LabJackWidget/LabJackLibs/64bit/LabJackM.h
/** * Name: LabJackM.h * Desc: Header file describing C-style exposed * API functions for the LabJackM Library * Auth: LabJack Corp. **/ #ifndef LAB_JACK_M_HEADER #define LAB_JACK_M_HEADER #define LJM_VERSION 1.0806 // Format: xx.yyzz // xx is the major version (left of the decimal). // yy is the minor version (the two places to the right of the decimal). // zz is the revision version (the two places to the right of the minor // version). /****************************************************************************** * How To Use This Library: * * See the LJM User's Guide: labjack.com/support/ljm/users-guide * * Check out the example files for examples of workflow * * To write/read other Modbus addresses, check out labjack.com/support/modbus * *****************************************************************************/ #define LJM_ERROR_CODE static const int #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 #define LJM_ERROR_RETURN int __stdcall #define LJM_VOID_RETURN void __stdcall #define LJM_ERROR_STRING const char * __stdcall #define LJM_DOUBLE_RETURN double __stdcall #else #define LJM_ERROR_RETURN int #define LJM_VOID_RETURN void #define LJM_ERROR_STRING const char * #define LJM_DOUBLE_RETURN double #endif /************* * Constants * *************/ // Read/Write direction constants: static const int LJM_READ = 0; static const int LJM_WRITE = 1; // Data Types: // These do automatic endianness conversion, if needed by the local machine's // processor. static const int LJM_UINT16 = 0; // C type of unsigned short static const int LJM_UINT32 = 1; // C type of unsigned int static const int LJM_INT32 = 2; // C type of int static const int LJM_FLOAT32 = 3; // C type of float // Advanced users data types: // These do not do any endianness conversion. static const int LJM_BYTE = 99; // Contiguous bytes. If the number of LJM_BYTEs is // odd, the last, (least significant) byte is 0x00. // For example, for 3 LJM_BYTES of values // [0x01, 0x02, 0x03], LJM sends the contiguous byte // array [0x01, 0x02, 0x03, 0x00] static const int LJM_STRING = 98; // Same as LJM_BYTE, but LJM automatically appends // a null-terminator. static const unsigned int LJM_STRING_MAX_SIZE = 49; // Max LJM_STRING size not including the automatic null-terminator // Max LJM_STRING size with the null-terminator enum { LJM_STRING_ALLOCATION_SIZE = 50 }; // LJM_NamesToAddresses uses this when a register name is not found static const int LJM_INVALID_NAME_ADDRESS = -1; enum { LJM_MAX_NAME_SIZE = 256 }; // 18 = 6 * 2 (number of byte chars) + 5 (number of colons) + 1 (null-terminator) enum { LJM_MAC_STRING_SIZE = 18 }; // 16 is INET_ADDRSTRLEN enum { LJM_IPv4_STRING_SIZE = 16 }; static const int LJM_BYTES_PER_REGISTER = 2; // Device types: static const int LJM_dtANY = 0; static const int LJM_dtT7 = 7; static const int LJM_dtDIGIT = 200; // Connection types: static const int LJM_ctANY = 0; static const int LJM_ctUSB = 1; static const int LJM_ctTCP = 2; static const int LJM_ctETHERNET = 3; static const int LJM_ctWIFI = 4; // TCP/Ethernet constants: static const int LJM_NO_IP_ADDRESS = 0; static const int LJM_NO_PORT = 0; static const int LJM_DEFAULT_PORT = 502; // Identifier types: static const char * const LJM_DEMO_MODE = "-2"; static const int LJM_idANY = 0; // LJM_AddressesToMBFB Constants enum { LJM_DEFAULT_FEEDBACK_ALLOCATION_SIZE = 62 }; static const int LJM_USE_DEFAULT_MAXBYTESPERMBFB = 0; // LJM_MBFBComm Constants; static const int LJM_DEFAULT_UNIT_ID = 1; // LJM_ListAll Constants enum { LJM_LIST_ALL_SIZE = 128 }; // Please note that some devices must append 2 bytes to certain packets. // Please check the docs for the device you are using. static const int LJM_MAX_USB_PACKET_NUM_BYTES = 64; static const int LJM_MAX_TCP_PACKET_NUM_BYTES_T7 = 1040; // Deprecated static const int LJM_MAX_ETHERNET_PACKET_NUM_BYTES_T7 = 1040; static const int LJM_MAX_WIFI_PACKET_NUM_BYTES_T7 = 500; // Timeout Constants. Times in milliseconds. static const int LJM_NO_TIMEOUT = 0; static const int LJM_DEFAULT_USB_SEND_RECEIVE_TIMEOUT_MS = 2600; static const int LJM_DEFAULT_ETHERNET_OPEN_TIMEOUT_MS = 1000; static const int LJM_DEFAULT_ETHERNET_SEND_RECEIVE_TIMEOUT_MS = 2600; static const int LJM_DEFAULT_WIFI_OPEN_TIMEOUT_MS = 1000; static const int LJM_DEFAULT_WIFI_SEND_RECEIVE_TIMEOUT_MS = 4000; // Stream Constants static const int LJM_DUMMY_VALUE = -9999; static const int LJM_SCAN_NOT_READ = -8888; static const int LJM_GND = 199; /***************************************************************************** * Return Values * * Success: * * Constant: LJME_NOERROR * * Description: The function executed without error. * * Range: 0 * * * * Warnings: * * Prefix: LJME_ * * Description: Some or all outputs might be valid. * * Range: 200-399 * * * * Modbus Errors: * * Prefix: LJME_MBE * * Description: Errors corresponding to official Modbus errors which are * * returned from the device. * * Note: To find the original Modbus error in base 10, subtract 1200. * * Ranges: 1200-1216 * * * * Library Errors: * * Prefix: LJME_ * * Description: Errors where all outputs are null, invalid, 0, or 9999. * * Range: 1220-1399 * * * * Device Errors: * * Description: Errors returned from the firmware on the device. * * Range: 2000-2999 * * * * User Area: * * Description: Errors defined by users. * * Range: 3900-3999 * * */ // Success LJM_ERROR_CODE LJME_NOERROR = 0; // Warnings: LJM_ERROR_CODE LJME_WARNINGS_BEGIN = 200; LJM_ERROR_CODE LJME_WARNINGS_END = 399; LJM_ERROR_CODE LJME_FRAMES_OMITTED_DUE_TO_PACKET_SIZE = 201; // Functions: // LJM_AddressesToMBFB: // Problem: This indicates that the length (in bytes) of the Feedback // command being created was greater than the value passed as // MaxBytesPerMBFB. As a result, the command returned is a valid // Feedback command that includes some of the frames originally // specified, but not all of them. You can check the NumFrames // pointer to find out how many frames were included. // Solutions: // 1) Pass a larger value for MaxBytesPerMBFB and make sure // aMBFBCommand has memory allocated of size MaxBytesPerMBFB. // The default size for MaxBytesPerMBFB is 64. // 2) Split the command into multiple commands. // Any other function that creates a Feedback command: // Problem: The Feedback command being created was too large for // the device to handle on this connection type. // Solution: Split the command into multiple commands. LJM_ERROR_CODE LJME_DEBUG_LOG_FAILURE = 202; LJM_ERROR_CODE LJME_USING_DEFAULT_CALIBRATION = 203; // Problem: LJM has detected the device has one or more invalid calibration // constants and is using the default calibration constants. Readings may // inaccurate. // Solution: Contact LabJack support. LJM_ERROR_CODE LJME_DEBUG_LOG_FILE_NOT_OPEN = 204; // Modbus Errors: LJM_ERROR_CODE LJME_MODBUS_ERRORS_BEGIN = 1200; LJM_ERROR_CODE LJME_MODBUS_ERRORS_END = 1216; LJM_ERROR_CODE LJME_MBE1_ILLEGAL_FUNCTION = 1201; LJM_ERROR_CODE LJME_MBE2_ILLEGAL_DATA_ADDRESS = 1202; LJM_ERROR_CODE LJME_MBE3_ILLEGAL_DATA_VALUE = 1203; LJM_ERROR_CODE LJME_MBE4_SLAVE_DEVICE_FAILURE = 1204; LJM_ERROR_CODE LJME_MBE5_ACKNOWLEDGE = 1205; LJM_ERROR_CODE LJME_MBE6_SLAVE_DEVICE_BUSY = 1206; LJM_ERROR_CODE LJME_MBE8_MEMORY_PARITY_ERROR = 1208; LJM_ERROR_CODE LJME_MBE10_GATEWAY_PATH_UNAVAILABLE = 1210; LJM_ERROR_CODE LJME_MBE11_GATEWAY_TARGET_NO_RESPONSE = 1211; // Library Errors: LJM_ERROR_CODE LJME_LIBRARY_ERRORS_BEGIN = 1220; LJM_ERROR_CODE LJME_LIBRARY_ERRORS_END = 1399; LJM_ERROR_CODE LJME_UNKNOWN_ERROR = 1221; LJM_ERROR_CODE LJME_INVALID_DEVICE_TYPE = 1222; LJM_ERROR_CODE LJME_INVALID_HANDLE = 1223; LJM_ERROR_CODE LJME_DEVICE_NOT_OPEN = 1224; LJM_ERROR_CODE LJME_STREAM_NOT_INITIALIZED = 1225; LJM_ERROR_CODE LJME_DEVICE_DISCONNECTED = 1226; LJM_ERROR_CODE LJME_DEVICE_NOT_FOUND = 1227; LJM_ERROR_CODE LJME_DEVICE_ALREADY_OPEN = 1229; LJM_ERROR_CODE LJME_COULD_NOT_CLAIM_DEVICE = 1230; LJM_ERROR_CODE LJME_CANNOT_CONNECT = 1231; LJM_ERROR_CODE LJME_SOCKET_LEVEL_ERROR = 1233; LJM_ERROR_CODE LJME_CANNOT_OPEN_DEVICE = 1236; LJM_ERROR_CODE LJME_CANNOT_DISCONNECT = 1237; LJM_ERROR_CODE LJME_WINSOCK_FAILURE = 1238; LJM_ERROR_CODE LJME_RECONNECT_FAILED = 1239; LJM_ERROR_CODE LJME_U3_CANNOT_BE_OPENED_BY_LJM = 1243; LJM_ERROR_CODE LJME_U6_CANNOT_BE_OPENED_BY_LJM = 1246; LJM_ERROR_CODE LJME_UE9_CANNOT_BE_OPENED_BY_LJM = 1249; LJM_ERROR_CODE LJME_INVALID_ADDRESS = 1250; LJM_ERROR_CODE LJME_INVALID_CONNECTION_TYPE = 1251; LJM_ERROR_CODE LJME_INVALID_DIRECTION = 1252; LJM_ERROR_CODE LJME_INVALID_FUNCTION = 1253; // Function: LJM_MBFBComm // Problem: The aMBFB buffer passed as an input parameter // did not have a function number corresponding to Feedback. // Solution: Make sure the 8th byte of your buffer is 76 (base 10). // (For example, aMBFB[7] == 76 should evaluate to true.) LJM_ERROR_CODE LJME_INVALID_NUM_REGISTERS = 1254; LJM_ERROR_CODE LJME_INVALID_PARAMETER = 1255; LJM_ERROR_CODE LJME_INVALID_PROTOCOL_ID = 1256; // Problem: The Protocol ID was not in the proper range. LJM_ERROR_CODE LJME_INVALID_TRANSACTION_ID = 1257; // Problem: The Transaction ID was not in the proper range. LJM_ERROR_CODE LJME_INVALID_VALUE_TYPE = 1259; LJM_ERROR_CODE LJME_MEMORY_ALLOCATION_FAILURE = 1260; // Problem: A memory allocation attempt has failed, probably due to a // lack of available memory. LJM_ERROR_CODE LJME_NO_COMMAND_BYTES_SENT = 1261; // Problem: No bytes could be sent to the device. // Possibilities: // * The device was previously connected, but was suddenly // disconnected. LJM_ERROR_CODE LJME_INCORRECT_NUM_COMMAND_BYTES_SENT = 1262; // Problem: The expected number of bytes could not be sent to the device. // Possibilities: // * The device was disconnected while bytes were being sent. LJM_ERROR_CODE LJME_NO_RESPONSE_BYTES_RECEIVED = 1263; // Problem: No bytes could be received from the device. // Possibilities: // * The device was previously connected, but was suddenly // disconnected. // * The timeout length was too short for the device to respond. LJM_ERROR_CODE LJME_INCORRECT_NUM_RESPONSE_BYTES_RECEIVED = 1264; // Problem: The expected number of bytes could not be received from the // device. // Possibilities: // * The device was previously connected, but was suddenly // disconnected. // * The device needs a firmware update. LJM_ERROR_CODE LJME_MIXED_FORMAT_IP_ADDRESS = 1265; // Functions: LJM_OpenS and LJM_Open // Problem: The string passed as an identifier contained an IP address // that was ambiguous. // Solution: Make sure the IP address is in either decimal format // (i.e. "192.168.1.25") or hex format (i.e. "0xC0.A8.0.19"). LJM_ERROR_CODE LJME_UNKNOWN_IDENTIFIER = 1266; LJM_ERROR_CODE LJME_NOT_IMPLEMENTED = 1267; LJM_ERROR_CODE LJME_INVALID_INDEX = 1268; // Problem: An error internal to the LabJackM Library has occurred. // Solution: Please report this error to LabJack. LJM_ERROR_CODE LJME_INVALID_LENGTH = 1269; LJM_ERROR_CODE LJME_ERROR_BIT_SET = 1270; LJM_ERROR_CODE LJME_INVALID_MAXBYTESPERMBFB = 1271; // Functions: // LJM_AddressesToMBFB: // Problem: This indicates the MaxBytesPerMBFB value was // insufficient for any Feedback command. // Solution: Pass a larger value for MaxBytesPerMBFB and make sure // aMBFBCommand has memory allocated of size MaxBytesPerMBFB. // The default size for MaxBytesPerMBFB is 64. LJM_ERROR_CODE LJME_NULL_POINTER = 1272; // Problem: The Library has received an invalid pointer. // Solution: Make sure that any functions that have pointers in their // parameter list are valid pointers that point to allocated memory. LJM_ERROR_CODE LJME_NULL_OBJ = 1273; // Functions: // LJM_OpenS and LJM_Open: // Problem: The Library failed to parse the input parameters. // Solution: Check the validity of your inputs and if the problem // persists, please contact LabJack support. LJM_ERROR_CODE LJME_RESERVED_NAME = 1274; // LJM_OpenS and LJM_Open: // Problem: The string passed as Identifier was a reserved name. // Solution: Use a different name for your device. You can also connect // by passing the device's serial number or IP address, if // applicable. LJM_ERROR_CODE LJME_UNPARSABLE_DEVICE_TYPE = 1275; // LJM_OpenS: // Problem: This Library could not parse the DeviceType. // Solution: Check the LJM_OpenS documentation and make sure the // DeviceType does not contain any unusual characters. LJM_ERROR_CODE LJME_UNPARSABLE_CONNECTION_TYPE = 1276; // LJM_OpenS: // Problem: This Library could not parse the ConnectionType. // Solution: Check the LJM_OpenS documentation and make sure the // ConnectionType does not contain any unusual characters. LJM_ERROR_CODE LJME_UNPARSABLE_IDENTIFIER = 1277; // LJM_OpenS and LJM_Open: // Problem: This Library could not parse the Identifier. // Solution: Check the LJM_OpenS documentation and make sure the // Identifier does not contain any unusual characters. LJM_ERROR_CODE LJME_PACKET_SIZE_TOO_LARGE = 1278; // Problems: The packet being sent to the device contained too many bytes. // Note: Some LabJack devices need two bytes appended to any Modbus packets // sent to a device. The packet size plus these two appended bytes // could have exceeded the packet size limit. // Solution: Send a smaller packet, i.e. break your packet up into multiple // packets. LJM_ERROR_CODE LJME_TRANSACTION_ID_ERR = 1279; // Problem: LJM received an unexpected Modbus Transaction ID. LJM_ERROR_CODE LJME_PROTOCOL_ID_ERR = 1280; // Problem: LJM received an unexpected Modbus Protocol ID. LJM_ERROR_CODE LJME_LENGTH_ERR = 1281; // Problem: LJM received a packet with an unexpected Modbus Length. LJM_ERROR_CODE LJME_UNIT_ID_ERR = 1282; // Problem: LJM received a packet with an unexpected Modbus Unit ID. LJM_ERROR_CODE LJME_FUNCTION_ERR = 1283; // Problem: LJM received a packet with an unexpected Modbus Function. LJM_ERROR_CODE LJME_STARTING_REG_ERR = 1284; // Problem: LJM received a packet with an unexpected Modbus address. LJM_ERROR_CODE LJME_NUM_REGS_ERR = 1285; // Problem: LJM received a packet with an unexpected Modbus number of // registers. LJM_ERROR_CODE LJME_NUM_BYTES_ERR = 1286; // Problem: LJM received a packet with an unexpected Modbus number of bytes. LJM_ERROR_CODE LJME_CONFIG_FILE_NOT_FOUND = 1289; LJM_ERROR_CODE LJME_CONFIG_PARSING_ERROR = 1290; LJM_ERROR_CODE LJME_INVALID_NUM_VALUES = 1291; LJM_ERROR_CODE LJME_CONSTANTS_FILE_NOT_FOUND = 1292; LJM_ERROR_CODE LJME_INVALID_CONSTANTS_FILE = 1293; LJM_ERROR_CODE LJME_INVALID_NAME = 1294; // Problem: LJM received a name that was not found/matched in the constants // file or was otherwise an invalid name. // Solution: Use LJM_ErrorToString to find the invalid name(s). LJM_ERROR_CODE LJME_OVERSPECIFIED_PORT = 1296; // Functions: LJM_Open, LJM_OpenS // Problem: LJM received an Identifier that specified a port/pipe, but // connection type was not specified. LJM_ERROR_CODE LJME_INTENT_NOT_READY = 1297; // Please contact LabJack support if the problem is not apparent. LJM_ERROR_CODE LJME_ATTR_LOAD_COMM_FAILURE = 1298; /** * Name: LJME_ATTR_LOAD_COMM_FAILURE * Functions: LJM_Open, LJM_OpenS * Desc: Indicates that a device was found and opened, but communication with * that device failed, so the device was closed. The handle returned is * not a valid handle. This communication failure can mean the device is * in a non-responsive state or has out-of-date firmware. * Solutions: a) Power your device off, then back on, i.e. unplug it then plug * it back in. * b) Make sure your device(s) have up-to-date firmware. **/ LJM_ERROR_CODE LJME_INVALID_CONFIG_NAME = 1299; // Functions: LJM_WriteLibraryConfigS, LJM_WriteLibraryConfigStringS, // LJM_ReadLibraryConfigS, LJM_ReadLibraryConfigStringS // Problem: An unknown string has been passed in as Parameter. // Solution: Please check the documentation in this header file for the // configuration parameter you are trying to read or write. Not all // config parameters can be read, nor can all config parameters be // written. LJM_ERROR_CODE LJME_ERROR_RETRIEVAL_FAILURE = 1300; // Problem: A device has reported an error and LJM failed to to retrieve the // error code from the device. // Solution: Please make sure the device has current firmware and that this // is a current of LJM. If the problem persists, please contact LabJack // support. LJM_ERROR_CODE LJME_LJM_BUFFER_FULL = 1301; LJM_ERROR_CODE LJME_COULD_NOT_START_STREAM = 1302; LJM_ERROR_CODE LJME_STREAM_NOT_RUNNING = 1303; LJM_ERROR_CODE LJME_UNABLE_TO_STOP_STREAM = 1304; LJM_ERROR_CODE LJME_INVALID_VALUE = 1305; LJM_ERROR_CODE LJME_SYNCHRONIZATION_TIMEOUT = 1306; LJM_ERROR_CODE LJME_OLD_FIRMWARE = 1307; LJM_ERROR_CODE LJME_CANNOT_READ_OUT_ONLY_STREAM = 1308; LJM_ERROR_CODE LJME_NO_SCANS_RETURNED = 1309; LJM_ERROR_CODE LJME_TEMPERATURE_OUT_OF_RANGE = 1310; LJM_ERROR_CODE LJME_VOLTAGE_OUT_OF_RANGE = 1311; /******************************* * Device Management Functions * *******************************/ /** * Name: LJM_ListAll, LJM_ListAllS * Desc: Scans for LabJack devices, returning arrays describing the devices * found, allowing LJM_dtANY and LJM_ctANY to be used * Para: DeviceType, filters which devices will be returned (LJM_dtT7, * LJM_dtDIGIT, etc.). LJM_dtANY is allowed. * ConnectionType, filters by connection type (LJM_ctUSB or LJM_ctTCP). * LJM_ctANY is allowed. * NumFound, a pointer that returns the number of devices found * aDeviceTypes, an array that must be preallocated to size * LJM_LIST_ALL_SIZE, returns the device type for each of the * NumFound devices * aConnectionTypes, an array that must be preallocated to size * LJM_LIST_ALL_SIZE, returns the connect type for each of the * NumFound devices * aSerialNumbers, an array that must be preallocated to size * LJM_LIST_ALL_SIZE, returns the serial number for each of the * NumFound devices * aIPAddresses, an array that must be preallocated to size * LJM_LIST_ALL_SIZE, returns the IPAddresses for each of the * NumFound devices, but only if ConnectionType is TCP-based. For * each corresponding device for which aConnectionTypes[i] is not * TCP-based, aIPAddresses[i] will be LJM_NO_IP_ADDRESS. * Note: These functions only show what devices could be opened. To actually * open a device, use LJM_Open or LJM_OpenS. * Note: These functions will ignore NULL pointers, except for NumFound. **/ LJM_ERROR_RETURN LJM_ListAll(int DeviceType, int ConnectionType, int * NumFound, int * aDeviceTypes, int * aConnectionTypes, int * aSerialNumbers, int * aIPAddresses); LJM_ERROR_RETURN LJM_ListAllS(const char * DeviceType, const char * ConnectionType, int * NumFound, int * aDeviceTypes, int * aConnectionTypes, int * aSerialNumbers, int * aIPAddresses); /** * Name: LJM_ListAllExtended * Desc: Advanced version of LJM_ListAll that performs an additional query of * arbitrary registers on the device. * Para: DeviceType, filters which devices will be returned (LJM_dtT7, * LJM_dtDIGIT, etc.). LJM_dtANY is allowed. * ConnectionType, filters by connection type (LJM_ctUSB or LJM_ctTCP). * LJM_ctANY is allowed. * NumAddresses, the number of addresses to query. Also the size of * aAddresses and aNumRegs. * aAddresses, the addresses to query for each device that is found. * aNumRegs, the number of registers to query for each address. * Each aNumRegs[i] corresponds to aAddresses[i]. * MaxNumFound, the maximum number of devices to find. Also the size of * aDeviceTypes, aConnectionTypes, aSerialNumbers, and aIPAddresses. * NumFound, a pointer that returns the number of devices found * aDeviceTypes, an array that must be preallocated to size * MaxNumFound, returns the device type for each of the * NumFound devices * aConnectionTypes, an array that must be preallocated to size * MaxNumFound, returns the connect type for each of the * NumFound devices * aSerialNumbers, an array that must be preallocated to size * MaxNumFound, returns the serial number for each of the * NumFound devices * aIPAddresses, an array that must be preallocated to size * MaxNumFound, returns the IPAddresses for each of the * NumFound devices, but only if ConnectionType is TCP-based. For * each corresponding device for which aConnectionTypes[i] is not * TCP-based, aIPAddresses[i] will be LJM_NO_IP_ADDRESS. * aBytes, an array that must be preallocated to size: * MaxNumFound * <the sum of aNumRegs> * LJM_BYTES_PER_REGISTER, * which will contain the query bytes sequentially. A device * represented by index i would have an aBytes index of: * (i * <the sum of aNumRegs> * LJM_BYTES_PER_REGISTER). * Note: These functions only show what devices could be opened. To actually * open a device, use LJM_Open or LJM_OpenS. * Note: These functions will ignore NULL pointers, except for NumFound and * aBytes. * * * TODO: Define error behavior * * **/ LJM_ERROR_RETURN LJM_ListAllExtended(int DeviceType, int ConnectionType, int NumAddresses, const int * aAddresses, const int * aNumRegs, int MaxNumFound, int * NumFound, int * aDeviceTypes, int * aConnectionTypes, int * aSerialNumbers, int * aIPAddresses, unsigned char * aBytes); /** * Name: LJM_OpenS * Desc: Opens a LabJack device. * Para: DeviceType, a string containing the type of the device to be connected, * optionally prepended by "LJM_dt". Possible values include "ANY", * "T7", and "DIGIT". * ConnectionType, a string containing the type of the connection desired, * optionally prepended by "LJM_ct". Possible values include "ANY", * "USB", "TCP", "ETHERNET", and "WIFI". * Identifier, a string identifying the device to be connected or * "LJM_idANY"/"ANY". This can be a serial number, IP address, or * device name. Device names may not contain periods. * Handle, the new handle that represents a device connection upon success * Retr: LJME_NOERROR, if a device was successfully opened. * LJME_ATTR_LOAD_COMM_FAILURE, if a device was found, but there was a * communication failure. * Note: Input parameters are not case-sensitive. * Note: Empty strings passed to DeviceType, ConnectionType, or Identifier * indicate the same thing as LJM_dtANY, LJM_ctANY, or LJM_idANY, * respectively. **/ LJM_ERROR_RETURN LJM_OpenS(const char * DeviceType, const char * ConnectionType, const char * Identifier, int * Handle); /** * Name: LJM_Open * Desc: See the description for LJM_OpenS. The only difference between * LJM_Open and LJM_OpenS is the first two parameters. * Para: DeviceType, a constant corresponding to the type of device to open, * such as LJM_dtT7, or LJM_dtANY. * ConnectionType, a constant corresponding to the type of connection to * open, such as LJM_ctUSB, or LJM_ctANY. **/ LJM_ERROR_RETURN LJM_Open(int DeviceType, int ConnectionType, const char * Identifier, int * Handle); /** * Name: LJM_GetHandleInfo * Desc: Takes a device handle as input and returns details about that device. * Para: Handle, a valid handle to an open device. * DeviceType, the output device type corresponding to a constant such as * LJM_dtT7. * ConnectionType, the output device type corresponding to a constant * such as LJM_ctUSB. * SerialNumber, the output serial number of the device. * IPAddress, the output integer representation of the device's IP * address when ConnectionType is TCP-based. If ConnectionType is not * TCP-based, this will be LJM_NO_IP_ADDRESS. Note that this can be * converted to a human-readable string with the LJM_NumberToIP * function. * Port, the output port if the device connection is TCP-based, or the pipe * if the device connection is USB-based. * MaxBytesPerMB, the maximum packet size in number of bytes that can be * sent to or received from this device. Note that this can change * depending on connection type and device type. * Note: This function returns device information loaded during an open call * and therefore does not initiate communications with the device. In * other words, it is fast but will not represent changes to serial * number or IP address since the device was opened. * Warn: This function ignores null pointers **/ LJM_ERROR_RETURN LJM_GetHandleInfo(int Handle, int * DeviceType, int * ConnectionType, int * SerialNumber, int * IPAddress, int * Port, int * MaxBytesPerMB); /** * Name: LJM_Close * Desc: Closes the connection to the device. * Para: Handle, a valid handle to an open device. **/ LJM_ERROR_RETURN LJM_Close(int Handle); /** * Name: LJM_CloseAll * Desc: Closes all connections to all devices **/ LJM_ERROR_RETURN LJM_CloseAll(); /****************************** * Easy Read/Write Functions * ******************************/ // Easy Functions: All type, either reading or writing, single address /** * Name: LJM_eReadAddress, LJM_eReadName * LJM_eWriteAddress, LJM_eWriteName * Desc: Creates and sends a Modbus operation, then receives and parses the * response. * Para: Handle, a valid handle to an open device * (Address), an address to read/write * (Type), the type corresponding to Address * (Name), a name to read/write * Value, a value to write or read * Note: These functions may take liberties in deciding what kind of Modbus * operation to create. For more control of what kind of packets may be * sent/received, please see the LJM_WriteLibraryConfigS function. **/ LJM_ERROR_RETURN LJM_eWriteAddress(int Handle, int Address, int Type, double Value); LJM_ERROR_RETURN LJM_eReadAddress(int Handle, int Address, int Type, double * Value); LJM_ERROR_RETURN LJM_eWriteName(int Handle, const char * Name, double Value); LJM_ERROR_RETURN LJM_eReadName(int Handle, const char * Name, double * Value); // Easy Functions: All type, either reading or writing, multiple addresses /** * Name: LJM_eReadAddresses, LJM_eReadNames * LJM_eWriteAddresses, LJM_eWriteNames * Desc: Creates and sends a Modbus operation, then receives and parses the * response. * Para: Handle, a valid handle to an open device. * NumFrames, the total number of reads/writes to perform. * (aAddresses), an array of size NumFrames of the addresses to * read/write for each frame. * (aTypes), an array of size NumFrames of the data types corresponding * to each address in aAddresses. * (aNames), an array of size NumFrames of the names to read/write for * each frame. * aValues, an array of size NumFrames that represents the values to * write from or read to. * ErrorAddress, a pointer to an integer, which in the case of a relevant * error, gets updated to contain the device-reported address that * caused an error. * Note: Reads/writes are compressed into arrays for consecutive addresses that * line up, based on type. See the LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES * configuration. * Note: These functions may take liberties in deciding what kind of Modbus * operation to create. For more control of what kind of packets may be * sent/received, please see the LJM_WriteLibraryConfigS function. **/ LJM_ERROR_RETURN LJM_eReadAddresses(int Handle, int NumFrames, const int * aAddresses, const int * aTypes, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eReadNames(int Handle, int NumFrames, const char ** aNames, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eWriteAddresses(int Handle, int NumFrames, const int * aAddresses, const int * aTypes, const double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eWriteNames(int Handle, int NumFrames, const char ** aNames, const double * aValues, int * ErrorAddress); // Easy Functions: All type, reading and writing, multiple values to one address /** * Name: LJM_eReadAddressArray, LJM_eReadNameArray * LJM_eWriteAddressArray, LJM_eWriteNameArray * Desc: Performs a Modbus operation to either read or write an array. * Para: Handle, a valid handle to an open device. * (Address), the address to read an array from or write an array to. * (Type), the data type of Address. * (Name), the register name to read an array from or write an array to. * NumValues, the size of the array to read or write. * aValues, an array of size NumValues that represents the values to * write from or read to. * ErrorAddress, a pointer to an integer, which in the case of a relevant * error, gets updated to contain the device-reported address that * caused an error. * Note: These functions may take liberties in deciding what kind of Modbus * operation to create. For more control of what kind of packets may be * sent/received, please see the LJM_WriteLibraryConfigS function. **/ LJM_ERROR_RETURN LJM_eReadAddressArray(int Handle, int Address, int Type, int NumValues, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eReadNameArray(int Handle, const char * Name, int NumValues, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eWriteAddressArray(int Handle, int Address, int Type, int NumValues, const double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eWriteNameArray(int Handle, const char * Name, int NumValues, const double * aValues, int * ErrorAddress); // Easy Functions: All type, reading and writing, multiple addresses with // multiple values for each /** * Name: LJM_eAddresses, LJM_eNames * Desc: Performs Modbus operations that write/read data. * Para: Handle, a valid handle to an open device. * NumFrames, the total number of reads/writes frames to perform. * (aAddresses), an array of size NumFrames of the addresses to * read/write for each frame. * (aTypes), an array of size NumFrames of the data types corresponding * to each address in aAddresses. * (aNames), an array of size NumFrames of the names to read/write for * each frame. * aWrites, an array of size NumFrames of the direction/access type * (LJM_READ or LJM_WRITE) for each frame. * aNumValues, an array of size NumFrames giving the number of values to * read/write for each frame. * aValues, an array that represents the values to write or read. The * size of this array must be the sum of aNumValues. * ErrorAddress, a pointer to an integer, which in the case of a relevant * error, gets updated to contain the device-reported address that * caused an error. * Note: Reads/writes are compressed into arrays for consecutive addresses that * line up, based on type. See the LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES * configuration. * Note: These functions may take liberties in deciding what kind of Modbus * operation to create. For more control of what kind of packets may be * sent/received, please see the LJM_WriteLibraryConfigS function. **/ LJM_ERROR_RETURN LJM_eAddresses(int Handle, int NumFrames, const int * aAddresses, const int * aTypes, const int * aWrites, const int * aNumValues, double * aValues, int * ErrorAddress); LJM_ERROR_RETURN LJM_eNames(int Handle, int NumFrames, const char ** aNames, const int * aWrites, const int * aNumValues, double * aValues, int * ErrorAddress); /** * Name: LJM_eReadNameString, LJM_eReadAddressString * Desc: Reads a 50-byte string from a device. * Para: Handle, a valid handle to an open device. * (Name), the name of the registers to read, which must be of type * LJM_STRING. * (Address), the address of the registers to read an LJM_STRING from. * String, A string that is updated to contain the result of the read. * Must be allocated to size LJM_STRING_ALLOCATION_SIZE or * greater prior to calling this function. * Note: This is a convenience function for LJM_eNames/LJM_eAddressess. * Note: LJM_eReadNameString checks to make sure that Name is in the constants * file and describes registers that have a data type of LJM_STRING, * but LJM_eReadAddressString does not perform any data type checking. **/ LJM_ERROR_RETURN LJM_eReadNameString(int Handle, const char * Name, char * String); LJM_ERROR_RETURN LJM_eReadAddressString(int Handle, int Address, char * String); /** * Name: LJM_eWriteNameString, LJM_eWriteAddressString * Desc: Writes a 50-byte string to a device. * Para: Handle, a valid handle to an open device. * (Name), the name of the registers to write to, which must be of type * LJM_STRING * (Address), the address of the registers to write an LJM_STRING to * String, The string to write. Must null-terminate at length * LJM_STRING_ALLOCATION_SIZE or less. * Note: This is a convenience function for LJM_eNames/LJM_eAddressess * Note: LJM_eWriteNameString checks to make sure that Name is in the constants * file and describes registers that have a data type of LJM_STRING, * but LJM_eWriteAddressString does not perform any data type checking. **/ LJM_ERROR_RETURN LJM_eWriteNameString(int Handle, const char * Name, const char * String); LJM_ERROR_RETURN LJM_eWriteAddressString(int Handle, int Address, const char * String); /********************* * Stream Functions * *********************/ /** * Name: LJM_eStreamStart * Desc: Initializes a stream object and begins streaming. This includes * creating a buffer in LJM that collects data from the device. * Para: Handle, a valid handle to an open device. * ScansPerRead, Number of scans returned by each call to the * LJM_eStreamRead function. This is not tied to the maximum packet * size for the device. * NumAddresses, The size of aScanList. The number of addresses to scan. * aScanList, Array of Modbus addresses to collect samples from, per scan. * ScanRate, intput/output pointer. Sets the desired number of scans per * second. Upon successful return of this function, gets updated to * the actual scan rate that the device will scan at. * Note: Address configuration such as range, resolution, and differential * voltages are handled by writing to the device. * Note: Check your device's documentation for which addresses are valid for * aScanList. **/ LJM_ERROR_RETURN LJM_eStreamStart(int Handle, int ScansPerRead, int NumAddresses, const int * aScanList, double * ScanRate); /** * Name: LJM_eStreamRead * Desc: Returns data from an initialized and running LJM stream buffer. Waits * for data to become available, if necessary. * Para: Handle, a valid handle to an open device. * aData, Output data array. Returns all addresses interleaved. Must be * large enough to hold (ScansPerRead * NumAddresses) values. * ScansPerRead and NumAddresses are set when stream is set up with * LJM_eStreamStart. The data returned is removed from the LJM stream * buffer. * DeviceScanBacklog, The number of scans left in the device buffer, as * measured from when data was last collected from the device. This * should usually be near zero and not growing for healthy streams. * LJMScanBacklog, The number of scans left in the LJM buffer, as * measured from after the data returned from this function is * removed from the LJM buffer. This should usually be near zero and * not growing for healthy streams. * Note: Returns LJME_NO_SCANS_RETURNED if LJM_STREAM_SCANS_RETURN is * LJM_STREAM_SCANS_RETURN_ALL_OR_NONE. **/ LJM_ERROR_RETURN LJM_eStreamRead(int Handle, double * aData, int * DeviceScanBacklog, int * LJMScanBacklog); /** * Name: LJM_SetStreamCallback * Desc: Sets a callback that is called by LJM when the stream has collected * ScansPerRead scans. * Para: Handle, a valid handle to an open device. * Callback, the callback function for LJM's stream thread to call * when stream data is ready, which should call LJM_eStreamRead to * acquire data. * Arg, the user-defined argument that is passed to Callback when it is * invoked. * Note: LJM_SetStreamCallback should be called after LJM_eStreamStart. * Note: LJM_eStreamStop may be called at any time when using * LJM_SetStreamCallback, but the Callback function should not try to * stop stream. If the Callback function detects that stream needs to be * stopped, it should signal to a different thread that stream should be * stopped. * Note: To disable the previous callback for stream reading, pass 0 or NULL as * Callback. **/ typedef void (*LJM_StreamReadCallback)(void *); LJM_ERROR_RETURN LJM_SetStreamCallback(int Handle, LJM_StreamReadCallback Callback, void * Arg); /** * Name: LJM_eStreamStop * Desc: Stops LJM from streaming any more data from the device, while leaving * any collected data in the LJM buffer to be read. Stops the device from * streaming. * Para: Handle, a valid handle to an open device. **/ LJM_ERROR_RETURN LJM_eStreamStop(int Handle); /*************************************** * Byte-oriented Read/Write Functions * ***************************************/ /** * Name: LJM_WriteRaw * Desc: Sends an unaltered data packet to a device. * Para: Handle, a valid handle to an open device. * Data, the byte array packet to send. * NumBytes, the size of Data. **/ LJM_ERROR_RETURN LJM_WriteRaw(int Handle, const unsigned char * Data, int NumBytes); /** * Name: LJM_ReadRaw * Desc: Reads an unaltered data packet from a device. * Para: Handle, a valid handle to an open device. * Data, the allocated byte array to receive the data packet. * NumBytes, the number of bytes to receive. **/ LJM_ERROR_RETURN LJM_ReadRaw(int Handle, unsigned char * Data, int NumBytes); /** * Name: LJM_AddressesToMBFB * Desc: Takes in arrays that together represent operations to be performed on a * device and outputs a byte array representing a valid Feedback command, * which can be used as input to the LJM_MBFBComm function. * Para: MaxBytesPerMBFB, the maximum number of bytes that the Feedback command * is allowed to consist of. It is highly recommended to pass the size * of the aMBFBCommand buffer as MaxBytesPerMBFB to prevent buffer * overflow. See LJM_DEFAULT_FEEDBACK_ALLOCATION_SIZE. * aAddresses, an array of size NumFrames representing the register * addresses to read from or write to for each frame. * aTypes, an array of size NumFrames representing the data types to read * or write. See the Data Type constants in this header file. * aWrites, an array of size NumFrames of the direction/access type * (LJM_READ or LJM_WRITE) for each frame. * aNumValues, an array of size NumFrames giving the number of values to * read/write for each frame. * aValues, for every entry in aWrites[i] that is LJM_WRITE, this contains * aNumValues[i] values to write and for every entry in aWrites that * is LJM_READ, this contains aNumValues[i] values that can later be * updated in the LJM_UpdateValues function. aValues values must be * in the same order as the rest of the arrays. For example, if aWrite is * {LJM_WRITE, LJM_READ, LJM_WRITE}, * and aNumValues is * {1, 4, 2} * aValues would have one value to be written, then 4 blank/garbage * values to later be updated, and then 2 values to be written. * NumFrames, A pointer to the number of frames being created, which is * also the size of aAddresses, aTypes, aWrites, and aNumValues. Once * this function returns, NumFrames will be updated to the number of * frames aMBFBCommand contains. * aMBFBCommand, the output parameter that contains the valid Feedback * command. Transaction ID and Unit ID will be blanks that * LJM_MBFBComm will fill in. * Warn: aMBFBCommand must be an allocated array of size large enough to hold * the Feedback command (including its frames). You can use * MaxBytesPerMBFB to limit the size of the Feedback command. * Note: If this function returns LJME_FRAMES_OMITTED_DUE_TO_PACKET_SIZE, * aMBFBCommand is still valid, but does not contain all of the frames * that were intended and NumFrames is updated to contain the number of * frames that were included. **/ LJM_ERROR_RETURN LJM_AddressesToMBFB(int MaxBytesPerMBFB, const int * aAddresses, const int * aTypes, const int * aWrites, const int * aNumValues, const double * aValues, int * NumFrames, unsigned char * aMBFBCommand); /** * Name: LJM_MBFBComm * Desc: Sends a Feedback command and receives a Feedback response, parsing the * response for obvious errors. This function adds its own Transaction ID * to the command. The Feedback response may be parsed with the * LJM_UpdateValues function. * Para: Handle, a valid handle to an open device. * UnitID, the ID of the specific unit that the Feedback command should * be sent to. Use LJM_DEFAULT_UNIT_ID unless the device * documentation instructs otherwise. * aMBFB, both an input parameter and an output parameter. As an input * parameter, it is a valid Feedback command. As an output parameter, * it is a Feedback response, which may be an error response. * ErrorAddress, a pointer to an integer, which in the case of a relevant * error, gets updated to contain the device-reported * address that caused an error. * Note: aMBFB must be an allocated array of size large enough to hold the * Feedback response. **/ LJM_ERROR_RETURN LJM_MBFBComm(int Handle, unsigned char UnitID, unsigned char * aMBFB, int * ErrorAddress); /** * Name: LJM_UpdateValues * Desc: Takes a Feedback response named aMBFBResponse from a device and the * arrays corresponding to the Feedback command for which aMBFBResponse * is a response and updates the aValues array based on the read data in * aMBFBResponse. * Para: aMBFBResponse, a valid Feedback response. * aTypes, an array of size NumFrames representing the data types to read * or write. See the Data Type constants in this header file. * aWrites, the array of constants from LabJackM.h - either LJM_WRITE or * LJM_READ. * aNumValues, the array representing how many values were read or written. * NumFrames, the number of frames in aTypes, aWrites, and aNumValues. * aValues, for every entry in aWrites[i] that is LJM_WRITE, this contains * aNumValues[i] values that were written and for every entry in * aWrites that is LJM_READ, this contains aNumValues[i] values * that will now be updated. aValues values must be in the same * order as the rest of the arrays. For example, if aWrite is * {LJM_WRITE, LJM_READ, LJM_WRITE}, * and aNumValues is * {1, 4, 2} * LJM_UpdateValues would skip one value, then update 4 values with * the data in aMBFBResponse, then do nothing with the last 2 values. **/ LJM_ERROR_RETURN LJM_UpdateValues(unsigned char * aMBFBResponse, const int * aTypes, const int * aWrites, const int * aNumValues, int NumFrames, double * aValues); /**************************** * Constants File Functions * ****************************/ /** * Name: LJM_NamesToAddresses * Desc: Takes a list of Modbus register names as input and produces two lists * as output - the corresponding Modbus addresses and types. These two * lists can serve as input to functions that have Address/aAddresses and * Type/aTypes as input parameters. * Para: NumFrames, the number of names in aNames and the allocated size of * aAddresses and aTypes. * aNames, an array of null-terminated C-string register identifiers. * These register identifiers can be register names or register * alternate names. * aAddresses, output parameter containing the addresses described by * aNames in the same order, must be allocated to the size NumFrames * before calling LJM_NamesToAddresses. * aTypes, output parameter containing the types described by aNames in * the same order, must be allocated to the size NumFrames before * calling LJM_NamesToAddresses. * Note: For each register identifier in aNames that is invalid, the * corresponding aAddresses value will be set to LJM_INVALID_NAME_ADDRESS. **/ LJM_ERROR_RETURN LJM_NamesToAddresses(int NumFrames, const char ** aNames, int * aAddresses, int * aTypes); /** * Name: LJM_NameToAddress * Desc: Takes a Modbus register name as input and produces the corresponding * Modbus address and type. These two values can serve as input to * functions that have Address/aAddresses and Type/aTypes as input * parameters. * Para: Name, a null-terminated C-string register identifier. These register * identifiers can be register names or register alternate names. * Address, output parameter containing the address described by Name. * Type, output parameter containing the type described by Names. * Note: If Name is not a valid register identifier, Address will be set to * LJM_INVALID_NAME_ADDRESS. **/ LJM_ERROR_RETURN LJM_NameToAddress(const char * Name, int * Address, int * Type); /** * Name: LJM_AddressesToTypes * Desc: Retrieves multiple data types for given Modbus register addresses. * Para: NumAddresses, the number of addresses to convert to data types. * aAddresses, an array of size NumAddresses of Modbus register addresses. * aType, a pre-allocated array of size NumAddresses which gets updated * to the data type for each corresponding entry in Addresses. * Note: For each aAddresses[i] that is not found, the corresponding entry * aTypes[i] will be set to LJM_INVALID_NAME_ADDRESS and this function * will return LJME_INVALID_ADDRESS. **/ LJM_ERROR_RETURN LJM_AddressesToTypes(int NumAddresses, int * aAddresses, int * aTypes); /** * Name: LJM_AddressToType * Desc: Retrieves the data type for a given Modbus register address. * Para: Address, the Modbus register address to look up. * Type, an integer pointer which gets updated to the data type of * Address. **/ LJM_ERROR_RETURN LJM_AddressToType(int Address, int * Type); /** * Name: LJM_LookupConstantValue * Desc: Takes a register name or other scope and a constant name, and returns * the constant value. * Para: Scope, the register name or other scope to search within. Must be of * size LJM_MAX_NAME_SIZE or less. * ConstantName, the name of the constant to search for. Must be of size * LJM_MAX_NAME_SIZE or less. * ConstantValue, the returned value of ConstantName within the scope * of Scope, if found. **/ LJM_ERROR_RETURN LJM_LookupConstantValue(const char * Scope, const char * ConstantName, double * ConstantValue); /** * Name: LJM_LookupConstantName * Desc: Takes a register name or other scope and a value, and returns the * name of that value, if found within the given scope. * Para: Scope, the register name or other scope to search within. Must be of * size LJM_MAX_NAME_SIZE or less. * ConstantValue, the constant value to search for. * ConstantName, a pointer to a char array allocated to size * LJM_MAX_NAME_SIZE, used to return the null-terminated constant * name. **/ LJM_ERROR_RETURN LJM_LookupConstantName(const char * Scope, double ConstantValue, char * ConstantName); /** * Name: LJM_ErrorToString * Desc: Gets the name of an error code. * Para: ErrorCode, the error code to look up. * ErrorString, a pointer to a char array allocated to size * LJM_MAX_NAME_SIZE, used to return the null-terminated error name. * Note: If the constants file that has been loaded does not contain * ErrorCode, this returns a null-terminated message saying so. * If the constants file could not be opened, this returns a * null-terminated string saying so and where that constants file was * expected to be. **/ LJM_VOID_RETURN LJM_ErrorToString(int ErrorCode, char * ErrorString); /** * Name: LJM_LoadConstants * Desc: Manually loads or reloads the constants files associated with * the LJM_ErrorToString and LJM_NamesToAddresses functions. * Note: This step is handled automatically. This function does not need to be * called before either LJM_ErrorToString or LJM_NamesToAddresses. **/ LJM_VOID_RETURN LJM_LoadConstants(); /** * Name: LJM_LoadConstantsFromFile * Desc: Alias for executing: * LJM_WriteLibraryConfigStringS(LJM_CONSTANTS_FILE, FileName) * Para: FileName, the absolute or relative file path string to pass to * LJM_WriteLibraryConfigStringS as the String parameter. Must * null-terminate. **/ LJM_ERROR_RETURN LJM_LoadConstantsFromFile(const char * FileName); /** * Name: LJM_LoadConstantsFromString * Desc: Parses JsonString as the constants file and loads it. * Para: JsonString, A JSON string containing a "registers" array and/or an "errors" * array. * Note: If the JSON string does not contain a "registers" array, the Modbus-related * constants are not affected. Similarly, if the JSON string does not contain * an "errors" array, the errorcode-related constants are not affected. **/ LJM_ERROR_RETURN LJM_LoadConstantsFromString(const char * JsonString); /****************************** * Type Conversion Functions * ******************************/ // Thermocouple conversion // Thermocouple Type constants static const long LJM_ttB = 6001; static const long LJM_ttE = 6002; static const long LJM_ttJ = 6003; static const long LJM_ttK = 6004; static const long LJM_ttN = 6005; static const long LJM_ttR = 6006; static const long LJM_ttS = 6007; static const long LJM_ttT = 6008; static const long LJM_ttC = 6009; /** * Desc: Converts thermocouple voltage to temperature. * Para: TCType, the thermocouple type. See "Thermocouple Type constants". * TCVolts, the voltage reported by the thermocouple. * CJTempK, the cold junction temperature in degrees Kelvin. * pTCTempK, outputs the calculated temperature in degrees Kelvin. **/ LJM_ERROR_RETURN LJM_TCVoltsToTemp(int TCType, double TCVolts, double CJTempK, double * pTCTempK); /** * Name: LJM_TYPE#BitsToByteArray * Desc: Converts an array of values from C-types to bytes, performing automatic * endian conversions if necessary. * Para: aTYPE#Bits (such as aFLOAT32), the array of values to be converted. * RegisterOffset, the register offset to put the converted values in aBytes. * The actual offset depends on how many bits the type is. * NumTYPE#Bits (such as NumFLOAT32), the number of values to convert. * aBytes, the converted values in byte form. **/ /** * Name: LJM_ByteArrayToTYPE#Bits * Desc: Converts an array of values from bytes to C-types, performing automatic * endian conversions if necessary. * Para: aBytes, the bytes to be converted. * RegisterOffset, the register offset to get the values from in aBytes. * The actual offset depends on how many bits the type is. * NumTYPE#Bits (such as NumFLOAT32), the number of values to convert. * aTYPE#Bits (such as aFLOAT32), the converted values in C-type form. **/ // Single precision float, 32 bits // (the C type "float") LJM_VOID_RETURN LJM_FLOAT32ToByteArray(const float * aFLOAT32, int RegisterOffset, int NumFLOAT32, unsigned char * aBytes); LJM_VOID_RETURN LJM_ByteArrayToFLOAT32(const unsigned char * aBytes, int RegisterOffset, int NumFLOAT32, float * aFLOAT32); // Unsigned 16 bit integer // (the C type "unsigned short" or similar) LJM_VOID_RETURN LJM_UINT16ToByteArray(const unsigned short * aUINT16, int RegisterOffset, int NumUINT16, unsigned char * aBytes); LJM_VOID_RETURN LJM_ByteArrayToUINT16(const unsigned char * aBytes, int RegisterOffset, int NumUINT16, unsigned short * aUINT16); // Unsigned 32 bit integer // (the C type "unsigned int" or similar) LJM_VOID_RETURN LJM_UINT32ToByteArray(const unsigned int * aUINT32, int RegisterOffset, int NumUINT32, unsigned char * aBytes); LJM_VOID_RETURN LJM_ByteArrayToUINT32(const unsigned char * aBytes, int RegisterOffset, int NumUINT32, unsigned int * aUINT32); // Signed 32 bit integer // (the C type "int" or similar) LJM_VOID_RETURN LJM_INT32ToByteArray(const int * aINT32, int RegisterOffset, int NumINT32, unsigned char * aBytes); LJM_VOID_RETURN LJM_ByteArrayToINT32(const unsigned char * aBytes, int RegisterOffset, int NumINT32, int * aINT32); /** * Name: LJM_NumberToIP * Desc: Takes an integer representing an IPv4 address and outputs the corresponding * decimal-dot IPv4 address as a null-terminated string. * Para: Number, the numerical representation of an IP address to be converted to * a string representation. * IPv4String, a char array that must be allocated to size LJM_IPv4_STRING_SIZE * which will be set to contain the null-terminated string representation * of the IP address after the completion of this function. * Retr: LJME_NOERROR for no detected errors, * LJME_NULL_POINTER if IPv4String is NULL. **/ LJM_ERROR_RETURN LJM_NumberToIP(unsigned int Number, char * IPv4String); /** * Name: LJM_IPToNumber * Desc: Takes a decimal-dot IPv4 string representing an IPv4 address and outputs the * corresponding integer version of the address. * Para: IPv4String, the string representation of the IP address to be converted to * a numerical representation. * Number, the output parameter that will be updated to contain the numerical * representation of IPv4String after the completion of this function. * Retr: LJME_NOERROR for no detected errors, * LJME_NULL_POINTER if IPv4String or Number is NULL, * LJME_INVALID_PARAMETER if IPv4String could not be parsed as a IPv4 address. **/ LJM_ERROR_RETURN LJM_IPToNumber(const char * IPv4String, unsigned int * Number); /** * Name: LJM_NumberToMAC * Desc: Takes an integer representing a MAC address and outputs the corresponding * hex-colon MAC address as a string. * Para: Number, the numerical representation of a MAC address to be converted to * a string representation. * MACString, a char array that must be allocated to size LJM_MAC_STRING_SIZE * which will be set to contain the string representation of the MAC * address after the completion of this function. * Retr: LJME_NOERROR for no detected errors, * LJME_NULL_POINTER if MACString is NULL. **/ LJM_ERROR_RETURN LJM_NumberToMAC(unsigned long long Number, char * MACString); /** * Name: LJM_MACToNumber * Desc: Takes a hex-colon string representing a MAC address and outputs the * corresponding integer version of the address. * Para: MACString, the string representation of the MAC address to be converted to * a numerical representation. * Number, the output parameter that will be updated to contain the numerical * representation of MACString after the completion of this function. * Retr: LJME_NOERROR for no detected errors, * LJME_NULL_POINTER if MACString or Number is NULL, * LJME_INVALID_PARAMETER if MACString could not be parsed as a MAC address. **/ LJM_ERROR_RETURN LJM_MACToNumber(const char * MACString, unsigned long long * Number); /********************** * LJM Configuration * **********************/ // Config Parameters /** * Desc: The maximum number of milliseconds that LJM will wait for a packet to * be sent and also for a packet to be received before timing out. In * other words, LJM can wait this long for a command to be sent, then * wait this long again for the response to be received. **/ static const char * const LJM_USB_SEND_RECEIVE_TIMEOUT_MS = "LJM_USB_SEND_RECEIVE_TIMEOUT_MS"; static const char * const LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS = "LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS"; static const char * const LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS = "LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS"; /** * Desc: Sets LJM_USB_SEND_RECEIVE_TIMEOUT_MS, LJM_ETHERNET_SEND_RECEIVE_TIMEOUT_MS, * and LJM_WIFI_SEND_RECEIVE_TIMEOUT_MS. * Note: Write-only. May not be read. **/ static const char * const LJM_SEND_RECEIVE_TIMEOUT_MS = "LJM_SEND_RECEIVE_TIMEOUT_MS"; /** * Name: LJM_ETHERNET_OPEN_TIMEOUT_MS * Desc: The maximum number of milliseconds that LJM will wait for a device * being opened via TCP to respond before timing out. **/ static const char * const LJM_ETHERNET_OPEN_TIMEOUT_MS = "LJM_ETHERNET_OPEN_TIMEOUT_MS"; /** * Name: LJM_WIFI_OPEN_TIMEOUT_MS * Desc: The maximum number of milliseconds that LJM will wait for a device * being opened via TCP to respond before timing out. **/ static const char * const LJM_WIFI_OPEN_TIMEOUT_MS = "LJM_WIFI_OPEN_TIMEOUT_MS"; /** * Name: LJM_OPEN_TCP_DEVICE_TIMEOUT_MS * Desc: Sets both LJM_ETHERNET_OPEN_TIMEOUT_MS and LJM_WIFI_OPEN_TIMEOUT_MS. * Note: Write-only. May not be read. **/ static const char * const LJM_OPEN_TCP_DEVICE_TIMEOUT_MS = "LJM_OPEN_TCP_DEVICE_TIMEOUT_MS"; /** * Name: LJM_DEBUG_LOG_MODE * Desc: Any of the following modes: * Vals: 1 (default) - Never logs anything, regardless of LJM_DEBUG_LOG_LEVEL. * 2 - Log continuously to the log file according to LJM_DEBUG_LOG_LEVEL (see LJM_DEBUG_LOG_FILE). * 3 - Continuously stores a finite number of log messages, writes them to file upon error. **/ static const char * const LJM_DEBUG_LOG_MODE = "LJM_DEBUG_LOG_MODE"; enum { LJM_DEBUG_LOG_MODE_NEVER = 1, LJM_DEBUG_LOG_MODE_CONTINUOUS = 2, LJM_DEBUG_LOG_MODE_ON_ERROR = 3 }; /** * Name: LJM_DEBUG_LOG_LEVEL * Desc: The level of priority that LJM will log. Levels that are lower than * the current LJM_DEBUG_LOG_LEVEL are not logged. For example, if log * priority is set to LJM_WARNING, messages with priority level * LJM_WARNING and greater are logged to the debug file. * Vals: See below. * Note: LJM_PACKET is the default value. **/ static const char * const LJM_DEBUG_LOG_LEVEL = "LJM_DEBUG_LOG_LEVEL"; enum { LJM_STREAM_PACKET = 1, LJM_TRACE = 2, LJM_DEBUG = 4, LJM_INFO = 6, LJM_PACKET = 7, LJM_WARNING = 8, LJM_USER = 9, LJM_ERROR = 10, LJM_FATAL = 12 }; /** * Name: LJM_DEBUG_LOG_BUFFER_MAX_SIZE * Desc: The number of log messages LJM's logger buffer can hold. **/ static const char * const LJM_DEBUG_LOG_BUFFER_MAX_SIZE = "LJM_DEBUG_LOG_BUFFER_MAX_SIZE"; /** * Name: LJM_DEBUG_LOG_SLEEP_TIME_MS * Desc: The number of milliseconds the logger thread will sleep for between * flushing the messages in the logger buffer to the log file. * Note: See also LJM_DEBUG_LOG_BUFFER_MAX_SIZE **/ static const char * const LJM_DEBUG_LOG_SLEEP_TIME_MS = "LJM_DEBUG_LOG_SLEEP_TIME_MS"; /** * Name: LJM_LIBRARY_VERSION * Desc: Returns the current version of LJM. This will match LJM_VERSION (at * the top of this header file) if you are using the executable LJM that * corresponds to this header file. **/ static const char * const LJM_LIBRARY_VERSION = "LJM_LIBRARY_VERSION"; /** * Name: LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS * Desc: A mode that sets whether or not LJM will automatically send/receive * multiple Feedback commands when the desired operations would exceed * the maximum packet length. This mode is relevant to Easy functions * such as LJM_eReadNames. * Vals: 0 - Disable * Anything else - Enable (default) **/ static const char * const LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS = "LJM_ALLOWS_AUTO_MULTIPLE_FEEDBACKS"; /** * Name: LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES * Desc: A mode that sets whether or not LJM will automatically condense * single address reads/writes into array reads/writes, which minimizes * packet size. This mode is relevant to Easy functions such as * LJM_eReadNames. * Vals: 0 - Disable * Anything else - Enable (default) **/ static const char * const LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES = "LJM_ALLOWS_AUTO_CONDENSE_ADDRESSES"; /** * Name: LJM_AUTO_RECONNECT_STICKY_CONNECTION * Desc: Sets whether or not LJM attempts to reconnect disrupted / disconnected * connections according to same connection type as the original handle. * Vals: 0 - Disable * 1 - Enable (default) **/ static const char * const LJM_AUTO_RECONNECT_STICKY_CONNECTION = "LJM_AUTO_RECONNECT_STICKY_CONNECTION"; /** * Name: LJM_AUTO_RECONNECT_STICKY_SERIAL * Desc: Sets whether or not LJM attempts to reconnect disrupted / disconnected * connections according to same serial number as the original handle. * Vals: 0 - Disable * 1 - Enable (default) **/ static const char * const LJM_AUTO_RECONNECT_STICKY_SERIAL = "LJM_AUTO_RECONNECT_STICKY_SERIAL"; /** * Name: LJM_OPEN_MODE * Desc: Specifies the mode of interaction LJM will use when communicating with * opened devices. * Vals: See following values. * Note: See LJM_KEEP_OPEN and LJM_OPEN_MODE. **/ static const char * const LJM_OPEN_MODE = "LJM_OPEN_MODE"; enum { /** * Name: LJM_KEEP_OPEN * Desc: A LJM_OPEN_MODE that claims ownership of each opened device until * the device is explicitly closed. In this mode, LJM maintains a * connection to each opened device at all times. * Note: This is a somewhat faster mode, but it is not multi-process friendly. * If there is another process trying to access a device that is opened * with LJM using this mode, it will not be able to. **/ LJM_KEEP_OPEN = 1, /** * THIS MODE IS NOT YET IMPLEMENTED * Name: LJM_KEEP_OPEN * Desc: A multi-process friendly LJM_OPEN_MODE that does not claim ownership * of any opened devices except when the device is being communicated * with. In this mode, LJM will automatically close connection(s) to * devices that are not actively sending/receiving communications and * automatically reopen connection(s) when needed. * Note: This mode is slightly slower, but allows other processes/programs to * access a LJM-opened device without needing to close the device with * LJM first. * When using LJM_KEEP_OPEN mode, LJM_Close or LJM_CloseAll still need * to be called (to clean up memory). **/ LJM_OPEN_CLOSE = 2 }; /** * Name: LJM_MODBUS_MAP_CONSTANTS_FILE * Desc: Specifies absolute or relative path of the constants file to use for * functions that use the LJM Name functionality, such as * LJM_NamesToAddresses and LJM_eReadName. **/ static const char * const LJM_MODBUS_MAP_CONSTANTS_FILE = "LJM_MODBUS_MAP_CONSTANTS_FILE"; /** * Name: LJM_ERROR_CONSTANTS_FILE * Desc: Specifies absolute or relative path of the constants file to use for * LJM_ErrorToString. **/ static const char * const LJM_ERROR_CONSTANTS_FILE = "LJM_ERROR_CONSTANTS_FILE"; /** * Name: LJM_DEBUG_LOG_FILE * Desc: Describes the absolute or relative path of the file to output log * messages to. * Note: See LJM_DEBUG_LOG_MODE and LJM_DEBUG_LOG_LEVEL. **/ static const char * const LJM_DEBUG_LOG_FILE = "LJM_DEBUG_LOG_FILE"; /** * Name: LJM_CONSTANTS_FILE * Desc: Sets LJM_MODBUS_MAP_CONSTANTS_FILE and LJM_ERROR_CONSTANTS_FILE at the same * time, as an absolute or relative file path. * Note: Cannot be read, since LJM_MODBUS_MAP_CONSTANTS_FILE and * LJM_ERROR_CONSTANTS_FILE can be different files. **/ static const char * const LJM_CONSTANTS_FILE = "LJM_CONSTANTS_FILE"; /** * Name: LJM_DEBUG_LOG_FILE_MAX_SIZE * Desc: The maximum size of the log file in number of characters. * Note: This is an approximate limit. **/ static const char * const LJM_DEBUG_LOG_FILE_MAX_SIZE = "LJM_DEBUG_LOG_FILE_MAX_SIZE"; /** * Name: LJM_STREAM_AIN_BINARY * Desc: Sets whether data returned from LJM_eStreamRead will be * calibrated or uncalibrated. * Vals: 0 - Calibrated floating point AIN data (default) * 1 - Uncalibrated binary AIN data **/ static const char * const LJM_STREAM_AIN_BINARY = "LJM_STREAM_AIN_BINARY"; /** * Name: LJM_STREAM_SCANS_RETURN * Desc: Sets how LJM_eStreamRead will return data. * Note: Does not affect currently running or already initialized streams. **/ static const char * const LJM_STREAM_SCANS_RETURN = "LJM_STREAM_SCANS_RETURN"; enum { /** * Name: LJM_STREAM_SCANS_RETURN_ALL * Desc: A mode that will cause LJM_eStreamRead to sleep until the full * ScansPerRead scans are collected by LJM. * Note: ScansPerRead is a parameter of LJM_eStreamStart. * Note: This mode may not be apporpriate for stream types that are not * consistently timed, such as gate stream mode or external clock stream * mode. **/ LJM_STREAM_SCANS_RETURN_ALL = 1, /** * Name: LJM_STREAM_SCANS_RETURN_ALL_OR_NONE * Desc: A mode that will cause LJM_eStreamRead to never sleep, and instead * either: * consume ScansPerRead scans and return LJME_NOERROR, or * consume no scans and return LJME_NO_SCANS_RETURNED. * LJM_eStreamRead will consume ScansPerRead if the LJM handle has * received ScansPerRead or more scans, otherwise it will consume none. * Note: ScansPerRead is a parameter of LJM_eStreamStart. **/ LJM_STREAM_SCANS_RETURN_ALL_OR_NONE = 2 /** * Name: LJM_STREAM_SCANS_RETURN_AVAILABLE * Desc: A mode that will cause LJM_eStreamRead to never sleep, and always * consume the number of scans that the LJM handle has received, up to * a maximum of ScansPerRead. Fills the excess scan places in aData * not read, if any, with LJM_SCAN_NOT_READ. * Note: ScansPerRead is a parameter of LJM_eStreamStart. * TODO: LJM_STREAM_SCANS_RETURN_AVAILABLE is not currently implemented. **/ // LJM_STREAM_SCANS_RETURN_AVAILABLE = 3 }; /** * Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE * Desc: Sets how stream should time out. * Note: Does not affect currently running or already initialized streams. **/ static const char * const LJM_STREAM_RECEIVE_TIMEOUT_MODE = "LJM_STREAM_RECEIVE_TIMEOUT_MODE"; enum { /** * Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE_CALCULATED * Desc: Calculates how long the stream timeout should be, according to the * scan rate reported by the device. * Note: This is the default LJM_STREAM_RECEIVE_TIMEOUT_MODE. **/ LJM_STREAM_RECEIVE_TIMEOUT_MODE_CALCULATED = 1, /** * Name: LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL * Desc: Manually sets how long the stream timeout should be. * Note: The actual stream timeout value is set via * LJM_STREAM_RECEIVE_TIMEOUT_MS. **/ LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL = 2 }; /** * Name: LJM_STREAM_RECEIVE_TIMEOUT_MS * Desc: Manually sets the stream receive timeout in milliseconds. Writing to * this configuration sets LJM_STREAM_RECEIVE_TIMEOUT_MODE to be * LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL. * Note: 0 is never timeout. * Note: Only affects currently running or already initialized streams if those * streams were initialized with a LJM_STREAM_RECEIVE_TIMEOUT_MODE of * LJM_STREAM_RECEIVE_TIMEOUT_MODE_MANUAL. **/ static const char * const LJM_STREAM_RECEIVE_TIMEOUT_MS = "LJM_STREAM_RECEIVE_TIMEOUT_MS"; /** * Name: LJM_STREAM_TRANSFERS_PER_SECOND * Desc: Sets/gets the number of times per second stream threads attempt to * read from the stream. * Note: Does not affect currently running or already initialized streams. **/ static const char * const LJM_STREAM_TRANSFERS_PER_SECOND = "LJM_STREAM_TRANSFERS_PER_SECOND"; /** * Name: LJM_RETRY_ON_TRANSACTION_ID_MISMATCH * Desc: Sets/gets whether or not LJM will automatically retry an operation if * an LJME_TRANSACTION_ID_ERR occurs. * Vals: 0 - Disable * 1 - Enable (default) **/ static const char * const LJM_RETRY_ON_TRANSACTION_ID_MISMATCH = "LJM_RETRY_ON_TRANSACTION_ID_MISMATCH"; /** * Name: LJM_OLD_FIRMWARE_CHECK * Desc: Sets/gets whether or not LJM will check the constants file (see * LJM_CONSTANTS_FILE) to make sure the firmware of the current device is * compatible with the Modbus register(s) being read from or written to, * when applicable. When device firmware is lower than fwmin for the * register(s) being read/written, LJM will return LJME_OLD_FIRMWARE and * not perform the Modbus operation(s). * Vals: 0 - Disable * 1 - Enable (default) * Note: When enabled, LJM will perform a check that is linear in size * proportional to the number of register entries in the constants file * for each address/name being read/written. **/ static const char * const LJM_OLD_FIRMWARE_CHECK = "LJM_OLD_FIRMWARE_CHECK"; /** * Name: LJM_ZERO_LENGTH_ARRAY_MODE * Desc: Determines the behavior of array read/write functions when the array * size is 0. **/ static const char * const LJM_ZERO_LENGTH_ARRAY_MODE = "LJM_ZERO_LENGTH_ARRAY_MODE"; enum { /** * Name: LJM_ZERO_LENGTH_ARRAY_ERROR * Desc: Sets LJM to return an error when an array of size 0 is detected. **/ LJM_ZERO_LENGTH_ARRAY_ERROR = 1, /** * Name: LJM_ZERO_LENGTH_ARRAY_IGNORE_OPERATION * Desc: Sets LJM to ignore the operation when all arrays in the * operation are of size 0. **/ LJM_ZERO_LENGTH_ARRAY_IGNORE_OPERATION = 2 }; // Config functions /** * Name: LJM_WriteLibraryConfigS * Desc: Writes/sets a library configuration/setting. * Para: Parameter, the name of the configuration setting. Not * case-sensitive. Must null-terminate. * Value, the config value to apply to Parameter. * Retr: LJM_NOERROR for success, * LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown. * Note: See "Config Parameters" for valid Parameters and "Config Values" for * valid Values. **/ LJM_ERROR_RETURN LJM_WriteLibraryConfigS(const char * Parameter, double Value); /** * Name: LJM_WriteLibraryConfigStringS * Desc: Writes/sets a library configuration/setting. * Para: Parameter, the name of the configuration setting. Not * case-sensitive. Must null-terminate. * String, the config value string to apply to Parameter. Must * null-terminate. Must not be of size greater than * LJM_MAX_NAME_SIZE, including null-terminator. * Retr: LJM_NOERROR for success, * LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown * Note: See "Config Parameters" for valid Parameters and "Config Values" for * valid Values. **/ LJM_ERROR_RETURN LJM_WriteLibraryConfigStringS(const char * Parameter, const char * String); /** * Name: LJM_ReadLibraryConfigS * Desc: Reads a configuration/setting from the library. * Para: Parameter, the name of the configuration setting. Not * case-sensitive. Must null-terminate. * Value, return value representing the config value. * Retr: LJM_NOERROR for success, * LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown. * Note: See "Config Parameters" for valid Parameters and "Config Values" for * valid Values. **/ LJM_ERROR_RETURN LJM_ReadLibraryConfigS(const char * Parameter, double * Value); /** * Name: LJM_ReadLibraryConfigStringS * Desc: Reads a configuration/setting from the library. * Para: Parameter, the name of the configuration setting. Not * case-sensitive. Must null-terminate. * string, return value representing the config string. Must be * pre-allocated to size LJM_MAX_NAME_SIZE. * Retr: LJM_NOERROR for success, * LJME_INVALID_CONFIG_NAME for a Parameter value that is unknown. * Note: See "Config Parameters" for valid Parameters and "Config Values" for * valid Values. **/ LJM_ERROR_RETURN LJM_ReadLibraryConfigStringS(const char * Parameter, char * String); /** * Desc: Load all the configuration values in a specified file. * Para: FileName, a relative or absolute file location. "default" maps to the * default configuration file ljm_startup_config.json in the * constants file location. Must null-terminate. **/ LJM_ERROR_RETURN LJM_LoadConfigurationFile(const char * FileName); /****************** * Log Functions * ******************/ /** * Name: LJM_Log * Desc: Sends a message of the specified level to the LJM debug logger. * Para: Level, the level to output the message at. See LJM_DEBUG_LOG_LEVEL. * String, the debug message to be written to the log file. * Note: By default, LJM_DEBUG_LOG_MODE is to never log, so LJM does not output * any log messages, even from this function. * Note: For more information on the LJM debug logger, see LJM_DEBUG_LOG_MODE, * LJM_DEBUG_LOG_LEVEL, LJM_DEBUG_LOG_BUFFER_MAX_SIZE, * LJM_DEBUG_LOG_SLEEP_TIME_MS, LJM_DEBUG_LOG_FILE, * LJM_DEBUG_LOG_FILE_MAX_SIZE **/ LJM_ERROR_RETURN LJM_Log(int Level, const char * String); /** * Name: LJM_ResetLog * Desc: Clears all characters from the debug log file. * Note: See the LJM configuration properties for Log-related properties. **/ LJM_ERROR_RETURN LJM_ResetLog(); #ifdef __cplusplus } #endif #endif // #define LAB_JACK_M_HEADER
76,915
C
43.980117
129
0.680894
adegirmenci/HBL-ICEbot/old/frmgrab.cpp
#include "frmgrab.h" #include "ui_frmgrab.h" FrmGrab::FrmGrab(QWidget *parent) : QWidget(parent), ui(new Ui::FrmGrab) { ui->setupUi(this); m_fg = NULL; m_isInitialized = false; m_isConnected = false; m_numFramesWritten = 0; } FrmGrab::~FrmGrab() { frmGrabDisconnect(); delete ui; } bool FrmGrab::frmGrabConnect() { m_isConnected = false; m_fg = FrmGrabLocal_Open(); if(!(m_fg == NULL)) { m_isConnected = FrmGrab_Start(m_fg); // set global variable to true to indicate frmGrabber is initialized if(m_isConnected) qDebug() << "FrmGrab started."; else qDebug() << "FrmGrab failed to start."; } else { ui->statusLineEdit->setText("Failed to open device!"); qDebug() << "Failed to open device!"; } return m_isConnected; } bool FrmGrab::SetFileName(const QString &fileName) { QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope if(!m_txtFile.isOpen()) // file is not open { m_txtFile.setFileName(fileName); return true; } else // file is already open { return false; } } bool FrmGrab::frmGrabInitialize(const char *location) { bool state = false; if(m_isConnected && (!m_isInitialized) ) // successfully connected and not alreadxy initialized { qDebug() << "Initializing file."; QString t = getCurrDateTimeFileStr(); // get date time now m_saveDir.clear(); // clear filename m_saveDir.append("RECORDED_FRMGRAB/").append(t); // set the directory // check if the directory exists, if not, create it QDir dir; if( ! dir.exists(m_saveDir) ){ if( dir.mkpath(m_saveDir) ) { qDebug() << "Folder created: " << m_saveDir; state = true; } else qDebug() << "Folder creation failed: " << m_saveDir; } // set file name m_imgFname_pre = getCurrDateTimeFileStr(); m_txtFname = m_saveDir; m_txtFname.append("/"); m_txtFname.append(m_imgFname_pre); m_txtFname.append("_"); m_txtFname.append(location); m_txtFname.append(".txt"); state = SetFileName(m_txtFname); //Open file for write and append if(!m_txtFile.open(QIODevice::WriteOnly | QIODevice::Append)) { qDebug() << "File could not be opened: " << m_txtFile.fileName(); state = false; } else { m_textStream.setDevice(&m_txtFile); m_textStream << "File opened at: " << getCurrDateTimeStr() << '\n'; m_textStream << location << endl; // write to file where initialize is called from m_textStream << "File Name \t Time (s)" << endl; // write header state = state && true; qDebug() << "File opened:" << m_txtFile.fileName(); } } m_isInitialized = state; qDebug() << "State is " << state; return state; // return false if already initialized or if the file couldn't be opened } bool FrmGrab::grabFrame() { bool state = false; if(m_fg == NULL) { ui->statusLineEdit->setText("Failed to read device."); } else { std::shared_ptr<Frame> newFrame( new Frame ); newFrame->timestamp_ = m_epoch.elapsed()/1000.; // get time stamp m_frame = FrmGrab_Frame(m_fg, V2U_GRABFRAME_FORMAT_BGR24, NULL); m_imgSize = cv::Size(m_frame->mode.width, m_frame->mode.height); //qDebug() << m_imgSize.width << " x " << m_imgSize.height; if (m_frame) { m_src = cv::Mat(m_imgSize,CV_8UC3); m_src.data = (uchar*)(m_frame->pixbuf); cv::cvtColor(m_src, m_dst, CV_BGR2GRAY); newFrame->image_ = m_dst; // add frame to container FrmGrab_Release(m_fg, m_frame); newFrame->index_ = m_numFramesWritten; m_numFramesWritten++; QMutexLocker locker(&m_mutex); m_frmList.push_back( newFrame ); state = true; } } return state; } bool FrmGrab::saveFrame(std::shared_ptr<Frame> frm) { bool state = false; if(m_isInitialized) // not already initialized { QString m_imgFname = m_saveDir; // contains file name of frame m_imgFname.append("/").append(m_imgFname_pre); // populate m_imgFname with index m_imgFname.append( QString("_%1.jpg").arg(frm->index_) ); // save frame //state = frame->image_.save(m_imgFname, "JPG", 100); cv::imwrite(m_imgFname.toStdString().c_str(), frm->image_ ); // write frame // output to text if(m_txtFile.isOpen()) { m_textStream << m_imgFname_pre << QString("_%1.jpg").arg(frm->index_) << "\t" << QString::number(frm->timestamp_, 'f', 6) << '\n'; m_textStream.flush(); state = true; } } // save image to file using QtConcurrent calls return state; } bool FrmGrab::frmGrabDisconnect() { FrmGrab_Close(m_fg); // if(m_fg == NULL) // return true; // else // return false; return true; } bool FrmGrab::setEpoch(const QTime &epoch) { m_epoch = epoch; return true; } // ------------------------------ // // GUI INTERACTION IMPLEMENTATION // // ------------------------------ // void FrmGrab::on_connectButton_clicked() { if( frmGrabConnect() ) { ui->connectButton->setEnabled(false); ui->initButton->setEnabled(true); ui->disconnectButton->setEnabled(true); ui->statusLineEdit->setText("Connected."); } else ui->statusLineEdit->setText("Failed to connect."); } void FrmGrab::on_initButton_clicked() { if( frmGrabInitialize("GUI_Button") ) { ui->initButton->setEnabled(false); ui->statusLineEdit->setText("Initialized."); ui->acquireButton->setEnabled(true); ui->saveButton->setEnabled(true); } else { ui->statusLineEdit->setText("Failed to initialize."); ui->acquireButton->setEnabled(false); ui->saveButton->setEnabled(false); } } void FrmGrab::on_disconnectButton_clicked() { if( frmGrabDisconnect() ) { ui->connectButton->setEnabled(true); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(false); ui->acquireButton->setEnabled(false); ui->saveButton->setEnabled(false); ui->statusLineEdit->setText("Disconnected."); } else ui->statusLineEdit->setText("Failed to disconnect."); } void FrmGrab::on_acquireButton_clicked() { for( int i = 0; i < 120; i++) grabFrame(); if( grabFrame() ) ui->statusLineEdit->setText("Frame grabbed."); else ui->statusLineEdit->setText("Failed to grab frame."); } void FrmGrab::on_saveButton_clicked() { while( m_frmList.size() > 0) { if( saveFrame(m_frmList.front()) ) { ui->statusLineEdit->setText("Frame saved."); QMutexLocker locker(&m_mutex); m_frmList.pop_front(); } else ui->statusLineEdit->setText("Failed to save frame."); } ui->statusLineEdit->setText("No more frames to write."); } // ------------------------------------- // // GUI INTERACTION IMPLEMENTATION - DONE // // ------------------------------------- // inline const QString getCurrDateTimeFileStr() { return QDateTime::currentDateTime().toString("ddMMyyyy_hhmmsszzz"); } inline const QString getCurrDateTimeStr() { return QDateTime::currentDateTime().toString("dd/MM/yyyy - hh:mm:ss.zzz"); }
7,807
C++
24.025641
113
0.55937
adegirmenci/HBL-ICEbot/old/frmgrab.h
#ifndef FRMGRAB_H #define FRMGRAB_H #include <QWidget> #include <QString> #include <QFile> #include <QTextStream> #include <QImage> #include <list> #include <memory> #include <QTime> #include <QDir> #include <QDebug> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> //#include <epiphan/include/v2u_defs.h> #include <epiphan/frmgrab/include/frmgrab.h> //#include <v2u_defs.h> //#include <frmgrab.h> //#include "epiphan/include/v2u_defs.h" //#include "epiphan/frmgrab/include/frmgrab.h" /** Frame structure. * This will hold an image, a timestamp, and an index. */ struct Frame{ cv::Mat image_; /*!< Image data. */ double timestamp_; /*!< Timestamp, msec since some epoch. */ int index_; /*!< Index value of Frame, indicate order of acquisition. */ //! Constructor. Frame() { image_ = NULL; timestamp_ = -1.; index_ = -1; } Frame(cv::Mat& img, double ts, int id) { image_ = img; timestamp_ = ts; index_ = id; } }; namespace Ui { class FrmGrab; } class FrmGrab : public QWidget { Q_OBJECT public: explicit FrmGrab(QWidget *parent = 0); bool setEpoch(const QTime &epoch); ~FrmGrab(); private slots: void on_connectButton_clicked(); void on_initButton_clicked(); void on_disconnectButton_clicked(); void on_acquireButton_clicked(); void on_saveButton_clicked(); private: Ui::FrmGrab *ui; // File names for frame grabber use QString m_saveDir; // the directory where files will be saved QString m_txtFname; // contains file name of each frame and its timestamp QString m_imgFname_pre; // filename prepend // File for time stamps : open file for output, delete content if already exists QFile m_txtFile; QTextStream m_textStream; bool m_isConnected; bool m_isInitialized; int m_numFramesWritten; QTime m_epoch; // when was the GUI started - can be set externally //cv::VideoCapture m_frmGrab_cap; FrmGrabber* m_fg; V2U_GrabFrame2* m_frame; cv::Mat m_src; // Image containers cv::Mat m_dst; cv::Size m_imgSize; std::list< std::shared_ptr<Frame> > m_frmList; // DO NOT use m_mutex.lock() // INSTEAD use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex m_mutex; bool frmGrabConnect(); bool SetFileName(const QString &fileName); bool frmGrabInitialize(const char* location); bool grabFrame(); bool saveFrame(std::shared_ptr<Frame> frm); bool frmGrabDisconnect(); }; inline const QString getCurrDateTimeFileStr(); inline const QString getCurrDateTimeStr(); #endif // FRMGRAB_H
2,761
C
21.455284
84
0.661355
adegirmenci/HBL-ICEbot/old/Point.cpp
#include "Point.h" Point::Point() { m_x = 0.0; m_y = 0.0; m_z = 0.0; } Point::Point(double x, double y, double z) { m_x = x; m_y = y; m_z = z; } void Point::update(double px, double py, double pz) { m_x = px; m_y = py; m_z = pz; } // Distance to another point. Pythagorean thm. double Point::dist(const Point other) { double xd = m_x - other.m_x; double yd = m_y - other.m_y; double zd = m_z - other.m_z; return sqrt(xd*xd + yd*yd + zd*zd); } // Add or subtract two points. Point Point::operator+(const Point& rhs) { return Point(m_x + rhs.getx(), m_y + rhs.gety(), m_z + rhs.getz()); } Point Point::operator-(const Point& rhs) { return Point(m_x - rhs.getx(), m_y - rhs.gety(), m_z - rhs.getz()); } Point Point::operator*(const double k) { return Point(m_x*k, m_y*k, m_z*k); } Point Point::operator/(const double k) { return Point(m_x/k, m_y/k, m_z/k); } Point& Point::operator=(const Point& rhs) { m_x = rhs.getx(); m_y = rhs.gety(); m_z = rhs.getz(); return *this; } // Move the existing point. void Point::move(double a, double b, double c) { m_x += a; m_y += b; m_z += c; }
1,253
C++
16.416666
51
0.523543
adegirmenci/HBL-ICEbot/old/Point.h
#ifndef POINT_H #define POINT_H #include <math.h> class Point { private: double m_x; double m_y; double m_z; public: Point(); Point(double x, double y, double z); ~Point(){} // helper functions - data access void setx(double pk) { m_x = pk; } void sety(double pk) { m_y = pk; } void setz(double pk) { m_z = pk; } // helper functions - modifiers double getx() const { return m_x; } double gety() const { return m_y; } double getz() const { return m_z; } void update(double px, double py, double pz); double dist(const Point other); Point operator+(const Point& rhs); Point operator-(const Point& rhs); Point operator*(const double k); Point operator/(const double k); Point& operator=(const Point& rhs); void move(double a, double b, double c); }; #endif // POINT_H
861
C
20.549999
49
0.608595
adegirmenci/HBL-ICEbot/old/labjack.h
#ifndef LABJACK_H #define LABJACK_H #include <QWidget> #include <QFile> #include <QTextStream> #include <QDebug> #include <QPointer> #include <QThread> #include <QTimer> #include <QDateTime> #include "LabJackUD.h" // ------------------------------------------- \\ // -------------- LabJackWorker -------------- \\ // ------------------------------------------- \\ class LabJackWorker : public QObject { Q_OBJECT public: LabJackWorker(); LabJackWorker(int samplesPsec); ~LabJackWorker(); public slots: bool ConnectToLabJack(); // helper function to connect to LabJack bool SetFileName(const QString &fileName); bool ConfigureStream(); bool StartStream(); bool StopStream(); bool DisconnectFromLabJack(); // helper function to disconnect from LabJack void setEpoch(const QTime &epoch); bool workerIsReady(); bool workerIsRecording(); private slots: bool ReadStream(); signals: void finished(); private: QPointer<QTimer> m_eventTimer; // timer for event loop QFile m_outputFile; // output file QTextStream m_textStream; int m_timeCurr; QTime m_epoch; // when was the GUI started - can be set externally // Flag to keep track of connection bool m_LabJackReady; // DO NOT use m_mutex.lock() // INSTEAD use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex m_mutex; // LabJack specific variables LJ_ERROR m_lngErrorcode; LJ_HANDLE m_lngHandle; long m_lngGetNextIteration; unsigned long long int m_i, m_k; long m_lngIOType, m_lngChannel; double m_dblValue, m_dblCommBacklog, m_dblUDBacklog; double m_scanRate; //scan rate = sample rate / #channels int m_delayms; double m_numScans; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000). double m_numScansRequested; double *m_adblData; long m_padblData; // LabJack specific variables \\ bool ErrorHandler(LJ_ERROR lngErrorcode, long lngLineNumber, long lngIteration); }; // ------------------------------------- \\ // -------------- LabJack -------------- \\ // ------------------------------------- \\ namespace Ui { class LabJack; } class LabJack : public QWidget { Q_OBJECT QPointer<QThread> workerThread; public: explicit LabJack(QWidget *parent = 0); ~LabJack(); bool isReady(); bool isRecording(); bool setWorkerEpoch(const QTime &epoch); bool setWorkerFileName(const QString &fileName); public slots: signals: private slots: void on_connectButton_clicked(); void on_disconnectButton_clicked(); void on_initializeLJbutton_clicked(); void on_startRecordButton_clicked(); void on_stopRecordButton_clicked(); private: Ui::LabJack *ui; QPointer<LabJackWorker> worker; bool ConfigureWorker(int samplesPsec); }; inline const QString getCurrTimeStr(); inline const QString getCurrDateTimeStr(); #endif // LABJACK_H
3,010
C
22.341085
109
0.640199
adegirmenci/HBL-ICEbot/old/labjack.cpp
#include "labjack.h" #include "ui_labjack.h" // ------------------------------------------- \\ // -------------- LabJackWorker -------------- \\ // ------------------------------------------- \\ LabJackWorker::LabJackWorker() { // default samples per second is 1000 LabJackWorker(1000); } LabJackWorker::LabJackWorker(int samplesPsec) { QMutexLocker locker(&m_mutex); // lock mutex m_lngErrorcode = 0; m_lngHandle = 0; m_i = 0; m_k = 0; m_lngIOType = 0; m_lngChannel = 0; m_dblValue = 0; m_dblCommBacklog = 0; m_dblUDBacklog = 0; m_scanRate = samplesPsec; //scan rate = sample rate / #channels m_delayms = 1000; // 1 seconds per 1000 samples m_numScans = 2*m_scanRate*m_delayms/1000; //Max number of scans per read. 2x the expected # of scans (2*scanRate*delayms/1000). m_adblData = (double *)calloc( m_numScans, sizeof(double)); //Max buffer size (#channels*numScansRequested) m_padblData = (long)&m_adblData[0]; m_LabJackReady = false; //m_keepRecording = false; // flag for the while loop m_eventTimer = new QTimer(this->thread()); connect(m_eventTimer, SIGNAL(timeout()), this, SLOT(ReadStream())); // mutex unlocks when locker goes out of scope } LabJackWorker::~LabJackWorker() { qDebug() << "[Destroy LabJack Worker] Disconnect From Labjack" << DisconnectFromLabJack(); qDebug() << "[Destroy LabJack Worker] DeleteLater m_eventTimer"; if(!m_eventTimer.isNull()) delete m_eventTimer;//->deleteLater(); qDebug() << "[Destroy LabJack Worker] Free m_adblData"; free( m_adblData ); } bool LabJackWorker::ConnectToLabJack() { bool success = false; QMutexLocker locker(&m_mutex); // lock mutex //Open the first found LabJack U6. m_lngErrorcode = OpenLabJack(LJ_dtU6, LJ_ctUSB, "1", 1, &m_lngHandle); success = ErrorHandler(m_lngErrorcode, __LINE__, 0); //Read and display the hardware version of this U6. m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_CONFIG, LJ_chHARDWARE_VERSION, &m_dblValue, 0); printf("U6 Hardware Version = %.3f\n\n", m_dblValue); ErrorHandler(m_lngErrorcode, __LINE__, 0); //Read and display the firmware version of this U6. m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, &m_dblValue, 0); printf("U6 Firmware Version = %.3f\n\n", m_dblValue); ErrorHandler(m_lngErrorcode, __LINE__, 0); return success; // mutex unlocks when locker goes out of scope } bool LabJackWorker::SetFileName(const QString &fileName) { QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope if(!m_outputFile.isOpen()) // file is not open { m_outputFile.setFileName(fileName); return true; } else // file is already open { return false; } } bool LabJackWorker::ConfigureStream() { bool success = false; QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope //Open file for write and append if(!m_outputFile.open(QIODevice::WriteOnly | QIODevice::Append)) { qDebug() << "File could not be opened: " << m_outputFile.fileName(); return false; } else { m_textStream.setDevice(&m_outputFile); m_textStream << "File opened at: " << getCurrDateTimeStr() << '\n'; } //Configure the stream: //Configure resolution of the analog inputs (pass a non-zero value for quick sampling). //See section 2.6 / 3.1 for more information. m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chAIN_RESOLUTION, 0, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); // Configure the analog input range on channel 0 for bipolar + -5 volts. //m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_AIN_RANGE, 0, LJ_rgBIP5V, 0, 0); //ErrorHandler(m_lngErrorcode, __LINE__, 0); //Set the scan rate. m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_SCAN_FREQUENCY, m_scanRate, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); //Give the driver a 5 second buffer (scanRate * 1 channels * 5 seconds). m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_BUFFER_SIZE, m_scanRate * 1 * 5, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); //Configure reads to retrieve whatever data is available without waiting (wait mode LJ_swNONE). m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioPUT_CONFIG, LJ_chSTREAM_WAIT_MODE, LJ_swNONE, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); //Define the scan list as AIN0. m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioCLEAR_STREAM_CHANNELS, 0, 0, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); m_lngErrorcode = AddRequest(m_lngHandle, LJ_ioADD_STREAM_CHANNEL, 0, 0, 0, 0); // first method for single ended reading - AIN0 ErrorHandler(m_lngErrorcode, __LINE__, 0); //Execute the list of requests. m_lngErrorcode = GoOne(m_lngHandle); success = ErrorHandler(m_lngErrorcode, __LINE__, 0); //Get all the results just to check for errors. m_lngErrorcode = GetFirstResult(m_lngHandle, &m_lngIOType, &m_lngChannel, &m_dblValue, 0, 0); success = success && ErrorHandler(m_lngErrorcode, __LINE__, 0); m_lngGetNextIteration = 0; //Used by the error handling function. while (m_lngErrorcode < LJE_MIN_GROUP_ERROR) { m_lngErrorcode = GetNextResult(m_lngHandle, &m_lngIOType, &m_lngChannel, &m_dblValue, 0, 0); if (m_lngErrorcode != LJE_NO_MORE_DATA_AVAILABLE) { success = success && ErrorHandler(m_lngErrorcode, __LINE__, m_lngGetNextIteration); } m_lngGetNextIteration++; } return m_LabJackReady = success; } bool LabJackWorker::StartStream() { QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope if(m_LabJackReady) // ready to read data { m_timeCurr = m_epoch.elapsed(); // msec since epoch //Start the stream. m_lngErrorcode = eGet(m_lngHandle, LJ_ioSTART_STREAM, 0, &m_dblValue, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); // Write start time if(m_outputFile.isOpen()) { m_textStream << "Epoch at: " << m_epoch.toString("dd/MM/yyyy - hh:mm:ss.zzz") << '\n'; m_textStream << "Recording started at: " << getCurrTimeStr() << '\n'; // write actual scan rate to file m_textStream << "Actual Scan Rate = " << m_dblValue << '\n'; m_textStream << "Time Since Epoch (ms) \t Voltage (V)" << '\n'; } else { qDebug() << getCurrTimeStr() << "[StartStream] File is closed."; return false; } qDebug() << "Starting timer."; m_eventTimer->start(m_delayms); if(m_eventTimer->isActive()) { qDebug() << "Timer started."; return true; } else { qDebug() << getCurrTimeStr() << "[StartStream] m_eventTimer is not active."; return false; } } else { qDebug() << getCurrTimeStr() << "[StartStream] LabJack is not ready."; return false; } } bool LabJackWorker::StopStream() { QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope if(m_eventTimer->isActive()) { m_eventTimer->stop(); while(m_eventTimer->isActive()) { ; // twiddle thumbs } m_lngErrorcode = eGet(m_lngHandle, LJ_ioSTOP_STREAM, 0, 0, 0); ErrorHandler(m_lngErrorcode, __LINE__, 0); m_textStream << "Recording stopped at: " << getCurrTimeStr() << '\n\n'; m_textStream.flush(); qDebug() << "Timer stopped."; return true; } else { qDebug() << "Timer already stopped."; return false; } } bool LabJackWorker::DisconnectFromLabJack() { bool success = StopStream(); QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope if(m_outputFile.isOpen()) { m_textStream.flush(); m_outputFile.flush(); m_outputFile.close(); } else qDebug() << "textStream is already closed!"; emit finished(); //this->moveToThread(this->thread()); return success; } void LabJackWorker::setEpoch(const QTime &epoch) { QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope m_epoch = epoch; } bool LabJackWorker::workerIsReady() { QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope bool result = m_LabJackReady; return result; } bool LabJackWorker::workerIsRecording() { QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope bool result = m_eventTimer->isActive(); return result; } bool LabJackWorker::ReadStream() { QTime tmr; tmr.start(); QMutexLocker locker(&m_mutex); // lock mutex // mutex unlocks when locker goes out of scope if(m_LabJackReady) { for (m_k = 0; m_k < m_numScans; m_k++) { m_adblData[m_k] = 9999.0; } //Read the data. We will request twice the number we expect, to //make sure we get everything that is available. //Note that the array we pass must be sized to hold enough SAMPLES, and //the Value we pass specifies the number of SCANS to read. m_numScansRequested = m_numScans; m_lngErrorcode = eGet(m_lngHandle, LJ_ioGET_STREAM_DATA, LJ_chALL_CHANNELS, &m_numScansRequested, m_padblData); //The displays the number of scans that were actually read. //printf("\nIteration # %d\n", i); //printf("Number scans read = %.0f\n", numScansRequested); //outputFile << "Number scans read = " << numScansRequested << std::endl; //This displays just the first and last scans. //printf("First scan = %.3f, %.3f\n", adblData[0], adblData[(int)numScansRequested - 1]); ErrorHandler(m_lngErrorcode, __LINE__, 0); //Retrieve the current Comm backlog. The UD driver retrieves stream data from //the U6 in the background, but if the computer is too slow for some reason //the driver might not be able to read the data as fast as the U6 is //acquiring it, and thus there will be data left over in the U6 buffer. //lngErrorcode = eGet(lngHandle, LJ_ioGET_CONFIG, LJ_chSTREAM_BACKLOG_COMM, &dblCommBacklog, 0); //printf("Comm Backlog = %.0f\n", dblCommBacklog); //Retrieve the current UD driver backlog. If this is growing, then the application //software is not pulling data from the UD driver fast enough. //lngErrorcode = eGet(lngHandle, LJ_ioGET_CONFIG, LJ_chSTREAM_BACKLOG_UD, &dblUDBacklog, 0); //printf("UD Backlog = %.0f\n", dblUDBacklog); double tick = 1000./((double)m_scanRate); // msec // Write to file if (m_outputFile.isOpen()) // file is ready { for (int idx = 0; idx < m_numScansRequested; idx++) { m_textStream << QString::number(m_timeCurr + idx*tick, 'f', 3) << '\t' << QString::number(m_adblData[idx], 'f', 6) << '\n'; } // update current time for next iteration m_timeCurr += m_numScansRequested*tick; m_textStream.flush(); m_i++; qDebug() << "Data acq took (ms): " << tmr.elapsed(); return true; } else // file is not ready { qDebug() << "Data acq took (ms): " << tmr.elapsed(); return false; } } else // LabJack not ready { qDebug() << "Data acq took (ms): " << tmr.elapsed(); return false; } } bool LabJackWorker::ErrorHandler(LJ_ERROR lngErrorcode, long lngLineNumber, long lngIteration) { char err[255]; if (lngErrorcode != LJE_NOERROR) { ErrorToString(lngErrorcode, err); qDebug() << "Error number = " << lngErrorcode; qDebug() << "Error string = " << err; qDebug() << "Source line number = " << lngLineNumber; qDebug() << "Iteration = " << lngIteration; if (lngErrorcode > LJE_MIN_GROUP_ERROR) { qDebug() << "FATAL ERROR!"; } return false; // there was an error } else return true; // no errors - success } // ------------------------------------- \\ // -------------- LabJack -------------- \\ // ------------------------------------- \\ LabJack::LabJack(QWidget *parent) : QWidget(parent), ui(new Ui::LabJack) { ui->setupUi(this); } LabJack::~LabJack() { if(ui->disconnectButton->isEnabled()) ui->disconnectButton->click(); // if(!workerThread.isNull()) // { // if(workerThread->isRunning()) // { // workerThread->quit(); // workerThread->terminate(); // workerThread->wait(); // if(!worker.isNull()) // { // delete worker;//->deleteLater(); // } // } // delete workerThread;//->deleteLater(); // } // if(!worker.isNull()) // { // delete worker;//->deleteLater(); // } delete ui; } bool LabJack::isReady() { if(workerThread->isRunning()) return worker->workerIsReady(); else return false; } bool LabJack::isRecording() { if(workerThread->isRunning()) return worker->workerIsRecording(); else return false; } bool LabJack::setWorkerEpoch(const QTime &epoch) { if(workerThread->isRunning()) { worker->setEpoch(epoch); return true; } else return false; } bool LabJack::setWorkerFileName(const QString &fileName) { if(workerThread->isRunning()) { if(!isRecording()) { worker->SetFileName(fileName); return true; } else return false; } else return false; } bool LabJack::ConfigureWorker(int samplesPsec) { workerThread = new QThread; worker = new LabJackWorker(samplesPsec); worker->moveToThread(workerThread); connect(worker, SIGNAL(finished()), workerThread, SLOT(quit())); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(workerThread, SIGNAL(finished()), workerThread, SLOT(deleteLater())); workerThread->start(); return workerThread->isRunning(); } void LabJack::on_connectButton_clicked() { // get the desired number of samples from the GUI int samplesPsec = ui->samplesPsecSpinBox->value(); bool result = ConfigureWorker(samplesPsec); // TODO: EPOCH SHOULD COME FROM MAIN GUI QTime tmp; tmp.start(); result = result && setWorkerEpoch(tmp); // TODO: FILENAME SHOULD COME FROM MAIN GUI result = result && setWorkerFileName("test.txt"); result = result && worker->ConnectToLabJack(); if( result ) { // update GUI elements ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->samplesPsecSpinBox->setEnabled(false); ui->statusLineEdit->setText("Connected"); ui->initializeLJbutton->setEnabled(true); } } void LabJack::on_disconnectButton_clicked() { worker->DisconnectFromLabJack(); // Stop collection, stop thread, delete worker //worker->StopStream(); // workerThread->quit(); // workerThread->terminate(); // workerThread->wait(); // delete worker;//->deleteLater(); // delete workerThread;//->deleteLater(); // update GUI elements ui->connectButton->setEnabled(true); ui->disconnectButton->setEnabled(false); ui->samplesPsecSpinBox->setEnabled(true); ui->statusLineEdit->setText("Disconnected"); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(false); ui->stopRecordButton->setEnabled(false); } void LabJack::on_initializeLJbutton_clicked() { bool result = worker->ConfigureStream(); if( result ) { // update GUI elements ui->statusLineEdit->setText("Initialized."); ui->initializeLJbutton->setEnabled(false); ui->startRecordButton->setEnabled(true); ui->stopRecordButton->setEnabled(false); } } void LabJack::on_startRecordButton_clicked() { bool result = worker->StartStream(); if( result ) { // update GUI elements ui->statusLineEdit->setText("Recording!"); ui->startRecordButton->setEnabled(false); ui->stopRecordButton->setEnabled(true); } } void LabJack::on_stopRecordButton_clicked() { bool result = worker->StopStream(); if( result ) { // update GUI elements ui->statusLineEdit->setText("Stopped! Ready."); ui->startRecordButton->setEnabled(true); ui->stopRecordButton->setEnabled(false); } } inline const QString getCurrTimeStr() { return QTime::currentTime().toString("HH.mm.ss.zzz"); } inline const QString getCurrDateTimeStr() { return QDateTime::currentDateTime().toString("dd/MM/yyyy - hh:mm:ss.zzz"); }
17,372
C++
28.445763
133
0.600679
adegirmenci/HBL-ICEbot/old/epos2.cpp
#include "epos2.h" #include "ui_epos2.h" #include <QDebug> epos2::epos2(QWidget *parent) : QWidget(parent), ui(new Ui::epos2) { ui->setupUi(this); m_KeyHandle = 0; //user has to open connection to motors using the GUI m_motorsEnabled = FALSE; m_transMotor.m_nodeID = TRANS_MOTOR_ID; m_pitchMotor.m_nodeID = PITCH_MOTOR_ID; m_yawMotor.m_nodeID = YAW_MOTOR_ID; m_rollMotor.m_nodeID = ROLL_MOTOR_ID; qDebug() << "Initizializing pointers to eposMotor"; m_motors.reserve(4); m_motors.push_back(QSharedPointer<eposMotor>(&m_transMotor)); m_motors.push_back(QSharedPointer<eposMotor>(&m_pitchMotor)); m_motors.push_back(QSharedPointer<eposMotor>(&m_yawMotor)); m_motors.push_back(QSharedPointer<eposMotor>(&m_rollMotor)); } epos2::~epos2() { on_connectionButtonBox_rejected(); //disable motors and close EPOS connection m_motors.clear(); qDebug() << "Cleared motor list."; //VCS_CloseAllDevices(&m_ulErrorCode); delete ui; } BOOL epos2::InitMotor(QSharedPointer<eposMotor> mot) { mot.data()->m_bMode = 0; mot.data()->m_lActualValue = 0; mot.data()->m_lStartPosition = 0; mot.data()->m_lTargetPosition = 0; //mot.data()->m_ulProfileVelocity = EPOS_VELOCITY; //mot.data()->m_ulProfileAcceleration = EPOS_ACCEL; //mot.data()->m_ulProfileDeceleration = EPOS_DECEL; WORD motorID = mot.data()->m_nodeID; ui->outputText->append(QString("Connecting to Node %1...").arg(motorID)); mot.data()->m_enabled = FALSE; if(m_KeyHandle) { //Clear Error History if(VCS_ClearFault(m_KeyHandle, motorID, &m_ulErrorCode)) { //Enable if( VCS_SetEnableState(m_KeyHandle, motorID, &m_ulErrorCode) ) { //Read Operation Mode if(VCS_GetOperationMode(m_KeyHandle, motorID, &(mot.data()->m_bMode), &m_ulErrorCode)) { //Read Position Profile Objects if(VCS_GetPositionProfile(m_KeyHandle, motorID, &(mot.data()->m_ulProfileVelocity), &(mot.data()->m_ulProfileAcceleration), &(mot.data()->m_ulProfileDeceleration), &m_ulErrorCode)) { //Write Profile Position Mode if(VCS_SetOperationMode(m_KeyHandle, motorID, OMD_PROFILE_POSITION_MODE, &m_ulErrorCode)) { //Write Profile Position Objects if(VCS_SetPositionProfile(m_KeyHandle, motorID, EPOS_VELOCITY, EPOS_ACCEL, EPOS_DECEL, &m_ulErrorCode)) { //Read Actual Position if(VCS_GetPositionIs(m_KeyHandle, motorID, &(mot.data()->m_lStartPosition), &m_ulErrorCode)) { ui->outputText->append("DONE!"); mot.data()->m_enabled = TRUE; } } } } } } } if(!mot.data()->m_enabled) { ui->outputText->append("Can't connect to motor!"); ShowErrorInformation(m_ulErrorCode); } } else { ui->outputText->append("Can't open device!"); mot.data()->m_enabled = FALSE; } return mot.data()->m_enabled; } BOOL epos2::DisableMotor(QSharedPointer<eposMotor> mot) { WORD nodeId = mot.data()->m_nodeID; //get motor ID mot.data()->m_enabled = FALSE; // set flag to false // disable motor BOOL result = VCS_SetDisableState(m_KeyHandle, nodeId, &m_ulErrorCode); if(result) qDebug() <<"Motor " << nodeId << " disabled."; else ShowErrorInformation(m_ulErrorCode); return result; } BOOL epos2::OpenDevice() //(WORD motorID) { ui->outputText->append("Opening connection to EPOS..."); if(m_KeyHandle) { //Close Previous Device VCS_CloseDevice(m_KeyHandle, &m_ulErrorCode); m_KeyHandle = 0; } else m_KeyHandle = 0; //Settings m_oImmediately = TRUE; m_oUpdateActive = FALSE; HANDLE hNewKeyHandle; hNewKeyHandle = VCS_OpenDeviceDlg(&m_ulErrorCode); if(hNewKeyHandle) m_KeyHandle = hNewKeyHandle; else return FALSE; // Set properties of each motor BOOL initSuccess = TRUE; initSuccess = initSuccess && InitMotor(m_motors[TRANS]); initSuccess = initSuccess && InitMotor(m_motors[PITCH]); initSuccess = initSuccess && InitMotor(m_motors[YAW]); initSuccess = initSuccess && InitMotor(m_motors[ROLL]); return initSuccess; } void epos2::moveMotor(long targetPos, QSharedPointer<eposMotor> mot, BOOL moveAbsOrRel) { if(moveAbsOrRel) mot.data()->m_lTargetPosition = targetPos; else mot.data()->m_lTargetPosition += targetPos; WORD usNodeId = mot.data()->m_nodeID; QElapsedTimer elTimer; qDebug() << "Using clock type " << elTimer.clockType(); elTimer.start(); if(mot.data()->m_enabled) { if(!VCS_MoveToPosition(m_KeyHandle, usNodeId, targetPos, moveAbsOrRel, m_oImmediately, &m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } } qDebug() << "Elapsed Time: " << elTimer.nsecsElapsed()/1000000. << " ms"; getMotorQC(mot); } void epos2::getMotorQC(QSharedPointer<eposMotor> mot) { WORD usNodeId = mot.data()->m_nodeID; QElapsedTimer elTimer; elTimer.start(); if(!VCS_GetPositionIs(m_KeyHandle, usNodeId, &(mot.data()->m_lStartPosition), &m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } qDebug() << "Elapsed Time: " << elTimer.nsecsElapsed()/1000000. << " ms"; qDebug() << "Motor is at " << mot.data()->m_lStartPosition << " qc"; } void epos2::haltMotor(QSharedPointer<eposMotor> mot) { WORD usNodeId = mot.data()->m_nodeID; if(!VCS_HaltPositionMovement(m_KeyHandle, usNodeId, &m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } } BOOL epos2::ShowErrorInformation(DWORD p_ulErrorCode) { char* pStrErrorInfo; const char* strDescription; if((pStrErrorInfo = (char*)malloc(100)) == NULL) { qDebug() << "Not enough memory to allocate buffer for error information string."; return FALSE; } if(VCS_GetErrorInfo(p_ulErrorCode, pStrErrorInfo, 100)) { strDescription = pStrErrorInfo; qDebug() << "Maxon: " << strDescription; free(pStrErrorInfo); return TRUE; } else { free(pStrErrorInfo); qDebug() << "Error information can't be read!"; return FALSE; } } void epos2::on_connectionButtonBox_accepted() { if(OpenDevice()) { m_motorsEnabled = TRUE; ui->enableNodeButton->setEnabled(false); ui->disableNodeButton->setEnabled(true); ui->moveAbsButton->setEnabled(true); ui->moveRelButton->setEnabled(true); ui->haltButton->setEnabled(true); ui->homingButton->setEnabled(true); } else { m_motorsEnabled = FALSE; ui->enableNodeButton->setEnabled(true); ui->disableNodeButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homingButton->setEnabled(false); } } void epos2::on_connectionButtonBox_rejected() { m_motorsEnabled = FALSE; if(m_KeyHandle) { for(int i = 0; i < 4; i++) { DisableMotor(m_motors[i]); } qDebug() << "Motors disabled."; if(VCS_CloseDevice(m_KeyHandle, &m_ulErrorCode)) { m_KeyHandle = 0; qDebug() << "EPOS closed successfully."; ui->outputText->append("Closed.\n"); ui->enableNodeButton->setEnabled(false); ui->disableNodeButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homingButton->setEnabled(false); } else ShowErrorInformation(m_ulErrorCode); } else { ui->outputText->append("EPOS is already closed.\n"); ui->enableNodeButton->setEnabled(false); ui->disableNodeButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homingButton->setEnabled(false); } //VCS_CloseAllDevices(&m_ulErrorCode); } void epos2::on_enableNodeButton_clicked() { int selection = ui->nodeIDcomboBox->currentIndex(); if(InitMotor(m_motors[selection])) { ui->enableNodeButton->setEnabled(false); ui->disableNodeButton->setEnabled(true); ui->moveAbsButton->setEnabled(true); ui->moveRelButton->setEnabled(true); ui->haltButton->setEnabled(true); ui->homingButton->setEnabled(true); } } void epos2::on_disableNodeButton_clicked() { int selection = ui->nodeIDcomboBox->currentIndex(); if(DisableMotor(m_motors[selection])) { ui->enableNodeButton->setEnabled(true); ui->disableNodeButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homingButton->setEnabled(false); } } void epos2::on_moveAbsButton_clicked() { int selection = ui->nodeIDcomboBox->currentIndex(); long counts = (long)ui->targetQClineEdit->value(); qDebug() << "Moving motor " << m_motors[selection].data()->m_nodeID << " to " << counts; moveMotor(counts, m_motors[selection], true); } void epos2::on_moveRelButton_clicked() { int selection = ui->nodeIDcomboBox->currentIndex(); long counts = (long)ui->targetQClineEdit->value(); moveMotor(counts, m_motors[selection], false); } void epos2::on_nodeIDcomboBox_currentIndexChanged(int index) { if(m_motors[index].data()->m_enabled) { ui->enableNodeButton->setEnabled(false); ui->disableNodeButton->setEnabled(true); ui->moveAbsButton->setEnabled(true); ui->moveRelButton->setEnabled(true); ui->haltButton->setEnabled(true); ui->homingButton->setEnabled(true); } else { ui->enableNodeButton->setEnabled(true); ui->disableNodeButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homingButton->setEnabled(false); } } void epos2::on_haltButton_clicked() { int selection = ui->nodeIDcomboBox->currentIndex(); haltMotor(m_motors[selection]); } void epos2::on_homingButton_clicked() { long homepos[4]={0, 0, 0, 0}; // set a lower speed for(int i = 0; i < 4; i++) { WORD nodeID = m_motors[i].data()->m_nodeID; if(!VCS_SetPositionProfile(m_KeyHandle,nodeID, 1400,2000,2000,&m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } } for(int i = 0; i < 4; i++) { WORD nodeID = m_motors[i].data()->m_nodeID; if(!VCS_MoveToPosition(m_KeyHandle,nodeID,homepos[i],true,true,&m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } } //TODO: reset the motor limits since roll is back to zero //------ // reset the profile for(int i = 0; i < 4; i++) { WORD nodeID = m_motors[i].data()->m_nodeID; if(!VCS_SetPositionProfile(m_KeyHandle,nodeID, EPOS_VELOCITY,EPOS_ACCEL,EPOS_DECEL, &m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } } }
12,675
C++
28.686183
111
0.559132
adegirmenci/HBL-ICEbot/old/SharedPoint.cpp
#include "SharedPoint.h" class SharedPointData : public QSharedData { public: SharedPointData() { m_x = 0.0; m_y = 0.0; m_z = 0.0; } SharedPointData(double x, double y, double z) { m_x = x; m_y = y; m_z = z; } SharedPointData(const SharedPointData &rhs) : QSharedData(rhs) { m_x = rhs.m_x; m_y = rhs.m_y; m_z = rhs.m_z; } ~SharedPointData() {} double m_x; double m_y; double m_z; }; // Zero Constructor SharedPoint::SharedPoint() : data(new SharedPointData) {} // Constructor SharedPoint::SharedPoint(double x, double y, double z) { data( new SharedPointData(x, y, z) ); } // Copy SharedPoint::SharedPoint(const SharedPoint &rhs) : data(rhs.data) {} // Copy SharedPoint &SharedPoint::operator=(const SharedPoint &rhs) { if (this != &rhs) data.operator=(rhs.data); return *this; } // Destructor SharedPoint::~SharedPoint() {} SharedPoint SharedPoint::update(double px, double py, double pz) { this->setx(px); this->sety(py); this->setz(pz); return this; } // Distance to another point. Pythagorean thm. double SharedPoint::dist(SharedPoint& other) { double xd = this->getx() - other.getx(); double yd = this->gety() - other.gety(); double zd = this->getz() - other.getz(); return sqrt(xd*xd + yd*yd + zd*zd); } SharedPoint SharedPoint::operator+(const SharedPoint& b) const { return SharedPoint(this->getx() + b.getx(), this->gety() + b.gety(), this->getz() + b.getz()); } SharedPoint SharedPoint::operator-(const SharedPoint& b) const { return SharedPoint(this->getx() - b.getx(), this->gety() - b.gety(), this->getz() - b.getz()); } SharedPoint SharedPoint::operator*(const double k) const { return SharedPoint(this->getx()*k, this->gety()*k, this->getz()*k); } SharedPoint SharedPoint::operator/(const double k) const { return SharedPoint(this->getx()/k, this->gety()/k, this->getz()/k); } void SharedPoint::move(double a, double b, double c) { this->setx(this->getx() + a); this->sety(this->gety() + b); this->setz(this->getz() + c); }
2,357
C++
20.833333
68
0.557488
adegirmenci/HBL-ICEbot/old/epos2.h
#ifndef EPOS2_H #define EPOS2_H #include <QWidget> #include <QSharedPointer> #include <QList> #include <QElapsedTimer> #include "MaxonLibs/Definitions.h" #include <stdio.h> #include <Windows.h> #define EPOS_VELOCITY 5000 #define EPOS_ACCEL 8000 #define EPOS_DECEL 8000 // node ID's for motors #define TRANS_MOTOR_ID 1 #define PITCH_MOTOR_ID 2 #define YAW_MOTOR_ID 3 #define ROLL_MOTOR_ID 4 // indices for the motor in list #define TRANS 0 #define PITCH 1 #define YAW 2 #define ROLL 3 struct eposMotor { __int8 m_bMode; WORD m_nodeID; // motor ID DWORD m_ulProfileAcceleration; // acceleration value DWORD m_ulProfileDeceleration; // deceleration value DWORD m_ulProfileVelocity; // velocity value BOOL m_enabled; long m_lActualValue; // volatile? long m_lStartPosition; // volatile? long m_lTargetPosition; // volatile? long m_maxQC; // upper limit long m_minQC; // lower limit }; namespace Ui { class epos2; } class epos2 : public QWidget { Q_OBJECT public: explicit epos2(QWidget *parent = 0); ~epos2(); long m_lActualValue; long m_lStartPosition; long m_lTargetPosition; void moveMotor(long targetPos, QSharedPointer<eposMotor> mot, BOOL moveAbsOrRel); void getMotorQC(QSharedPointer<eposMotor> mot); void haltMotor(QSharedPointer<eposMotor> mot); BOOL m_motorsEnabled; private slots: void on_connectionButtonBox_accepted(); void on_connectionButtonBox_rejected(); void on_enableNodeButton_clicked(); void on_disableNodeButton_clicked(); void on_moveAbsButton_clicked(); void on_nodeIDcomboBox_currentIndexChanged(int index); void on_moveRelButton_clicked(); void on_haltButton_clicked(); void on_homingButton_clicked(); private: Ui::epos2 *ui; BOOL OpenDevice(); BOOL InitMotor(QSharedPointer<eposMotor> mot); BOOL DisableMotor(QSharedPointer<eposMotor> mot); BOOL ShowErrorInformation(DWORD p_ulErrorCode); BOOL m_oImmediately; BOOL m_oInitialisation; BOOL m_oUpdateActive; DWORD m_ulErrorCode; HANDLE m_KeyHandle; QList<QSharedPointer<eposMotor>> m_motors; eposMotor m_transMotor; eposMotor m_pitchMotor; eposMotor m_yawMotor; eposMotor m_rollMotor; }; #endif // EPOS2_H
2,293
C
20.045871
85
0.706934
adegirmenci/HBL-ICEbot/old/SharedPoint.h
#ifndef SHAREDPOINT_H #define SHAREDPOINT_H #include <QSharedDataPointer> class SharedPointData; class SharedPoint { public: SharedPoint(); SharedPoint(double x, double y, double z); SharedPoint(const SharedPoint& rhs); SharedPoint &operator=(const SharedPoint& rhs); ~SharedPoint(); // modifiers void setx(double pk) { data->m_x = pk; } void sety(double pk) { data->m_y = pk; } void setz(double pk) { data->m_z = pk; } // accessors double getx() const { return data->m_x; } double gety() const { return data->m_y; } double getz() const { return data->m_z; } SharedPoint update(double px, double py, double pz); double dist(SharedPoint& other); SharedPoint operator+(const SharedPoint& b) const; SharedPoint operator-(const SharedPoint& b) const; SharedPoint operator*(const double k) const; SharedPoint operator/(const double k) const; void move(double a, double b, double c); signals: public slots: private: QSharedDataPointer<SharedPointData> data; }; #endif // SHAREDPOINT_H
1,074
C
22.888888
56
0.675047
adegirmenci/HBL-ICEbot/SceneVizWidget/usentity.h
#ifndef USENTITY_H #define USENTITY_H #include <QtCore/QObject> #include <Qt3DCore/qentity.h> #include <QFileInfo> #include <QUrl> #include <Qt3DCore/qtransform.h> #include <QVector3D> #include <QQuaternion> #include <QtCore/QVector> #include <QtCore/QDebug> #include <QColor> #include <Qt3DRender/qmesh.h> #include <Qt3DRender/qtextureimage.h> #include <Qt3DExtras/qdiffusemapmaterial.h> #include <Qt3DRender/qcullface.h> #include <Qt3DRender/qdepthtest.h> #include <QSharedPointer> #include <Qt3DRender/qeffect.h> #include <Qt3DRender/qtechnique.h> #include <Qt3DRender/qrenderpass.h> #include <Qt3DRender/qrenderstate.h> #include <QDir> class usEntity : public Qt3DCore::QEntity { Q_OBJECT public: explicit usEntity(QEntity *parent = nullptr); ~usEntity(); QVector3D getTranslation() { return m_usTransforms->translation(); } QQuaternion getRotation() { return m_usTransforms->rotation(); } // signals: public slots: // setDisplayed // implemented by QEntity void translate(QVector3D &trans); void rotate(QQuaternion &rot); void setTransformation(Qt3DCore::QTransform &tform); private: Qt3DRender::QMesh *m_usMesh; QVector<Qt3DCore::QEntity *> m_usEntityList; Qt3DRender::QTextureImage *m_usImage; Qt3DExtras::QDiffuseMapMaterial *m_usMaterial; Qt3DCore::QTransform *m_usTransforms; bool isShown; }; #endif // USENTITY_H
1,452
C
22.063492
72
0.710055
adegirmenci/HBL-ICEbot/SceneVizWidget/extendedqt3dwindow.cpp
#include "extendedqt3dwindow.h" ExtendedQt3DWindow::ExtendedQt3DWindow(QScreen *screen) : Qt3DExtras::Qt3DWindow(screen) { qRegisterMetaType< QSharedPointer<QWheelEvent> >("QSharedPointer<QWheelEvent>"); } void ExtendedQt3DWindow::wheelEvent(QWheelEvent *event) { emit wheelScrolled(QSharedPointer<QWheelEvent>( new QWheelEvent(*event) )); event->accept(); }
374
C++
25.785712
88
0.770053
adegirmenci/HBL-ICEbot/SceneVizWidget/triadentity.h
#ifndef TRIADENTITY_H #define TRIADENTITY_H #include <QtCore/QObject> #include <Qt3DCore/qentity.h> #include <QFileInfo> #include <QUrl> #include <Qt3DCore/qtransform.h> #include <QVector3D> #include <QQuaternion> #include <QtCore/QVector> #include <QtCore/QDebug> #include <QColor> #include <Qt3DRender/qmesh.h> #include <QSharedPointer> #include <Qt3DExtras/QPhongMaterial> #include <Qt3DExtras/QGoochMaterial> //typedef QVector<QComponent*> QComponentVector; class TriadEntity : public Qt3DCore::QEntity { Q_OBJECT public: explicit TriadEntity(QEntity *parent = nullptr); ~TriadEntity(); QVector3D getTranslation() { return m_triadTransforms->translation(); } QQuaternion getRotation() { return m_triadTransforms->rotation(); } // signals: public slots: // setDisplayed // implemented by QEntity void translate(const QVector3D &trans); void rotate(const QQuaternion &rot); void setTransformation(const Qt3DCore::QTransform &tform); private: Qt3DRender::QMesh *m_arrowMesh; //QSharedPointer<Qt3DRender::QMesh> arrowMesh; QVector<Qt3DCore::QEntity *> m_arrowEntityList; Qt3DCore::QTransform *m_triadTransforms; bool isShown; }; #endif // TRIADENTITY_H
1,225
C
20.892857
75
0.736327
adegirmenci/HBL-ICEbot/SceneVizWidget/usentity.cpp
#include "usentity.h" usEntity::usEntity(Qt3DCore::QEntity *parent) : Qt3DCore::QEntity(parent) , m_usTransforms(new Qt3DCore::QTransform()) , m_usMaterial(new Qt3DExtras::QDiffuseMapMaterial()) , m_usImage(new Qt3DRender::QTextureImage()) , m_usMesh(new Qt3DRender::QMesh()) { // LOAD MESH m_usMesh->setMeshName("USplane"); QFileInfo check_file( QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\SceneVizWidget\\ultrasound2.obj") ); if( check_file.exists() && check_file.isFile() ) { m_usMesh->setSource(QUrl::fromLocalFile(check_file.absoluteFilePath())); qDebug() << "Loaded ultrasound mesh."; } else { qDebug() << "Ultrasound mesh file doesn't exist!"; } // LOAD MESH DONE // SET GLOBAL TRANSFORM m_usTransforms->setTranslation(QVector3D(0.0f, 0.0f, 0.0f)); m_usTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(1, 0, 0),0.0f) ); this->addComponent(m_usTransforms); // SET GLOBAL TRANSFORM DONE // SET ULTRASOUND IMAGE AS TEXTURE check_file.setFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\SceneVizWidget\\1.jpg")); if( check_file.exists() && check_file.isFile() ) { m_usImage->setSource(QUrl::fromLocalFile(check_file.absoluteFilePath())); qDebug() << "Loaded ultrasound image."; } else { qDebug() << "Ultrasound image file doesn't exist!"; } m_usMaterial->diffuse()->addTextureImage(m_usImage); m_usMaterial->setShininess(10.0f); m_usMaterial->setSpecular(QColor::fromRgbF(0.75f, 0.75f, 0.75f, 1.0f)); //m_usMaterial->diffuse()->setSize(720,480); // SET ULTRASOUND IMAGE AS TEXTURE DONE // m_usMaterial->setSpecular(Qt::gray); // m_usMaterial->setAmbient(Qt::gray); // m_usMaterial->setShininess(10.0f); // m_usMaterial->setTextureScale(0.01f); // Begin: No culling // Access the render states of the material Qt3DRender::QEffect *effect_ = m_usMaterial->effect(); QVector<Qt3DRender::QTechnique *> tqs = effect_->techniques(); if(tqs.size() > 0) { QVector<Qt3DRender::QRenderPass *> rps = tqs[0]->renderPasses(); if(rps.size() > 0) { QVector<Qt3DRender::QRenderState *> rss = rps[0]->renderStates(); if(rss.size() > 0) { qDebug() << "A render state already exists:" << rss[0]->objectName(); } else { Qt3DRender::QCullFace *cullFront = new Qt3DRender::QCullFace(); cullFront->setMode(Qt3DRender::QCullFace::NoCulling); rps[0]->addRenderState(cullFront); Qt3DRender::QDepthTest *depthTest = new Qt3DRender::QDepthTest(); depthTest->setDepthFunction(Qt3DRender::QDepthTest::LessOrEqual); rps[0]->addRenderState(depthTest); } } else qDebug() << "No renderPasses."; } else qDebug() << "No techniques."; // End: No culling // ADD MESH TO ULTRASOUND ENTITY qDebug() << "Adding meshes to usEntityList."; m_usEntityList.fill(new Qt3DCore::QEntity(this), 1); for(int i = 0; i < m_usEntityList.size(); i++) { //m_usEntityList.replace(i, new Qt3DCore::QEntity(this)); Qt3DCore::QTransform *usTransforms = new Qt3DCore::QTransform(); usTransforms->setTranslation(QVector3D(0.0f, 0.0f, 0.0f)); usTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(0, 1, 0),90.0f) ); usTransforms->setScale3D(QVector3D(10,10,10)); m_usEntityList[i]->addComponent(m_usMesh); m_usEntityList[i]->addComponent(m_usMaterial); m_usEntityList[i]->addComponent(usTransforms); } qDebug() << "Adding meshes done."; } usEntity::~usEntity() { qDebug() << "Destroying usEntity."; qDebug() << m_usImage->status(); // m_usMesh->deleteLater(); // m_usImage->deleteLater(); // m_usMaterial->deleteLater(); // m_usTransforms->deleteLater(); } void usEntity::translate(QVector3D &trans) { m_usTransforms->setTranslation(trans); } void usEntity::rotate(QQuaternion &rot) { m_usTransforms->setRotation(rot); } void usEntity::setTransformation(Qt3DCore::QTransform &tform) { m_usTransforms->setMatrix(tform.matrix()); }
4,553
C++
33.763359
136
0.599824
adegirmenci/HBL-ICEbot/SceneVizWidget/scenemodifier.h
#ifndef SCENEMODIFIER_H #define SCENEMODIFIER_H #include <QtCore/QObject> #include <iostream> #include <Qt3DCore/qentity.h> #include <Qt3DCore/qtransform.h> #include <QMatrix4x4> #include <QtCore/QVector> #include <QtCore/QHash> #include <QtCore/QDebug> #include <QSharedPointer> #include <QVector3D> #include <QTime> #include "../icebot_definitions.h" #include "../AscensionWidget/3DGAPI/ATC3DG.h" #include "triadentity.h" #include "usentity.h" class SceneModifier : public QObject { Q_OBJECT public: explicit SceneModifier(Qt3DCore::QEntity *rootEntity); ~SceneModifier(); QVector3D getTriadPosition(EM_SENSOR_IDS sensorID); signals: public slots: void enableObject(bool enabled, int objID); void receiveEMreading(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data); void receiveEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> data); void resetBase(); void changeTFormOption(int opt); void setUSangle(int ang); private: QVector<Qt3DCore::QEntity *> m_entityList; QHash<QString, int> m_entityHash; // look up entities by name Qt3DCore::QEntity *m_rootEntity; QMatrix4x4 m_calibMat; Qt3DCore::QTransform m_Box_US; // Emitter to US crystal transforms QMatrix4x4 m_T_Box_EM; QMatrix4x4 m_T_EM_CT; Qt3DCore::QTransform m_CT_US; QMatrix4x4 m_baseEMpose; // for relative stuff int m_tformOption; float m_usAngle; }; // TRIADOBJECT #endif // SCENEMODIFIER_H
1,539
C
21.985074
82
0.701754
adegirmenci/HBL-ICEbot/SceneVizWidget/scenevizwidget.h
#ifndef SCENEVIZWIDGET_H #define SCENEVIZWIDGET_H /*! * Written by Alperen Degirmenci * Harvard Biorobotics Laboratory */ #include <QWidget> #include <Qt3DRender/qcamera.h> #include <Qt3DCore/qentity.h> #include <Qt3DRender/qcameralens.h> #include <QtWidgets/QWidget> #include <QtWidgets/QHBoxLayout> #include <QtGui/QScreen> #include <Qt3DInput/QInputAspect> #include <Qt3DInput/QWheelEvent> #include <Qt3DExtras/qtorusmesh.h> #include <Qt3DRender/qmesh.h> #include <Qt3DRender/qtechnique.h> #include <Qt3DRender/qmaterial.h> #include <Qt3DRender/qeffect.h> #include <Qt3DRender/qtexture.h> #include <Qt3DRender/qrenderpass.h> #include <Qt3DRender/qsceneloader.h> #include <Qt3DCore/qtransform.h> #include <Qt3DCore/qaspectengine.h> #include <Qt3DRender/qrenderaspect.h> #include <Qt3DExtras/qforwardrenderer.h> #include <Qt3DExtras/qt3dwindow.h> #include <Qt3DExtras/qorbitcameracontroller.h> #include "scenemodifier.h" #include "extendedqt3dwindow.h" namespace Ui { class SceneVizWidget; } class SceneVizWidget : public QWidget { Q_OBJECT public: explicit SceneVizWidget(QWidget *parent = 0); ~SceneVizWidget(); // Scenemodifier SceneModifier *m_modifier; private slots: void on_toggleRenderWindowButton_clicked(); void acceptScroll(QSharedPointer<QWheelEvent> event); void on_baseCheckBox_toggled(bool checked); void on_pushButton_clicked(); void on_resetBaseButton_clicked(); void on_noTformRadio_clicked(); void on_tform1Radio_clicked(); void on_tform2Radio_clicked(); void on_usAngleSpinBox_valueChanged(int arg1); void on_tipCheckBox_toggled(bool checked); void on_instrCheckBox_toggled(bool checked); void on_chestCheckBox_toggled(bool checked); private: Ui::SceneVizWidget *ui; ExtendedQt3DWindow *m_view; //Qt3DExtras::Qt3DWindow *view; QWidget *m_container; QSize m_screenSize; QWidget *m_widget; QHBoxLayout *m_hLayout; QVBoxLayout *m_vLayout; Qt3DInput::QInputAspect *m_input; Qt3DCore::QEntity *m_rootEntity; Qt3DRender::QCamera *m_cameraEntity; Qt3DExtras::QOrbitCameraController *m_camController; bool m_isShown; protected: // void wheelEvent(QWheelEvent *event); }; #endif // SCENEVIZWIDGET_H
2,263
C
20.980582
63
0.743261
adegirmenci/HBL-ICEbot/SceneVizWidget/scenemodifier.cpp
#include "scenemodifier.h" SceneModifier::SceneModifier(Qt3DCore::QEntity *rootEntity) : m_rootEntity(rootEntity) { // Y axis points up in OpenGL renderer m_entityList.append(new TriadEntity(m_rootEntity)); m_entityList.append(new TriadEntity(m_rootEntity)); m_entityList.append(new TriadEntity(m_rootEntity)); m_entityList.append(new TriadEntity(m_rootEntity)); m_entityList.append(new TriadEntity(m_rootEntity)); //m_entityList.append(new usEntity(m_rootEntity)); m_entityList.append(new usEntity(m_entityList[1])); // US plane attached to the BT static_cast<TriadEntity*>(m_entityList[0])->translate(QVector3D(0.0f, 0.0f, 0.0f)); // EM_SENSOR_BB m_entityList[0]->setEnabled(false); m_entityList[1]->setEnabled(false); m_entityList[2]->setEnabled(false); m_entityList[3]->setEnabled(false); m_entityList[4]->setEnabled(true); // EM Box m_entityList[5]->setEnabled(true); // US plane Qt3DCore::QTransform tf; tf.setTranslation(QVector3D(0,0,0)); static_cast<TriadEntity*>(m_entityList[4])->setTransformation(tf); static_cast<usEntity*>(m_entityList[5])->setTransformation(tf); //static_cast<usEntity*>(m_entityList[5])->setProperty(); // dummy m_baseEMpose = tf.matrix(); Qt3DCore::QTransform calib; calib.setRotation(QQuaternion(0.0098f, -0.0530f, -0.9873f, -0.1492f)); m_calibMat = calib.matrix(); m_tformOption = 0; // QMatrix4x4 T_Box_EM(-1, 0, 0, 0, // 0, 0, -1, 0, // 0, -1, 0, 0, // 0, 0, 0, 1); m_T_Box_EM = QMatrix4x4(0, 0, 1, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1); m_T_EM_CT = QMatrix4x4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 14.5, 0, 0, 0, 1); m_CT_US.setRotationZ(0); m_Box_US.setMatrix(m_T_Box_EM * m_T_EM_CT * m_CT_US.matrix()); //T_Box_EM } SceneModifier::~SceneModifier() { //m_entityList.clear(); } QVector3D SceneModifier::getTriadPosition(EM_SENSOR_IDS sensorID) { return static_cast<TriadEntity*>(m_entityList[sensorID])->getTranslation(); } void SceneModifier::enableObject(bool enabled, int objID) { // // Look at this example for creating object classes // // http://doc.qt.io/qt-5/qt3drenderer-materials-cpp-barrel-cpp.html // // arrow class can be useful to create triads, and then a triad class Q_ASSERT(objID < m_entityList.size()); m_entityList[objID]->setEnabled(enabled); } void SceneModifier::receiveEMreading(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data) { QMatrix4x4 tmp(data.s[0][0], data.s[0][1], data.s[0][2], data.x, data.s[1][0], data.s[1][1], data.s[1][2], data.y, data.s[2][0], data.s[2][1], data.s[2][2], data.z, 0.0, 0.0, 0.0, 1.0); Qt3DCore::QTransform tf; tf.setMatrix(tmp); // tf.setRotation(QQuaternion(data.q[0],data.q[1],data.q[2],data.q[3])); // tf.setTranslation(QVector3D(data.x,data.y,data.z)); if(m_tformOption == 0) tf.setMatrix(tf.matrix()); else if(m_tformOption == 1) tf.setMatrix(m_calibMat*tf.matrix()*m_Box_US.matrix()); else if(m_tformOption == 2) tf.setMatrix(m_baseEMpose.inverted()*m_T_Box_EM.inverted() * tf.matrix()*m_Box_US.matrix()); else tf.setMatrix(tf.matrix()); static_cast<TriadEntity*>(m_entityList[sensorID])->setTransformation(tf); // static_cast<TriadEntity*>(m_entityList[sensorID])->rotate(QQuaternion(data.q[0],data.q[1],data.q[2],data.q[3])); // static_cast<TriadEntity*>(m_entityList[sensorID])->translate(QVector3D(data.x,data.y,data.z)); } void SceneModifier::receiveEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> data) { Q_ASSERT(data.size() == 4); for(size_t i = 0; i < data.size(); i++) { QMatrix4x4 tmp(data[i].s[0][0], data[i].s[0][1], data[i].s[0][2], data[i].x, data[i].s[1][0], data[i].s[1][1], data[i].s[1][2], data[i].y, data[i].s[2][0], data[i].s[2][1], data[i].s[2][2], data[i].z, 0.0, 0.0, 0.0, 1.0); Qt3DCore::QTransform tf; tf.setMatrix(tmp); if(m_tformOption == 0) tf.setMatrix(tf.matrix()); else if(m_tformOption == 1) tf.setMatrix(m_calibMat*tf.matrix()*m_Box_US.matrix()); else if(m_tformOption == 2) tf.setMatrix(m_baseEMpose.inverted()*m_T_Box_EM.inverted() * tf.matrix()*m_Box_US.matrix()); else tf.setMatrix(tf.matrix()); static_cast<TriadEntity*>(m_entityList[i])->setTransformation(tf); } } void SceneModifier::resetBase() { Qt3DCore::QTransform tf; tf.setRotation(static_cast<TriadEntity*>(m_entityList[EM_SENSOR_BB])->getRotation()); tf.setTranslation(static_cast<TriadEntity*>(m_entityList[EM_SENSOR_BB])->getTranslation()); m_baseEMpose = tf.matrix(); } void SceneModifier::changeTFormOption(int opt) { std::cout << "m_tformOption changed to " << opt << std::endl; m_tformOption = opt; } void SceneModifier::setUSangle(int ang) { std::cout << "US angle changed to " << ang << std::endl; m_usAngle = ang; m_CT_US.setRotationZ(m_usAngle); m_Box_US.setMatrix(m_T_Box_EM * m_T_EM_CT * m_CT_US.matrix()); //T_Box_EM }
5,524
C++
33.53125
118
0.588342
adegirmenci/HBL-ICEbot/SceneVizWidget/extendedqt3dwindow.h
#ifndef EXTENDEDQT3DWINDOW_H #define EXTENDEDQT3DWINDOW_H #include <QObject> #include <QDebug> #include <QScreen> #include <Qt3DExtras/Qt3DWindow> #include <Qt3DInput/QWheelEvent> #include <QSharedPointer> Q_DECLARE_METATYPE(QSharedPointer<QWheelEvent>) class ExtendedQt3DWindow : public Qt3DExtras::Qt3DWindow { Q_OBJECT public: ExtendedQt3DWindow(QScreen *screen = nullptr); signals: void wheelScrolled(QSharedPointer<QWheelEvent> event); protected: void wheelEvent(QWheelEvent *event); }; #endif // EXTENDEDQT3DWINDOW_H
547
C
17.896551
58
0.775137
adegirmenci/HBL-ICEbot/SceneVizWidget/scenevizwidget.cpp
#include "scenevizwidget.h" #include "ui_scenevizwidget.h" SceneVizWidget::SceneVizWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SceneVizWidget) { ui->setupUi(this); m_view = new ExtendedQt3DWindow(); //view = new Qt3DExtras::Qt3DWindow(); m_view->defaultFrameGraph()->setClearColor(QColor(QRgb(0x4d4d4f))); m_container = QWidget::createWindowContainer(m_view); m_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_widget = ui->dockWidgetContents; m_hLayout = new QHBoxLayout(m_widget); m_vLayout = new QVBoxLayout(); m_vLayout->setAlignment(Qt::AlignTop); m_hLayout->addWidget(m_container, 1); m_hLayout->addLayout(m_vLayout); ui->dockWidget->setWindowTitle(QStringLiteral("Scene Visualizer")); m_input = new Qt3DInput::QInputAspect(); m_view->registerAspect(m_input); // Root entity m_rootEntity = new Qt3DCore::QEntity(); m_rootEntity->setObjectName(QStringLiteral("rootEntity")); // Camera m_cameraEntity = m_view->camera(); m_cameraEntity->lens()->setPerspectiveProjection(45.0f, 16.0f/9.0f, 0.1f, 1000.0f); m_cameraEntity->setPosition(QVector3D(0, 20.0f, 0)); m_cameraEntity->setUpVector(QVector3D(0, 0, 1)); // Z is up m_cameraEntity->setViewCenter(QVector3D(0, 0, 0)); // For camera controls m_camController = new Qt3DExtras::QOrbitCameraController(m_rootEntity); m_camController->setLinearSpeed( 50.0f ); m_camController->setLookSpeed( 180.0f ); m_camController->setCamera(m_cameraEntity); // Set root object of the scene m_view->setRootEntity(m_rootEntity); // Scenemodifier m_modifier = new SceneModifier(m_rootEntity); // Show window //view->show(); //connect(view, SIGNAL(wheelScrolled(std::shared_ptr<QWheelEvent>)), this, SLOT(acceptScroll(std::shared_ptr<QWheelEvent>))); connect(m_view, SIGNAL(wheelScrolled(QSharedPointer<QWheelEvent>)), this, SLOT(acceptScroll(QSharedPointer<QWheelEvent>))); m_isShown = true; } SceneVizWidget::~SceneVizWidget() { // if(ui->dockWidget->isHidden()) // ui->dockWidget->setHidden(false); // if window was closed // ui->dockWidget->setFloating(false); // view->close(); // view->destroy(); m_modifier->deleteLater(); // view->deleteLater(); // container->deleteLater(); // widget->deleteLater(); // hLayout->deleteLater(); // vLayout->deleteLater(); // input->deleteLater(); // rootEntity->deleteLater(); // cameraEntity->deleteLater(); // camController->deleteLater(); delete ui; } //void SceneVizWidget::wheelEvent(QWheelEvent *event) //{ // QPoint angle = event->angleDelta(); // qDebug() << "Mouse wheel" << angle; // double ang = static_cast<double>(angle.y())/240. + 1.; // cameraEntity->setPosition(cameraEntity->position()*ang); // event->accept(); //} void SceneVizWidget::acceptScroll(QSharedPointer<QWheelEvent> event) { double ang = static_cast<double>(event->angleDelta().y())/240.; m_cameraEntity->setPosition(m_cameraEntity->position()*(1-ang) + m_cameraEntity->viewCenter()*ang); // TODO: add zoom with reference to the pointer location } void SceneVizWidget::on_toggleRenderWindowButton_clicked() { if(m_view->isVisible()) { ui->dockWidget->hide(); //view->hide(); ui->toggleRenderWindowButton->setText("Show Window"); m_isShown = false; } else { ui->dockWidget->show(); if(ui->dockWidget->isFloating()) { ui->dockWidget->resize(ui->dockFrame->size()); ui->dockWidget->move(1,1); ui->dockWidget->setFloating(false); } //view->show(); ui->toggleRenderWindowButton->setText("Hide Window"); m_isShown = true; } } void SceneVizWidget::on_baseCheckBox_toggled(bool checked) { m_modifier->enableObject(checked, EM_SENSOR_BB); } void SceneVizWidget::on_tipCheckBox_toggled(bool checked) { m_modifier->enableObject(checked, EM_SENSOR_BT); } void SceneVizWidget::on_instrCheckBox_toggled(bool checked) { m_modifier->enableObject(checked, EM_SENSOR_INST); } void SceneVizWidget::on_chestCheckBox_toggled(bool checked) { m_modifier->enableObject(checked, EM_SENSOR_CHEST); } void SceneVizWidget::on_pushButton_clicked() { QVector3D pos = m_modifier->getTriadPosition(EM_SENSOR_BB); m_cameraEntity->setViewCenter(pos); } void SceneVizWidget::on_resetBaseButton_clicked() { m_modifier->resetBase(); } void SceneVizWidget::on_noTformRadio_clicked() { m_modifier->changeTFormOption(0); } void SceneVizWidget::on_tform1Radio_clicked() { m_modifier->changeTFormOption(1); } void SceneVizWidget::on_tform2Radio_clicked() { m_modifier->changeTFormOption(2); } void SceneVizWidget::on_usAngleSpinBox_valueChanged(int arg1) { m_modifier->setUSangle(arg1); }
4,903
C++
26.396648
129
0.673057
adegirmenci/HBL-ICEbot/SceneVizWidget/triadentity.cpp
#include "triadentity.h" TriadEntity::TriadEntity(Qt3DCore::QEntity *parent) : Qt3DCore::QEntity(parent) { // LOAD MESH m_arrowMesh = new Qt3DRender::QMesh(); //arrowMesh = QSharedPointer<Qt3DRender::QMesh>(new Qt3DRender::QMesh()); m_arrowMesh->setMeshName("Arrow"); QFileInfo check_file( QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\SceneVizWidget\\Arrow.obj") ); if( check_file.exists() && check_file.isFile() ) { m_arrowMesh->setSource(QUrl::fromLocalFile(QStringLiteral("C:\\Users\\Alperen\\Documents\\QT Projects\\ICEbot_QT_v1\\SceneVizWidget\\Arrow.obj"))); qDebug() << "Loaded arrow mesh."; } else { qDebug() << "Arrow mesh file doesn't exist!"; } // m_triadTransforms = new Qt3DCore::QTransform(); m_triadTransforms->setTranslation(QVector3D(0.0f, 0.0f, 0.0f)); this->addComponent(m_triadTransforms); // ADD MESH TO THREE ARROW ENTITIES qDebug() << "Adding meshes to arrowEntityList."; m_arrowEntityList.resize(3); for(size_t i = 0; i < 3; i++) { m_arrowEntityList.replace(i, new Qt3DCore::QEntity(this)); m_arrowEntityList[i]->addComponent(m_arrowMesh); Qt3DCore::QTransform *arrowTransforms; arrowTransforms = new Qt3DCore::QTransform(this); arrowTransforms->setTranslation(QVector3D(0.0f, 0.0f, 0.0f)); switch(i){ case 0: arrowTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(1, 0, 0),0.0f) ); break; case 1: arrowTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(0, 0, 1),90.0f) ); break; case 2: arrowTransforms->setRotation( QQuaternion::fromAxisAndAngle(QVector3D(0, 1, 0),-90.0f) ); break; } arrowTransforms->setScale3D(QVector3D(3,2,2)); Qt3DExtras::QGoochMaterial *arrowMaterial = new Qt3DExtras::QGoochMaterial(this); arrowMaterial->setAlpha(0.5f); arrowMaterial->setBeta(0.5f); switch(i){ case 0: arrowMaterial->setDiffuse(QColor(200,50,50)); //arrowMaterial->setDiffuse(QColor(200,50,50)); arrowMaterial->setWarm(QColor(155,0,0)); arrowMaterial->setCool(QColor(90,20,20)); //arrowMaterial->setSpecular(QColor(200,50,50)); break; case 1: arrowMaterial->setDiffuse(QColor(50,200,50)); //arrowMaterial->setDiffuse(QColor(50,200,50)); arrowMaterial->setWarm(QColor(0,127,0)); arrowMaterial->setCool(QColor(20,90,20)); //arrowMaterial->setSpecular(QColor(50,200,50)); break; case 2: arrowMaterial->setDiffuse(QColor(50,50,200)); //arrowMaterial->setDiffuse(QColor(50,50,200)); arrowMaterial->setWarm(QColor(0,0,127)); arrowMaterial->setCool(QColor(20,20,90)); //arrowMaterial->setSpecular(QColor(50,50,200)); break; } arrowMaterial->setShininess(1.0f); m_arrowEntityList[i]->addComponent(arrowMaterial); m_arrowEntityList[i]->addComponent(arrowTransforms); } qDebug() << "Adding meshes done."; } TriadEntity::~TriadEntity() { qDebug() << "Destroying TriadEntity."; //arrowEntityList.clear(); //arrowMesh->deleteLater(); } void TriadEntity::translate(const QVector3D &trans) { m_triadTransforms->setTranslation(trans); } void TriadEntity::rotate(const QQuaternion &rot) { m_triadTransforms->setRotation(rot); } void TriadEntity::setTransformation(const Qt3DCore::QTransform &tform) { m_triadTransforms->setMatrix(tform.matrix()); }
3,723
C++
33.165137
155
0.627182
adegirmenci/HBL-ICEbot/FrmGrabWidget/frmgrabthread.cpp
#include "frmgrabthread.h" FrmGrabThread::FrmGrabThread(QObject *parent) : QObject(parent) { qRegisterMetaType< std::shared_ptr<Frame> >("std::shared_ptr<Frame>"); m_isEpochSet = false; m_isReady = false; m_keepStreaming = false; m_showLiveFeed = false; m_numSaveImageRequests = 0; m_frameCount = 0; m_abort = false; m_continuousSaving = false; m_videoFPS = 0; m_mutex = new QMutex(QMutex::Recursive); } FrmGrabThread::~FrmGrabThread() { frmGrabDisconnect(); m_mutex->lock(); m_continuousSaving = false; m_abort = true; qDebug() << "Ending FrmGrabThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; m_mutex->unlock(); delete m_mutex; m_src.release(); m_dst.release(); emit finished(); } void FrmGrabThread::frmGrabConnect() { QMutexLocker locker(m_mutex); emit statusChanged(FRMGRAB_CONNECT_BEGIN); m_cap.open(0); // open the default camera if(m_cap.isOpened()) // check if we succeeded { emit statusChanged(FRMGRAB_CONNECTED); // success } else { emit statusChanged(FRMGRAB_CONNECT_FAILED); // failed } } void FrmGrabThread::frmGrabInitialize(int width, int height, double fps) { QMutexLocker locker(m_mutex); if(m_cap.isOpened()) { m_videoFPS = fps; // m_cap.get(CV_CAP_PROP_FPS); m_imgSize.height = height; //m_cap.get(CV_CAP_PROP_FRAME_HEIGHT); m_imgSize.width = width; //m_cap.get(CV_CAP_PROP_FRAME_WIDTH); m_cap.set(CV_CAP_PROP_FRAME_HEIGHT, m_imgSize.height); m_cap.set(CV_CAP_PROP_FRAME_WIDTH, m_imgSize.width); m_cap.set(CV_CAP_PROP_FPS, m_videoFPS); qDebug() << "Width:" << m_imgSize.width << "Height:" << m_imgSize.height << "FPS:" << m_videoFPS; emit statusChanged(FRMGRAB_INITIALIZED); } else emit statusChanged(FRMGRAB_INITIALIZE_FAILED); } void FrmGrabThread::startStream() { QMutexLocker locker(m_mutex); if(!m_keepStreaming) { m_timer = new QTimer(this); m_timer->start(floor(1000./m_videoFPS)); connect(m_timer, SIGNAL(timeout()), this, SLOT(grabFrame())); m_keepStreaming = true; emit logEvent(SRC_FRMGRAB, LOG_INFO, QTime::currentTime(), FRMGRAB_LOOP_STARTED); emit statusChanged(FRMGRAB_LOOP_STARTED); qDebug() << "Streaming started."; } } void FrmGrabThread::stopStream() { QMutexLocker locker(m_mutex); if ( m_keepStreaming ) { if(m_showLiveFeed) toggleLiveFeed(); m_keepStreaming = false; m_timer->stop(); disconnect(m_timer,SIGNAL(timeout()), 0, 0); delete m_timer; emit logEvent(SRC_FRMGRAB, LOG_INFO, QTime::currentTime(), FRMGRAB_LOOP_STOPPED); qDebug() << "Streaming stopped."; } else { qDebug() << "Streaming already stopped."; } emit statusChanged(FRMGRAB_LOOP_STOPPED); } void FrmGrabThread::toggleLiveFeed() { QMutexLocker locker(m_mutex); m_showLiveFeed = !m_showLiveFeed; if(m_showLiveFeed) { cv::namedWindow(m_winName.toStdString()); cv::resizeWindow(m_winName.toStdString(), m_imgSize.width, m_imgSize.height); // make connections connect(this, SIGNAL(imageAcquired(std::shared_ptr<Frame>)), this, SLOT(displayFrame(std::shared_ptr<Frame>))); emit statusChanged(FRMGRAB_LIVE_FEED_STARTED); } else { // break connections disconnect(this, SIGNAL(imageAcquired(std::shared_ptr<Frame>)), this, SLOT(displayFrame(std::shared_ptr<Frame>))); cv::destroyWindow(m_winName.toStdString()); emit statusChanged(FRMGRAB_LIVE_FEED_STOPPED); } } void FrmGrabThread::displayFrame(std::shared_ptr<Frame> frm) { QMutexLocker locker(m_mutex); cv::imshow(m_winName.toStdString(), frm->image_); } void FrmGrabThread::frmGrabDisconnect() { stopStream(); QMutexLocker locker(m_mutex); m_cap.release(); // release video capture device emit statusChanged(FRMGRAB_DISCONNECTED); } void FrameDeleter(Frame* frm) { frm->image_.release(); } void FrmGrabThread::grabFrame() { QMutexLocker locker(m_mutex); // capture frame m_cap >> m_src; //m_cap.read(m_src); qint64 msec = QDateTime::currentMSecsSinceEpoch(); // convert to grayscale cv::cvtColor(m_src, m_dst, CV_BGR2GRAY); // construct new frame std::shared_ptr<Frame> frame(new Frame(m_dst, msec, m_frameCount), FrameDeleter); if(m_continuousSaving) { m_numSaveImageRequests++; } if(m_numSaveImageRequests > 0) { emit pleaseSaveImage(frame); m_frameCount++; m_numSaveImageRequests--; } //if(m_showLiveFeed) emit imageAcquired(frame); } void FrmGrabThread::startSaving() { QMutexLocker locker(m_mutex); m_continuousSaving = true; } void FrmGrabThread::stopSaving() { QMutexLocker locker(m_mutex); m_continuousSaving = false; } void FrmGrabThread::addSaveRequest(unsigned short numFrames) { QMutexLocker locker(m_mutex); m_numSaveImageRequests += numFrames; } void FrmGrabThread::setEpoch(const QDateTime &datetime) { QMutexLocker locker(m_mutex); if(!m_keepStreaming) { m_epoch = datetime; m_isEpochSet = true; emit logEventWithMessage(SRC_FRMGRAB, LOG_INFO, QTime::currentTime(), FRMGRAB_EPOCH_SET, m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz")); } else emit logEvent(SRC_FRMGRAB, LOG_INFO, QTime::currentTime(), FRMGRAB_EPOCH_SET_FAILED); }
5,638
C++
22.016326
122
0.632316
adegirmenci/HBL-ICEbot/FrmGrabWidget/frmgrabwidget.h
#ifndef FRMGRABWIDGET_H #define FRMGRABWIDGET_H #include <QWidget> #include "frmgrabthread.h" namespace Ui { class FrmGrabWidget; } class FrmGrabWidget : public QWidget { Q_OBJECT public: explicit FrmGrabWidget(QWidget *parent = 0); ~FrmGrabWidget(); FrmGrabThread *m_worker; signals: void frmGrabConnect(); void frmGrabInitialize(int width, int height, double fps); void startStream(); void stopStream(); void addSaveRequest(unsigned short numFrames); void frmGrabDisconnect(); void toggleLiveFeed(); void startSaving(); void stopSaving(); private slots: void workerStatusChanged(int status); void on_connectButton_clicked(); void on_initButton_clicked(); void on_disconnectButton_clicked(); void on_startStreamButton_clicked(); void on_liveFeedButton_clicked(); void on_saveFrameButton_clicked(); void on_stopStreamButton_clicked(); void on_saveFramesButton_clicked(); void controlStarted(); void controlStopped(); private: Ui::FrmGrabWidget *ui; QThread m_thread; // FrmGrab Thread will live in here bool mKeepSavingFrames; }; #endif // FRMGRABWIDGET_H
1,186
C
17.261538
62
0.700675
adegirmenci/HBL-ICEbot/FrmGrabWidget/frmgrabwidget.cpp
#include "frmgrabwidget.h" #include "ui_frmgrabwidget.h" FrmGrabWidget::FrmGrabWidget(QWidget *parent) : QWidget(parent), ui(new Ui::FrmGrabWidget) { ui->setupUi(this); m_worker = new FrmGrabThread; m_worker->moveToThread(&m_thread); mKeepSavingFrames = false; //connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater); connect(&m_thread, SIGNAL(finished()), m_worker, SLOT(deleteLater())); m_thread.start(); connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int))); connect(this, SIGNAL(frmGrabConnect()), m_worker, SLOT(frmGrabConnect())); connect(this, SIGNAL(frmGrabInitialize(int,int,double)), m_worker, SLOT(frmGrabInitialize(int,int,double))); connect(this, SIGNAL(startStream()), m_worker, SLOT(startStream())); connect(this, SIGNAL(stopStream()), m_worker, SLOT(stopStream())); connect(this, SIGNAL(toggleLiveFeed()), m_worker, SLOT(toggleLiveFeed())); connect(this, SIGNAL(addSaveRequest(unsigned short)), m_worker, SLOT(addSaveRequest(unsigned short))); connect(this, SIGNAL(frmGrabDisconnect()), m_worker, SLOT(frmGrabDisconnect())); connect(this, SIGNAL(startSaving()), m_worker, SLOT(startSaving())); connect(this, SIGNAL(stopSaving()), m_worker, SLOT(stopSaving())); } FrmGrabWidget::~FrmGrabWidget() { m_thread.quit(); m_thread.wait(); qDebug() << "FrmGrab thread quit."; delete ui; } void FrmGrabWidget::workerStatusChanged(int status) { switch(status) { case FRMGRAB_CONNECT_BEGIN: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(true); ui->disconnectButton->setEnabled(false); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Connecting."); break; case FRMGRAB_CONNECT_FAILED: ui->connectButton->setEnabled(true); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(false); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Connection failed."); break; case FRMGRAB_CONNECTED: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(true); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Connected."); break; case FRMGRAB_INITIALIZE_BEGIN: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Initializing."); break; case FRMGRAB_INITIALIZE_FAILED: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(true); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Initialization failed."); break; case FRMGRAB_INITIALIZED: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(true); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Initialized."); break; case FRMGRAB_LOOP_STARTED: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(true); ui->saveFrameButton->setEnabled(true); ui->stopStreamButton->setEnabled(true); ui->statusLineEdit->setText("Streaming."); break; case FRMGRAB_LOOP_STOPPED: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(true); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Stream stopped."); break; case FRMGRAB_LIVE_FEED_STARTED: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(true); ui->liveFeedButton->setText("Close Feed"); ui->saveFrameButton->setEnabled(true); ui->stopStreamButton->setEnabled(true); ui->statusLineEdit->setText("Streaming."); break; case FRMGRAB_LIVE_FEED_STOPPED: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(true); ui->liveFeedButton->setText("Live Feed"); ui->saveFrameButton->setEnabled(true); ui->stopStreamButton->setEnabled(true); ui->statusLineEdit->setText("Streaming."); break; case FRMGRAB_EPOCH_SET: qDebug() << "Epoch set."; break; case FRMGRAB_EPOCH_SET_FAILED: qDebug() << "Epoch set failed."; break; case FRMGRAB_DISCONNECTED: ui->connectButton->setEnabled(true); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(false); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Disconnected."); break; case FRMGRAB_DISCONNECT_FAILED: ui->connectButton->setEnabled(false); ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->startStreamButton->setEnabled(false); ui->liveFeedButton->setEnabled(false); ui->saveFrameButton->setEnabled(false); ui->stopStreamButton->setEnabled(false); ui->statusLineEdit->setText("Disconnect failed."); break; default: qDebug() << "Unknown state!"; break; } } void FrmGrabWidget::on_connectButton_clicked() { emit frmGrabConnect(); } void FrmGrabWidget::on_initButton_clicked() { int width = ui->widthSpinBox->value(); int height = ui->heightSpinBox->value(); double fps = ui->fpsSpinBox->value(); emit frmGrabInitialize(width, height, fps); } void FrmGrabWidget::on_disconnectButton_clicked() { emit frmGrabDisconnect(); } void FrmGrabWidget::on_startStreamButton_clicked() { emit startStream(); } void FrmGrabWidget::on_liveFeedButton_clicked() { emit toggleLiveFeed(); } void FrmGrabWidget::on_saveFrameButton_clicked() { emit addSaveRequest(1); // request a single frame } void FrmGrabWidget::on_stopStreamButton_clicked() { emit stopStream(); } void FrmGrabWidget::on_saveFramesButton_clicked() { if(mKeepSavingFrames) // already saving, so stop saving { mKeepSavingFrames = false; ui->saveFramesButton->setText("Start Saving"); emit stopSaving(); } else { mKeepSavingFrames = true; ui->saveFramesButton->setText("Stop Saving"); emit startSaving(); } } void FrmGrabWidget::controlStarted() { if(!mKeepSavingFrames) { mKeepSavingFrames = true; ui->saveFramesButton->setText("Stop Saving"); emit startSaving(); } } void FrmGrabWidget::controlStopped() { if(mKeepSavingFrames) { mKeepSavingFrames = false; ui->saveFramesButton->setText("Start Saving"); emit stopSaving(); } }
8,568
C++
32.869565
112
0.656162
adegirmenci/HBL-ICEbot/FrmGrabWidget/frmgrabthread.h
#ifndef FRMGRABTHREAD_H #define FRMGRABTHREAD_H #include <QObject> #include <QMutex> #include <QMutexLocker> #include <QThread> #include <QString> #include <QTime> #include <QTimer> #include <QDebug> #include <QSharedPointer> #include <vector> #include <memory> #include "../icebot_definitions.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> //#include "opencv2/video/video.hpp" //#include <epiphan/frmgrab/include/frmgrab.h> /** Frame structure. * This will hold an image, a timestamp, and an index. */ struct Frame{ cv::Mat image_; /*!< Image data. */ qint64 timestamp_; /*!< Timestamp, msec since some epoch. */ int index_; /*!< Index value of Frame, indicate order of acquisition. */ //! Constructor. explicit Frame(cv::Mat img = cv::Mat(), qint64 ts = -1, int id = -1) : timestamp_(ts), index_(id) { image_ = img; } //! Destructor ~Frame() { image_.release(); } }; Q_DECLARE_METATYPE(std::shared_ptr<Frame>) class FrmGrabThread : public QObject { Q_OBJECT public: explicit FrmGrabThread(QObject *parent = 0); ~FrmGrabThread(); signals: void statusChanged(int event); void imageAcquired(std::shared_ptr<Frame> frm); void pleaseSaveImage(std::shared_ptr<Frame> frm); void logData(QTime timeStamp, int frameIdx, QString &data); void logEvent(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int eventID); // FRMGRAB_EVENT_IDS void logEventWithMessage(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int eventID, // FRMGRAB_EVENT_IDS QString &message); void logError(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int errCode, // FRMGRAB_ERROR_CODES QString message); void finished(); // emit upon termination public slots: void frmGrabConnect(); void frmGrabInitialize(int width, int height, double fps); void startStream(); void stopStream(); void toggleLiveFeed(); void displayFrame(std::shared_ptr<Frame> frm); void addSaveRequest(unsigned short numFrames); void frmGrabDisconnect(); void setEpoch(const QDateTime &datetime); // set Epoch void grabFrame(); void startSaving(); void stopSaving(); private: // Instead of using "m_mutex.lock()" // use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex *m_mutex; // Timer for calling grabFrame every xxx msecs QTimer *m_timer; // Epoch for time stamps // During initializeFrmGrab(), check 'isEpochSet' flag // If Epoch is set externally from MainWindow, the flag will be true // Otherwise, Epoch will be set internally QDateTime m_epoch; bool m_isEpochSet; // Flag to indicate if Frame Grabber is ready // True if InitializeFrmGrab was successful bool m_isReady; // Flag to tell that we are still recording bool m_keepStreaming; // Flag for live feed bool m_showLiveFeed; // Flag to abort actions (e.g. initialize, acquire, etc.) bool m_abort; // Image containers cv::Mat m_src; cv::Mat m_dst; cv::Size m_imgSize; int m_frameCount; // keep a count of number of saved frames int m_numSaveImageRequests; // Counter to keep track of image saving bool m_continuousSaving; cv::VideoCapture m_cap; // video capture device const QString m_winName = QString("Live Feed"); double m_videoFPS; }; #endif // FRMGRABTHREAD_H
3,798
C
25.2
76
0.635071
adegirmenci/HBL-ICEbot/AscensionWidget/ascensionthread.h
#ifndef ASCENSIONTHREAD_H #define ASCENSIONTHREAD_H #include <QObject> #include <QMutex> #include <QMutexLocker> #include <QThread> #include <QWaitCondition> #include <QString> #include <QDateTime> #include <QTimer> #include <QDebug> #include <QQuaternion> #include <QMatrix3x3> #include <vector> #include "../icebot_definitions.h" #include "3DGAPI/ATC3DG.h" // ############################## // # ATC3DG (Ascension) classes # // ############################## // System class class CSystem { public: SYSTEM_CONFIGURATION m_config; }; // Sensor class class CSensor { public: SENSOR_CONFIGURATION m_config; }; // Transmitter class class CXmtr { public: TRANSMITTER_CONFIGURATION m_config; }; // ------------------------------ Q_DECLARE_METATYPE(DOUBLE_POSITION_MATRIX_TIME_Q_RECORD) Q_DECLARE_METATYPE(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>) // ################################## // # Ascension Thread Class Members # // ################################## class AscensionThread : public QObject { Q_OBJECT public: explicit AscensionThread(QObject *parent = 0); ~AscensionThread(); //bool isEMready(); //bool isRecording(); int getSampleRate(); int getNumSensors(); signals: void statusChanged(int status); //void EM_Ready(bool status); // tells the widget that the EM tracker is ready void logData(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data); void sendLatestReading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> latestReading); void logEvent(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int eventID); // EM_EVENT_IDS void logEventWithMessage(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int eventID, // EM_EVENT_IDS QString &message); void logError(int source, // LOG_SOURCE int logType, // LOG_TYPES QTime timeStamp, int errCode, // EM_ERROR_CODES QString message); void sendDataToGUI(int sensorID, const QString &output); void finished(); // emit upon termination public slots: bool initializeEM(); // open connection to EM void startAcquisition(); // start timer void stopAcquisition(); // stop timer bool disconnectEM(); // disconnect from EM void setEpoch(const QDateTime &datetime); // set Epoch void setSampleRate(int freq); // set freq void getLatestReading(const int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &dataContainer); void getLatestReadingsAll(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> &dataContainer); private slots: void getSample(); // called by timer private: // Instead of using "m_mutex.lock()" // use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex *m_mutex; // Timer for calling acquire data every 1/m_samplingFreq QTimer *m_timer; // Epoch for time stamps // During initializeEM(), check 'isEpochSet' flag // If Epoch is set externally from MainWindow, the flag will be true // Otherwise, Epoch will be set internally QDateTime m_epoch; bool m_isEpochSet; // Flag to indicate if EM tracker is ready for data collection // True if InitializeEM was successful bool m_isReady; // Flag to tell the run() loop to keep acquiring readings from EM bool m_keepRecording; // Fllag to abort actions (e.g. initialize, acquire, etc.) bool m_abort; // EM tracker variables CSystem m_ATC3DG; CSensor *m_pSensor; CXmtr *m_pXmtr; int m_errorCode; int m_i; int m_numSensorsAttached; int m_sensorID; short m_id; int m_samplingFreq; int m_records; int m_numberBytes; // latest reading std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> m_latestReading; std::vector<double> m_deltaT; double m_avgSamplingFreq; const int m_prec = 4; // precision for print operations // EM tracker error handler function void errorHandler_(int error); QString formatOutput(QTime &timeStamp, const int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &record); }; // ---------------- // HELPER FUNCTIONS // ---------------- inline const QString getCurrTimeStr(); inline const QString getCurrDateTimeStr(); #endif // ASCENSIONTHREAD_H
4,565
C
27.185185
99
0.630668
adegirmenci/HBL-ICEbot/AscensionWidget/ascensionthread.cpp
#include "ascensionthread.h" AscensionThread::AscensionThread(QObject *parent) : QObject(parent) { m_isEpochSet = false; m_isReady = false; m_keepRecording = false; m_abort = false; m_mutex = new QMutex(QMutex::Recursive); m_numSensorsAttached = 0; m_records = 0; m_latestReading.resize(4); m_deltaT.resize(EM_DELTA_T_SIZE,0); m_avgSamplingFreq = 0.0; qRegisterMetaType<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>("DOUBLE_POSITION_MATRIX_TIME_Q_RECORD"); qRegisterMetaType< std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> >("std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>"); } AscensionThread::~AscensionThread() { disconnectEM(); m_mutex->lock(); m_abort = true; qDebug() << "Ending AscensionThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; m_mutex->unlock(); delete m_mutex; emit finished(); } // ------------------------------ // SLOTS IMPLEMENTATION // ------------------------------ bool AscensionThread::initializeEM() // open connection to EM { bool status = true; QMutexLocker locker(m_mutex); // Initialize the ATC3DG driver and DLL // It is always necessary to first initialize the ATC3DG "system". By // "system" we mean the set of ATC3DG cards installed in the PC. All cards // will be initialized by a single call to InitializeBIRDSystem(). This // call will first invoke a hardware reset of each board. If at any time // during operation of the system an unrecoverable error occurs then the // first course of action should be to attempt to Recall InitializeBIRDSystem() // if this doesn't restore normal operating conditions there is probably a // permanent failure - contact tech support. // A call to InitializeBIRDSystem() does not return any information. // emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_INITIALIZE_BEGIN); emit statusChanged(EM_INITIALIZE_BEGIN); m_errorCode = InitializeBIRDSystem(); if(m_errorCode!=BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_INITIALIZE_FAILED); return status = false; } // GET SYSTEM CONFIGURATION // // In order to get information about the system we have to make a call to // GetBIRDSystemConfiguration(). This call will fill a fixed size structure // containing amongst other things the number of boards detected and the // number of sensors and transmitters the system can support (Note: This // does not mean that all sensors and transmitters that can be supported // are physically attached) // m_errorCode = GetBIRDSystemConfiguration(&m_ATC3DG.m_config); if(m_errorCode!=BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_INITIALIZE_FAILED); return status = false; } // GET SENSOR CONFIGURATION // // Having determined how many sensors can be supported we can dynamically // allocate storage for the information about each sensor. // This information is acquired through a call to GetSensorConfiguration() // This call will fill a fixed size structure containing amongst other things // a status which indicates whether a physical sensor is attached to this // sensor port or not. // m_pSensor = new CSensor[m_ATC3DG.m_config.numberSensors]; for(m_i = 0; m_i < m_ATC3DG.m_config.numberSensors; m_i++) { m_errorCode = GetSensorConfiguration(m_i, &(m_pSensor + m_i)->m_config); if(m_errorCode!=BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_INITIALIZE_FAILED); return status = false; } // if this sensor is attached, set number of sensors to current index // !THIS ASSUMES THAT SENSORS ARE ATTACHED IN ORDER // !BEGINNING AT 1 ON THE BOX (AND 0 IN C++) if( (m_pSensor + m_i)->m_config.attached ) m_numSensorsAttached = m_i + 1; } emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_SENSORS_DETECTED, QString::number(m_numSensorsAttached)); // GET TRANSMITTER CONFIGURATION // // The call to GetTransmitterConfiguration() performs a similar task to the // GetSensorConfiguration() call. It also returns a status in the filled // structure which indicates whether a transmitter is attached to this // port or not. In a single transmitter system it is only necessary to // find where that transmitter is in order to turn it on and use it. // m_pXmtr = new CXmtr[m_ATC3DG.m_config.numberTransmitters]; for(m_i = 0; m_i < m_ATC3DG.m_config.numberTransmitters; m_i++) { m_errorCode = GetTransmitterConfiguration(m_i, &(m_pXmtr + m_i)->m_config); if(m_errorCode!=BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_INITIALIZE_FAILED); return status = false; } } // Search for the first attached transmitter and turn it on // for(m_id = 0; m_id < m_ATC3DG.m_config.numberTransmitters; m_id++) { if((m_pXmtr + m_id)->m_config.attached) { // Transmitter selection is a system function. // Using the SELECT_TRANSMITTER parameter we send the id of the // transmitter that we want to run with the SetSystemParameter() call m_errorCode = SetSystemParameter(SELECT_TRANSMITTER, &m_id, sizeof(m_id)); if(m_errorCode!=BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_INITIALIZE_FAILED); return status = false; } break; } } // report the transmitter being used emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_TRANSMITTER_SET, QString::number(m_id)); // report the detected sampling rate m_samplingFreq = m_ATC3DG.m_config.measurementRate; emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_FREQ_DETECTED, QString::number(m_samplingFreq)); // Set sensor output to position + rotation matrix + time stamp for(m_sensorID = 0; m_sensorID < m_numSensorsAttached; m_sensorID++) { DATA_FORMAT_TYPE buf = DOUBLE_POSITION_MATRIX_TIME_Q; DATA_FORMAT_TYPE *pBuf = &buf; m_errorCode = SetSensorParameter(m_sensorID, DATA_FORMAT, pBuf, sizeof(buf)); if(m_errorCode!=BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_INITIALIZE_FAILED); return status = false; } } // resize container based on the number of sensors m_latestReading.resize(m_numSensorsAttached); // set flag to ready m_isReady = status; //locker.unlock(); // set sample rate setSampleRate(EM_DEFAULT_SAMPLE_RATE); // set to METRIC BOOL isMetric = TRUE; m_errorCode = SetSystemParameter(METRIC, &isMetric, sizeof(isMetric)); if(m_errorCode!=BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_INITIALIZE_FAILED); return status = false; } emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_INITIALIZED); emit statusChanged(EM_INITIALIZED); return status; } void AscensionThread::startAcquisition() // start timer { QMutexLocker locker(m_mutex); // reset stats m_deltaT.clear(); m_deltaT.resize(EM_DELTA_T_SIZE,0); m_avgSamplingFreq = 0; // start timer m_timer = new QTimer(this); connect(m_timer,SIGNAL(timeout()),this,SLOT(getSample())); m_timer->start(1000./m_samplingFreq); m_keepRecording = true; m_i = 0; emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_ACQUISITION_STARTED); emit statusChanged(EM_ACQUISITION_STARTED); } void AscensionThread::getSample() // called by timer { // Collect data from all birds // Note: The default data format is DOUBLE_POSITION_ANGLES. We can use this // format without first setting it. // 4 sensors DOUBLE_POSITION_MATRIX_TIME_Q_RECORD record[8*4], *pRecord = record; //DOUBLE_POSITION_MATRIX_TIME_STAMP_RECORD *pRecord = record //DOUBLE_POSITION_MATRIX_TIME_STAMP_RECORD record, *pRecord = &record; QMutexLocker locker(m_mutex); // request all sensor readings at once m_errorCode = GetSynchronousRecord(ALL_SENSORS, pRecord, sizeof(record[0]) * m_numSensorsAttached); QTime tstamp = QTime::currentTime(); // get time if(m_errorCode != BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_ACQUIRE_FAILED); //locker.unlock(); stopAcquisition(); return; } // async version, not prefered, therefore commented out /* // // scan the sensors and request a record - this is async, not preferred // for(m_sensorID = 0; m_sensorID < m_numSensorsAttached; m_sensorID++) // { // m_errorCode = GetAsynchronousRecord(m_sensorID, &record[m_sensorID], sizeof(record[m_sensorID])); // //m_errorCode = GetSynchronousRecord(m_sensorID, &record[m_sensorID], sizeof(record[m_sensorID])); // if(m_errorCode != BIRD_ERROR_SUCCESS) // { // errorHandler_(m_errorCode); // emit statusChanged(EM_ACQUIRE_FAILED); // //locker.unlock(); // stopAcquisition(); // return; // } // // Weirdly, the vector part is reported with a flipped sign. Scalar part is fine. // // You can check this in MATLAB // // Use the Cubes.exe provided by Ascension to get the azimuth, elevation, and roll. // // These are the Z,Y,X rotation angles. // // You can use the Robotics Toolbox by P. Corke and run convert from quat to rpy // // rad2deg(quat2rpy(q0,q1,q2,q3)) -> this gives you the X,Y,Z rotation angles (notice the flipped order!) // // Flipping the sign of q1,q2,q3 will fix the mismatch // record[m_sensorID].q[1] *= -1.0; // record[m_sensorID].q[2] *= -1.0; // record[m_sensorID].q[3] *= -1.0; // } */ // get time difference between readings // m_deltaT hold the latest index as the last element in the vector // this index is incremented to essentially create a circular buffer m_deltaT[m_deltaT[EM_DELTA_T_SIZE-1]] = record[0].time - m_latestReading[0].time; m_deltaT[EM_DELTA_T_SIZE-1] = ((int)(m_deltaT[EM_DELTA_T_SIZE-1] + 1))%(EM_DELTA_T_SIZE-1); // average the deltaT's m_avgSamplingFreq = std::accumulate(m_deltaT.begin(),m_deltaT.end()-1,0.0)/(EM_DELTA_T_SIZE-1); m_latestReading.clear(); m_latestReading.resize(4); for(m_sensorID = 0; m_sensorID < m_numSensorsAttached; m_sensorID++) { // get the status of the last data record // only report the data if everything is okay unsigned int status = GetSensorStatus( m_sensorID ); if( status == VALID_STATUS) { // The rotations are reported in inverted form. // You can check this in MATLAB // Use the Cubes.exe provided by Ascension to get the azimuth, elevation, and roll. // These are the Z,Y,X rotation angles. // You can use the Robotics Toolbox by P. Corke and run convert from quat to rpy // rad2deg(quat2rpy(q0,q1,q2,q3)) -> this gives you the X,Y,Z rotation angles (notice the flipped order!) // Flipping the sign of q1,q2,q3 will fix the mismatch // For a quaternion, this corresponds to the vector part being negated. // record[m_sensorID].q[1] *= -1.0; // record[m_sensorID].q[2] *= -1.0; // record[m_sensorID].q[3] *= -1.0; // transpose rotation matrix to invert it (R transpose = R inverse) double temp = record[m_sensorID].s[1][0]; record[m_sensorID].s[1][0] = record[m_sensorID].s[0][1]; record[m_sensorID].s[0][1] = temp; temp = record[m_sensorID].s[2][0]; record[m_sensorID].s[2][0] = record[m_sensorID].s[0][2]; record[m_sensorID].s[0][2] = temp; temp = record[m_sensorID].s[1][2]; record[m_sensorID].s[1][2] = record[m_sensorID].s[2][1]; record[m_sensorID].s[2][1] = temp; // transpose done m_latestReading[m_sensorID] = record[m_sensorID]; emit logData(tstamp, m_sensorID, record[m_sensorID]); //emit logData(tstamp, m_sensorID, record); if( m_i == 0 ){ //emit sendDataToGUI(m_sensorID, formatOutput(tstamp, m_sensorID, record)); emit sendDataToGUI(m_sensorID, formatOutput(tstamp, m_sensorID, record[m_sensorID])); } } else qDebug() << "Invalid data received, sensorID:" << m_sensorID; } // if( m_i == 0 ){ // std::printf("EM rate: %.3f ms\n", m_avgSamplingFreq*1000.0); // } m_i = (m_i + 1)%(int)(m_samplingFreq/10); // emit m_latestReading for use with the controller emit sendLatestReading(m_latestReading); } void AscensionThread::stopAcquisition() // stop timer { QMutexLocker locker(m_mutex); if ( m_keepRecording ) { m_keepRecording = false; m_timer->stop(); disconnect(m_timer,SIGNAL(timeout()),0,0); delete m_timer; emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_ACQUISITION_STOPPED); emit statusChanged(EM_ACQUISITION_STOPPED); } } bool AscensionThread::disconnectEM() // disconnect from EM { bool status = true; stopAcquisition(); QMutexLocker locker(m_mutex); // Turn off the transmitter before exiting // We turn off the transmitter by "selecting" a transmitter with an id of "-1" if(m_id != -1) { m_id = -1; m_errorCode = SetSystemParameter(SELECT_TRANSMITTER, &m_id, sizeof(m_id)); if(m_errorCode != BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_DISCONNECT_FAILED); return status = false; } // Free memory allocations before exiting delete[] m_pSensor; delete[] m_pXmtr; emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_DISCONNECTED); emit statusChanged(EM_DISCONNECTED); } return status; } void AscensionThread::setEpoch(const QDateTime &datetime) // set Epoch { QMutexLocker locker(m_mutex); if(!m_keepRecording) { m_epoch = datetime; m_isEpochSet = true; emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_EPOCH_SET, m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz")); } else emit logEvent(SRC_EM, LOG_INFO, QTime::currentTime(), EM_EPOCH_SET_FAILED); } void AscensionThread::setSampleRate(int freq) // set freq { QMutexLocker locker(m_mutex); // not recording if(!m_keepRecording) { // freq too low, clamp if( EM_MIN_SAMPLE_RATE > freq ) { freq = EM_MIN_SAMPLE_RATE; emit logError(SRC_EM, LOG_ERROR, QTime::currentTime(), EM_BELOW_MIN_SAMPLE_RATE, QString::number(freq)); } // freq too high, clamp else if( EM_MAX_SAMPLE_RATE < freq ) { freq = EM_ABOVE_MAX_SAMPLE_RATE; emit logError(SRC_EM, LOG_ERROR, QTime::currentTime(), EM_ABOVE_MAX_SAMPLE_RATE, QString::number(freq)); } // set freq double rate = freq*1.0f; m_errorCode = SetSystemParameter(MEASUREMENT_RATE, &rate, sizeof(rate)); if(m_errorCode!=BIRD_ERROR_SUCCESS) { errorHandler_(m_errorCode); emit statusChanged(EM_FREQ_SET_FAILED); } else { m_samplingFreq = freq; // log event emit logEventWithMessage(SRC_EM, LOG_INFO, QTime::currentTime(), EM_FREQ_SET, QString::number(m_samplingFreq)); // emit status change emit statusChanged(EM_FREQ_SET); } } else { emit logError(SRC_EM, LOG_ERROR, QTime::currentTime(), EM_CANT_MUTATE_WHILE_RUNNING, QString("")); emit statusChanged(EM_FREQ_SET_FAILED); } } // ---------------- // ACCESSORS // ---------------- int AscensionThread::getSampleRate() { QMutexLocker locker(m_mutex); return m_samplingFreq; } int AscensionThread::getNumSensors() { QMutexLocker locker(m_mutex); return m_numSensorsAttached; } void AscensionThread::getLatestReading(const int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &dataContainer) { QMutexLocker locker(m_mutex); if(sensorID < 0) qDebug() << "sensorID can not be negative!"; else if(sensorID < m_numSensorsAttached) dataContainer = m_latestReading[sensorID]; else qDebug() << "sensorID exceeds number of sensors!"; } void AscensionThread::getLatestReadingsAll(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> &dataContainer) { QMutexLocker locker(m_mutex); dataContainer = m_latestReading; } // ---------------- // HELPER FUNCTIONS // ---------------- void AscensionThread::errorHandler_(int error) { char buffer[1024]; char *pBuffer = &buffer[0]; int numberBytes; while(error!=BIRD_ERROR_SUCCESS) { QString msg(QString("Error Code %1: ").arg(QString::number(error))); error = GetErrorText(error, pBuffer, sizeof(buffer), SIMPLE_MESSAGE); numberBytes = strlen(buffer); //buffer[numberBytes] = '\n'; // append a newline to buffer //printf("%s", buffer); msg.append(buffer); qDebug() << msg; emit logError(SRC_EM, LOG_ERROR, QTime::currentTime(), EM_FAIL, msg); } } QString AscensionThread::formatOutput(QTime &timeStamp, const int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD &data) { QDateTime ts; ts.setMSecsSinceEpoch(data.time*1000); QString output; output.append(QString("[Sensor %1 - %2] - ").arg(sensorID + 1).arg(EM_SENSOR_NAMES[sensorID])); output.append(timeStamp.toString("HH.mm.ss.zzz\n")); // output.append(QString("%1\t%2\t%3\n") // .arg(QString::number(data.x,'f',m_prec)) // .arg(QString::number(data.y,'f',m_prec)) // .arg(QString::number(data.z,'f',m_prec))); // TODO: comment out the quaternion // output.append("Rot (Quat)\n"); // output.append(QString("%1\t%2\t%3\n%4\n") // .arg(QString::number(data.q[0],'f',m_prec)) // .arg(QString::number(data.q[1],'f',m_prec)) // .arg(QString::number(data.q[2],'f',m_prec)) // .arg(QString::number(data.q[3],'f',m_prec))); // QQuaternion qu = QQuaternion(data.q[0], data.q[1], data.q[2], data.q[3]); // QMatrix3x3 mat = qu.toRotationMatrix(); output.append(QString("%1 %2 %3 %4\n%5 %6 %7 %8\n%9 %10 %11 %12\n") .arg(QString::number(data.s[0][0],'f',m_prec)) .arg(QString::number(data.s[0][1],'f',m_prec)) .arg(QString::number(data.s[0][2],'f',m_prec)) .arg(QString::number(data.x ,'f',m_prec)) .arg(QString::number(data.s[1][0],'f',m_prec)) .arg(QString::number(data.s[1][1],'f',m_prec)) .arg(QString::number(data.s[1][2],'f',m_prec)) .arg(QString::number(data.y ,'f',m_prec)) .arg(QString::number(data.s[2][0],'f',m_prec)) .arg(QString::number(data.s[2][1],'f',m_prec)) .arg(QString::number(data.s[2][2],'f',m_prec)) .arg(QString::number(data.z ,'f',m_prec))); output.append("Quality: "); output.append(QString("%1\n") .arg(QString::number(data.quality,'f',1))); output.append(QString("Time: %1").arg(ts.toString("hh:mm:ss.zzz\n"))); return output; } inline const QString getCurrTimeStr() { return QTime::currentTime().toString("HH.mm.ss.zzz"); } inline const QString getCurrDateTimeStr() { return QDateTime::currentDateTime().toString("yyyy/MM/dd - hh:mm:ss.zzz"); }
20,677
C++
35.793594
128
0.5997
adegirmenci/HBL-ICEbot/AscensionWidget/ascensionwidget.cpp
#include "ascensionwidget.h" #include "ui_ascensionwidget.h" AscensionWidget::AscensionWidget(QWidget *parent) : QWidget(parent), ui(new Ui::AscensionWidget) { ui->setupUi(this); m_worker = new AscensionThread; m_worker->moveToThread(&m_thread); connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater); m_thread.start(); connect(ui->initButton, SIGNAL(clicked()), m_worker, SLOT(initializeEM())); connect(ui->acquireButton, SIGNAL(clicked()), m_worker, SLOT(startAcquisition())); connect(ui->stopButton, SIGNAL(clicked()), m_worker, SLOT(stopAcquisition())); connect(ui->disconnectButton, SIGNAL(clicked()), m_worker, SLOT(disconnectEM())); connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int))); connect(m_worker, SIGNAL(sendDataToGUI(int,QString)), this, SLOT(receiveDataFromWorker(int,QString))); } AscensionWidget::~AscensionWidget() { m_thread.quit(); m_thread.wait(); qDebug() << "Ascension thread quit."; delete ui; } void AscensionWidget::workerStatusChanged(int status) { switch(status) { case EM_INITIALIZE_BEGIN: ui->initButton->setEnabled(false); ui->statusLineEdit->setText("Initializing..."); ui->outputTextEdit->appendPlainText("Initializing...This will take a minute."); break; case EM_INITIALIZE_FAILED: ui->initButton->setEnabled(true); ui->statusLineEdit->setText("Initialization failed!"); ui->outputTextEdit->appendPlainText("Initialization failed!"); break; case EM_INITIALIZED: ui->initButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->acquireButton->setEnabled(true); ui->outputTextEdit->appendPlainText(QString("%1 sensor(s) plugged in.") .arg(m_worker->getNumSensors())); ui->outputTextEdit->appendPlainText(QString("Measurement Rate: %1Hz") .arg(m_worker->getSampleRate())); ui->numBirdsComboBox->setCurrentIndex(m_worker->getNumSensors()); break; case EM_DISCONNECT_FAILED: ui->statusLineEdit->setText("Disconnection failed."); ui->outputTextEdit->appendPlainText("Disconnection failed! FATAL ERROR!"); break; case EM_DISCONNECTED: ui->initButton->setEnabled(true); ui->disconnectButton->setEnabled(false); ui->acquireButton->setEnabled(false); ui->statusLineEdit->setText("Disconnected."); ui->outputTextEdit->appendPlainText("Disconnected."); break; case EM_FREQ_SET_FAILED: ui->outputTextEdit->appendPlainText("Sample rate could not be changed!"); break; case EM_FREQ_SET: ui->outputTextEdit->appendPlainText(QString("Sample rate changed to %1Hz.") .arg(m_worker->getSampleRate())); break; case EM_ACQUISITION_STARTED: ui->statusLineEdit->setText("Acquiring data."); ui->acquireButton->setEnabled(false); ui->stopButton->setEnabled(true); break; case EM_ACQUISITION_STOPPED: ui->statusLineEdit->setText("Acquisition stopped."); ui->acquireButton->setEnabled(true); ui->stopButton->setEnabled(false); break; case EM_ACQUIRE_FAILED: ui->statusLineEdit->setText("Acquisition failed."); break; default: ui->statusLineEdit->setText("Unknown state!"); break; } } void AscensionWidget::receiveDataFromWorker(int sensorID, const QString &data) { if(sensorID == 0) ui->outputTextEdit->clear(); ui->outputTextEdit->appendPlainText(data); } void AscensionWidget::on_initButton_clicked() { ui->initButton->setEnabled(false); }
3,849
C++
34.321101
88
0.639127
adegirmenci/HBL-ICEbot/AscensionWidget/ascensionwidget.h
#ifndef ASCENSIONWIDGET_H #define ASCENSIONWIDGET_H #include <QWidget> #include <QThread> #include "ascensionthread.h" namespace Ui { class AscensionWidget; } class AscensionWidget : public QWidget { Q_OBJECT public: explicit AscensionWidget(QWidget *parent = 0); ~AscensionWidget(); AscensionThread *m_worker; private slots: void workerStatusChanged(int status); void on_initButton_clicked(); void receiveDataFromWorker(int sensorID, const QString &data); private: Ui::AscensionWidget *ui; QThread m_thread; // Ascension Thread will live in here }; #endif // ASCENSIONWIDGET_H
625
C
16.388888
66
0.728
adegirmenci/HBL-ICEbot/AscensionWidget/3DGAPI/ATC3DG.h
//*****************************************************************************// //*****************************************************************************// // // Author: crobertson // // Revision for ATC3DG 36.0.19.7 // // // Date: 02/01/2012 // // COPYRIGHT: COPYRIGHT ASCENSION TECHNOLOGY CORPORATION - 2012 // //*****************************************************************************// //*****************************************************************************// // // DESCRIPTION: ATC3DG3.h // // Header file containing function prototypes for the BIRD system API // Also contains definitions of constants and structures required. // //*****************************************************************************// //*****************************************************************************// #ifndef ATC3DG_H #define ATC3DG_H #ifdef LINUX #define ATC3DG_API #else #ifdef MAC #define ATC3DG_API #else #ifdef DEF_FILE #define ATC3DG_API #else #ifdef ATC3DG_EXPORTS #define ATC3DG_API extern "C" __declspec(dllexport) #else #define ATC3DG_API extern "C" __declspec(dllimport) #endif #endif #endif #endif /***************************************************************************** ENUMERATED CONSTANTS *****************************************************************************/ //***************************************************************************** // // ERROR MESSAGE format is as follows: // =================================== // // All commands return a 32-bit integer with the following bit definitions: // // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 // +-+-+-+-+-+-+---------+---------+-------------------------------+ // |E|W|X|R|B|M| Reserved| Address | Code | // +-+-+-+-+-+-+---------+---------+-------------------------------+ // // where // // E - indicates an ERROR // (Operation either cannot or will not proceed as intended // e.g. EEPROM error of some kind. Requires hardware reset // of system and/or replacement of hardware) // W - indicates a WARNING // (Operation may proceed but remedial action needs to be taken // e.g. Sensor has been removed. Fix by replacing Sensor) // X - indicates Transmitter related message // R - indicates Sensor related message // (If neither X nor R is set then the message is a SYSTEM message) // B - indicates message originated in the BIRD hardware // M - indicates there are more messages pending (no longer used) // // Address gives the index number of the device generating the message // (Driver and system messages always have address 0) // // Code - is the status code as enumerated in BIRD_ERROR_CODES // //***************************************************************************** enum BIRD_ERROR_CODES { // ERROR CODE DISPOSITION // | (Some error codes have been retired. // | The column below describes which codes // | have been retired and why. O = Obolete, // V I = handled internally) BIRD_ERROR_SUCCESS=0, //00 < > No error BIRD_ERROR_PCB_HARDWARE_FAILURE, //01 < > indeterminate failure on PCB BIRD_ERROR_TRANSMITTER_EEPROM_FAILURE, //02 <I> transmitter bad eeprom BIRD_ERROR_SENSOR_SATURATION_START, //03 <I> sensor has gone into saturation BIRD_ERROR_ATTACHED_DEVICE_FAILURE, //04 <O> either a sensor or transmitter reports bad BIRD_ERROR_CONFIGURATION_DATA_FAILURE, //05 <O> device EEPROM detected but corrupt BIRD_ERROR_ILLEGAL_COMMAND_PARAMETER, //06 < > illegal PARAMETER_TYPE passed to driver BIRD_ERROR_PARAMETER_OUT_OF_RANGE, //07 < > PARAMETER_TYPE legal, but PARAMETER out of range BIRD_ERROR_NO_RESPONSE, //08 <O> no response at all from target card firmware BIRD_ERROR_COMMAND_TIME_OUT, //09 < > time out before response from target board BIRD_ERROR_INCORRECT_PARAMETER_SIZE, //10 < > size of parameter passed is incorrect BIRD_ERROR_INVALID_VENDOR_ID, //11 <O> driver started with invalid PCI vendor ID BIRD_ERROR_OPENING_DRIVER, //12 < > couldn't start driver BIRD_ERROR_INCORRECT_DRIVER_VERSION, //13 < > wrong driver version found BIRD_ERROR_NO_DEVICES_FOUND, //14 < > no BIRDs were found anywhere BIRD_ERROR_ACCESSING_PCI_CONFIG, //15 < > couldn't access BIRDs config space BIRD_ERROR_INVALID_DEVICE_ID, //16 < > device ID out of range BIRD_ERROR_FAILED_LOCKING_DEVICE, //17 < > couldn't lock driver BIRD_ERROR_BOARD_MISSING_ITEMS, //18 < > config space items missing BIRD_ERROR_NOTHING_ATTACHED, //19 <O> card found but no sensors or transmitters attached BIRD_ERROR_SYSTEM_PROBLEM, //20 <O> non specific system problem BIRD_ERROR_INVALID_SERIAL_NUMBER, //21 <O> serial number does not exist in system BIRD_ERROR_DUPLICATE_SERIAL_NUMBER, //22 <O> 2 identical serial numbers passed in set command BIRD_ERROR_FORMAT_NOT_SELECTED, //23 <O> data format not selected yet BIRD_ERROR_COMMAND_NOT_IMPLEMENTED, //24 < > valid command, not implemented yet BIRD_ERROR_INCORRECT_BOARD_DEFAULT, //25 < > incorrect response to reading parameter BIRD_ERROR_INCORRECT_RESPONSE, //26 <O> response received, but data,values in error BIRD_ERROR_NO_TRANSMITTER_RUNNING, //27 < > there is no transmitter running BIRD_ERROR_INCORRECT_RECORD_SIZE, //28 < > data record size does not match data format size BIRD_ERROR_TRANSMITTER_OVERCURRENT, //29 <I> transmitter over-current detected BIRD_ERROR_TRANSMITTER_OPEN_CIRCUIT, //30 <I> transmitter open circuit or removed BIRD_ERROR_SENSOR_EEPROM_FAILURE, //31 <I> sensor bad eeprom BIRD_ERROR_SENSOR_DISCONNECTED, //32 <I> previously good sensor has been removed BIRD_ERROR_SENSOR_REATTACHED, //33 <I> previously good sensor has been reattached BIRD_ERROR_NEW_SENSOR_ATTACHED, //34 <O> new sensor attached BIRD_ERROR_UNDOCUMENTED, //35 <I> undocumented error code received from bird BIRD_ERROR_TRANSMITTER_REATTACHED, //36 <I> previously good transmitter has been reattached BIRD_ERROR_WATCHDOG, //37 < > watchdog timeout BIRD_ERROR_CPU_TIMEOUT_START, //38 <I> CPU ran out of time executing algorithm (start) BIRD_ERROR_PCB_RAM_FAILURE, //39 <I> BIRD on-board RAM failure BIRD_ERROR_INTERFACE, //40 <I> BIRD PCI interface error BIRD_ERROR_PCB_EPROM_FAILURE, //41 <I> BIRD on-board EPROM failure BIRD_ERROR_SYSTEM_STACK_OVERFLOW, //42 <I> BIRD program stack overrun BIRD_ERROR_QUEUE_OVERRUN, //43 <I> BIRD error message queue overrun BIRD_ERROR_PCB_EEPROM_FAILURE, //44 <I> PCB bad EEPROM BIRD_ERROR_SENSOR_SATURATION_END, //45 <I> Sensor has gone out of saturation BIRD_ERROR_NEW_TRANSMITTER_ATTACHED, //46 <O> new transmitter attached BIRD_ERROR_SYSTEM_UNINITIALIZED, //47 < > InitializeBIRDSystem not called yet BIRD_ERROR_12V_SUPPLY_FAILURE, //48 <I > 12V Power supply not within specification BIRD_ERROR_CPU_TIMEOUT_END, //49 <I> CPU ran out of time executing algorithm (end) BIRD_ERROR_INCORRECT_PLD, //50 < > PCB PLD not compatible with this API DLL BIRD_ERROR_NO_TRANSMITTER_ATTACHED, //51 < > No transmitter attached to this ID BIRD_ERROR_NO_SENSOR_ATTACHED, //52 < > No sensor attached to this ID // new error codes added 2/27/03 // (Version 1,31,5,01) multi-sensor, synchronized BIRD_ERROR_SENSOR_BAD, //53 < > Non-specific hardware problem BIRD_ERROR_SENSOR_SATURATED, //54 < > Sensor saturated error BIRD_ERROR_CPU_TIMEOUT, //55 < > CPU unable to complete algorithm on current cycle BIRD_ERROR_UNABLE_TO_CREATE_FILE, //56 < > Could not create and open file for saving setup BIRD_ERROR_UNABLE_TO_OPEN_FILE, //57 < > Could not open file for restoring setup BIRD_ERROR_MISSING_CONFIGURATION_ITEM, //58 < > Mandatory item missing from configuration file BIRD_ERROR_MISMATCHED_DATA, //59 < > Data item in file does not match system value BIRD_ERROR_CONFIG_INTERNAL, //60 < > Internal error in config file handler BIRD_ERROR_UNRECOGNIZED_MODEL_STRING, //61 < > Board does not have a valid model string BIRD_ERROR_INCORRECT_SENSOR, //62 < > Invalid sensor type attached to this board BIRD_ERROR_INCORRECT_TRANSMITTER, //63 < > Invalid transmitter type attached to this board // new error code added 1/18/05 // (Version 1.31.5.22) // multi-sensor, // synchronized-fluxgate, // integrating micro-sensor, // flat panel transmitter BIRD_ERROR_ALGORITHM_INITIALIZATION, //64 < > Flat panel algorithm initialization failed // new error code for multi-sync BIRD_ERROR_LOST_CONNECTION, //65 < > USB connection has been lost BIRD_ERROR_INVALID_CONFIGURATION, //66 < > Invalid configuration // VPD error code BIRD_ERROR_TRANSMITTER_RUNNING, //67 < > TX running while reading/writing VPD BIRD_ERROR_MAXIMUM_VALUE = 0x7F // ## value = number of error codes ## }; // error message defines #define ERROR_FLAG 0x80000000 #define WARNING_FLAG 0x40000000 #define XMTR_ERROR_SOURCE 0x20000000 #define RCVR_ERROR_SOURCE 0x10000000 #define BIRD_ERROR_SOURCE 0x08000000 #define DIAG_ERROR_SOURCE 0x04000000 // SYSTEM error = none of the above // NOTE: The MULTIPLE_ERRORS flag is no longer generated // It has been left in for backwards compatibility #define MULTIPLE_ERRORS 0x04000000 // DEVICE STATUS ERROR BIT DEFINITIONS #define VALID_STATUS 0x00000000 #define GLOBAL_ERROR 0x00000001 #define NOT_ATTACHED 0x00000002 #define SATURATED 0x00000004 #define BAD_EEPROM 0x00000008 #define HARDWARE 0x00000010 #define NON_EXISTENT 0x00000020 #define UNINITIALIZED 0x00000040 #define NO_TRANSMITTER_RUNNING 0x00000080 #define BAD_12V 0x00000100 #define CPU_TIMEOUT 0x00000200 #define INVALID_DEVICE 0x00000400 #define NO_TRANSMITTER_ATTACHED 0x00000800 #define OUT_OF_MOTIONBOX 0x00001000 #define ALGORITHM_INITIALIZING 0x00002000 #define TRUE 1 #define FALSE 0 enum MESSAGE_TYPE { SIMPLE_MESSAGE, // short string describing error code VERBOSE_MESSAGE, // long string describing error code }; enum TRANSMITTER_PARAMETER_TYPE { SERIAL_NUMBER_TX, // attached transmitter's serial number REFERENCE_FRAME, // structure of type DOUBLE_ANGLES_RECORD XYZ_REFERENCE_FRAME, // boolean value to select/deselect mode VITAL_PRODUCT_DATA_TX, // single byte parameter to be read/write from VPD section of xmtr EEPROM MODEL_STRING_TX, // 11 byte null terminated character string PART_NUMBER_TX, // 16 byte null terminated character string END_OF_TX_LIST }; enum SENSOR_PARAMETER_TYPE { DATA_FORMAT, // enumerated constant of type DATA_FORMAT_TYPE ANGLE_ALIGN, // structure of type DOUBLE_ANGLES_RECORD HEMISPHERE, // enumerated constant of type HEMISPHERE_TYPE FILTER_AC_WIDE_NOTCH, // boolean value to select/deselect filter FILTER_AC_NARROW_NOTCH, // boolean value to select/deselect filter FILTER_DC_ADAPTIVE, // double value in range 0.0 (no filtering) to 1.0 (max) FILTER_ALPHA_PARAMETERS,// structure of type ADAPTIVE_PARAMETERS FILTER_LARGE_CHANGE, // boolean value to select/deselect filter QUALITY, // structure of type QUALITY_PARAMETERS SERIAL_NUMBER_RX, // attached sensor's serial number SENSOR_OFFSET, // structure of type DOUBLE_POSITION_RECORD VITAL_PRODUCT_DATA_RX, // single byte parameter to be read/write from VPD section of sensor EEPROM VITAL_PRODUCT_DATA_PREAMP, // single byte parameter to be read/write from VPD section of preamp EEPROM MODEL_STRING_RX, // 11 byte null terminated character string PART_NUMBER_RX, // 16 byte null terminated character string MODEL_STRING_PREAMP, // 11 byte null terminated character string PART_NUMBER_PREAMP, // 16 byte null terminated character string PORT_CONFIGURATION, // enumerated constant of type PORT_CONFIGURATION_TYPE END_OF_RX_LIST }; enum BOARD_PARAMETER_TYPE { SERIAL_NUMBER_PCB, // installed board's serial number BOARD_SOFTWARE_REVISIONS, // BOARD_REVISIONS structure POST_ERROR_PCB, // board POST_ERROR_PARAMETER DIAGNOSTIC_TEST_PCB, // board DIAGNOSTIC_TEST_PARAMETER VITAL_PRODUCT_DATA_PCB, // single byte parameter to be read/write from VPD section of board EEPROM MODEL_STRING_PCB, // 11 byte null terminated character string PART_NUMBER_PCB, // 16 byte null terminated character string END_OF_PCB_LIST_BRD }; enum SYSTEM_PARAMETER_TYPE { SELECT_TRANSMITTER, // short int equal to transmitterID of selected transmitter POWER_LINE_FREQUENCY, // double value (range is hardware dependent) AGC_MODE, // enumerated constant of type AGC_MODE_TYPE MEASUREMENT_RATE, // double value (range is hardware dependent) MAXIMUM_RANGE, // double value (range is hardware dependent) METRIC, // boolean value to select metric units for position VITAL_PRODUCT_DATA, // single byte parameter to be read/write from VPD section of board EEPROM POST_ERROR, // system (board 0) POST_ERROR_PARAMETER DIAGNOSTIC_TEST, // system (board 0) DIAGNOSTIC_TEST_PARAMETER REPORT_RATE, // single byte 1-127 COMMUNICATIONS_MEDIA, // Media structure LOGGING, // Boolean RESET, // Boolean AUTOCONFIG, // BYTE 1-127 AUXILIARY_PORT, // structure of type AUXILIARY_PORT_PARAMETERS COMMUTATION_MODE, // boolean value to select commutation of sensor data for interconnect pickup rejection END_OF_LIST // end of list place holder }; enum COMMUNICATIONS_MEDIA_TYPE { USB, // Auto select USB driver RS232, // Force to RS232 TCPIP // Force to TCP/IP }; enum FILTER_OPTION { NO_FILTER, DEFAULT_FLOCK_FILTER }; enum HEMISPHERE_TYPE { FRONT, BACK, TOP, BOTTOM, LEFT, RIGHT }; enum AGC_MODE_TYPE { TRANSMITTER_AND_SENSOR_AGC, // Old style normal addressing mode SENSOR_AGC_ONLY // Old style extended addressing mode }; enum PORT_CONFIGURATION_TYPE { DOF_NOT_ACTIVE, // No sensor associated with this ID, e.g. ID 5 on a 6DOF port DOF_6_XYZ_AER, // 6 degrees of freedom DOF_5_XYZ_AE, // 5 degrees of freedom, no roll }; enum AUXILIARY_PORT_TYPE { AUX_PORT_NOT_SUPPORTED, // There is no auxiliary port associated with this sensor port AUX_PORT_NOT_SELECTED, // The auxiliary port is not selected. AUX_PORT_SELECTED, // The auxiliary port is selected. }; enum DATA_FORMAT_TYPE { NO_FORMAT_SELECTED=0, // SHORT (integer) formats SHORT_POSITION, SHORT_ANGLES, SHORT_MATRIX, SHORT_QUATERNIONS, SHORT_POSITION_ANGLES, SHORT_POSITION_MATRIX, SHORT_POSITION_QUATERNION, // DOUBLE (floating point) formats DOUBLE_POSITION, DOUBLE_ANGLES, DOUBLE_MATRIX, DOUBLE_QUATERNIONS, DOUBLE_POSITION_ANGLES, // system default DOUBLE_POSITION_MATRIX, DOUBLE_POSITION_QUATERNION, // DOUBLE (floating point) formats with time stamp appended DOUBLE_POSITION_TIME_STAMP, DOUBLE_ANGLES_TIME_STAMP, DOUBLE_MATRIX_TIME_STAMP, DOUBLE_QUATERNIONS_TIME_STAMP, DOUBLE_POSITION_ANGLES_TIME_STAMP, DOUBLE_POSITION_MATRIX_TIME_STAMP, DOUBLE_POSITION_QUATERNION_TIME_STAMP, // DOUBLE (floating point) formats with time stamp appended and quality # DOUBLE_POSITION_TIME_Q, DOUBLE_ANGLES_TIME_Q, DOUBLE_MATRIX_TIME_Q, DOUBLE_QUATERNIONS_TIME_Q, DOUBLE_POSITION_ANGLES_TIME_Q, DOUBLE_POSITION_MATRIX_TIME_Q, DOUBLE_POSITION_QUATERNION_TIME_Q, // These DATA_FORMAT_TYPE codes contain every format in a single structure SHORT_ALL, DOUBLE_ALL, DOUBLE_ALL_TIME_STAMP, DOUBLE_ALL_TIME_STAMP_Q, DOUBLE_ALL_TIME_STAMP_Q_RAW, // this format contains a raw data matrix and // is for factory use only... // DOUBLE (floating point) formats with time stamp appended, quality # and button DOUBLE_POSITION_ANGLES_TIME_Q_BUTTON, DOUBLE_POSITION_MATRIX_TIME_Q_BUTTON, DOUBLE_POSITION_QUATERNION_TIME_Q_BUTTON, // New types for button and wrapper DOUBLE_POSITION_ANGLES_MATRIX_QUATERNION_TIME_Q_BUTTON, MAXIMUM_FORMAT_CODE }; enum BOARD_TYPES { ATC3DG_MEDSAFE, // Standalone, DSP, 4 sensor PCIBIRD_STD1, // single standard sensor PCIBIRD_STD2, // dual standard sensor PCIBIRD_8mm1, // single 8mm sensor PCIBIRD_8mm2, // dual 8mm sensor PCIBIRD_2mm1, // single 2mm sensor (microsensor) PCIBIRD_2mm2, // dual 2mm sensor (microsensor) PCIBIRD_FLAT, // flat transmitter, 8mm PCIBIRD_FLAT_MICRO1, // flat transmitter, single TEM sensor (all types) PCIBIRD_FLAT_MICRO2, // flat transmitter, dual TEM sensor (all types) PCIBIRD_DSP4, // Standalone, DSP, 4 sensor PCIBIRD_UNKNOWN, // default ATC3DG_BB // BayBird }; enum DEVICE_TYPES { STANDARD_SENSOR, // 25mm standard sensor TYPE_800_SENSOR, // 8mm sensor STANDARD_TRANSMITTER, // TX for 25mm sensor MINIBIRD_TRANSMITTER, // TX for 8mm sensor SMALL_TRANSMITTER, // "compact" transmitter TYPE_500_SENSOR, // 5mm sensor TYPE_180_SENSOR, // 1.8mm microsensor TYPE_130_SENSOR, // 1.3mm microsensor TYPE_TEM_SENSOR, // 1.8mm, 1.3mm, 0.Xmm microsensors UNKNOWN_SENSOR, // default UNKNOWN_TRANSMITTER, // default TYPE_800_BB_SENSOR, // BayBird sensor TYPE_800_BB_STD_TRANSMITTER, // BayBird standard TX TYPE_800_BB_SMALL_TRANSMITTER, // BayBird small TX TYPE_090_BB_SENSOR // Baybird 0.9 mm sensor }; // Async and Sync sensor id parameter #define ALL_SENSORS 0xffff /***************************************************************************** TYPEDEF DEFINITIONS *****************************************************************************/ #ifndef BASETYPES #define BASETYPES typedef unsigned long ULONG; typedef ULONG *PULONG; typedef unsigned short USHORT; typedef USHORT *PUSHORT; typedef short SHORT; typedef SHORT *PSHORT; typedef unsigned char UCHAR; typedef UCHAR *PUCHAR; typedef char *PSZ; #endif /* !BASETYPES */ typedef char CHAR; typedef const CHAR *LPCSTR, *PCSTR; typedef int BOOL; typedef ULONG DEVICE_STATUS; typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD; /***************************************************************************** STRUCTURE DEFINITIONS *****************************************************************************/ typedef struct tagTRANSMITTER_CONFIGURATION { ULONG serialNumber; USHORT boardNumber; USHORT channelNumber; enum DEVICE_TYPES type; BOOL attached; } TRANSMITTER_CONFIGURATION; typedef struct tagSENSOR_CONFIGURATION { ULONG serialNumber; USHORT boardNumber; USHORT channelNumber; enum DEVICE_TYPES type; BOOL attached; } SENSOR_CONFIGURATION; typedef struct tagBOARD_CONFIGURATION { ULONG serialNumber; enum BOARD_TYPES type; USHORT revision; USHORT numberTransmitters; USHORT numberSensors; USHORT firmwareNumber; USHORT firmwareRevision; char modelString[10]; } BOARD_CONFIGURATION; typedef struct tagSYSTEM_CONFIGURATION { double measurementRate; double powerLineFrequency; double maximumRange; enum AGC_MODE_TYPE agcMode; int numberBoards; int numberSensors; int numberTransmitters; int transmitterIDRunning; BOOL metric; } SYSTEM_CONFIGURATION; typedef struct tagCOMMUNICATIONS_MEDIA_PARAMETERS { COMMUNICATIONS_MEDIA_TYPE mediaType; union { struct { CHAR comport[64]; } rs232; struct { USHORT port; CHAR ipaddr[64]; } tcpip; }; } COMMUNICATIONS_MEDIA_PARAMETERS; typedef struct tagADAPTIVE_PARAMETERS { USHORT alphaMin[7]; USHORT alphaMax[7]; USHORT vm[7]; BOOL alphaOn; } ADAPTIVE_PARAMETERS; typedef struct tagQUALITY_PARAMETERS { SHORT error_slope; SHORT error_offset; USHORT error_sensitivity; USHORT filter_alpha; } QUALITY_PARAMETERS; // New Drivebay system parameter structure(s) typedef struct tagVPD_COMMAND_PARAMETER { USHORT address; UCHAR value; } VPD_COMMAND_PARAMETER; typedef struct tagPOST_ERROR_PARAMETER { USHORT error; UCHAR channel; UCHAR fatal; UCHAR moreErrors; } POST_ERROR_PARAMETER; typedef struct tagDIAGNOSTIC_TEST_PARAMETER { UCHAR suite; // User sets this, 0 - All Suites UCHAR test; // User sets this, 0 - All Tests UCHAR suites; // set, returns suites run // get, returns num of suites, not used for # test query UCHAR tests; // set, returns tests run in the given suite // get, returns num of tests for given suite, not used for suite query PUCHAR pTestName; // User supplied ptr to 64 bytes, we fill it in USHORT testNameLen; USHORT diagError; // set only, result of diagnostic execution } DIAGNOSTIC_TEST_PARAMETER; typedef struct tagBOARD_REVISIONS { USHORT boot_loader_sw_number; // example 3.1 -> revision is 3, number is 1 USHORT boot_loader_sw_revision; USHORT mdsp_sw_number; USHORT mdsp_sw_revision; USHORT nondipole_sw_number; USHORT nondipole_sw_revision; USHORT fivedof_sw_number; USHORT fivedof_sw_revision; USHORT sixdof_sw_number; USHORT sixdof_sw_revision; USHORT dipole_sw_number; USHORT dipole_sw_revision; } BOARD_REVISIONS; typedef struct tagAUXILIARY_PORT_PARAMETERS { AUXILIARY_PORT_TYPE auxstate[4]; // one state for each sensor port } AUXILIARY_PORT_PARAMETERS; // // Data formatting structures // typedef struct tagSHORT_POSITION { short x; short y; short z; } SHORT_POSITION_RECORD; typedef struct tagSHORT_ANGLES { short a; // azimuth short e; // elevation short r; // roll } SHORT_ANGLES_RECORD; typedef struct tagSHORT_MATRIX { short s[3][3]; } SHORT_MATRIX_RECORD; typedef struct tagSHORT_QUATERNIONS { short q[4]; } SHORT_QUATERNIONS_RECORD; typedef struct tagSHORT_POSITION_ANGLES { short x; short y; short z; short a; short e; short r; } SHORT_POSITION_ANGLES_RECORD; typedef struct tagSHORT_POSITION_MATRIX { short x; short y; short z; short s[3][3]; } SHORT_POSITION_MATRIX_RECORD; typedef struct tagSHORT_POSITION_QUATERNION { short x; short y; short z; short q[4]; } SHORT_POSITION_QUATERNION_RECORD; typedef struct tagDOUBLE_POSITION { double x; double y; double z; } DOUBLE_POSITION_RECORD; typedef struct tagDOUBLE_ANGLES { double a; // azimuth double e; // elevation double r; // roll } DOUBLE_ANGLES_RECORD; typedef struct tagDOUBLE_MATRIX { double s[3][3]; } DOUBLE_MATRIX_RECORD; typedef struct tagDOUBLE_QUATERNIONS { double q[4]; } DOUBLE_QUATERNIONS_RECORD; typedef struct tagDOUBLE_POSITION_ANGLES { double x; double y; double z; double a; double e; double r; } DOUBLE_POSITION_ANGLES_RECORD; typedef struct tagDOUBLE_POSITION_MATRIX { double x; double y; double z; double s[3][3]; } DOUBLE_POSITION_MATRIX_RECORD; typedef struct tagDOUBLE_POSITION_QUATERNION { double x; double y; double z; double q[4]; } DOUBLE_POSITION_QUATERNION_RECORD; typedef struct tagDOUBLE_POSITION_TIME_STAMP { double x; double y; double z; double time; } DOUBLE_POSITION_TIME_STAMP_RECORD; typedef struct tagDOUBLE_ANGLES_TIME_STAMP { double a; // azimuth double e; // elevation double r; // roll double time; } DOUBLE_ANGLES_TIME_STAMP_RECORD; typedef struct tagDOUBLE_MATRIX_TIME_STAMP { double s[3][3]; double time; } DOUBLE_MATRIX_TIME_STAMP_RECORD; typedef struct tagDOUBLE_QUATERNIONS_TIME_STAMP { double q[4]; double time; } DOUBLE_QUATERNIONS_TIME_STAMP_RECORD; typedef struct tagDOUBLE_POSITION_ANGLES_TIME_STAMP { double x; double y; double z; double a; double e; double r; double time; } DOUBLE_POSITION_ANGLES_TIME_STAMP_RECORD; typedef struct tagDOUBLE_POSITION_MATRIX_STAMP_RECORD { double x; double y; double z; double s[3][3]; double time; } DOUBLE_POSITION_MATRIX_TIME_STAMP_RECORD; typedef struct tagDOUBLE_POSITION_QUATERNION_STAMP_RECORD { double x; double y; double z; double q[4]; double time; } DOUBLE_POSITION_QUATERNION_TIME_STAMP_RECORD; typedef struct tagDOUBLE_POSITION_TIME_Q { double x; double y; double z; double time; USHORT quality; } DOUBLE_POSITION_TIME_Q_RECORD; typedef struct tagDOUBLE_ANGLES_TIME_Q { double a; // azimuth double e; // elevation double r; // roll double time; USHORT quality; } DOUBLE_ANGLES_TIME_Q_RECORD; typedef struct tagDOUBLE_MATRIX_TIME_Q { double s[3][3]; double time; USHORT quality; } DOUBLE_MATRIX_TIME_Q_RECORD; typedef struct tagDOUBLE_QUATERNIONS_TIME_Q { double q[4]; double time; USHORT quality; } DOUBLE_QUATERNIONS_TIME_Q_RECORD; typedef struct tagDOUBLE_POSITION_ANGLES_TIME_Q_RECORD { double x; double y; double z; double a; double e; double r; double time; USHORT quality; } DOUBLE_POSITION_ANGLES_TIME_Q_RECORD; typedef struct tagDOUBLE_POSITION_MATRIX_TIME_Q_RECORD { double x; double y; double z; double s[3][3]; double time; USHORT quality; } DOUBLE_POSITION_MATRIX_TIME_Q_RECORD; typedef struct tagDOUBLE_POSITION_QUATERNION_TIME_Q_RECORD { double x; double y; double z; double q[4]; double time; USHORT quality; } DOUBLE_POSITION_QUATERNION_TIME_Q_RECORD; typedef struct tagDOUBLE_POSITION_ANGLES_TIME_Q_BUTTON_RECORD { double x; double y; double z; double a; double e; double r; double time; USHORT quality; USHORT button; } DOUBLE_POSITION_ANGLES_TIME_Q_BUTTON_RECORD; typedef struct tagDOUBLE_POSITION_MATRIX_TIME_Q_BUTTON_RECORD { double x; double y; double z; double s[3][3]; double time; USHORT quality; USHORT button; } DOUBLE_POSITION_MATRIX_TIME_Q_BUTTON_RECORD; typedef struct tagDOUBLE_POSITION_QUATERNION_TIME_Q_BUTTON_RECORD { double x; double y; double z; double q[4]; double time; USHORT quality; USHORT button; } DOUBLE_POSITION_QUATERNION_TIME_Q_BUTTON_RECORD; typedef struct tagDOUBLE_POSITION_ANGLES_MATRIX_QUATERNION_TIME_Q_BUTTON_RECORD { double x; double y; double z; double a; double e; double r; double s[3][3]; double q[4]; double time; USHORT quality; USHORT button; } DOUBLE_POSITION_ANGLES_MATRIX_QUATERNION_TIME_Q_BUTTON_RECORD; typedef struct tagSHORT_ALL_RECORD { short x; short y; short z; short a; // azimuth short e; // elevation short r; // roll short s[3][3]; short q[4]; }SHORT_ALL_RECORD; typedef struct tagDOUBLE_ALL_RECORD { double x; double y; double z; double a; // azimuth double e; // elevation double r; // roll double s[3][3]; double q[4]; }DOUBLE_ALL_RECORD; typedef struct tagDOUBLE_ALL_TIME_STAMP_RECORD { double x; double y; double z; double a; // azimuth double e; // elevation double r; // roll double s[3][3]; double q[4]; double time; }DOUBLE_ALL_TIME_STAMP_RECORD; typedef struct tagDOUBLE_ALL_TIME_STAMP_Q_RECORD { double x; double y; double z; double a; // azimuth double e; // elevation double r; // roll double s[3][3]; double q[4]; double time; USHORT quality; }DOUBLE_ALL_TIME_STAMP_Q_RECORD; typedef struct tagDOUBLE_ALL_TIME_STAMP_Q_RAW_RECORD { double x; double y; double z; double a; // azimuth double e; // elevation double r; // roll double s[3][3]; double q[4]; double time; USHORT quality; double raw[3][3]; }DOUBLE_ALL_TIME_STAMP_Q_RAW_RECORD; /***************************************************************************** FUNCTION PROTOTYPES *****************************************************************************/ /* InitializeBIRDSystem Starts and initializes driver, resets hardware and interrogates hardware. Builds local database of system resources. Parameters Passed: none Return Value: error status Remarks: Can be used anytime a catastrophic failure has occurred and the system needs to be restarted. */ ATC3DG_API int InitializeBIRDSystem(void); /* GetBIRDSystemConfiguration Parameters Passed: SYSTEM_CONFIGURATION* Return Value: error status Remarks: Returns SYSTEM_CONFIGURATION structure It contains values equal to the number of transmitters, sensors and boards detected in the system. (The board information is for test/diagnostic purposes, all commands reference sensors and transmitters only) Once the number of devices is known, (e.g. n) the range of IDs for those devices becomes 0..(n-1) */ ATC3DG_API int GetBIRDSystemConfiguration( SYSTEM_CONFIGURATION* systemConfiguration ); /* GetTransmitterConfiguration Parameters Passed: USHORT transmitterID TRANSMITTER_CONFIGURATION *transmitterConfiguration Return Value: error status Remarks: After getting system config the user can then pass the index of a transmitter of interest to this function which will then return the config for that transmitter. Items of interest are the serial number and status. */ ATC3DG_API int GetTransmitterConfiguration( USHORT transmitterID, TRANSMITTER_CONFIGURATION* transmitterConfiguration ); /* GetSensorConfiguration Parameters Passed: USHORT sensorID, SENSOR_CONFIGURATION* sensorConfiguration Return Value: error status Remarks: Similar to the transmitter function. */ ATC3DG_API int GetSensorConfiguration( USHORT sensorID, SENSOR_CONFIGURATION* sensorConfiguration ); /* GetBoardConfiguration Parameters Passed: USHORT boardID, BOARD_CONFIGURATION* boardConfiguration Return Value: error status Remarks: Similar to the Sensor and Transmitter functions. Also returns information on how many sensors and transmitters are attached. NOTE: Board information is not needed during normal operation this is only provided for "accounting" purposes. */ ATC3DG_API int GetBoardConfiguration( USHORT boardID, BOARD_CONFIGURATION* boardConfiguration ); /* GetAsynchronousRecord Parameters Passed: USHORT sensorID, void *pRecord, int recordSize Return Value: error status Remarks: Returns data immediately in the currently selected format from the last measurement cycle. Requires user providing a buffer large enough for the result otherwise an error is generated and data lost. (Old style BIRD POINT mode) */ ATC3DG_API int GetAsynchronousRecord( USHORT sensorID, void *pRecord, int recordSize ); /* GetSynchronousRecord Parameters Passed: USHORT sensorID, void *pRecord, int recordSize Return Value: error status Remarks: Returns a record after next measurement cycle. Puts system into mode where records are generated 1/cycle. Will return one and only one record per measurement cycle. Will queue the records for each measurement cycle if command not issued sufficiently often. If command issued too often will time-out with no data. (old style BIRD STREAM mode) */ ATC3DG_API int GetSynchronousRecord( USHORT sensorID, void *pRecord, int recordSize ); /* GetSystemParameter Parameters Passed: PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize Return Value: error status Remarks: When a properly enumerated parameter type constant is used, the command will return the parameter value to the buffer provided by the user. An error is generated if the buffer is incorrectly sized */ ATC3DG_API int GetSystemParameter( enum SYSTEM_PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize ); /* SetSystemParameter Parameters Passed: PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize Return Value: error status Remarks: Similar to GetSystemParameter but allows user to set (write) the parameter. */ ATC3DG_API int SetSystemParameter( enum SYSTEM_PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize ); /* GetSensorParameter Parameters Passed: USHORT sensorID, PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize Return Value: error status Remarks: When a sensor is selected with a valid index (ID) and a properly enumerated parameter type constant is used, the command will return the parameter value to the buffer provided by the user. An error is generated if the buffer is incorrectly sized */ ATC3DG_API int GetSensorParameter( USHORT sensorID, enum SENSOR_PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize ); /* SetSensorParameter Parameters Passed: USHORT sensorID, PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize Return Value: error status Remarks: Similar to GetSensorParameter but allows user to set (write) the parameter. */ ATC3DG_API int SetSensorParameter( USHORT sensorID, enum SENSOR_PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize ); /* GetTransmitterParameter Parameters Passed: USHORT transmitterID, PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize Return Value: error status Remarks: Same as Sensor command */ ATC3DG_API int GetTransmitterParameter( USHORT transmitterID, enum TRANSMITTER_PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize ); /* SetTransmitterParameter Parameters Passed: USHORT transmitterID, PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize Return Value: error status Remarks: Same as sensor command */ ATC3DG_API int SetTransmitterParameter( USHORT transmitterID, enum TRANSMITTER_PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize ); /* GetBIRDError Parameters Passed: none Return Value: error status Remarks: Returns next error in queue if available */ ATC3DG_API int GetBIRDError( void ); #define GetPOSTError GetBIRDError #define GetDIAGError GetBIRDError /* GetErrorText Parameters Passed: int errorCode char *pBuffer int bufferSize int type Return Value: error status as a text string Remarks: ErrorCode contains the error code returned from either a command or in response to GetBIRDError and which is to be described by a text string. Pass a pointer pBuffer to a buffer to contain the result of the command. The size of the buffer is contained in bufferSize. The type parameter is an enumerated constant of the type MESSAGE_TYPE. */ ATC3DG_API int GetErrorText( int errorCode, char *pBuffer, int bufferSize, enum MESSAGE_TYPE type ); /* */ ATC3DG_API DEVICE_STATUS GetSensorStatus( USHORT sensorID ); /* */ ATC3DG_API DEVICE_STATUS GetTransmitterStatus( USHORT transmitterID ); /* */ ATC3DG_API DEVICE_STATUS GetBoardStatus( USHORT boardID ); /* */ ATC3DG_API DEVICE_STATUS GetSystemStatus( // no id required ); /* */ ATC3DG_API int SaveSystemConfiguration( LPCSTR lpFileName ); /* */ ATC3DG_API int RestoreSystemConfiguration( LPCSTR lpFileName ); /* */ ATC3DG_API int GetBoardParameter( USHORT boardID, enum BOARD_PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize ); /* */ ATC3DG_API int SetBoardParameter( USHORT boardID, enum BOARD_PARAMETER_TYPE parameterType, void *pBuffer, int bufferSize ); /* */ ATC3DG_API int CloseBIRDSystem(void); #endif // ATC3DG_H
35,275
C
25.208024
107
0.686889
adegirmenci/HBL-ICEbot/FrameClientWidget/frameclientthread.cpp
#include "frameclientthread.h" FrameClientThread::FrameClientThread(QObject *parent) : QObject(parent) { qRegisterMetaType< FrameExtd >("FrameExtd"); m_isEpochSet = false; m_isReady = false; m_keepStreaming = false; m_continuousStreaming = false; m_frameCount = 0; m_abort = false; m_serverAddress = QHostAddress(QHostAddress::LocalHost); m_serverPort = (quint16)4417; m_TcpSocket = Q_NULLPTR; m_currExtdFrame = FrameExtd(); m_currFrame = nullptr; m_currFramePhase = 0.0; m_currBird = EMreading(); m_cardiacPhases.resize(N_PHASES,0.0); m_phaseTimes.resize(N_PHASES,0.0); m_mutex = new QMutex(QMutex::Recursive); } FrameClientThread::~FrameClientThread() { m_mutex->lock(); m_abort = true; m_isReady = false; m_keepStreaming = false; m_continuousStreaming = false; if(m_TcpSocket) { m_TcpSocket->flush(); m_TcpSocket->disconnectFromHost(); m_TcpSocket->deleteLater(); } m_mutex->unlock(); qDebug() << "Ending FrameClientThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; delete m_mutex; emit finished(); } void FrameClientThread::initializeFrameClient() { QMutexLocker locker(m_mutex); m_TcpSocket = new QTcpSocket(this); connect(m_TcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(handleTcpError(QAbstractSocket::SocketError))); connect(this, SIGNAL(tcpError(QAbstractSocket::SocketError)), this, SLOT(handleTcpError(QAbstractSocket::SocketError))); connect(m_TcpSocket, SIGNAL(connected()), this, SLOT(connectedToHost())); connect(m_TcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectedFromHost())); m_isReady = true; } void FrameClientThread::sendFrame() { QMutexLocker locker(m_mutex); if(!m_isReady) initializeFrameClient(); if(m_keepStreaming && (m_currFramePhase < 0.06)) { m_continuousStreaming = false; // construct frame - rot matrix from Ascension is transposed QMatrix4x4 tmp(m_currBird.data.s[0][0], m_currBird.data.s[0][1], m_currBird.data.s[0][2], m_currBird.data.x, m_currBird.data.s[1][0], m_currBird.data.s[1][1], m_currBird.data.s[1][2], m_currBird.data.y, m_currBird.data.s[2][0], m_currBird.data.s[2][1], m_currBird.data.s[2][2], m_currBird.data.z, 0.0, 0.0, 0.0, 1.0); Qt3DCore::QTransform tform; tform.setMatrix(tmp); // QQuaternion q(m_currBird.data.q[0], // m_currBird.data.q[1], // m_currBird.data.q[2], // m_currBird.data.q[3]); QQuaternion q = tform.rotation(); QVector3D v = tform.translation(); m_currExtdFrame.EMq_ = q; m_currExtdFrame.EMv_ = v; m_currExtdFrame.phaseHR_ = (float)m_currFramePhase; m_currExtdFrame.image_ = saveFrame(m_currFrame); // write to disk m_currExtdFrame.index_ = m_currFrame->index_; m_currExtdFrame.mask_ = tr("C:\\Users\\Alperen\\Documents\\QT Projects\\RT3DReconst_GUI\\Acuson_Epiphan.bin"); m_currExtdFrame.timestamp_ = m_currFrame->timestamp_; QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_7); out << (quint16)0; out << m_currExtdFrame; out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); m_TcpSocket->connectToHost(m_serverAddress, m_serverPort, QIODevice::WriteOnly); if (m_TcpSocket->waitForConnected(100)) { qDebug("Connected!"); m_TcpSocket->write(block); m_TcpSocket->flush(); m_TcpSocket->disconnectFromHost(); if( (m_TcpSocket->state() != QAbstractSocket::UnconnectedState) && (!m_TcpSocket->waitForDisconnected(100)) ) { emit statusChanged(FRMCLNT_DISCONNECTION_FAILED); } } else emit statusChanged(FRMCLNT_CONNECTION_FAILED); } else emit statusChanged(FRMCLNT_FIRST_FRAME_NOT_RECEIVED); } void FrameClientThread::receiveFrame(std::shared_ptr<Frame> frame) { QMutexLocker locker(m_mutex); // qDebug() << "FrameClientThread: receiveFrame"; m_currFrame = frame; // determine phase // take the difference of time stamps std::valarray<qint64> Tdiff(m_phaseTimes.data(), m_phaseTimes.size()); Tdiff = std::abs(Tdiff - m_currFrame->timestamp_); // find closest timestamp auto idx = std::distance(std::begin(Tdiff), std::min_element(std::begin(Tdiff), std::end(Tdiff))); m_currFramePhase = m_cardiacPhases[idx]; if(m_continuousStreaming) sendFrame(); } void FrameClientThread::receiveEMreading(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data) { QMutexLocker locker(m_mutex); // qDebug() << "FrameClientThread: receiveEMreading"; if(m_currFrame) { qint64 tBirdCurr(m_currBird.data.time*1000); qint64 tBirdNext(data.time*1000); qint64 diffCurr = qAbs(m_currFrame->timestamp_ - tBirdCurr); qint64 diffNext = qAbs(m_currFrame->timestamp_ - tBirdNext); if(diffNext < diffCurr) { m_currBird.data = data; m_currBird.sensorID = sensorID; m_currBird.timeStamp = timeStamp; } } if(m_currFrame) m_keepStreaming = true; } void FrameClientThread::receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> readings) { QMutexLocker locker(m_mutex); Q_ASSERT(4 == readings.size()); if(m_currFrame) { qint64 tBirdCurr(m_currBird.data.time*1000); qint64 tBirdNext(readings[EM_SENSOR_BT].time*1000); qint64 diffCurr = qAbs(m_currFrame->timestamp_ - tBirdCurr); qint64 diffNext = qAbs(m_currFrame->timestamp_ - tBirdNext); if(diffNext < diffCurr) { m_currBird.data = readings[EM_SENSOR_BT]; m_currBird.sensorID = EM_SENSOR_BT; m_currBird.timeStamp = QTime::currentTime(); } } if(m_currFrame) m_keepStreaming = true; } void FrameClientThread::receive_T_CT(std::vector<double> T_BB_CT, double time) { QMutexLocker locker(m_mutex); if(m_currFrame && (T_BB_CT.size() == 16)) { qint64 tBirdCurr(m_currBird.data.time*1000); qint64 tBirdNext(time*1000); qint64 diffCurr = qAbs(m_currFrame->timestamp_ - tBirdCurr); qint64 diffNext = qAbs(m_currFrame->timestamp_ - tBirdNext); if(diffNext < diffCurr) { // data in Eigen is stored as column-major m_currBird.data.s[0][0] = T_BB_CT[0]; m_currBird.data.s[1][0] = T_BB_CT[1]; m_currBird.data.s[2][0] = T_BB_CT[2]; m_currBird.data.s[0][1] = T_BB_CT[4]; m_currBird.data.s[1][1] = T_BB_CT[5]; m_currBird.data.s[2][1] = T_BB_CT[6]; m_currBird.data.s[0][2] = T_BB_CT[8]; m_currBird.data.s[1][2] = T_BB_CT[9]; m_currBird.data.s[2][2] = T_BB_CT[10]; m_currBird.data.x = T_BB_CT[12]; m_currBird.data.y = T_BB_CT[13]; m_currBird.data.z = T_BB_CT[14]; m_currBird.data.time = time; m_currBird.sensorID = EM_SENSOR_BT; m_currBird.timeStamp = QTime::currentTime(); } } if(m_currFrame) m_keepStreaming = true; } void FrameClientThread::receivePhase(qint64 timeStamp, double phase) { m_cardiacPhases.erase(m_cardiacPhases.begin()); m_phaseTimes.erase(m_phaseTimes.begin()); m_cardiacPhases.push_back(phase); m_phaseTimes.push_back(timeStamp); } void FrameClientThread::connectedToHost() { emit statusChanged(FRMCLNT_CONNECTED); } void FrameClientThread::disconnectedFromHost() { emit statusChanged(FRMCLNT_DISCONNECTED); } QString FrameClientThread::saveFrame(std::shared_ptr<Frame> frm) { QMutexLocker locker(m_mutex); QDateTime imgTime; imgTime.setMSecsSinceEpoch(frm->timestamp_); // file name of frame QString m_imgFname = imgTime.toString("ddMMyyyy_hhmmsszzz"); // populate m_imgFname with index m_imgFname.append( QString("_%1").arg(frm->index_) ); QString m_DirImgFname = QDir::currentPath(); m_DirImgFname.append("/"); m_DirImgFname.append(m_imgFname); // save frame //state = frame->image_.save(m_imgFname, "JPG", 100); cv::imwrite((m_DirImgFname + tr(".jp2")).toStdString().c_str(), frm->image_ ); // write frame // save EM data to file QFile txtfile(m_DirImgFname + tr(".txt")); if (txtfile.open(QFile::WriteOnly)) { QTextStream txtout(&txtfile); txtout << tr("%1\t%2\t%3\n") .arg(m_currExtdFrame.EMv_.x()) .arg(m_currExtdFrame.EMv_.y()) .arg(m_currExtdFrame.EMv_.z()); txtout << tr("%1\t%2\t%3\t%4\n") .arg(m_currExtdFrame.EMq_.x()) .arg(m_currExtdFrame.EMq_.y()) .arg(m_currExtdFrame.EMq_.z()) .arg(m_currExtdFrame.EMq_.scalar()); txtout << QString::number(m_currExtdFrame.phaseHR_, 'f', 3); txtout << "\nLine 1: QVector3D, Line2: QQuaternion, Line3: (float)phaseHR_"; } txtfile.close(); return m_DirImgFname; } void FrameClientThread::handleTcpError(QAbstractSocket::SocketError error) { QMutexLocker locker(m_mutex); QString errStr; switch(error) { case QAbstractSocket::ConnectionRefusedError: errStr = "ConnectionRefusedError"; break; case QAbstractSocket::RemoteHostClosedError: errStr = "RemoteHostClosedError"; break; case QAbstractSocket::HostNotFoundError: errStr = "HostNotFoundError"; break; case QAbstractSocket::SocketAccessError: errStr = "SocketAccessError"; break; case QAbstractSocket::SocketResourceError: errStr = "SocketResourceError"; break; case QAbstractSocket::SocketTimeoutError: errStr = "SocketTimeoutError"; break; case QAbstractSocket::DatagramTooLargeError: errStr = "DatagramTooLargeError"; break; case QAbstractSocket::NetworkError: errStr = "NetworkError"; break; case QAbstractSocket::AddressInUseError: errStr = "AddressInUseError"; break; case QAbstractSocket::SocketAddressNotAvailableError: errStr = "SocketAddressNotAvailableError"; break; case QAbstractSocket::UnsupportedSocketOperationError: errStr = "UnsupportedSocketOperationError"; break; case QAbstractSocket::OperationError: errStr = "OperationError"; break; case QAbstractSocket::TemporaryError: errStr = "TemporaryError"; break; case QAbstractSocket::UnknownSocketError: errStr = "UnknownSocketError"; break; default: errStr = "UnknownError"; } qDebug() << tr("Error in FrameClientThread: %1.") .arg(errStr); } void FrameClientThread::setEpoch(const QDateTime &datetime) { QMutexLocker locker(m_mutex); if(!m_keepStreaming) { m_epoch = datetime; m_isEpochSet = true; // emit logEventWithMessage(SRC_FRMCLNT, LOG_INFO, QTime::currentTime(), FRMCLNT_EPOCH_SET, // m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz")); } // else // emit logEvent(SRC_FRMCLNT, LOG_INFO, QTime::currentTime(), FRMCLNT_EPOCH_SET_FAILED); } QDataStream & operator << (QDataStream &o, const FrameExtd& f) { return o << f.image_ << f.index_ << f.timestamp_ << f.EMq_ << f.EMv_ << f.mask_ << f.phaseHR_ << f.phaseResp_ << '\0'; } QDataStream & operator >> (QDataStream &i, FrameExtd& f) { i >> f.image_ >> f.index_ >> f.timestamp_ >> f.EMq_ >> f.EMv_ >> f.mask_ >> f.phaseHR_ >> f.phaseResp_; return i; }
12,154
C++
31.413333
118
0.606961
adegirmenci/HBL-ICEbot/FrameClientWidget/frameclientwidget.h
#ifndef FRAMECLIENTWIDGET_H #define FRAMECLIENTWIDGET_H #include <QWidget> #include <QTimer> #include "frameclientthread.h" namespace Ui { class FrameClientWidget; } class FrameClientWidget : public QWidget { Q_OBJECT public: explicit FrameClientWidget(QWidget *parent = 0); ~FrameClientWidget(); FrameClientThread *m_worker; signals: void sendFrame(); private slots: void workerStatusChanged(int status); void on_sendFrameButton_clicked(); void on_toggleAutoButton_clicked(); private: Ui::FrameClientWidget *ui; bool m_keepTransmitting; QTimer *m_transmitTimer; QThread m_thread; // FrameClientThread will live in here }; #endif // FRAMECLIENTWIDGET_H
715
C
15.651162
60
0.725874
adegirmenci/HBL-ICEbot/FrameClientWidget/frameclientwidget.cpp
#include "frameclientwidget.h" #include "ui_frameclientwidget.h" FrameClientWidget::FrameClientWidget(QWidget *parent) : QWidget(parent), ui(new Ui::FrameClientWidget) { ui->setupUi(this); m_keepTransmitting = false; m_worker = new FrameClientThread; m_worker->moveToThread(&m_thread); connect(&m_thread, SIGNAL(finished()), m_worker, SLOT(deleteLater())); m_thread.start(); connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int))); connect(this, SIGNAL(sendFrame()), m_worker, SLOT(sendFrame())); m_transmitTimer = new QTimer(this); connect(m_transmitTimer, SIGNAL(timeout()), this, SLOT(on_sendFrameButton_clicked())); } FrameClientWidget::~FrameClientWidget() { m_keepTransmitting = false; if(m_transmitTimer) m_transmitTimer->stop(); m_thread.quit(); m_thread.wait(); qDebug() << "FrameClientWidget thread quit."; delete ui; } void FrameClientWidget::workerStatusChanged(int status) { switch(status) { case FRMCLNT_CONNECTED: ui->statusTextEdit->appendPlainText("Connected to server."); ui->addrPortLineEdit->setText(tr("%1:%2") .arg(m_worker->getServerAddress().toString()) .arg(m_worker->getServerPort())); break; case FRMCLNT_CONNECTION_FAILED: ui->statusTextEdit->appendPlainText("Server connection failed."); break; case FRMCLNT_DISCONNECTED: ui->statusTextEdit->appendPlainText("Server connection closed."); break; case FRMCLNT_DISCONNECTION_FAILED: ui->statusTextEdit->appendPlainText("Server disconnect failed."); break; case FRMCLNT_SOCKET_NOT_WRITABLE: ui->statusTextEdit->appendPlainText("Incoming connection."); break; case FRMCLNT_FRAME_SENT: ui->statusTextEdit->appendPlainText("Frame sent."); break; case FRMCLNT_EPOCH_SET: ui->statusTextEdit->appendPlainText("Epoch set."); break; case FRMCLNT_EPOCH_SET_FAILED: ui->statusTextEdit->appendPlainText("Epoch set failed."); break; case FRMCLNT_FIRST_FRAME_NOT_RECEIVED: ui->statusTextEdit->appendPlainText("First frame not yet received."); break; default: ui->statusTextEdit->appendPlainText("Unknown worker state."); } } void FrameClientWidget::on_sendFrameButton_clicked() { emit sendFrame(); } void FrameClientWidget::on_toggleAutoButton_clicked() { if(m_keepTransmitting) { m_keepTransmitting = false; ui->toggleAutoButton->setText("Start Automatic Collection"); m_transmitTimer->stop(); } else { m_keepTransmitting = true; ui->toggleAutoButton->setText("Stop Automatic Collection"); m_transmitTimer->start(30); } }
2,882
C++
28.121212
88
0.644344
adegirmenci/HBL-ICEbot/FrameClientWidget/frameclientthread.h
#ifndef FRAMECLIENTTHREAD_H #define FRAMECLIENTTHREAD_H #include <QObject> #include <QMutex> #include <QMutexLocker> #include <QThread> #include <QString> #include <QTime> #include <QTimer> #include <QDebug> #include <QSharedPointer> #include <QDir> #include <QNetworkInterface> #include <QTcpSocket> #include <QDataStream> #include <QByteArray> #include <QHostAddress> #include <QMatrix4x4> #include <Qt3DCore/QTransform> #include <QQuaternion> #include <QVector3D> #include <vector> #include <memory> #include <valarray> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "../icebot_definitions.h" #include "../AscensionWidget/3DGAPI/ATC3DG.h" #include "../FrmGrabWidget/frmgrabthread.h" #define N_PHASES 500 // keep track of the last N_PHASES cardiac phases and corresponding time stamps struct FrameExtd{ QString image_; /*!< Image data. */ QQuaternion EMq_; /*!< EM reading - rotation as Quaternion. */ QVector3D EMv_; /*!< EM reading - translation. */ float phaseHR_; /*!< Phase in the heart cycle (0.0 - 1.0). */ float phaseResp_; /*!< Phase in the respiration cycle (0.0 - 1.0). */ qint64 timestamp_; /*!< Timestamp, msec since some epoch. */ int index_; /*!< Index value of Frame, indicate order of acquisition. */ QString mask_; /*!< Image mask. */ //! Constructor. explicit FrameExtd(QString img = QString(), QQuaternion emq = QQuaternion(), QVector3D emv = QVector3D(), qint64 ts = -1, float pHR = 0.f, float pResp = 0.f, int id = -1, QString mask = QString()) : timestamp_(ts), phaseHR_(pHR), phaseResp_(pResp), index_(id) { image_ = img; EMq_ = emq; EMv_ = emv; mask_ = mask; } //! Destructor ~FrameExtd() { } }; struct EMreading{ QTime timeStamp; int sensorID; DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data; explicit EMreading(QTime t_ = QTime(), int s_ = -1, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD r_ = DOUBLE_POSITION_MATRIX_TIME_Q_RECORD()) : timeStamp(t_), sensorID(s_) { data = r_; } ~EMreading(){} }; Q_DECLARE_METATYPE(FrameExtd) class FrameClientThread : public QObject { Q_OBJECT public: explicit FrameClientThread(QObject *parent = 0); ~FrameClientThread(); friend QDataStream & operator << (QDataStream &o, const FrameExtd& f); friend QDataStream & operator >> (QDataStream &i, FrameExtd& f); signals: void statusChanged(int event); void finished(); // emit upon termination void tcpError(QAbstractSocket::SocketError error); public slots: void setEpoch(const QDateTime &datetime); // set Epoch void initializeFrameClient(); void sendFrame(); // change to Frame type void receiveFrame(std::shared_ptr<Frame> frame); void receiveEMreading(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data); void receiveLatestEMreading(std::vector<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD> readings); void receive_T_CT(std::vector<double> T_BB_CT, double time); void receivePhase(qint64 timeStamp, double phase); void handleTcpError(QAbstractSocket::SocketError error); void connectedToHost(); void disconnectedFromHost(); const QHostAddress getServerAddress() { return m_serverAddress; } const quint16 getServerPort() { return m_serverPort; } void toggleContinuousSteaming(bool state) { m_continuousStreaming = state; } private: QString saveFrame(std::shared_ptr<Frame>); // Instead of using "m_mutex.lock()" // use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex *m_mutex; // Epoch for time stamps // During initializeFrameClient(), check 'isEpochSet' flag // If Epoch is set externally from MainWindow, the flag will be true // Otherwise, Epoch will be set internally QDateTime m_epoch; bool m_isEpochSet; // Flag to indicate if Frame Client is ready // True if initializeFrameClient was successful bool m_isReady; // Flag to tell that we are still streaming bool m_keepStreaming; bool m_continuousStreaming; // Flag to abort actions (e.g. initialize, acquire, etc.) bool m_abort; int m_frameCount; // keep a count of number of transmitted frames // server info QHostAddress m_serverAddress; quint16 m_serverPort; QTcpSocket *m_TcpSocket; FrameExtd m_currExtdFrame; std::shared_ptr<Frame> m_currFrame; double m_currFramePhase; EMreading m_currBird; std::vector<double> m_cardiacPhases; std::vector<qint64> m_phaseTimes; }; #endif // FRAMECLIENTTHREAD_H
4,950
C
28.825301
106
0.650303
adegirmenci/HBL-ICEbot/EPOS2Widget/epos2thread.h
#ifndef EPOS2THREAD_H #define EPOS2THREAD_H #include <QObject> #include <QMutex> #include <QMutexLocker> #include <QThread> #include <QString> #include <QDateTime> #include <QTimer> #include <QElapsedTimer> #include <QDebug> #include <QSharedPointer> #include <vector> #include <memory> #include "../icebot_definitions.h" #include "MaxonLibs/Definitions.h" #include <stdio.h> #include <Windows.h> Q_DECLARE_METATYPE(std::vector<long>) //Q_DECLARE_METATYPE(std::vector<int>) struct eposMotor { __int8 m_bMode; WORD m_nodeID; // motor ID DWORD m_ulProfileAcceleration; // acceleration value DWORD m_ulProfileDeceleration; // deceleration value DWORD m_ulProfileVelocity; // velocity value bool m_enabled; EPOS_MOTOR_STATUS m_motorStatus; long m_lActualValue; // volatile? long m_lStartPosition; // volatile? long m_lTargetPosition; // volatile? long m_maxQC; // upper limit long m_minQC; // lower limit }; class EPOS2Thread : public QObject { Q_OBJECT public: explicit EPOS2Thread(QObject *parent = 0); ~EPOS2Thread(); bool isInServoLoop(){QMutexLocker locker(m_mutex); return m_keepServoing;} signals: void statusChanged(int event); void motorStatusChanged(const int motID, const int status); void motorStatusChanged(std::vector<int> status); void motorQcChanged(const int motID, const long QC); void motorQcChanged(std::vector<long> QCs); //void EPOS_Ready(bool status); // tells the widget that the EPOS is ready void logData(QTime timeStamp, int dataType, // EPOS_DATA_IDS const int motID, long data); void logData(QTime timeStamp, int dataType, // EPOS_DATA_IDS std::vector<long> data); void logEvent(int source, // LOG_SOURCE int logType, // LOG_TYPE QTime timeStamp, int eventID); // EPOS_EVENT_IDS void logEventWithMessage(int source, // LOG_SOURCE int logType, // LOG_TYPE QTime timeStamp, int eventID, // EPOS_EVENT_IDS QString &message); void logError(int source, // LOG_SOURCE int logType, // LOG_TYPE QTime timeStamp, int errCode, // EPOS_ERROR_CODES QString message); void sendDataToGUI(const int id, const QString &output); void finished(); // emit upon termination public slots: bool initializeEPOS(); // open connection to EPOS void startServoing(); // start timer void setServoTargetPos(const int axisID, long targetPos, bool moveAbsOrRel); // update target for one motor void setServoTargetPos(std::vector<long> targetPos, bool moveAbsOrRel); // update target for all motors void servoToPosition(); // called by timer void servoToPosition(const int axisID); void haltMotor(const int axisID); // immediately stop all motors void stopServoing(); // stop timer bool disconnectEPOS(); // disconnect from EPOS void setEpoch(const QDateTime &datetime); // set Epoch void updateMotorQC(const int axisID); void updateMotorQCs(); const int getMotorStatus(const int axisID); bool initializeMotor(const int motID); bool disableMotor(const int motID); void homeAxis(const int axisID); void homeAllAxes(); private: // Instead of using "m_mutex.lock()" // use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex *m_mutex; // Timer for calling servoToPosition every xxx msecs QTimer *m_timer; // Epoch for time stamps // During initializeEPOS(), check 'isEpochSet' flag // If Epoch is set externally from MainWindow, the flag will be true // Otherwise, Epoch will be set internally QDateTime m_epoch; bool m_isEpochSet; // Flag to indicate if EPOS tracker is ready // True if InitializeEPOS was successful bool m_isReady; // Flag to tell that we are still servoing bool m_keepServoing; // Flag to abort actions (e.g. initialize, acquire, etc.) bool m_abort; // EPOS variables BOOL m_oImmediately; BOOL m_oInitialisation; BOOL m_oUpdateActive; DWORD m_ulErrorCode; HANDLE m_KeyHandle; // list of motors std::vector< std::shared_ptr<eposMotor> > m_motors; const int m_prec = 4; // precision for print operations // error handler bool ShowErrorInformation(DWORD p_ulErrorCode); QString formatOutput(QTime &timeStamp, const int motorID, long pos); // ----- int checkMotorLimits(const int axisID, const long targetPos); long clampToMotorLimits(const int axisID, const long targetPos); bool checkMotorID(const int motID); }; // ---------------- // HELPER FUNCTIONS // ---------------- inline const QString getCurrTimeStr(); inline const QString getCurrDateTimeStr(); #endif // EPOS2THREAD_H
5,033
C
29.695122
111
0.654878
adegirmenci/HBL-ICEbot/EPOS2Widget/epos2widget.cpp
#include "epos2widget.h" #include "ui_epos2widget.h" EPOS2Widget::EPOS2Widget(QWidget *parent) : QWidget(parent), ui(new Ui::EPOS2Widget) { ui->setupUi(this); m_worker = new EPOS2Thread; m_worker->moveToThread(&m_thread); connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater); m_thread.start(); connect(ui->connectButton, SIGNAL(clicked(bool)), m_worker, SLOT(initializeEPOS())); // connect(ui->acquireButton, SIGNAL(clicked(bool)), m_worker, SLOT(startAcquisition())); // connect(ui->stopButton, SIGNAL(clicked(bool)), m_worker, SLOT(stopAcquisition())); connect(ui->disconnectButton, SIGNAL(clicked(bool)), m_worker, SLOT(disconnectEPOS())); connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int))); connect(m_worker, SIGNAL(motorStatusChanged(int,int)), this, SLOT(workerMotorStatusChanged(int,int))); connect(m_worker, SIGNAL(motorStatusChanged(std::vector<int>)), this, SLOT(workerMotorStatusChanged(std::vector<int>))); connect(m_worker, SIGNAL(motorQcChanged(int,long)), this, SLOT(workerMotorQcChanged(int,long))); connect(m_worker, SIGNAL(motorQcChanged(std::vector<long>)), this, SLOT(workerMotorQcChanged(std::vector<long>))); connect(m_worker, SIGNAL(sendDataToGUI(int,QString)), this, SLOT(receiveDataFromWorker(int,QString))); connect(this, SIGNAL(setServoTargetPos(int,long,bool)), m_worker, SLOT(setServoTargetPos(int,long,bool))); connect(this, SIGNAL(setServoTargetPos(std::vector<long>,bool)), m_worker, SLOT(setServoTargetPos(std::vector<long>,bool))); connect(this, SIGNAL(servoToPos()), m_worker, SLOT(servoToPosition())); connect(this, SIGNAL(servoToPos(int)), m_worker, SLOT(servoToPosition(int))); connect(this, SIGNAL(haltMotor(int)), m_worker, SLOT(haltMotor(int))); connect(this, SIGNAL(enableMotor(int)), m_worker, SLOT(initializeMotor(int))); connect(this, SIGNAL(disableMotor(int)), m_worker, SLOT(disableMotor(int))); connect(this, SIGNAL(startServoLoop()), m_worker, SLOT(startServoing())); connect(this, SIGNAL(stopServoLoop()), m_worker, SLOT(stopServoing())); connect(this, SIGNAL(homeAxis(int)), m_worker, SLOT(homeAxis(int))); connect(this, SIGNAL(homeAllAxes()), m_worker, SLOT(homeAllAxes())); // status labels motLabels.push_back(ui->transStatusLabel); motLabels.push_back(ui->pitchStatusLabel); motLabels.push_back(ui->yawStatusLabel); motLabels.push_back(ui->rollStatusLabel); // LCD numbers motQCs.push_back(ui->transQC_LCD); motQCs.push_back(ui->pitchQC_LCD); motQCs.push_back(ui->yawQC_LCD); motQCs.push_back(ui->rollQC_LCD); // trajectory m_keepDriving = false; m_currTrajIdx = 0; } EPOS2Widget::~EPOS2Widget() { //motLabels.clear(); m_thread.quit(); m_thread.wait(); qDebug() << "EPOS thread quit."; delete ui; } void EPOS2Widget::workerStatusChanged(int status) { // TODO: consider putting this in a truth table and reading the entry based on the status code // then we will get rid of the entire switch/case and just have a few lines of code switch(status) { case EPOS_INITIALIZE_BEGIN: ui->connectButton->setEnabled(false); ui->outputTextEdit->appendPlainText("Connecting to EPOS..."); break; case EPOS_INITIALIZE_FAILED: ui->connectButton->setEnabled(true); ui->outputTextEdit->appendPlainText("Connection failed!"); break; case EPOS_INITIALIZED: ui->connectButton->setEnabled(false); ui->disconnectButton->setEnabled(true); ui->nodeIDcomboBox->setEnabled(true); ui->enableServoLoopButton->setEnabled(true); ui->disableServoLoopButton->setEnabled(false); ui->outputTextEdit->appendPlainText("Connected to EPOS."); // ui->outputTextEdit->appendPlainText(QString("%1 motor(s) plugged in.") // .arg(m_worker->getNumMotors())); break; case EPOS_DISCONNECTED: ui->connectButton->setEnabled(true); ui->disconnectButton->setEnabled(false); ui->enableNodeButton->setEnabled(false); ui->nodeIDcomboBox->setEnabled(false); ui->enableServoLoopButton->setEnabled(false); ui->disableServoLoopButton->setEnabled(false); ui->outputTextEdit->appendPlainText("Disconnected from EPOS."); break; case EPOS_DISCONNECT_FAILED: ui->outputTextEdit->appendPlainText("Disconnection from EPOS failed!"); break; case EPOS_SERVO_LOOP_STARTED: ui->enableServoLoopButton->setEnabled(false); ui->disableServoLoopButton->setEnabled(true); ui->haltButton->setEnabled(false); // disable halt button, use 'Disable Servo Loop' button to halt motors ui->outputTextEdit->appendPlainText("Servo loop started."); break; case EPOS_SERVO_LOOP_STOPPED: ui->enableServoLoopButton->setEnabled(true); ui->disableServoLoopButton->setEnabled(false); //ui->haltButton->setEnabled(true); updateManualControls(m_worker->getMotorStatus( ui->nodeIDcomboBox->currentIndex() )); ui->outputTextEdit->appendPlainText("Servo loop stopped."); break; case EPOS_SERVO_TO_POS_FAILED: ui->outputTextEdit->appendPlainText("Servo to position failed!"); break; case EPOS_EPOCH_SET: ui->outputTextEdit->appendPlainText("Epoch set."); break; case EPOS_EPOCH_SET_FAILED: ui->outputTextEdit->appendPlainText("Epoch set failed!"); break; case EPOS_DISABLE_MOTOR_FAILED: ui->outputTextEdit->appendPlainText("Motor disabled."); break; case EPOS_DISABLE_MOTOR_SUCCESS: ui->outputTextEdit->appendPlainText("Disable motor failed!"); break; case EPOS_DEVICE_CANT_CONNECT: ui->outputTextEdit->appendPlainText("Can't connect to device!"); break; case EPOS_UPDATE_QC_FAILED: ui->outputTextEdit->appendPlainText("Update QC failed!"); break; case EPOS_HALT_FAILED: ui->outputTextEdit->appendPlainText("Halt failed!"); break; default: ui->outputTextEdit->appendPlainText("Unknown state!"); break; } } void EPOS2Widget::workerMotorStatusChanged(const int motID, const int status) { int currID = ui->nodeIDcomboBox->currentIndex(); if(currID == motID) updateManualControls(status); if( status == EPOS_MOTOR_ENABLED ) { motLabels[motID]->setText("Enabled"); motLabels[motID]->setStyleSheet("QLabel { background-color : green;}"); ui->outputTextEdit->appendPlainText(QString("Motor %1 enabled.").arg(motID+1)); } else if( status == EPOS_MOTOR_DISABLED ) { motLabels[motID]->setText("Disabled"); motLabels[motID]->setStyleSheet("QLabel { background-color : yellow;}"); ui->outputTextEdit->appendPlainText(QString("Motor %1 disabled.").arg(motID+1)); } else if(status == EPOS_MOTOR_FAULT) { motLabels[motID]->setText("FAULT!"); motLabels[motID]->setStyleSheet("QLabel { background-color : red; color : white; }"); ui->outputTextEdit->appendPlainText(QString("Motor %1 fault!").arg(motID+1)); } else if(status == EPOS_MOTOR_CANT_CONNECT) { motLabels[motID]->setText("Can't connect!"); motLabels[motID]->setStyleSheet("QLabel { background-color : red; color : white; }"); ui->outputTextEdit->appendPlainText(QString("Cannot connect to Motor %1.").arg(motID+1)); } else { motLabels[motID]->setText("Unknown state!");// UNKNOWN STATE! motLabels[motID]->setStyleSheet("QLabel { background-color : red; color : white; }"); ui->outputTextEdit->appendPlainText(QString("Motor %1 in inknown state.").arg(motID+1)); } } void EPOS2Widget::workerMotorStatusChanged(std::vector<int> status) { for(size_t i = 0; i < status.size(); i++) workerMotorStatusChanged(i, status[i]); } void EPOS2Widget::workerMotorQcChanged(const int motID, const long QC) { if( motID < static_cast<int>(motQCs.size()) ) motQCs[motID]->display(QC); else qDebug() << "MotorID out of bounds!"; } void EPOS2Widget::workerMotorQcChanged(std::vector<long> QCs) { for(size_t i = 0; i < QCs.size(); i++) workerMotorQcChanged(i, QCs[i]); } void EPOS2Widget::receiveDataFromWorker(int motorID, const QString &data) { if(motorID == 0) ui->outputTextEdit->clear(); ui->outputTextEdit->appendPlainText(data); } void EPOS2Widget::on_moveAbsButton_clicked() { int axisID = ui->nodeIDcomboBox->currentIndex(); long targetPos = ui->targetQCspinBox->value(); emit setServoTargetPos(axisID, targetPos, true); if(!m_worker->isInServoLoop()) emit servoToPos(); } void EPOS2Widget::on_moveRelButton_clicked() { int axisID = ui->nodeIDcomboBox->currentIndex(); long targetPos = ui->targetQCspinBox->value(); emit setServoTargetPos(axisID, targetPos, false); if(!m_worker->isInServoLoop()) emit servoToPos(); } void EPOS2Widget::on_homingButton_clicked() { int axisID = ui->nodeIDcomboBox->currentIndex(); //long targetPos = 0; qDebug() << "Homing axis " << axisID; //if(!m_worker->isInServoLoop()) emit stopServoLoop(); // stop servo loop //emit setServoTargetPos(axisID, 0, true); // set target position emit homeAxis(axisID); emit servoToPos(); // servo to position } void EPOS2Widget::on_haltButton_clicked() { int axisID = ui->nodeIDcomboBox->currentIndex(); emit haltMotor(axisID); } void EPOS2Widget::updateManualControls(const int motorStatus) { if( motorStatus == EPOS_MOTOR_ENABLED ) { ui->enableNodeButton->setEnabled(false); ui->disableNodeButton->setEnabled(true); ui->homingButton->setEnabled(true); ui->moveAbsButton->setEnabled(true); ui->moveRelButton->setEnabled(true); if(!m_worker->isInServoLoop()) ui->haltButton->setEnabled(true); else ui->haltButton->setEnabled(false); ui->homeAllButton->setEnabled(true); } else if( motorStatus == EPOS_MOTOR_DISABLED ) { ui->enableNodeButton->setEnabled(true); ui->disableNodeButton->setEnabled(false); ui->homingButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homeAllButton->setEnabled(false); } else if(motorStatus == EPOS_MOTOR_FAULT) { ui->enableNodeButton->setEnabled(true); ui->disableNodeButton->setEnabled(false); ui->homingButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homeAllButton->setEnabled(false); } else if(motorStatus == EPOS_MOTOR_CANT_CONNECT) { ui->enableNodeButton->setEnabled(true); ui->disableNodeButton->setEnabled(false); ui->homingButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homeAllButton->setEnabled(false); } else { ui->enableNodeButton->setEnabled(true); ui->disableNodeButton->setEnabled(false); ui->homingButton->setEnabled(false); ui->moveAbsButton->setEnabled(false); ui->moveRelButton->setEnabled(false); ui->haltButton->setEnabled(false); ui->homeAllButton->setEnabled(false); } } void EPOS2Widget::on_nodeIDcomboBox_currentIndexChanged(int index) { const int motorStatus = m_worker->getMotorStatus(index); if(motorStatus != EPOS_INVALID_MOTOR_ID) updateManualControls(motorStatus); else qDebug() << "Invalid motorID!"; } void EPOS2Widget::on_enableNodeButton_clicked() { const int axisID = ui->nodeIDcomboBox->currentIndex(); emit enableMotor(axisID); } void EPOS2Widget::on_disableNodeButton_clicked() { const int axisID = ui->nodeIDcomboBox->currentIndex(); emit disableMotor(axisID); } void EPOS2Widget::on_enableServoLoopButton_clicked() { emit startServoLoop(); } void EPOS2Widget::on_disableServoLoopButton_clicked() { emit stopServoLoop(); } void EPOS2Widget::on_homeAllButton_clicked() { // stop servo loop emit stopServoLoop(); emit homeAllAxes(); } void EPOS2Widget::on_trajOpenFileButton_clicked() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open CSV File"), "../ICEbot_QT_v1/LoggedData", tr("CSV File (*.csv)")); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << file.errorString(); return; } QTextStream in(&file); m_pyrtQCs.clear(); while (!in.atEnd()) { QString line = in.readLine(); QStringList split = line.split(','); if(split.size() == 4) { PYRT qc; qc.pitchQC = split[0].toLong(); qc.yawQC = split[1].toLong(); qc.rollQC = split[2].toLong(); qc.transQC = split[3].toLong(); m_pyrtQCs.push_back(qc); } else { qDebug() << "Error reading CSV - number of elements in line is not equal to 4!"; break; } } qDebug() << "Read" << m_pyrtQCs.size() << "setpoints from trajectory file."; if(m_pyrtQCs.size() > 0){ ui->trajDriveButton->setEnabled(true); ui->trajStepLineEdit->setText(QString("%1 points loaded.").arg(m_pyrtQCs.size())); } else{ ui->trajDriveButton->setEnabled(false); ui->trajStepLineEdit->setText("Error reading file."); } } void EPOS2Widget::on_trajDriveButton_clicked() { if(m_keepDriving) { m_keepDriving = false; ui->trajDriveButton->setText("Drive"); // stop timer m_trajTimer->stop(); disconnect(m_trajTimer, SIGNAL(timeout()), 0, 0); delete m_trajTimer; } else { m_keepDriving = true; ui->trajDriveButton->setText("Stop"); m_currTrajIdx = 0; ui->trajStepLineEdit->setText(QString("%1 of %2.").arg(m_currTrajIdx).arg(m_pyrtQCs.size())); PYRT currPYRT = m_pyrtQCs[m_currTrajIdx]; std::vector<long> newPos(4); newPos[TRANS_AXIS_ID] = currPYRT.transQC; newPos[PITCH_AXIS_ID] = currPYRT.pitchQC; newPos[YAW_AXIS_ID] = currPYRT.yawQC; newPos[ROLL_AXIS_ID] = currPYRT.rollQC; setServoTargetPos(newPos, true); // start timer m_trajTimer = new QTimer(this); connect(m_trajTimer, SIGNAL(timeout()), this, SLOT(driveTrajectory())); m_trajTimer->start(10); } } void EPOS2Widget::driveTrajectory() { PYRT currPYRT = m_pyrtQCs[m_currTrajIdx]; if( (abs(ui->pitchQC_LCD->intValue() - ui->rollQC_LCD->intValue() - currPYRT.pitchQC) < 5) && (abs(ui->yawQC_LCD->intValue() + ui->rollQC_LCD->intValue() - currPYRT.yawQC) < 5) && (abs(ui->rollQC_LCD->intValue() - currPYRT.rollQC) < 5) && (abs(ui->transQC_LCD->intValue() - currPYRT.transQC) < 5) && m_keepDriving) { m_currTrajIdx++; ui->trajStepLineEdit->setText(QString("%1 of %2.").arg(m_currTrajIdx).arg(m_pyrtQCs.size())); if(m_currTrajIdx < m_pyrtQCs.size()) { currPYRT = m_pyrtQCs[m_currTrajIdx]; std::vector<long> newPos(4); newPos[TRANS_AXIS_ID] = currPYRT.transQC; newPos[PITCH_AXIS_ID] = currPYRT.pitchQC; newPos[YAW_AXIS_ID] = currPYRT.yawQC; newPos[ROLL_AXIS_ID] = currPYRT.rollQC; setServoTargetPos(newPos, true); // absolute qDebug() << "Drive to" << newPos[TRANS_AXIS_ID] << newPos[PITCH_AXIS_ID] << newPos[YAW_AXIS_ID] << newPos[ROLL_AXIS_ID]; } else { m_keepDriving = false; ui->trajDriveButton->setText("Drive"); } } }
16,314
C++
33.27521
132
0.635773
adegirmenci/HBL-ICEbot/EPOS2Widget/epos2widget.h
#ifndef EPOS2WIDGET_H #define EPOS2WIDGET_H #include <QWidget> #include <QThread> #include <QLabel> #include <QLCDNumber> #include <QFileDialog> #include <QTextStream> #include <QStringList> #include <QTimer> #include <vector> #include "epos2thread.h" namespace Ui { class EPOS2Widget; } struct PYRT { long pitchQC; long yawQC; long rollQC; long transQC; }; class EPOS2Widget : public QWidget { Q_OBJECT public: explicit EPOS2Widget(QWidget *parent = 0); ~EPOS2Widget(); EPOS2Thread *m_worker; signals: void setServoTargetPos(const int axisID, long targetPos, bool moveAbsOrRel); void setServoTargetPos(std::vector<long> targetPos, bool moveAbsOrRel); void servoToPos(); void servoToPos(const int axisID); void haltMotor(const int axisID); void enableMotor(const int axisID); void disableMotor(const int axisID); void startServoLoop(); void stopServoLoop(); void homeAxis(const int axisID); void homeAllAxes(); private slots: void workerStatusChanged(int status); void workerMotorStatusChanged(const int motID, const int status); void workerMotorStatusChanged(std::vector<int> status); void workerMotorQcChanged(const int motID, const long QC); void workerMotorQcChanged(std::vector<long> QCs); void receiveDataFromWorker(int motorID, const QString &data); void on_moveAbsButton_clicked(); void on_moveRelButton_clicked(); void on_homingButton_clicked(); void on_haltButton_clicked(); void on_nodeIDcomboBox_currentIndexChanged(int index); void on_enableNodeButton_clicked(); void on_disableNodeButton_clicked(); void on_enableServoLoopButton_clicked(); void on_disableServoLoopButton_clicked(); void on_homeAllButton_clicked(); void on_trajOpenFileButton_clicked(); void on_trajDriveButton_clicked(); void driveTrajectory(); private: Ui::EPOS2Widget *ui; QThread m_thread; // EPOS Thread will live in here std::vector<QLabel*> motLabels; std::vector<QLCDNumber*> motQCs; void updateManualControls(const int motorStatus); // trajectory std::vector<PYRT> m_pyrtQCs; bool m_keepDriving; size_t m_currTrajIdx; QTimer *m_trajTimer; }; #endif // EPOS2WIDGET_H
2,277
C
20.695238
80
0.711902
adegirmenci/HBL-ICEbot/EPOS2Widget/epos2thread.cpp
#include "epos2thread.h" EPOS2Thread::EPOS2Thread(QObject *parent) : QObject(parent) { qRegisterMetaType< std::vector<long> >("std::vector<long>"); m_isEpochSet = false; m_isReady = false; m_keepServoing = false; m_abort = false; m_KeyHandle = 0; m_mutex = new QMutex(QMutex::Recursive); qDebug() << "Initizializing pointers to eposMotor"; for(size_t i = 0; i < EPOS_NUM_MOTORS; i++) { m_motors.push_back(std::shared_ptr<eposMotor>(new eposMotor)); m_motors[i]->m_nodeID = EPOS_MOTOR_IDS[i]; m_motors[i]->m_minQC = EPOS_MOTOR_LIMITS[i][0]; // lower limit m_motors[i]->m_maxQC = EPOS_MOTOR_LIMITS[i][1]; // upper limit m_motors[i]->m_enabled = false; } } EPOS2Thread::~EPOS2Thread() { disconnectEPOS(); m_mutex->lock(); m_abort = true; qDebug() << "Ending EPOS2Thread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; m_mutex->unlock(); delete m_mutex; emit finished(); } bool EPOS2Thread::initializeEPOS() { QMutexLocker locker(m_mutex); emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_INITIALIZE_BEGIN); emit statusChanged(EPOS_INITIALIZE_BEGIN); qDebug() << "Opening connection to EPOS..."; if(m_KeyHandle) { //Close Previous Device if(!VCS_CloseDevice(m_KeyHandle, &m_ulErrorCode)) ShowErrorInformation(m_ulErrorCode); m_KeyHandle = 0; } else m_KeyHandle = 0; //Settings m_oImmediately = true; // don't wait until end of last move m_oUpdateActive = false; HANDLE hNewKeyHandle; hNewKeyHandle = VCS_OpenDeviceDlg(&m_ulErrorCode); if(hNewKeyHandle) m_KeyHandle = hNewKeyHandle; else { ShowErrorInformation(m_ulErrorCode); emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_INITIALIZE_FAILED); emit statusChanged(EPOS_INITIALIZE_FAILED); return false; } // Set properties of each motor bool status = true; //locker.unlock(); for(int i = 0; i < EPOS_NUM_MOTORS; i++) { if(!initializeMotor( EPOS_AXIS_IDS[i]) ) { status = false; ShowErrorInformation(m_ulErrorCode); } else status = status && true; } //locker.relock(); emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_INITIALIZED); emit statusChanged(EPOS_INITIALIZED); return status; } void EPOS2Thread::startServoing() { QMutexLocker locker(m_mutex); m_timer = new QTimer(this); m_timer->start(0); connect(m_timer,SIGNAL(timeout()),this,SLOT(servoToPosition())); m_keepServoing = true; // QElapsedTimer elTimer; // elTimer.start(); // QTime::currentTime(); // qint64 elNsec = elTimer.nsecsElapsed(); // qDebug() << "Nsec elapsed:" << elNsec; emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_SERVO_LOOP_STARTED); emit statusChanged(EPOS_SERVO_LOOP_STARTED); qDebug() << "Servo loop started."; } void EPOS2Thread::setServoTargetPos(const int axisID, long targetPos, bool moveAbsOrRel) { QMutexLocker locker(m_mutex); // check axis limits if(checkMotorID(axisID)) { if(moveAbsOrRel) targetPos = clampToMotorLimits(axisID, targetPos); // abs else targetPos = clampToMotorLimits(axisID, m_motors[axisID]->m_lActualValue + targetPos); // rel // compensate for roll if(ROLL_AXIS_ID == axisID) { // #relativeRoll = #currentIncrement - #oldPosition long relativeRoll; if(moveAbsOrRel) relativeRoll = targetPos; // this got added later (1/17/17) else relativeRoll = targetPos - m_motors[ROLL_AXIS_ID]->m_lActualValue; // it was just this before (1/17/17) // this works because roll is the last to update // if roll is not the last to get updated, then these target values // would get overwritten m_motors[PITCH_AXIS_ID]->m_lTargetPosition += relativeRoll; //pitch m_motors[YAW_AXIS_ID]->m_lTargetPosition -= relativeRoll; //yaw //update limits // m_motors[PITCH_AXIS_ID]->m_minQC += relativeRoll; // m_motors[PITCH_AXIS_ID]->m_maxQC += relativeRoll; // m_motors[YAW_AXIS_ID]->m_minQC -= relativeRoll; // m_motors[YAW_AXIS_ID]->m_maxQC -= relativeRoll; m_motors[PITCH_AXIS_ID]->m_minQC = EPOS_PITCH_MIN + targetPos; m_motors[PITCH_AXIS_ID]->m_maxQC = EPOS_PITCH_MAX + targetPos; m_motors[YAW_AXIS_ID]->m_minQC = EPOS_YAW_MIN - targetPos; m_motors[YAW_AXIS_ID]->m_maxQC = EPOS_YAW_MAX - targetPos; // recheck pitch and yaw m_motors[PITCH_AXIS_ID]->m_lTargetPosition = clampToMotorLimits(PITCH_AXIS_ID, m_motors[PITCH_AXIS_ID]->m_lTargetPosition); m_motors[YAW_AXIS_ID]->m_lTargetPosition = clampToMotorLimits(YAW_AXIS_ID, m_motors[YAW_AXIS_ID]->m_lTargetPosition); } // finally, update the target m_motors[axisID]->m_lTargetPosition = targetPos; } } void EPOS2Thread::setServoTargetPos(std::vector<long> targetPos, bool moveAbsOrRel) { QMutexLocker locker(m_mutex); if(targetPos.size() != EPOS_NUM_MOTORS) qDebug() << "Wrong vector size in setServoTargetPos."; // reset the limit changes due to roll if(moveAbsOrRel) { m_motors[PITCH_AXIS_ID]->m_minQC = EPOS_PITCH_MIN; m_motors[PITCH_AXIS_ID]->m_maxQC = EPOS_PITCH_MAX; m_motors[YAW_AXIS_ID]->m_minQC = EPOS_YAW_MIN; m_motors[YAW_AXIS_ID]->m_maxQC = EPOS_YAW_MAX; } for(int i = 0; i < EPOS_NUM_MOTORS; i++) { // if(moveAbsOrRel) // m_motors[i]->m_lTargetPosition = targetPos[i]; // else // m_motors[i]->m_lTargetPosition += targetPos[i]; setServoTargetPos(i, targetPos[i], moveAbsOrRel); } } int EPOS2Thread::checkMotorLimits(const int axisID, const long targetPos) { QMutexLocker locker(m_mutex); if(targetPos < m_motors[axisID]->m_minQC) // too small return -1; else if(targetPos > m_motors[axisID]->m_maxQC) // too large return 1; else // just right return 0; } long EPOS2Thread::clampToMotorLimits(const int axisID, const long targetPos) { QMutexLocker locker(m_mutex); if(targetPos < m_motors[axisID]->m_minQC) // too small return m_motors[axisID]->m_minQC; else if(targetPos > m_motors[axisID]->m_maxQC) // too large return m_motors[axisID]->m_maxQC; else // just right return targetPos; } // Calls to the motors will ALWAYS be executed SEQUENTIALLY over a single USB line, because data can only travel sequentially // over a serial port. // If we need to REDUCE the LATENCY, then we should consider using two USB cables. // If the main concern is SYNCING the MOTION COMMANDS, then we can have the master (root) EPOS send a trigger signal to the // slave boards AFTER all the motor target positions have been updated. void EPOS2Thread::servoToPosition() { QMutexLocker locker(m_mutex); updateMotorQCs(); // QElapsedTimer elTimer; // qDebug() << "Using clock type " << elTimer.clockType(); // elTimer.start(); for(int i = 0; i < EPOS_NUM_MOTORS; i++) { servoToPosition(i); } // qDebug() << "Elapsed Time: " << elTimer.nsecsElapsed()/1000000. << " ms"; } void EPOS2Thread::servoToPosition(const int axisID) { QMutexLocker locker(m_mutex); if(checkMotorID(axisID)) { WORD usNodeId = m_motors[axisID]->m_nodeID; if(m_motors[axisID]->m_enabled) { //updateMotorQC(axisID); // this may not be the best place to put this emit logData(QTime::currentTime(), EPOS_COMMANDED, axisID, m_motors[axisID]->m_lTargetPosition); if(!VCS_MoveToPosition(m_KeyHandle, usNodeId, m_motors[axisID]->m_lTargetPosition, true, m_oImmediately, &m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); qDebug() << QString("Servo to pos failed! Axis %1, Node %2").arg(axisID).arg(usNodeId); emit statusChanged(EPOS_SERVO_TO_POS_FAILED); } } } } void EPOS2Thread::stopServoing() { QMutexLocker locker(m_mutex); if ( m_keepServoing ) { m_keepServoing = false; m_timer->stop(); disconnect(m_timer,SIGNAL(timeout()),0,0); delete m_timer; emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_SERVO_LOOP_STOPPED); emit statusChanged(EPOS_SERVO_LOOP_STOPPED); qDebug() << "Servo loop stopped."; } } void EPOS2Thread::updateMotorQC(const int axisID) { QMutexLocker locker(m_mutex); if(checkMotorID(axisID)) { //Read Actual Position if(VCS_GetPositionIs(m_KeyHandle, m_motors[axisID]->m_nodeID, &(m_motors[axisID]->m_lActualValue), &m_ulErrorCode)) { emit logData(QTime::currentTime(), EPOS_READ, axisID, m_motors[axisID]->m_lActualValue); emit motorQcChanged(axisID, m_motors[axisID]->m_lActualValue); } else { ShowErrorInformation(m_ulErrorCode); emit statusChanged(EPOS_UPDATE_QC_FAILED); } } } void EPOS2Thread::updateMotorQCs() { QMutexLocker locker(m_mutex); for(int i = 0; i < EPOS_NUM_MOTORS; i++) { if(m_motors[i]->m_enabled) updateMotorQC(i); } } void EPOS2Thread::haltMotor(const int axisID) { QMutexLocker locker(m_mutex); if(checkMotorID(axisID)) { if(VCS_HaltPositionMovement(m_KeyHandle, m_motors[axisID]->m_nodeID, &m_ulErrorCode)) { //Read Actual Position updateMotorQC(axisID); } else { ShowErrorInformation(m_ulErrorCode); qDebug() << QString("Halt failed! Node %1").arg(m_motors[axisID]->m_nodeID); emit statusChanged(EPOS_HALT_FAILED); } } } void EPOS2Thread::homeAxis(const int axisID) { QMutexLocker locker(m_mutex); if(checkMotorID(axisID)) { // set a lower speed if(m_motors[axisID]->m_enabled) { WORD nodeID = m_motors[axisID]->m_nodeID; if(!VCS_SetPositionProfile(m_KeyHandle,nodeID, 1400,2000,2000,&m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } m_motors[axisID]->m_minQC = EPOS_MOTOR_LIMITS[axisID][0]; // reset lower limit m_motors[axisID]->m_maxQC = EPOS_MOTOR_LIMITS[axisID][1]; // reset upper limit setServoTargetPos(axisID, 0, true); // set target position to 0 // TODO: this should be a blocking call, otherwise speed gets reset during motion servoToPosition(axisID); // servo motor // reset speed if(!VCS_SetPositionProfile(m_KeyHandle,nodeID, EPOS_VELOCITY[axisID],EPOS_ACCEL[axisID],EPOS_DECEL[axisID],&m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } } } } void EPOS2Thread::homeAllAxes() { QMutexLocker locker(m_mutex); for(int i = 0; i < EPOS_NUM_MOTORS; i++) { if(m_motors[i]->m_enabled) { // set a lower speed WORD nodeID = m_motors[i]->m_nodeID; if(!VCS_SetPositionProfile(m_KeyHandle,nodeID, 1400,2000,2000,&m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } m_motors[i]->m_minQC = EPOS_MOTOR_LIMITS[i][0]; // reset lower limit m_motors[i]->m_maxQC = EPOS_MOTOR_LIMITS[i][1]; // reset upper limit // don't use setServoPos here, since that will compensate for roll // self comment: setServoPos(vector) would probably work though? m_motors[i]->m_lTargetPosition = 0; // TODO: a better strategy is probably to get the catheter straight first, then home } } // TODO: this should be a blocking call, otherwise speed gets reset during motion servoToPosition(); // servo motors // reset speed for(int i = 0; i < EPOS_NUM_MOTORS; i++) { if(m_motors[i]->m_enabled) { WORD nodeID = m_motors[i]->m_nodeID; if(!VCS_SetPositionProfile(m_KeyHandle,nodeID, EPOS_VELOCITY[i],EPOS_ACCEL[i],EPOS_DECEL[i],&m_ulErrorCode)) { ShowErrorInformation(m_ulErrorCode); } } } } bool EPOS2Thread::disconnectEPOS() { bool status = true; homeAllAxes(); QThread::sleep(2); stopServoing(); QMutexLocker locker(m_mutex); if(m_KeyHandle) { //locker.unlock(); for(int i = 0; i < EPOS_NUM_MOTORS; i++) { status = status && disableMotor( EPOS_AXIS_IDS[i] ); } //locker.relock(); if(status) qDebug() << "Motors disabled."; status = VCS_CloseDevice(m_KeyHandle, &m_ulErrorCode); if(status) { m_KeyHandle = 0; qDebug() << "EPOS closed successfully."; emit statusChanged(EPOS_DISCONNECTED); } else { ShowErrorInformation(m_ulErrorCode); emit statusChanged(EPOS_DISCONNECT_FAILED); } } else { qDebug() << ("EPOS is already closed."); } return status; } void EPOS2Thread::setEpoch(const QDateTime &datetime) { QMutexLocker locker(m_mutex); if(!m_keepServoing) { m_epoch = datetime; m_isEpochSet = true; emit logEventWithMessage(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_EPOCH_SET, m_epoch.toString("yyyy/MM/dd - hh:mm:ss.zzz")); } else emit logEvent(SRC_EPOS, LOG_INFO, QTime::currentTime(), EPOS_EPOCH_SET_FAILED); } // ---------------- // HELPER FUNCTIONS // ---------------- bool EPOS2Thread::initializeMotor(const int motID) { QMutexLocker locker(m_mutex); bool result = checkMotorID(motID); if(result && !m_motors[motID]->m_enabled) { std::shared_ptr<eposMotor> mot = m_motors[motID]; mot->m_bMode = 0; mot->m_lActualValue = 0; mot->m_lStartPosition = 0; mot->m_lTargetPosition = 0; WORD usNodeID = mot->m_nodeID; qDebug() << QString("Connecting to Node %1...").arg(usNodeID); mot->m_enabled = false; if(m_KeyHandle) { //Clear Error History if(VCS_ClearFault(m_KeyHandle, usNodeID, &m_ulErrorCode)) { //Enable if( VCS_SetEnableState(m_KeyHandle, usNodeID, &m_ulErrorCode) ) { //Read Operation Mode if(VCS_GetOperationMode(m_KeyHandle, usNodeID, &(mot->m_bMode), &m_ulErrorCode)) { //Read Position Profile Objects if(VCS_GetPositionProfile(m_KeyHandle, usNodeID, &(mot->m_ulProfileVelocity), &(mot->m_ulProfileAcceleration), &(mot->m_ulProfileDeceleration), &m_ulErrorCode)) { //Write Profile Position Mode if(VCS_SetOperationMode(m_KeyHandle, usNodeID, OMD_PROFILE_POSITION_MODE, &m_ulErrorCode)) { //Write Profile Position Objects if(VCS_SetPositionProfile(m_KeyHandle, usNodeID, EPOS_VELOCITY[motID], EPOS_ACCEL[motID], EPOS_DECEL[motID], &m_ulErrorCode)) { mot->m_ulProfileVelocity = EPOS_VELOCITY[motID]; mot->m_ulProfileAcceleration = EPOS_ACCEL[motID]; mot->m_ulProfileDeceleration = EPOS_DECEL[motID]; //Read Actual Position if(VCS_GetPositionIs(m_KeyHandle, usNodeID, &(mot->m_lStartPosition), &m_ulErrorCode)) { qDebug() << "DONE!"; mot->m_lActualValue = mot->m_lStartPosition; mot->m_lTargetPosition = mot->m_lStartPosition; mot->m_enabled = true; mot->m_motorStatus = EPOS_MOTOR_ENABLED; result = true; emit motorStatusChanged(motID, EPOS_MOTOR_ENABLED); emit motorQcChanged(motID, mot->m_lActualValue); } } } } } } } if(!mot->m_enabled) { qDebug() << "Can't connect to motor!"; ShowErrorInformation(m_ulErrorCode); mot->m_motorStatus = EPOS_MOTOR_CANT_CONNECT; emit motorStatusChanged(motID, EPOS_MOTOR_CANT_CONNECT); result = false; } } else { qDebug() << "Can't open device!"; mot->m_enabled = false; mot->m_motorStatus = EPOS_MOTOR_CANT_CONNECT; result = false; emit statusChanged(EPOS_DEVICE_CANT_CONNECT); } } return result; } bool EPOS2Thread::disableMotor(const int motID) { QMutexLocker locker(m_mutex); bool result = checkMotorID(motID); if(result && m_motors[motID]->m_enabled) { std::shared_ptr<eposMotor> mot = m_motors[motID]; WORD usNodeID = mot->m_nodeID; //get motor ID mot->m_enabled = false; // set flag to false mot->m_motorStatus = EPOS_MOTOR_DISABLED; // disable motor result = VCS_SetDisableState(m_KeyHandle, usNodeID, &m_ulErrorCode); if(result) { qDebug() <<"Motor " << usNodeID << " disabled."; emit motorStatusChanged(motID, EPOS_MOTOR_DISABLED); } else ShowErrorInformation(m_ulErrorCode); } return result; } const int EPOS2Thread::getMotorStatus(const int axisID) { QMutexLocker locker(m_mutex); bool result = checkMotorID(axisID); if(result) return m_motors[axisID]->m_motorStatus; else return EPOS_INVALID_MOTOR_ID; } bool EPOS2Thread::ShowErrorInformation(DWORD p_ulErrorCode) { char* pStrErrorInfo; const char* strDescription; QString msg(QString("Error Code %1: ").arg(QString::number(p_ulErrorCode))); if((pStrErrorInfo = (char*)malloc(100)) == NULL) { msg.append("Not enough memory to allocate buffer for error information string."); qDebug() << "Maxon: " << msg; return false; } if(VCS_GetErrorInfo(p_ulErrorCode, pStrErrorInfo, 100)) { strDescription = pStrErrorInfo; msg.append(strDescription); qDebug() << "Maxon: " << msg; emit logError(SRC_EPOS, LOG_ERROR, QTime::currentTime(), EPOS_FAIL, msg); free(pStrErrorInfo); return true; } else { msg.append("Error information can't be read!"); free(pStrErrorInfo); qDebug() << "Maxon: " << msg; emit logError(SRC_EPOS, LOG_ERROR, QTime::currentTime(), EPOS_FAIL, msg); return false; } } bool EPOS2Thread::checkMotorID(const int motID) { if( (motID >= EPOS_NUM_MOTORS) || (motID < 0) ) { QString msg = QString("Motor ID (%1) out of bounds").arg(motID); emit logEventWithMessage(SRC_EPOS, LOG_ERROR, QTime::currentTime(), EPOS_DISABLE_MOTOR_FAILED, msg); qDebug() << msg; return false; } return true; } QString EPOS2Thread::formatOutput(QTime &timeStamp, const int motorID, long pos) { QString output; output.append(timeStamp.toString("HH.mm.ss.zzz\n")); output.append(QString("[Motor %1] - %2 QCs").arg(motorID).arg(pos)); return QString(); } inline const QString getCurrTimeStr() { return QTime::currentTime().toString("HH.mm.ss.zzz"); } inline const QString getCurrDateTimeStr() { return QDateTime::currentDateTime().toString("yyyy/MM/dd - hh:mm:ss.zzz"); }
21,645
C++
29.359046
135
0.54225
adegirmenci/HBL-ICEbot/EPOS2Widget/MaxonLibs/Definitions.h
/********************************************************************* ** maxon motor ag, CH-6072 Sachseln ********************************************************************** ** ** File: Definitions.h ** Description: Functions definitions for EposCmd.dll/EposCmd64.dll library for Developer Platform Microsoft Visual C++ ** ** Date: 20.10.03 ** Dev. Platform: Microsoft Visual C++ ** Target: Windows Operating Systems ** Written by: maxon motor ag, CH-6072 Sachseln ** ** History: 1.00 (20.10.03): Initial version ** 1.01 (01.12.03): Changed Functions: VCS_GetDeviceNameSelection, BOOL VCS_GetDeviceName, VCS_GetProtocolStackNameSelection, ** VCS_GetInterfaceNameSelection, VCS_GetPortNameSelection, VCS_GetBaudrateSelection, ** VCS_GetProtocolStackModeSelection, VCS_GetProtocolStackName, VCS_GetInterfaceName, VCS_GetPortName ** 1.1.0.0 (13.01.04): Bugfix: If the functions GetXXXSelection were alone called, no manager was initialized. Again an inquiry inserted ** (21.01.04): New Functions: VCS_CloseAllDevices, VCS_DigitalInputConfiguration, VCS_DigitalOutputConfiguration, ** VCS_GetAllDigitalInputs, VCS_GetAllDigitalOutputs, VCS_GetAnalogInput, VCS_SetAllDigitalOutputs ** (29.03.04): New Functions: VCS_OpenDeviceDlg, SendNMTService ** Changed Functions: VCS_OpenDevice, VCS_SetObject, VCS_GetObject, VCS_FindHome, VCS_SetOperationMode, VCS_GetOperationMode, VCS_MoveToPosition ** Deleted Functions: VCS_GetProtocolStackMode, VCS_GetProtocolStackModeSelection ** 2.0.0.0 (07.04.04): Release version ** 2.0.1.0 (13.04.04): Bugfix version ** 2.0.2.0 (15.04.04): Bugfix version ** 2.0.3.0 (11.05.04): Bugfix version ** (07.12.04): New Functions: VCS_SendCANFrame, VCS_RequestCANFrame ** 3.0.0.0 (31.03.05): Changes: All EPOS - functions => new with the handle for the Journal ** New Functions: VCS_StartJournal, VCS_StopJournal ** 3.0.1.0 (08.03.05): Internal version ** 3.0.2.0 (09.09.05): BugFix: Support IXXAT interfaces with 2 ports ** 4.0.0.0 (21.10.05): Release version ** 4.1.0.0 (02.02.06): Internal version: New DLL structure (Dtms and GUI Version 2.01) ** 4.1.1.0 (12.04.06): Internal version ** 4.1.2.0 (12.06.06): Internal version ** 4.1.3.0 (03.07.06): Internal version: GUI Version 2.04 ** 4.1.4.0 (16.08.06): New: LSS functions implemented ** 4.2.0.0 (12.10.06): Customer version ** 4.3.0.0 (01.02.07): New: Support National Instruments CANopen interfaces ** 4.4.0.0 (10.08.07): Expansion: VCI3 driver support for IXXAT CANopen interfaces ** 4.5.0.0 (01.05.08): Internal: Converted to development environment Visual Studio 2005 ** New: Read device error history (VCS_GetNbOfDeviceError, VCS_GetDeviceErrorCode) ** 4.6.1.0 (04.09.09): New: Support for EPOS2 functionality, data recorder, parameter export and import. VCS_ReadCANFrame ** 4.7.1.0 (30.08.10): New: Add parameter DialogMode for Findxxx functions ** 4.7.2.0 (11.10.10): BugFix: Deadlock when closing application ** Communication for IXXAT VCI V3.3 ** 4.7.3.0 (28.10.10): Bugfix: Functions VCS_CloseDevice, VCS_CloseAllDevices ** 4.8.1.0 (28.01.11): New: Enlargement of 64-Bit operating systems ** Bugfix: Segmented Write ** 4.8.2.0 (02.02.11): Changes: Detect properly LIN devices ** 4.8.5.x (10.04.12): Bugfix: Sporadic CAN failure with IXXAT VCI V3.3 ** 4.8.6.x (08.10.12): New: Add support for Vector VN1600 series ** 4.8.7.x (10.10.12): New functions: VCS_GetVelocityRegulatorFeedForward, VCS_SetVelocityRegulatorFeedForward ** Bugfix: Command VCS_SendNmtService ** 4.9.1.0 (04.01.13): New Functions: VCS_GetHomingState, VCS_WaitForHomingAttained, VCS_GetVelocityIsAveraged, VCS_GetCurrentIsAveraged ** 4.9.2.0 (22.03.13): Bugfix: Function ExportParameter: Parameters renamed ** 4.9.3.0 (25.07.13): Internal version ** 4.9.4.0 (01.10.13): Bugfix: Function VCS_GetDriverInfo 64-Bit variant ** 4.9.5.0 (17.12.13): Changes: VCS_ExportChannelDataToFile: Check path exists ** 5.0.1.0 (24.10.14): New: Support Kvaser CANopen interfaces ** New: Support for NI-XNET driver ** *********************************************************************/ // -------------------------------------------------------------------------- // DIRECTIVES // -------------------------------------------------------------------------- #ifndef _WINDOWS_ #include <windows.h> #endif #if !defined(EposCommandLibraryDefinitions) #define EposCommandLibraryDefinitions // -------------------------------------------------------------------------- // IMPORTED FUNCTIONS PROTOTYPE // -------------------------------------------------------------------------- // INITIALISATION FUNCTIONS #define Initialisation_DllExport extern "C" __declspec( dllexport ) #define HelpFunctions_DllExport extern "C" __declspec( dllexport ) // CONFIGURATION FUNCTIONS #define Configuration_DllExport extern "C" __declspec( dllexport ) // OPERATION FUNCTIONS #define Status_DllExport extern "C" __declspec( dllexport ) #define StateMachine_DllExport extern "C" __declspec( dllexport ) #define ErrorHandling_DllExport extern "C" __declspec( dllexport ) #define MotionInfo_DllExport extern "C" __declspec( dllexport ) #define ProfilePositionMode_DllExport extern "C" __declspec( dllexport ) #define ProfileVelocityMode_DllExport extern "C" __declspec( dllexport ) #define HomingMode_DllExport extern "C" __declspec( dllexport ) #define InterpolatedPositionMode_DllExport extern "C" __declspec( dllexport ) #define PositionMode_DllExport extern "C" __declspec( dllexport ) #define VelocityMode_DllExport extern "C" __declspec( dllexport ) #define CurrentMode_DllExport extern "C" __declspec( dllexport ) #define MasterEncoderMode_DllExport extern "C" __declspec( dllexport ) #define StepDirectionMode_DllExport extern "C" __declspec( dllexport ) #define InputsOutputs_DllExport extern "C" __declspec( dllexport ) // DATA RECORDING FUNCTIONS #define DataRecording_DllExport extern "C" __declspec( dllexport ) // LOW LAYER FUNCTIONS #define CanLayer_DllExport extern "C" __declspec( dllexport ) /************************************************************************************************************************************* * INITIALISATION FUNCTIONS *************************************************************************************************************************************/ //Communication Initialisation_DllExport HANDLE __stdcall VCS_OpenDevice(char* DeviceName, char* ProtocolStackName, char* InterfaceName, char* PortName, DWORD* pErrorCode); Initialisation_DllExport HANDLE __stdcall VCS_OpenDeviceDlg(DWORD* pErrorCode); Initialisation_DllExport BOOL __stdcall VCS_SetProtocolStackSettings(HANDLE KeyHandle, DWORD Baudrate, DWORD Timeout, DWORD* pErrorCode); Initialisation_DllExport BOOL __stdcall VCS_GetProtocolStackSettings(HANDLE KeyHandle, DWORD* pBaudrate, DWORD* pTimeout, DWORD* pErrorCode); Initialisation_DllExport BOOL __stdcall VCS_FindDeviceCommunicationSettings(HANDLE *pKeyHandle, char *pDeviceName, char *pProtocolStackName, char *pInterfaceName, char *pPortName, WORD SizeName, DWORD *pBaudrate, DWORD *pTimeout, WORD *pNodeId, int DialogMode, DWORD *pErrorCode); Initialisation_DllExport BOOL __stdcall VCS_CloseDevice(HANDLE KeyHandle, DWORD* pErrorCode); Initialisation_DllExport BOOL __stdcall VCS_CloseAllDevices(DWORD* pErrorCode); //Info HelpFunctions_DllExport BOOL __stdcall VCS_GetDriverInfo(char* pLibraryName, WORD MaxNameSize, char* pLibraryVersion, WORD MaxVersionSize, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetVersion(HANDLE KeyHandle, WORD NodeId, WORD* pHardwareVersion, WORD* pSoftwareVersion, WORD* pApplicationNumber, WORD* pApplicationVersion, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetErrorInfo(DWORD ErrorCodeValue, char* pErrorInfo, WORD MaxStrSize); //Advanced Functions HelpFunctions_DllExport BOOL __stdcall VCS_GetDeviceNameSelection(BOOL StartOfSelection, char* pDeviceNameSel, WORD MaxStrSize, BOOL* pEndOfSelection, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetProtocolStackNameSelection(char* DeviceName, BOOL StartOfSelection, char* pProtocolStackNameSel, WORD MaxStrSize, BOOL* pEndOfSelection, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetInterfaceNameSelection(char* DeviceName, char* ProtocolStackName, BOOL StartOfSelection, char* pInterfaceNameSel, WORD MaxStrSize, BOOL* pEndOfSelection, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetPortNameSelection(char* DeviceName, char* ProtocolStackName, char* InterfaceName, BOOL StartOfSelection, char* pPortSel, WORD MaxStrSize, BOOL* pEndOfSelection, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetBaudrateSelection(char* DeviceName, char* ProtocolStackName, char* InterfaceName, char* PortName, BOOL StartOfSelection, DWORD* pBaudrateSel, BOOL* pEndOfSelection, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetKeyHandle(char* DeviceName, char* ProtocolStackName, char* InterfaceName, char* PortName, HANDLE* pKeyHandle, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetDeviceName(HANDLE KeyHandle, char* pDeviceName, WORD MaxStrSize, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetProtocolStackName(HANDLE KeyHandle, char* pProtocolStackName, WORD MaxStrSize, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetInterfaceName(HANDLE KeyHandle, char* pInterfaceName, WORD MaxStrSize, DWORD* pErrorCode); HelpFunctions_DllExport BOOL __stdcall VCS_GetPortName(HANDLE KeyHandle, char* pPortName, WORD MaxStrSize, DWORD* pErrorCode); /************************************************************************************************************************************* * CONFIGURATION FUNCTIONS *************************************************************************************************************************************/ //General Configuration_DllExport BOOL __stdcall VCS_ImportParameter(HANDLE KeyHandle, WORD NodeId, char *pParameterFileName, BOOL ShowDlg, BOOL ShowMsg, DWORD *pErrorCode); Configuration_DllExport BOOL __stdcall VCS_ExportParameter(HANDLE KeyHandle, WORD NodeId, char *pParameterFileName, char *pFirmwareFileName, char *pUserID, char *pComment, BOOL ShowDlg, BOOL ShowMsg, DWORD *pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetObject(HANDLE KeyHandle, WORD NodeId, WORD ObjectIndex, BYTE ObjectSubIndex, void* pData, DWORD NbOfBytesToWrite, DWORD* pNbOfBytesWritten, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetObject(HANDLE KeyHandle, WORD NodeId, WORD ObjectIndex, BYTE ObjectSubIndex, void* pData, DWORD NbOfBytesToRead, DWORD* pNbOfBytesRead, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_Restore(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_Store(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //Advanced Functions //Motor Configuration_DllExport BOOL __stdcall VCS_SetMotorType(HANDLE KeyHandle, WORD NodeId, WORD MotorType, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetDcMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD NominalCurrent, WORD MaxOutputCurrent, WORD ThermalTimeConstant, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetEcMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD NominalCurrent, WORD MaxOutputCurrent, WORD ThermalTimeConstant, BYTE NbOfPolePairs, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetMotorType(HANDLE KeyHandle, WORD NodeId, WORD* pMotorType, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetDcMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD* pNominalCurrent, WORD* pMaxOutputCurrent, WORD* pThermalTimeConstant, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetEcMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD* pNominalCurrent, WORD* pMaxOutputCurrent, WORD* pThermalTimeConstant, BYTE* pNbOfPolePairs, DWORD* pErrorCode); //Sensor Configuration_DllExport BOOL __stdcall VCS_SetSensorType(HANDLE KeyHandle, WORD NodeId, WORD SensorType, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetIncEncoderParameter(HANDLE KeyHandle, WORD NodeId, DWORD EncoderResolution, BOOL InvertedPolarity, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetHallSensorParameter(HANDLE KeyHandle, WORD NodeId, BOOL InvertedPolarity, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetSsiAbsEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD DataRate, WORD NbOfMultiTurnDataBits, WORD NbOfSingleTurnDataBits, BOOL InvertedPolarity, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetSensorType(HANDLE KeyHandle, WORD NodeId, WORD* pSensorType, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetIncEncoderParameter(HANDLE KeyHandle, WORD NodeId, DWORD* pEncoderResolution, BOOL* pInvertedPolarity, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetHallSensorParameter(HANDLE KeyHandle, WORD NodeId, BOOL* pInvertedPolarity, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetSsiAbsEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD* pDataRate, WORD* pNbOfMultiTurnDataBits, WORD* pNbOfSingleTurnDataBits, BOOL* pInvertedPolarity, DWORD* pErrorCode); //Safety Configuration_DllExport BOOL __stdcall VCS_SetMaxFollowingError(HANDLE KeyHandle, WORD NodeId, DWORD MaxFollowingError, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetMaxFollowingError(HANDLE KeyHandle, WORD NodeId, DWORD* pMaxFollowingError, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetMaxProfileVelocity(HANDLE KeyHandle, WORD NodeId, DWORD MaxProfileVelocity, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetMaxProfileVelocity(HANDLE KeyHandle, WORD NodeId, DWORD* pMaxProfileVelocity, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetMaxAcceleration(HANDLE KeyHandle, WORD NodeId, DWORD MaxAcceleration, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetMaxAcceleration(HANDLE KeyHandle, WORD NodeId, DWORD* pMaxAcceleration, DWORD* pErrorCode); //Position Regulator Configuration_DllExport BOOL __stdcall VCS_SetPositionRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD P, WORD I, WORD D, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetPositionRegulatorFeedForward(HANDLE KeyHandle, WORD NodeId, WORD VelocityFeedForward, WORD AccelerationFeedForward, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetPositionRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD* pP, WORD* pI, WORD* pD, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetPositionRegulatorFeedForward(HANDLE KeyHandle, WORD NodeId, WORD* pVelocityFeedForward, WORD* pAccelerationFeedForward, DWORD* pErrorCode); //Velocity Regulator Configuration_DllExport BOOL __stdcall VCS_SetVelocityRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD P, WORD I, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetVelocityRegulatorFeedForward(HANDLE KeyHandle, WORD NodeId, WORD VelocityFeedForward, WORD AccelerationFeedForward, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetVelocityRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD* pP, WORD* pI, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetVelocityRegulatorFeedForward(HANDLE KeyHandle, WORD NodeId, WORD* pVelocityFeedForward, WORD* pAccelerationFeedForward, DWORD* pErrorCode); //Current Regulator Configuration_DllExport BOOL __stdcall VCS_SetCurrentRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD P, WORD I, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetCurrentRegulatorGain(HANDLE KeyHandle, WORD NodeId, WORD* pP, WORD* pI, DWORD* pErrorCode); //Inputs/Outputs Configuration_DllExport BOOL __stdcall VCS_DigitalInputConfiguration(HANDLE KeyHandle, WORD NodeId, WORD DigitalInputNb, WORD Configuration, BOOL Mask, BOOL Polarity, BOOL ExecutionMask, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_DigitalOutputConfiguration(HANDLE KeyHandle, WORD NodeId, WORD DigitalOutputNb, WORD Configuration, BOOL State, BOOL Mask, BOOL Polarity, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_AnalogInputConfiguration(HANDLE KeyHandle, WORD NodeId, WORD AnlogInputNb, WORD Configuration, BOOL ExecutionMask, DWORD* pErrorCode); //Units Configuration_DllExport BOOL __stdcall VCS_SetVelocityUnits(HANDLE KeyHandle, WORD NodeId, BYTE VelDimension, char VelNotation, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetVelocityUnits(HANDLE KeyHandle, WORD NodeId, BYTE* pVelDimension, char* pVelNotation, DWORD* pErrorCode); //Compatibility Functions (do not use) Configuration_DllExport BOOL __stdcall VCS_SetMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD MotorType, WORD ContinuousCurrent, WORD PeakCurrent, BYTE PolePair, WORD ThermalTimeConstant, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_SetEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD Counts, WORD PositionSensorType, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetMotorParameter(HANDLE KeyHandle, WORD NodeId, WORD* pMotorType, WORD* pContinuousCurrent, WORD* pPeakCurrent, BYTE* pPolePair, WORD* pThermalTimeConstant, DWORD* pErrorCode); Configuration_DllExport BOOL __stdcall VCS_GetEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD* pCounts, WORD* pPositionSensorType, DWORD* pErrorCode); /************************************************************************************************************************************* * OPERATION FUNCTIONS *************************************************************************************************************************************/ //OperationMode Status_DllExport BOOL __stdcall VCS_SetOperationMode(HANDLE KeyHandle, WORD NodeId, __int8 OperationMode, DWORD* pErrorCode); Status_DllExport BOOL __stdcall VCS_GetOperationMode(HANDLE KeyHandle, WORD NodeId, __int8* pOperationMode, DWORD* pErrorCode); //StateMachine StateMachine_DllExport BOOL __stdcall VCS_ResetDevice(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_SetState(HANDLE KeyHandle, WORD NodeId, WORD State, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_SetEnableState(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_SetDisableState(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_SetQuickStopState(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_ClearFault(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_GetState(HANDLE KeyHandle, WORD NodeId, WORD* pState, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_GetEnableState(HANDLE KeyHandle, WORD NodeId, BOOL* pIsEnabled, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_GetDisableState(HANDLE KeyHandle, WORD NodeId, BOOL* pIsDisabled, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_GetQuickStopState(HANDLE KeyHandle, WORD NodeId, BOOL* pIsQuickStopped, DWORD* pErrorCode); StateMachine_DllExport BOOL __stdcall VCS_GetFaultState(HANDLE KeyHandle, WORD NodeId, BOOL* pIsInFault, DWORD* pErrorCode); //ErrorHandling ErrorHandling_DllExport BOOL __stdcall VCS_GetNbOfDeviceError(HANDLE KeyHandle, WORD NodeId, BYTE *pNbDeviceError, DWORD *pErrorCode); ErrorHandling_DllExport BOOL __stdcall VCS_GetDeviceErrorCode(HANDLE KeyHandle, WORD NodeId, BYTE DeviceErrorNumber, DWORD *pDeviceErrorCode, DWORD *pErrorCode); //Motion Info MotionInfo_DllExport BOOL __stdcall VCS_GetMovementState(HANDLE KeyHandle, WORD NodeId, BOOL* pTargetReached, DWORD* pErrorCode); MotionInfo_DllExport BOOL __stdcall VCS_GetPositionIs(HANDLE KeyHandle, WORD NodeId, long* pPositionIs, DWORD* pErrorCode); MotionInfo_DllExport BOOL __stdcall VCS_GetVelocityIs(HANDLE KeyHandle, WORD NodeId, long* pVelocityIs, DWORD* pErrorCode); MotionInfo_DllExport BOOL __stdcall VCS_GetVelocityIsAveraged(HANDLE KeyHandle, WORD NodeId, long* pVelocityIsAveraged, DWORD* pErrorCode); MotionInfo_DllExport BOOL __stdcall VCS_GetCurrentIs(HANDLE KeyHandle, WORD NodeId, short* pCurrentIs, DWORD* pErrorCode); MotionInfo_DllExport BOOL __stdcall VCS_GetCurrentIsAveraged(HANDLE KeyHandle, WORD NodeId, short* pCurrentIsAveraged, DWORD* pErrorCode); MotionInfo_DllExport BOOL __stdcall VCS_WaitForTargetReached(HANDLE KeyHandle, WORD NodeId, DWORD Timeout, DWORD* pErrorCode); //Profile Position Mode ProfilePositionMode_DllExport BOOL __stdcall VCS_ActivateProfilePositionMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); ProfilePositionMode_DllExport BOOL __stdcall VCS_SetPositionProfile(HANDLE KeyHandle, WORD NodeId, DWORD ProfileVelocity, DWORD ProfileAcceleration, DWORD ProfileDeceleration, DWORD* pErrorCode); ProfilePositionMode_DllExport BOOL __stdcall VCS_GetPositionProfile(HANDLE KeyHandle, WORD NodeId, DWORD* pProfileVelocity, DWORD* pProfileAcceleration, DWORD* pProfileDeceleration, DWORD* pErrorCode); ProfilePositionMode_DllExport BOOL __stdcall VCS_MoveToPosition(HANDLE KeyHandle, WORD NodeId, long TargetPosition, BOOL Absolute, BOOL Immediately, DWORD* pErrorCode); ProfilePositionMode_DllExport BOOL __stdcall VCS_GetTargetPosition(HANDLE KeyHandle, WORD NodeId, long* pTargetPosition, DWORD* pErrorCode); ProfilePositionMode_DllExport BOOL __stdcall VCS_HaltPositionMovement(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //Advanced Functions ProfilePositionMode_DllExport BOOL __stdcall VCS_EnablePositionWindow(HANDLE KeyHandle, WORD NodeId, DWORD PositionWindow, WORD PositionWindowTime, DWORD* pErrorCode); ProfilePositionMode_DllExport BOOL __stdcall VCS_DisablePositionWindow(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //Profile Velocity Mode ProfileVelocityMode_DllExport BOOL __stdcall VCS_ActivateProfileVelocityMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); ProfileVelocityMode_DllExport BOOL __stdcall VCS_SetVelocityProfile(HANDLE KeyHandle, WORD NodeId, DWORD ProfileAcceleration, DWORD ProfileDeceleration, DWORD* pErrorCode); ProfileVelocityMode_DllExport BOOL __stdcall VCS_GetVelocityProfile(HANDLE KeyHandle, WORD NodeId, DWORD* pProfileAcceleration, DWORD* pProfileDeceleration, DWORD* pErrorCode); ProfileVelocityMode_DllExport BOOL __stdcall VCS_MoveWithVelocity(HANDLE KeyHandle, WORD NodeId, long TargetVelocity, DWORD* pErrorCode); ProfileVelocityMode_DllExport BOOL __stdcall VCS_GetTargetVelocity(HANDLE KeyHandle, WORD NodeId, long* pTargetVelocity, DWORD* pErrorCode); ProfileVelocityMode_DllExport BOOL __stdcall VCS_HaltVelocityMovement(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //Advanced Functions ProfileVelocityMode_DllExport BOOL __stdcall VCS_EnableVelocityWindow(HANDLE KeyHandle, WORD NodeId, DWORD VelocityWindow, WORD VelocityWindowTime, DWORD* pErrorCode); ProfileVelocityMode_DllExport BOOL __stdcall VCS_DisableVelocityWindow(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //Homing Mode HomingMode_DllExport BOOL __stdcall VCS_ActivateHomingMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); HomingMode_DllExport BOOL __stdcall VCS_SetHomingParameter(HANDLE KeyHandle, WORD NodeId, DWORD HomingAcceleration, DWORD SpeedSwitch, DWORD SpeedIndex, long HomeOffset, WORD CurrentTreshold, long HomePosition, DWORD* pErrorCode); HomingMode_DllExport BOOL __stdcall VCS_GetHomingParameter(HANDLE KeyHandle, WORD NodeId, DWORD* pHomingAcceleration, DWORD* pSpeedSwitch, DWORD* pSpeedIndex, long* pHomeOffset, WORD* pCurrentTreshold, long* pHomePosition, DWORD* pErrorCode); HomingMode_DllExport BOOL __stdcall VCS_FindHome(HANDLE KeyHandle, WORD NodeId, __int8 HomingMethod, DWORD* pErrorCode); HomingMode_DllExport BOOL __stdcall VCS_StopHoming(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); HomingMode_DllExport BOOL __stdcall VCS_DefinePosition(HANDLE KeyHandle, WORD NodeId, long HomePosition, DWORD* pErrorCode); HomingMode_DllExport BOOL __stdcall VCS_WaitForHomingAttained(HANDLE KeyHandle, WORD NodeId, DWORD Timeout, DWORD* pErrorCode); HomingMode_DllExport BOOL __stdcall VCS_GetHomingState(HANDLE KeyHandle, WORD NodeId, BOOL* pHomingAttained, BOOL* pHomingError, DWORD* pErrorCode); //Interpolated Position Mode InterpolatedPositionMode_DllExport BOOL __stdcall VCS_ActivateInterpolatedPositionMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); InterpolatedPositionMode_DllExport BOOL __stdcall VCS_SetIpmBufferParameter(HANDLE KeyHandle, WORD NodeId, WORD UnderflowWarningLimit, WORD OverflowWarningLimit, DWORD* pErrorCode); InterpolatedPositionMode_DllExport BOOL __stdcall VCS_GetIpmBufferParameter(HANDLE KeyHandle, WORD NodeId, WORD* pUnderflowWarningLimit, WORD* pOverflowWarningLimit, DWORD* pMaxBufferSize, DWORD* pErrorCode); InterpolatedPositionMode_DllExport BOOL __stdcall VCS_ClearIpmBuffer(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); InterpolatedPositionMode_DllExport BOOL __stdcall VCS_GetFreeIpmBufferSize(HANDLE KeyHandle, WORD NodeId, DWORD* pBufferSize, DWORD* pErrorCode); InterpolatedPositionMode_DllExport BOOL __stdcall VCS_AddPvtValueToIpmBuffer(HANDLE KeyHandle, WORD NodeId, long Position, long Velocity, BYTE Time, DWORD* pErrorCode); InterpolatedPositionMode_DllExport BOOL __stdcall VCS_StartIpmTrajectory(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); InterpolatedPositionMode_DllExport BOOL __stdcall VCS_StopIpmTrajectory(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); InterpolatedPositionMode_DllExport BOOL __stdcall VCS_GetIpmStatus(HANDLE KeyHandle, WORD NodeId, BOOL* pTrajectoryRunning, BOOL* pIsUnderflowWarning, BOOL* pIsOverflowWarning, BOOL* pIsVelocityWarning, BOOL* pIsAccelerationWarning, BOOL* pIsUnderflowError, BOOL* pIsOverflowError, BOOL* pIsVelocityError, BOOL* pIsAccelerationError, DWORD* pErrorCode); //Position Mode PositionMode_DllExport BOOL __stdcall VCS_ActivatePositionMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); PositionMode_DllExport BOOL __stdcall VCS_SetPositionMust(HANDLE KeyHandle, WORD NodeId, long PositionMust, DWORD* pErrorCode); PositionMode_DllExport BOOL __stdcall VCS_GetPositionMust(HANDLE KeyHandle, WORD NodeId, long* pPositionMust, DWORD* pErrorCode); //Advanced Functions PositionMode_DllExport BOOL __stdcall VCS_ActivateAnalogPositionSetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, float Scaling, long Offset, DWORD* pErrorCode); PositionMode_DllExport BOOL __stdcall VCS_DeactivateAnalogPositionSetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, DWORD* pErrorCode); PositionMode_DllExport BOOL __stdcall VCS_EnableAnalogPositionSetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); PositionMode_DllExport BOOL __stdcall VCS_DisableAnalogPositionSetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //Velocity Mode VelocityMode_DllExport BOOL __stdcall VCS_ActivateVelocityMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); VelocityMode_DllExport BOOL __stdcall VCS_SetVelocityMust(HANDLE KeyHandle, WORD NodeId, long VelocityMust, DWORD* pErrorCode); VelocityMode_DllExport BOOL __stdcall VCS_GetVelocityMust(HANDLE KeyHandle, WORD NodeId, long* pVelocityMust, DWORD* pErrorCode); //Advanced Functions VelocityMode_DllExport BOOL __stdcall VCS_ActivateAnalogVelocitySetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, float Scaling, long Offset, DWORD* pErrorCode); VelocityMode_DllExport BOOL __stdcall VCS_DeactivateAnalogVelocitySetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, DWORD* pErrorCode); VelocityMode_DllExport BOOL __stdcall VCS_EnableAnalogVelocitySetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); VelocityMode_DllExport BOOL __stdcall VCS_DisableAnalogVelocitySetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //Current Mode CurrentMode_DllExport BOOL __stdcall VCS_ActivateCurrentMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); CurrentMode_DllExport BOOL __stdcall VCS_SetCurrentMust(HANDLE KeyHandle, WORD NodeId, short CurrentMust, DWORD* pErrorCode); CurrentMode_DllExport BOOL __stdcall VCS_GetCurrentMust(HANDLE KeyHandle, WORD NodeId, short* pCurrentMust, DWORD* pErrorCode); //Advanced Functions CurrentMode_DllExport BOOL __stdcall VCS_ActivateAnalogCurrentSetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, float Scaling, short Offset, DWORD* pErrorCode); CurrentMode_DllExport BOOL __stdcall VCS_DeactivateAnalogCurrentSetpoint(HANDLE KeyHandle, WORD NodeId, WORD AnalogInputNumber, DWORD* pErrorCode); CurrentMode_DllExport BOOL __stdcall VCS_EnableAnalogCurrentSetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); CurrentMode_DllExport BOOL __stdcall VCS_DisableAnalogCurrentSetpoint(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //MasterEncoder Mode MasterEncoderMode_DllExport BOOL __stdcall VCS_ActivateMasterEncoderMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); MasterEncoderMode_DllExport BOOL __stdcall VCS_SetMasterEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD ScalingNumerator, WORD ScalingDenominator, BYTE Polarity, DWORD MaxVelocity, DWORD MaxAcceleration, DWORD* pErrorCode); MasterEncoderMode_DllExport BOOL __stdcall VCS_GetMasterEncoderParameter(HANDLE KeyHandle, WORD NodeId, WORD* pScalingNumerator, WORD* pScalingDenominator, BYTE* pPolarity, DWORD* pMaxVelocity, DWORD* pMaxAcceleration, DWORD* pErrorCode); //StepDirection Mode StepDirectionMode_DllExport BOOL __stdcall VCS_ActivateStepDirectionMode(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); StepDirectionMode_DllExport BOOL __stdcall VCS_SetStepDirectionParameter(HANDLE KeyHandle, WORD NodeId, WORD ScalingNumerator, WORD ScalingDenominator, BYTE Polarity, DWORD MaxVelocity, DWORD MaxAcceleration, DWORD* pErrorCode); StepDirectionMode_DllExport BOOL __stdcall VCS_GetStepDirectionParameter(HANDLE KeyHandle, WORD NodeId, WORD* pScalingNumerator, WORD* pScalingDenominator, BYTE* pPolarity, DWORD* pMaxVelocity, DWORD* pMaxAcceleration, DWORD* pErrorCode); //Inputs Outputs //General InputsOutputs_DllExport BOOL __stdcall VCS_GetAllDigitalInputs(HANDLE KeyHandle, WORD NodeId, WORD* pInputs, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_GetAllDigitalOutputs(HANDLE KeyHandle, WORD NodeId, WORD* pOutputs, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_SetAllDigitalOutputs(HANDLE KeyHandle, WORD NodeId, WORD Outputs, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_GetAnalogInput(HANDLE KeyHandle, WORD NodeId, WORD InputNumber, WORD* pAnalogValue, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_SetAnalogOutput(HANDLE KeyHandle, WORD NodeId, WORD OutputNumber, WORD AnalogValue, DWORD* pErrorCode); //Position Compare InputsOutputs_DllExport BOOL __stdcall VCS_SetPositionCompareParameter(HANDLE KeyHandle, WORD NodeId, BYTE OperationalMode, BYTE IntervalMode, BYTE DirectionDependency, WORD IntervalWidth, WORD IntervalRepetitions, WORD PulseWidth, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_GetPositionCompareParameter(HANDLE KeyHandle, WORD NodeId, BYTE* pOperationalMode, BYTE* pIntervalMode, BYTE* pDirectionDependency, WORD* pIntervalWidth, WORD* pIntervalRepetitions, WORD* pPulseWidth, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_ActivatePositionCompare(HANDLE KeyHandle, WORD NodeId, WORD DigitalOutputNumber, BOOL Polarity, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_DeactivatePositionCompare(HANDLE KeyHandle, WORD NodeId, WORD DigitalOutputNumber, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_EnablePositionCompare(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_DisablePositionCompare(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_SetPositionCompareReferencePosition(HANDLE KeyHandle, WORD NodeId, long ReferencePosition, DWORD* pErrorCode); //Position Marker InputsOutputs_DllExport BOOL __stdcall VCS_SetPositionMarkerParameter(HANDLE KeyHandle, WORD NodeId, BYTE PositionMarkerEdgeType, BYTE PositionMarkerMode, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_GetPositionMarkerParameter(HANDLE KeyHandle, WORD NodeId, BYTE* pPositionMarkerEdgeType, BYTE* pPositionMarkerMode, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_ActivatePositionMarker(HANDLE KeyHandle, WORD NodeId, WORD DigitalInputNumber, BOOL Polarity, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_DeactivatePositionMarker(HANDLE KeyHandle, WORD NodeId, WORD DigitalInputNumber, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_ReadPositionMarkerCounter(HANDLE KeyHandle, WORD NodeId, WORD* pCount, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_ReadPositionMarkerCapturedPosition(HANDLE KeyHandle, WORD NodeId, WORD CounterIndex, long* pCapturedPosition, DWORD* pErrorCode); InputsOutputs_DllExport BOOL __stdcall VCS_ResetPositionMarkerCounter(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); /************************************************************************************************************************************* * DATA RECORDING FUNCTIONS *************************************************************************************************************************************/ //DataRecorder Setup DataRecording_DllExport BOOL __stdcall VCS_SetRecorderParameter(HANDLE KeyHandle, WORD NodeId, WORD SamplingPeriod, WORD NbOfPrecedingSamples, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_GetRecorderParameter(HANDLE KeyHandle, WORD NodeId, WORD* pSamplingPeriod, WORD* pNbOfPrecedingSamples, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_EnableTrigger(HANDLE KeyHandle, WORD NodeId, BYTE TriggerType, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_DisableAllTriggers(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_ActivateChannel(HANDLE KeyHandle, WORD NodeId, BYTE ChannelNumber, WORD ObjectIndex, BYTE ObjectSubIndex, BYTE ObjectSize, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_DeactivateAllChannels(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); //DataRecorder Status DataRecording_DllExport BOOL __stdcall VCS_StartRecorder(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_StopRecorder(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_ForceTrigger(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_IsRecorderRunning(HANDLE KeyHandle, WORD NodeId, BOOL* pRunning, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_IsRecorderTriggered(HANDLE KeyHandle, WORD NodeId, BOOL* pTriggered, DWORD* pErrorCode); //DataRecorder Data DataRecording_DllExport BOOL __stdcall VCS_ReadChannelVectorSize(HANDLE KeyHandle, WORD NodeId, DWORD* pVectorSize, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_ReadChannelDataVector(HANDLE KeyHandle, WORD NodeId, BYTE ChannelNumber, BYTE* pDataVector, DWORD VectorSize, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_ShowChannelDataDlg(HANDLE KeyHandle, WORD NodeId, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_ExportChannelDataToFile(HANDLE KeyHandle, WORD NodeId, char* FileName, DWORD* pErrorCode); //Advanced Functions DataRecording_DllExport BOOL __stdcall VCS_ReadDataBuffer(HANDLE KeyHandle, WORD NodeId, BYTE* pDataBuffer, DWORD BufferSizeToRead, DWORD* pBufferSizeRead, WORD* pVectorStartOffset, WORD* pMaxNbOfSamples, WORD* pNbOfRecordedSamples, DWORD* pErrorCode); DataRecording_DllExport BOOL __stdcall VCS_ExtractChannelDataVector(HANDLE KeyHandle, WORD NodeId, BYTE ChannelNumber, BYTE* pDataBuffer, DWORD BufferSize, BYTE* pDataVector, DWORD VectorSize, WORD VectorStartOffset, WORD MaxNbOfSamples, WORD NbOfRecordedSamples, DWORD* pErrorCode); /************************************************************************************************************************************* * LOW LAYER FUNCTIONS *************************************************************************************************************************************/ //CanLayer Functions CanLayer_DllExport BOOL __stdcall VCS_SendCANFrame(HANDLE KeyHandle, WORD CobID, WORD Length, void* pData, DWORD* pErrorCode); CanLayer_DllExport BOOL __stdcall VCS_ReadCANFrame(HANDLE KeyHandle, WORD CobID, WORD Length, void* pData, DWORD Timeout, DWORD* pErrorCode); CanLayer_DllExport BOOL __stdcall VCS_RequestCANFrame(HANDLE KeyHandle, WORD CobID, WORD Length, void* pData, DWORD* pErrorCode); CanLayer_DllExport BOOL __stdcall VCS_SendNMTService(HANDLE KeyHandle, WORD NodeId, WORD CommandSpecifier, DWORD* pErrorCode); /************************************************************************************************************************************* * TYPE DEFINITIONS *************************************************************************************************************************************/ //Communication //Dialog Mode const int DM_PROGRESS_DLG = 0; const int DM_PROGRESS_AND_CONFIRM_DLG = 1; const int DM_CONFIRM_DLG = 2; const int DM_NO_DLG = 3; //Configuration //MotorType const WORD MT_DC_MOTOR = 1; const WORD MT_EC_SINUS_COMMUTATED_MOTOR = 10; const WORD MT_EC_BLOCK_COMMUTATED_MOTOR = 11; //SensorType const WORD ST_UNKNOWN = 0; const WORD ST_INC_ENCODER_3CHANNEL = 1; const WORD ST_INC_ENCODER_2CHANNEL = 2; const WORD ST_HALL_SENSORS = 3; const WORD ST_SSI_ABS_ENCODER_BINARY = 4; const WORD ST_SSI_ABS_ENCODER_GREY = 5; //In- and outputs //Digital input configuration const WORD DIC_NEGATIVE_LIMIT_SWITCH = 0; const WORD DIC_POSITIVE_LIMIT_SWITCH = 1; const WORD DIC_HOME_SWITCH = 2; const WORD DIC_POSITION_MARKER = 3; const WORD DIC_DRIVE_ENABLE = 4; const WORD DIC_QUICK_STOP = 5; const WORD DIC_GENERAL_PURPOSE_J = 6; const WORD DIC_GENERAL_PURPOSE_I = 7; const WORD DIC_GENERAL_PURPOSE_H = 8; const WORD DIC_GENERAL_PURPOSE_G = 9; const WORD DIC_GENERAL_PURPOSE_F = 10; const WORD DIC_GENERAL_PURPOSE_E = 11; const WORD DIC_GENERAL_PURPOSE_D = 12; const WORD DIC_GENERAL_PURPOSE_C = 13; const WORD DIC_GENERAL_PURPOSE_B = 14; const WORD DIC_GENERAL_PURPOSE_A = 15; //Digital output configuration const WORD DOC_READY_FAULT = 0; const WORD DOC_POSITION_COMPARE = 1; const WORD DOC_GENERAL_PURPOSE_H = 8; const WORD DOC_GENERAL_PURPOSE_G = 9; const WORD DOC_GENERAL_PURPOSE_F = 10; const WORD DOC_GENERAL_PURPOSE_E = 11; const WORD DOC_GENERAL_PURPOSE_D = 12; const WORD DOC_GENERAL_PURPOSE_C = 13; const WORD DOC_GENERAL_PURPOSE_B = 14; const WORD DOC_GENERAL_PURPOSE_A = 15; //Analog input configuration const WORD AIC_ANALOG_CURRENT_SETPOINT = 0; const WORD AIC_ANALOG_VELOCITY_SETPOINT = 1; const WORD AIC_ANALOG_POSITION_SETPOINT = 2; //Units //VelocityDimension const BYTE VD_RPM = 0xA4; //VelocityNotation const char VN_STANDARD = 0; const char VN_DECI = -1; const char VN_CENTI = -2; const char VN_MILLI = -3; //Operational mode const __int8 OMD_PROFILE_POSITION_MODE = 1; const __int8 OMD_PROFILE_VELOCITY_MODE = 3; const __int8 OMD_HOMING_MODE = 6; const __int8 OMD_INTERPOLATED_POSITION_MODE = 7; const __int8 OMD_POSITION_MODE = -1; const __int8 OMD_VELOCITY_MODE = -2; const __int8 OMD_CURRENT_MODE = -3; const __int8 OMD_MASTER_ENCODER_MODE = -5; const __int8 OMD_STEP_DIRECTION_MODE = -6; //States const WORD ST_DISABLED = 0; const WORD ST_ENABLED = 1; const WORD ST_QUICKSTOP = 2; const WORD ST_FAULT = 3; //Homing mode //Homing method const __int8 HM_ACTUAL_POSITION = 35; const __int8 HM_NEGATIVE_LIMIT_SWITCH = 17; const __int8 HM_NEGATIVE_LIMIT_SWITCH_AND_INDEX = 1; const __int8 HM_POSITIVE_LIMIT_SWITCH = 18; const __int8 HM_POSITIVE_LIMIT_SWITCH_AND_INDEX = 2; const __int8 HM_HOME_SWITCH_POSITIVE_SPEED = 23; const __int8 HM_HOME_SWITCH_POSITIVE_SPEED_AND_INDEX = 7; const __int8 HM_HOME_SWITCH_NEGATIVE_SPEED = 27; const __int8 HM_HOME_SWITCH_NEGATIVE_SPEED_AND_INDEX = 11; const __int8 HM_CURRENT_THRESHOLD_POSITIVE_SPEED = -3; const __int8 HM_CURRENT_THRESHOLD_POSITIVE_SPEED_AND_INDEX = -1; const __int8 HM_CURRENT_THRESHOLD_NEGATIVE_SPEED = -4; const __int8 HM_CURRENT_THRESHOLD_NEGATIVE_SPEED_AND_INDEX = -2; const __int8 HM_INDEX_POSITIVE_SPEED = 34; const __int8 HM_INDEX_NEGATIVE_SPEED = 33; //Input Output PositionMarker //PositionMarkerEdgeType const BYTE PET_BOTH_EDGES = 0; const BYTE PET_RISING_EDGE = 1; const BYTE PET_FALLING_EDGE = 2; //PositionMarkerMode const BYTE PM_CONTINUOUS = 0; const BYTE PM_SINGLE = 1; const BYTE PM_MULTIPLE = 2; //Input Output PositionCompare //PositionCompareOperationalMode const BYTE PCO_SINGLE_POSITION_MODE = 0; const BYTE PCO_POSITION_SEQUENCE_MODE = 1; //PositionCompareIntervalMode const BYTE PCI_NEGATIVE_DIR_TO_REFPOS = 0; const BYTE PCI_POSITIVE_DIR_TO_REFPOS = 1; const BYTE PCI_BOTH_DIR_TO_REFPOS = 2; //PositionCompareDirectionDependency const BYTE PCD_MOTOR_DIRECTION_NEGATIVE = 0; const BYTE PCD_MOTOR_DIRECTION_POSITIVE = 1; const BYTE PCD_MOTOR_DIRECTION_BOTH = 2; //Data recorder //Trigger type const BYTE DR_MOVEMENT_START_TRIGGER = 1; const BYTE DR_ERROR_TRIGGER = 2; const BYTE DR_DIGITAL_INPUT_TRIGGER = 4; const BYTE DR_MOVEMENT_END_TRIGGER = 8; //CanLayer Functions const WORD NCS_START_REMOTE_NODE = 1; const WORD NCS_STOP_REMOTE_NODE = 2; const WORD NCS_ENTER_PRE_OPERATIONAL = 128; const WORD NCS_RESET_NODE = 129; const WORD NCS_RESET_COMMUNICATION = 130; #endif //EposCommandLibraryDefinitions
47,620
C
87.187037
357
0.669845
adegirmenci/HBL-ICEbot/epiphan/frmgrab/include/frmgrab.h
/**************************************************************************** * * $Id: frmgrab.h 21236 2013-03-16 12:32:41Z monich $ * * Copyright (C) 2008-2013 Epiphan Systems Inc. All rights reserved. * * Header file for the Epiphan frame grabber library * ****************************************************************************/ #ifndef _EPIPHAN_FRMGRAB_H_ #define _EPIPHAN_FRMGRAB_H_ 1 #include "v2u_defs.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ typedef struct _FrmGrabber FrmGrabber; struct sockaddr; struct sockaddr_in; /** * Initialize/deinitialize frmgrab library. Both functions may be invoked * several times, but there must be FrmGrab_Deinit call per each FrmGrab_Init. */ void FrmGrab_Init(void); void FrmGrab_Deinit(void); void FrmGrabNet_Init(void); void FrmGrabNet_Deinit(void); /** * Functions specific to local frame grabbers. */ FrmGrabber* FrmGrabLocal_Open(void); FrmGrabber* FrmGrabLocal_OpenSN(const char* sn); FrmGrabber* FrmGrabLocal_OpenIndex(int i); int FrmGrabLocal_Count(void); int FrmGrabLocal_OpenAll(FrmGrabber* grabbers[], int maxcount); /** * VGA2Ethernet authentication callback. Username buffer pointer is NULL * if username is not required. Maximum sizes of username and password * are defined below. Non-ASCII username and passwords must be UTF-8 * encoded. Note that FG_USERNAME_SIZE and FG_PASSWORD_SIZE define * maximum number of bytes (including NULL terminator), not characters. * In case of UTF-8 encoding it's not the same thing. */ typedef V2U_BOOL (*FrmGrabAuthProc)(char* user, char* pass, void* param); #define FG_USERNAME_SIZE 32 #define FG_PASSWORD_SIZE 64 /** * Connection status returned by FrmGrabNet_OpenAddress2 */ typedef enum _FrmGrabConnectStatus { FrmGrabConnectOK, /* Connection OK, authentication not needed */ FrmGrabConnectAuthOK, /* Connection OK, authentication successful */ FrmGrabConnectError, /* Connection failed */ FrmGrabConnectAuthFail, /* Authentication failure */ FrmGrabConnectAuthCancel /* Authentication was cancelled */ } FrmGrabConnectStatus; /** * VGA2Ethernet specific functions. IP address is in the host byte order. */ FrmGrabber* FrmGrabNet_Open(void); FrmGrabber* FrmGrabNet_OpenSN(const char* sn); FrmGrabber* FrmGrabNet_OpenLocation(const char* location); FrmGrabber* FrmGrabNet_OpenAddress(V2U_UINT32 ipaddr, V2U_UINT16 port); FrmGrabber* FrmGrabNet_OpenAddress2(V2U_UINT32 ipaddr, V2U_UINT16 port, FrmGrabAuthProc authproc, void* param, FrmGrabConnectStatus* status); /** * IPv6 friendly version of FrmGrabNet_OpenAddress. * * Available since version 3.27.7.1 */ FrmGrabber* FrmGrabNet_OpenAddress3(const struct sockaddr* sa, V2U_UINT32 len); /** * FrmGrabNet_Find finds network grabbers on the subnet. Callback is * invoked on each grabber found. Callback function is responsible for * calling FrmGrab_Close() on each FrmGrabber that was passed in. Search * terminates when either timeout expires or callback returns V2U_FALSE. * FrmGrabNet_Find returns number of times is has invoked the callback. * Timeout is measured in milliseconds. Zero timeout means that the library * should use the default timeout. Negative timeout means to search forever. * * Available since version 3.27.7.1 */ typedef V2U_BOOL (*FrmGrabFindProc)(FrmGrabber* fg, void* param); int FrmGrabNet_Find(FrmGrabFindProc proc, void* param, int timeout); /** * VGA2Ethernet authentication. These functions fail (but don't crash) on * local frame grabbers. */ V2U_BOOL FrmGrabNet_IsProtected(FrmGrabber* fg); FrmGrabConnectStatus FrmGrabNet_Auth(FrmGrabber* fg, FrmGrabAuthProc authproc, void* param); /** * Simple non-interactive username/password authentication. VGA2Ethernet * grabbers normally don't use usernames for viewer authentication, you * should pass NULL as the second parameter. * * Available since version 3.26.0.15 */ FrmGrabConnectStatus FrmGrabNet_Auth2(FrmGrabber* fg, const char* user, const char* pass); /** * Network statistics for a network frame grabber. These functions return * V2U_FALSE if invoked on a local frame grabber. */ typedef struct _FrmGrabNetStat { V2U_UINT64 bytesSent; /* Total bytes sent over the network */ V2U_UINT64 bytesReceived; /* Total bytes received from the network */ } FrmGrabNetStat; V2U_BOOL FrmGrabNet_GetStat(FrmGrabber* fg, FrmGrabNetStat* netstat); V2U_BOOL FrmGrabNet_GetRemoteAddr(FrmGrabber* fg, struct sockaddr_in* addr); /** * IPv6 friendly version of FrmGrabNet_GetRemoteAddr. * * Available since version 3.27.7.1 */ V2U_UINT32 FrmGrabNet_GetRemoteAddr2(FrmGrabber* fg, struct sockaddr* addr, V2U_UINT32 len); /* Other network-specific functions */ V2U_BOOL FrmGrabNet_IsAlive(FrmGrabber* fg); V2U_BOOL FrmGrabNet_SetAutoReconnect(FrmGrabber* fg, V2U_BOOL enable); /** Generic functions that work with all Frame Grabbers */ /** * Open frame grabber. The URL-like location parameter can be one of the * following: * * local:[SERIAL] * * Opens a local frame grabber. Optionally, the serial number can be * specified. * * net:[ADDRESS[:PORT]] * * Opens a network frame grabber at the specified address/port. If no * address is specified, opens a random network frame grabber. * * sn:SERIAL * * Opens a local or network frame grabber with the specified serial number. * Checks the local frame grabbers first then goes to the network. * * id:INDEX * * Opens a local frame grabber with the specified index. */ FrmGrabber* FrmGrab_Open(const char* location); /** * Duplicates handle to the frame grabber. Returns a new independent * FrmGrabber instance pointing to the same piece of hardware. */ FrmGrabber* FrmGrab_Dup(FrmGrabber* fg); /** * Checks whether two FrmGrabber instances point to the same physical grabber. */ V2U_BOOL FrmGrab_Equal(FrmGrabber* fg1, FrmGrabber* fg2); /** * Returns a hash code value for this FrmGrabber. * If two grabbers are equal according to FrmGrab_Equal() function (i.e. * they point to the same physical grabber), then calling FrmGrab_Hash() * function on each of the two grabbers is guaranteed to produce the same * integer result. Note that opposite is not true - two unequal grabbers * may have the same hash, although it's a fairly rare case. */ V2U_UINT32 FrmGrab_Hash(FrmGrabber* fg); /** * Returns frame grabber's serial number. */ const char* FrmGrab_GetSN(FrmGrabber* fg); /** * Grabber's id uniquely identifies the grabber. For those boards that have * one on-board grabber it's the same as the board's serial number. For those * boards that have more than one grabber (e.g. DVI2PCIe) it's different * for each grabber and looks like SSSSSSSS.X where SSSSSSSS is the board's * serial number and X is a string identifying the particular grabber. */ const char* FrmGrab_GetId(FrmGrabber* fg); /** * Returns the unique product id. Includes product type bits OR'ed with * type-specific product id. */ int FrmGrab_GetProductId(FrmGrabber* fg); #define PRODUCT_ID_MASK 0x0000ffff #define PRODUCT_TYPE_MASK 0x00ff0000 #define PRODUCT_TYPE_USB 0x00010000 /* Local USB grabber */ #define PRODUCT_TYPE_NET 0x00020000 /* Network grabber */ #define PRODUCT_TYPE_NETAPP 0x00030000 /* Network appliance, not a grabber */ #define PRODUCT_TYPE_FILE 0x00040000 /* Reserved */ #define PRODUCT_TYPE_PCI 0x00050000 /* Local PCI grabber */ #define PRODUCT_TYPE_VPFE 0x00060000 /* TI davinci video input bus */ #define FrmGrab_IsNetGrabberId(id) \ (((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_NET) #define FrmGrab_IsUsbGrabberId(id) \ (((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_USB) #define FrmGrab_IsPciGrabberId(id) \ (((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_PCI) #define FrmGrab_IsLocalGrabberId(id) \ (FrmGrab_IsUsbGrabberId(id) || \ FrmGrab_IsPciGrabberId(id) || \ ((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_FILE || \ ((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_VPFE) #define FrmGrab_IsNetworkDeviceId(id) \ (((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_NET || \ ((id) & PRODUCT_TYPE_MASK) == PRODUCT_TYPE_NETAPP) #define FrmGrab_IsNetGrabber(fg) \ FrmGrab_IsNetGrabberId(FrmGrab_GetProductId(fg)) #define FrmGrab_IsUsbGrabber(fg) \ FrmGrab_IsUsbGrabberId(FrmGrab_GetProductId(fg)) #define FrmGrab_IsPciGrabber(fg) \ FrmGrab_IsPciGrabberId(FrmGrab_GetProductId(fg)) #define FrmGrab_IsLocalGrabber(fg) \ FrmGrab_IsLocalGrabberId(FrmGrab_GetProductId(fg)) #define FrmGrab_IsNetworkDevice(fg) \ FrmGrab_IsNetworkDeviceId(FrmGrab_GetProductId(fg)) /** * Returns the product description ("VGA2USB", "VGA2Ethernet", etc) */ const char* FrmGrab_GetProductName(FrmGrabber* fg); /** * Returns a string that describes the location of the grabber ("USB, * "192.168.0.122", etc) */ const char* FrmGrab_GetLocation(FrmGrabber* fg); /** * Returns device capabilities (V2U_CAPS_* flags defined in v2u_defs.h). * Returns zero if an error occurs. */ V2U_UINT32 FrmGrab_GetCaps(FrmGrabber* fg); /** * Returns the last known video mode, detecting is if necessary. * Unlike FrmGrab_DetectVideoMode, this function doesn't force the * video mode detection, but most of the time it's accurate enough. * Note that video mode detection is a relatively expensive operation. */ void FrmGrab_GetVideoMode(FrmGrabber* fg, V2U_VideoMode* vm); /** * Detects current video mode. If no signal is detected, the output * V2U_VideoMode structure is zeroed. */ V2U_BOOL FrmGrab_DetectVideoMode(FrmGrabber* fg, V2U_VideoMode* vm); /** * Queries current VGA capture parameters. */ V2U_BOOL FrmGrab_GetGrabParams(FrmGrabber* fg, V2U_GrabParameters* gp); /** * Queries current VGA capture parameters and adjustment ranges in one shot. * More efficient for network grabbers. FrmGrab_GetGrabParams2(fg,gp,NULL) * is equivalent to FrmGrab_GetGrabParams(fg,gp) */ V2U_BOOL FrmGrab_GetGrabParams2(FrmGrabber* fg, V2U_GrabParameters* gp, V2UAdjRange* range); /** * Sets VGA capture parameters. */ V2U_BOOL FrmGrab_SetGrabParams(FrmGrabber* fg, const V2U_GrabParameters* gp); /** * Queries the device property. */ V2U_BOOL FrmGrab_GetProperty(FrmGrabber* fg, V2U_Property* prop); /** * Sets the device property. */ V2U_BOOL FrmGrab_SetProperty(FrmGrabber* fg, const V2U_Property* prop); /** * VGA mode table can be queried or modified with a bunch of GetProperty * or SetProperty calls, but getting and settinng the entire VGA mode table * with one call is more efficient, especially for network frame grabbers. * Number of custom modes doesn't exceed V2U_CUSTOM_VIDEOMODE_COUNT. The * whole FrmGrabVgaModes structure returned by FrmGrab_GetVGAModes is * allocated as a single memory block. The caller is responsible for * deallocating it with with a single FrmGrab_Free call. */ typedef struct _FrmGrabVgaModes { V2UVideoModeDescr* customModes; /* Custom modes */ V2UVideoModeDescr* stdModes; /* Standard modes */ int numCustomModes; /* Number of custom modes */ int numStdModes; /* Number of standard modes */ } FrmGrabVgaModes; /** * Gets VGA mode table. The returned pointer must be deallocated * with FrmGrab_Free() */ FrmGrabVgaModes* FrmGrab_GetVGAModes(FrmGrabber* fg); /** * Sets VGA mode table. Custom modes can be modified, standard modes can only * enabled or disabled (VIDEOMODE_TYPE_ENABLED flag). */ V2U_BOOL FrmGrab_SetVGAModes(FrmGrabber* fg, const FrmGrabVgaModes* vgaModes); /** * Sends PS/2 events to the frame grabber (KVM capable products only). */ V2U_BOOL FrmGrab_SendPS2(FrmGrabber* fg, const V2U_SendPS2* ps2); /** * Sets intended frame rate limit (average number of FrmGrab_Frame calls per * second). The frame grabber may use this hint to reduce resource usage, * especially in low fps case. */ V2U_BOOL FrmGrab_SetMaxFps(FrmGrabber* fg, double maxFps); /** * Signals the grabber to prepare for capturing frames with maximum * frame rate. While it currently doesn't matter for local grabbers, it's * really important for network grabbers (it turns streaming on, otherwise * FrmGrab_Frame will have to work on request/response basis, which is * much slower). Returns V2U_TRUE if streaming is supported, or V2U_FALSE * if this call has no effect. */ V2U_BOOL FrmGrab_Start(FrmGrabber* fg); /** * Signals the grabber to stop capturing frames with maximum frame rate. */ void FrmGrab_Stop(FrmGrabber* fg); /** * Grabs one frame. The caller doesn't have to call FrmGrab_Start first, * but it's recommended in order to get maximum frame rate. * * The second parameter is the capture format, i.e. one of * V2U_GRABFRAME_FORMAT_* constants defined in v2u_defs.h * * The last parameter is a pointer to the requested crop rectangle. Pass * NULL if you need the whole frame. * * All frames returned by this function must be eventually released with * FrmGrab_Release which makes them eligible for deallocation or recycling. * All frames captured via particular FrmGrabber handle must be released * before you close the handle with FrmGrab_Close. If FrmGrab_Release is * called after closing FrmGrabber handle, the behavior of frmgrab library * is undefined. Most likely, it would result in either crash or memory leak. */ V2U_GrabFrame2* FrmGrab_Frame(FrmGrabber* fg, V2U_UINT32 format, const V2URect* crop); /** * Deallocates or recycles the frame previously returned by FrmGrab_Frame. * FrmGrabber handle must match the one passed to FrmGrab_Frame. * * All frames captured via particular FrmGrabber handle must be released * before you close the handle with FrmGrab_Close. */ void FrmGrab_Release(FrmGrabber* fg, V2U_GrabFrame2* frame); /** * Closes the frame grabber and invalidates the handle. * * All frames captured via particular FrmGrabber handle must be released * before you close the handle with FrmGrab_Close. */ void FrmGrab_Close(FrmGrabber* fg); /** * Deallocates memory allocated by frmgrab. */ void FrmGrab_Free(void* ptr); /** Memory allocation callbacks */ typedef void* (*FrmGrabMemAlloc)(void* param, V2U_UINT32 len); typedef void (*FrmGrabMemFree)(void* param, void* ptr); typedef struct _FrmGrabMemCB { FrmGrabMemAlloc alloc; FrmGrabMemFree free; } FrmGrabMemCB; /** * Sets functions for allocating and deallocating memory for the frame * buffers. NOTE that these callbacks are ONLY invoked to allocate memory * for the frame buffer. For all other allocations, frmgrab library uses * its own allocator. The allocator and deallocator callbacks may be invoked * in arbitrary thread context, not necessarily the thread that invokes * FrmGrab_Frame. The contents of FrmGrabMemCB is copied to internal storage. */ void FrmGrab_SetAlloc(FrmGrabber* fg, const FrmGrabMemCB* memcb, void* param); #ifdef __cplusplus } /* end of extern "C" */ #endif /* __cplusplus */ #endif /* _EPIPHAN_FRMGRAB_H_ */ /* * Local Variables: * c-basic-offset: 4 * indent-tabs-mode: nil * End: */
15,048
C
33.437071
79
0.730728
adegirmenci/HBL-ICEbot/epiphan/codec/avi_writer/avi_writer.c
/**************************************************************************** * * $Id: avi_writer.c 10003 2010-06-10 11:28:31Z monich $ * * Copyright (C) 2007-2010 Epiphan Systems Inc. All rights reserved. * * Platform-independent library for creating AVI files. * ****************************************************************************/ #include "avi_writer.h" #include <stdlib.h> #include <memory.h> #include <assert.h> #define AVIF_HASINDEX 0x00000010 #define AVIF_MUSTUSEINDEX 0x00000020 #define AVIF_ISINTERLEAVED 0x00000100 #define AVIF_TRUSTCKTYPE 0x00000800 #define AVIF_WASCAPTUREFILE 0x00010000 /* AW will set this flag by default */ #define AVIF_COPYRIGHTED 0x00020000 #define AVIH_CHUNK_OFFSET 32 #define AVIH_CHUNK_SIZE 56 #define AVIH_CHUNK_STREAM_COUNT_OFFSET 24 #define STRH_CHUNK_SIZE 56 #define STRF_VIDEO_CHUNK_SIZE 40 #define AW_FALSE 0 #define AW_TRUE 1 typedef int AW_BOOL; typedef unsigned char AW_BYTE; typedef unsigned int AW_UINT32; /* rgb121 */ static const AW_BYTE aw_palette_4bpp[16*4] = { 0x00,0x00,0x00,0, 0x00,0x00,0xff,0, 0x00,0x55,0x00,0, 0x00,0x55,0xff,0, 0x00,0xaa,0x00,0, 0x00,0xaa,0xff,0, 0x00,0xff,0x00,0, 0x00,0xff,0xff,0, 0xff,0x00,0x00,0, 0xff,0x00,0xff,0, 0xff,0x55,0x00,0, 0xff,0x55,0xff,0, 0xff,0xaa,0x00,0, 0xff,0xaa,0xff,0, 0xff,0xff,0x00,0, 0xff,0xff,0xff,0, }; /* rgb233 */ static const AW_BYTE aw_palette_8bpp[256*4] = { 0x00,0x00,0x00,0, 0x24,0x00,0x00,0, 0x49,0x00,0x00,0, 0x6D,0x00,0x00,0, 0x92,0x00,0x00,0, 0xB6,0x00,0x00,0, 0xDB,0x00,0x00,0, 0xFF,0x00,0x00,0, 0x00,0x24,0x00,0, 0x24,0x24,0x00,0, 0x49,0x24,0x00,0, 0x6D,0x24,0x00,0, 0x92,0x24,0x00,0, 0xB6,0x24,0x00,0, 0xDB,0x24,0x00,0, 0xFF,0x24,0x00,0, 0x00,0x49,0x00,0, 0x24,0x49,0x00,0, 0x49,0x49,0x00,0, 0x6D,0x49,0x00,0, 0x92,0x49,0x00,0, 0xB6,0x49,0x00,0, 0xDB,0x49,0x00,0, 0xFF,0x49,0x00,0, 0x00,0x6D,0x00,0, 0x24,0x6D,0x00,0, 0x49,0x6D,0x00,0, 0x6D,0x6D,0x00,0, 0x92,0x6D,0x00,0, 0xB6,0x6D,0x00,0, 0xDB,0x6D,0x00,0, 0xFF,0x6D,0x00,0, 0x00,0x92,0x00,0, 0x24,0x92,0x00,0, 0x49,0x92,0x00,0, 0x6D,0x92,0x00,0, 0x92,0x92,0x00,0, 0xB6,0x92,0x00,0, 0xDB,0x92,0x00,0, 0xFF,0x92,0x00,0, 0x00,0xB6,0x00,0, 0x24,0xB6,0x00,0, 0x49,0xB6,0x00,0, 0x6D,0xB6,0x00,0, 0x92,0xB6,0x00,0, 0xB6,0xB6,0x00,0, 0xDB,0xB6,0x00,0, 0xFF,0xB6,0x00,0, 0x00,0xDB,0x00,0, 0x24,0xDB,0x00,0, 0x49,0xDB,0x00,0, 0x6D,0xDB,0x00,0, 0x92,0xDB,0x00,0, 0xB6,0xDB,0x00,0, 0xDB,0xDB,0x00,0, 0xFF,0xDB,0x00,0, 0x00,0xFF,0x00,0, 0x24,0xFF,0x00,0, 0x49,0xFF,0x00,0, 0x6D,0xFF,0x00,0, 0x92,0xFF,0x00,0, 0xB6,0xFF,0x00,0, 0xDB,0xFF,0x00,0, 0xFF,0xFF,0x00,0, 0x00,0x00,0x55,0, 0x24,0x00,0x55,0, 0x49,0x00,0x55,0, 0x6D,0x00,0x55,0, 0x92,0x00,0x55,0, 0xB6,0x00,0x55,0, 0xDB,0x00,0x55,0, 0xFF,0x00,0x55,0, 0x00,0x24,0x55,0, 0x24,0x24,0x55,0, 0x49,0x24,0x55,0, 0x6D,0x24,0x55,0, 0x92,0x24,0x55,0, 0xB6,0x24,0x55,0, 0xDB,0x24,0x55,0, 0xFF,0x24,0x55,0, 0x00,0x49,0x55,0, 0x24,0x49,0x55,0, 0x49,0x49,0x55,0, 0x6D,0x49,0x55,0, 0x92,0x49,0x55,0, 0xB6,0x49,0x55,0, 0xDB,0x49,0x55,0, 0xFF,0x49,0x55,0, 0x00,0x6D,0x55,0, 0x24,0x6D,0x55,0, 0x49,0x6D,0x55,0, 0x6D,0x6D,0x55,0, 0x92,0x6D,0x55,0, 0xB6,0x6D,0x55,0, 0xDB,0x6D,0x55,0, 0xFF,0x6D,0x55,0, 0x00,0x92,0x55,0, 0x24,0x92,0x55,0, 0x49,0x92,0x55,0, 0x6D,0x92,0x55,0, 0x92,0x92,0x55,0, 0xB6,0x92,0x55,0, 0xDB,0x92,0x55,0, 0xFF,0x92,0x55,0, 0x00,0xB6,0x55,0, 0x24,0xB6,0x55,0, 0x49,0xB6,0x55,0, 0x6D,0xB6,0x55,0, 0x92,0xB6,0x55,0, 0xB6,0xB6,0x55,0, 0xDB,0xB6,0x55,0, 0xFF,0xB6,0x55,0, 0x00,0xDB,0x55,0, 0x24,0xDB,0x55,0, 0x49,0xDB,0x55,0, 0x6D,0xDB,0x55,0, 0x92,0xDB,0x55,0, 0xB6,0xDB,0x55,0, 0xDB,0xDB,0x55,0, 0xFF,0xDB,0x55,0, 0x00,0xFF,0x55,0, 0x24,0xFF,0x55,0, 0x49,0xFF,0x55,0, 0x6D,0xFF,0x55,0, 0x92,0xFF,0x55,0, 0xB6,0xFF,0x55,0, 0xDB,0xFF,0x55,0, 0xFF,0xFF,0x55,0, 0x00,0x00,0xAA,0, 0x24,0x00,0xAA,0, 0x49,0x00,0xAA,0, 0x6D,0x00,0xAA,0, 0x92,0x00,0xAA,0, 0xB6,0x00,0xAA,0, 0xDB,0x00,0xAA,0, 0xFF,0x00,0xAA,0, 0x00,0x24,0xAA,0, 0x24,0x24,0xAA,0, 0x49,0x24,0xAA,0, 0x6D,0x24,0xAA,0, 0x92,0x24,0xAA,0, 0xB6,0x24,0xAA,0, 0xDB,0x24,0xAA,0, 0xFF,0x24,0xAA,0, 0x00,0x49,0xAA,0, 0x24,0x49,0xAA,0, 0x49,0x49,0xAA,0, 0x6D,0x49,0xAA,0, 0x92,0x49,0xAA,0, 0xB6,0x49,0xAA,0, 0xDB,0x49,0xAA,0, 0xFF,0x49,0xAA,0, 0x00,0x6D,0xAA,0, 0x24,0x6D,0xAA,0, 0x49,0x6D,0xAA,0, 0x6D,0x6D,0xAA,0, 0x92,0x6D,0xAA,0, 0xB6,0x6D,0xAA,0, 0xDB,0x6D,0xAA,0, 0xFF,0x6D,0xAA,0, 0x00,0x92,0xAA,0, 0x24,0x92,0xAA,0, 0x49,0x92,0xAA,0, 0x6D,0x92,0xAA,0, 0x92,0x92,0xAA,0, 0xB6,0x92,0xAA,0, 0xDB,0x92,0xAA,0, 0xFF,0x92,0xAA,0, 0x00,0xB6,0xAA,0, 0x24,0xB6,0xAA,0, 0x49,0xB6,0xAA,0, 0x6D,0xB6,0xAA,0, 0x92,0xB6,0xAA,0, 0xB6,0xB6,0xAA,0, 0xDB,0xB6,0xAA,0, 0xFF,0xB6,0xAA,0, 0x00,0xDB,0xAA,0, 0x24,0xDB,0xAA,0, 0x49,0xDB,0xAA,0, 0x6D,0xDB,0xAA,0, 0x92,0xDB,0xAA,0, 0xB6,0xDB,0xAA,0, 0xDB,0xDB,0xAA,0, 0xFF,0xDB,0xAA,0, 0x00,0xFF,0xAA,0, 0x24,0xFF,0xAA,0, 0x49,0xFF,0xAA,0, 0x6D,0xFF,0xAA,0, 0x92,0xFF,0xAA,0, 0xB6,0xFF,0xAA,0, 0xDB,0xFF,0xAA,0, 0xFF,0xFF,0xAA,0, 0x00,0x00,0xFF,0, 0x24,0x00,0xFF,0, 0x49,0x00,0xFF,0, 0x6D,0x00,0xFF,0, 0x92,0x00,0xFF,0, 0xB6,0x00,0xFF,0, 0xDB,0x00,0xFF,0, 0xFF,0x00,0xFF,0, 0x00,0x24,0xFF,0, 0x24,0x24,0xFF,0, 0x49,0x24,0xFF,0, 0x6D,0x24,0xFF,0, 0x92,0x24,0xFF,0, 0xB6,0x24,0xFF,0, 0xDB,0x24,0xFF,0, 0xFF,0x24,0xFF,0, 0x00,0x49,0xFF,0, 0x24,0x49,0xFF,0, 0x49,0x49,0xFF,0, 0x6D,0x49,0xFF,0, 0x92,0x49,0xFF,0, 0xB6,0x49,0xFF,0, 0xDB,0x49,0xFF,0, 0xFF,0x49,0xFF,0, 0x00,0x6D,0xFF,0, 0x24,0x6D,0xFF,0, 0x49,0x6D,0xFF,0, 0x6D,0x6D,0xFF,0, 0x92,0x6D,0xFF,0, 0xB6,0x6D,0xFF,0, 0xDB,0x6D,0xFF,0, 0xFF,0x6D,0xFF,0, 0x00,0x92,0xFF,0, 0x24,0x92,0xFF,0, 0x49,0x92,0xFF,0, 0x6D,0x92,0xFF,0, 0x92,0x92,0xFF,0, 0xB6,0x92,0xFF,0, 0xDB,0x92,0xFF,0, 0xFF,0x92,0xFF,0, 0x00,0xB6,0xFF,0, 0x24,0xB6,0xFF,0, 0x49,0xB6,0xFF,0, 0x6D,0xB6,0xFF,0, 0x92,0xB6,0xFF,0, 0xB6,0xB6,0xFF,0, 0xDB,0xB6,0xFF,0, 0xFF,0xB6,0xFF,0, 0x00,0xDB,0xFF,0, 0x24,0xDB,0xFF,0, 0x49,0xDB,0xFF,0, 0x6D,0xDB,0xFF,0, 0x92,0xDB,0xFF,0, 0xB6,0xDB,0xFF,0, 0xDB,0xDB,0xFF,0, 0xFF,0xDB,0xFF,0, 0x00,0xFF,0xFF,0, 0x24,0xFF,0xFF,0, 0x49,0xFF,0xFF,0, 0x6D,0xFF,0xFF,0, 0x92,0xFF,0xFF,0, 0xB6,0xFF,0xFF,0, 0xDB,0xFF,0xFF,0, 0xFF,0xFF,0xFF,0 }; static const AW_UINT32 aw_mask_bgr16[3] = {0x001F, 0x07E0, 0xF800}; static const AW_UINT32 aw_mask_rgb16[3] = {0xF800, 0x07E0, 0x001F}; static const AW_BYTE aw_mask_rgb32[3*4] = { 0,0xFF,0x00,0x00, 0,0x00,0xFF,0x00, 0,0x00,0x00,0xFF }; #define AW_FSEEK( f,pos ) (fseek( (f),(pos),SEEK_SET ) == 0) static AW_BOOL AW_FWRITE( AW_FHANDLE f,const void *buf,unsigned long count,unsigned long *fpos ) { if (count) { if( fwrite( buf,1,count,f ) == count ) { if( fpos ) *fpos += count; return AW_TRUE; } return AW_FALSE; } return AW_TRUE; } typedef enum { AW_ST_Video, AW_ST_Audio } AW_StreamTypes_e; typedef struct _STREAM_CTX { AW_StreamTypes_e stype; unsigned long frame_count; unsigned long streamh_start; unsigned char fourcc[4]; unsigned long rate; unsigned long scale; } STREAM_CTX; typedef enum { AW_StreamError, AW_StreamsConfig, AW_FramesAdd, } AW_States_e; typedef struct _AW_Idx_s { unsigned char fourcc[4]; unsigned long flags; unsigned long offs; unsigned long size; } AW_Idx_s; /* Numbers should be power of 8 to speed up calculations */ #define AW_Idx_Plane_Size 2048 #define AW_Idx_Plane_Count 1024 typedef AW_Idx_s AW_Idx_Plane[AW_Idx_Plane_Size]; typedef AW_Idx_Plane *pAW_Idx_Plane; const int AW_CTX_magic = 0x501E1E55; struct __AW_CTX { unsigned long magic; unsigned long write_pos; int stream_count; STREAM_CTX streams[AW_MAX_STREAMS]; AW_FHANDLE f; unsigned long movi_ch_start; AW_States_e state; unsigned long width; unsigned long height; pAW_Idx_Plane idx[AW_Idx_Plane_Count]; unsigned long idx_count; }; static const unsigned char riff4cc[4] = "RIFF"; static const unsigned char AVI4cc[4] = "AVI "; static const unsigned char LIST4cc[4] = "LIST"; static const unsigned char hdrl4cc[4] = "hdrl"; static const unsigned char avih4cc[4] = "avih"; static const unsigned char strl4cc[4] = "strl"; static const unsigned char strh4cc[4] = "strh"; static const unsigned char vids4cc[4] = "vids"; static const unsigned char auds4cc[4] = "auds"; static const unsigned char strf4cc[4] = "strf"; static const unsigned char movi4cc[4] = "movi"; static const unsigned char idx14cc[4] = "idx1"; static const unsigned char JUNK4cc[4] = "JUNK"; static const unsigned char DIB4cc[4] = "DIB "; /* Platform indepent conversions */ static AW_BOOL AW_WriteULONG( AW_CTX *ctx,unsigned long l ) { unsigned char c[4]; c[0] = (unsigned char)l; c[1] = (unsigned char)((l >> 8)); c[2] = (unsigned char)((l >> 16)); c[3] = (unsigned char)((l >> 24)); return AW_FWRITE( ctx->f,&c[0],4,&ctx->write_pos ); } static AW_BOOL AW_WriteUSHORT( AW_CTX *ctx,unsigned long s ) { unsigned char c[2]; c[0] = (unsigned char)s; c[1] = (unsigned char)(s >> 8); return AW_FWRITE( ctx->f,&c[0],2,&ctx->write_pos ); } static AW_BOOL AW_WriteFourCC( AW_CTX *ctx,const unsigned char* fourcc ) { return AW_FWRITE( ctx->f,fourcc,4,&ctx->write_pos ); } static AW_BOOL AW_Seek( AW_CTX *ctx,unsigned long pos ) { if (AW_FSEEK(ctx->f, pos)) { ctx->write_pos = pos; return AW_TRUE; } return AW_FALSE; } static AW_RET AW_AddIdx( AW_CTX *ctx,const unsigned char *fourcc, unsigned long flags,unsigned long offs,unsigned long size ) { unsigned long il = ctx->idx_count % AW_Idx_Plane_Size; unsigned long ih = ctx->idx_count / AW_Idx_Plane_Size; AW_Idx_Plane *pl; if( ih >= AW_Idx_Plane_Count ) return AW_ERR_INTERNAL_LIMIT; if( !ctx->idx[ih] ) ctx->idx[ih] = malloc( sizeof( AW_Idx_Plane )); if( !ctx->idx[ih] ) return AW_ERR_MEMORY; pl = ctx->idx[ih]; memcpy( (*pl)[il].fourcc,fourcc,4 ); (*pl)[il].flags = flags; (*pl)[il].offs = offs; (*pl)[il].size = size; ctx->idx_count++; return AW_OK; } static AW_BOOL AW_Align( AW_CTX *ctx,unsigned long align_amount ) { unsigned long write_amount = align_amount - ( ctx->write_pos % align_amount ); #define empty_buf_size 2048 static char empty_buf[empty_buf_size] = "q"; if( empty_buf[0] ) memset( empty_buf,0,empty_buf_size ); while( write_amount <= 8 ) write_amount += align_amount; if( !AW_WriteFourCC( ctx,JUNK4cc ) || !AW_WriteULONG( ctx,write_amount ) ) goto err_io; while( write_amount ) { if( write_amount > empty_buf_size ) { if( !AW_FWRITE( ctx->f,empty_buf,empty_buf_size,&ctx->write_pos ) ) goto err_io; write_amount -= empty_buf_size; } else { if( !AW_FWRITE( ctx->f,empty_buf,write_amount,&ctx->write_pos ) ) goto err_io; write_amount = 0; } } return AW_TRUE; err_io: return AW_FALSE; } AW_RET AW_FInit( AW_CTX **ctx,AW_FHANDLE f,unsigned long width,unsigned long height ) { AW_CTX *lctx; if( !ctx ) return AW_ERR_PARAM; lctx = (AW_CTX *)malloc( sizeof( AW_CTX )); if( !lctx ) return AW_ERR_MEMORY; memset( lctx,0,sizeof( AW_CTX )); lctx->magic = AW_CTX_magic; lctx->f = f; lctx->height = height; lctx->width = width; if( AW_Seek( lctx,0 ) /* Just to be sure */ && AW_WriteFourCC( lctx,riff4cc ) && /* Size of full file, offset 4, fill later */ AW_WriteULONG( lctx,0 ) && AW_WriteFourCC( lctx,AVI4cc ) && AW_WriteFourCC( lctx,LIST4cc ) && /* Size of AVI LIST chunk, offset 16, fill later */ AW_WriteULONG( lctx,0 ) && AW_WriteFourCC( lctx,hdrl4cc ) && AW_WriteFourCC( lctx,avih4cc ) && /* avih chunk is always 56 bytes */ AW_WriteULONG( lctx,AVIH_CHUNK_SIZE ) ) { #ifdef _DEBUG unsigned long d1 = lctx->write_pos; #endif /* _DEBUG */ /* * typedef struct{ * DWORD dwMicroSecPerFrame; * DWORD dwMaxBytesPerSec; * DWORD dwPaddingGranularity; * DWORD dwFlags; * DWORD dwTotalFrames; * DWORD dwInitialFrames; * DWORD dwStreams; * DWORD dwSuggestedBufferSize; * DWORD dwWidth; * DWORD dwHeight; * DWORD dwReserved[4]; * } MainAVIHeader; */ /* dwMicroSecPerFrame - do not know now, let's write NTSC value */ if( AW_WriteULONG( lctx,33367 ) && /* dwMaxBytesPerSec - by default width * height * 3 * 30fps for NTSC */ AW_WriteULONG( lctx,width * height * 3 * 30 ) && /* dwPaddingGranularity */ AW_WriteULONG( lctx,0 ) && /* dwFlags */ AW_WriteULONG( lctx,AVIF_WASCAPTUREFILE | AVIF_HASINDEX ) && /* dwTotalFrames - have to be set later */ AW_WriteULONG( lctx,0 ) && /* dwInitialFrames */ AW_WriteULONG( lctx,0 ) && /* dwStreams - let's write 1 stream by default */ AW_WriteULONG( lctx,1 ) && /* dwSuggestedBufferSize - max unpacked frame by default */ AW_WriteULONG( lctx,width * height * 3 ) && /* dwWidth */ AW_WriteULONG( lctx,width ) && /* dwHeight */ AW_WriteULONG( lctx,height ) && /* dwReserved */ AW_WriteULONG( lctx,0 ) && AW_WriteULONG( lctx,0 ) && AW_WriteULONG( lctx,0 ) && AW_WriteULONG( lctx,0 ) ) { #ifdef _DEBUG assert( d1 + AVIH_CHUNK_SIZE == lctx->write_pos ); #endif /* _DEBUG */ lctx->state = AW_StreamsConfig; *ctx = lctx; return AW_OK; } } /* I/O error */ free( lctx ); *ctx = NULL; return AW_ERR_FILE_IO; } AW_RET AW_FDone( AW_CTX *ctx ) { unsigned long q; if( !ctx ) return AW_ERR_PARAM; /* Let's do full AVI close if the stream is in right state Call in other state mean that we have to do emergency clean up */ if( ctx->state == AW_FramesAdd ) { unsigned long tmppos = 0; unsigned long movich_size = 0; unsigned long RIFF_size = 0; int i = 0; STREAM_CTX *s = NULL; if( !AW_Align( ctx,2048 ) ) goto err_io; /* Align to CD sector size */ movich_size = ctx->write_pos - ( ctx->movi_ch_start + 8 ); /* LIST and size are not counted */ /* write idx1 chunk */ if( !AW_WriteFourCC( ctx,idx14cc ) || !AW_WriteULONG( ctx,16 * ctx->idx_count ) ) goto err_io; for( q = 0; q < ctx->idx_count; q++ ) { unsigned long il = q % AW_Idx_Plane_Size; unsigned long ih = q / AW_Idx_Plane_Size; AW_Idx_Plane *pl = ctx->idx[ih]; if( !pl ) goto err_io; if( !AW_WriteFourCC( ctx,(*pl)[il].fourcc ) || !AW_WriteULONG( ctx,(*pl)[il].flags ) || !AW_WriteULONG( ctx,(*pl)[il].offs ) || !AW_WriteULONG( ctx,(*pl)[il].size ) ) goto err_io; } /* ------------------------------------------------------------*/ tmppos = ctx->write_pos; RIFF_size = tmppos - 8; /* RIFF size */ if( !AW_Seek( ctx,4 ) || !AW_WriteULONG( ctx,RIFF_size ) || /* movi list chunk size */ !AW_Seek( ctx,ctx->movi_ch_start + 4 ) || !AW_WriteULONG( ctx,movich_size ) ) goto err_io; /* Calculated from 1st video stream */ for( i = 0; i < ctx->stream_count; i++ ) { if( ctx->streams[i].stype == AW_ST_Video ) { s = &ctx->streams[i]; break; } } if( s ) { /* should avoid overflow here */ unsigned long ms_per_frame = (unsigned long)( 1000000.0 * (double)s->scale / s->rate ); /* dwMicroSecPerFrame */ if( !AW_Seek( ctx,32 ) || !AW_WriteULONG( ctx,ms_per_frame ) || /* dwTotalFrames */ !AW_Seek( ctx,48 ) || !AW_WriteULONG( ctx,s->frame_count ) ) goto err_io; } for( i = 0; i < ctx->stream_count; i++ ) { s = &ctx->streams[i]; switch( s->stype ) { case AW_ST_Video: case AW_ST_Audio: /* dwTotalLength */ if( !AW_Seek( ctx,s->streamh_start + 20 + 32 ) || !AW_WriteULONG( ctx,s->frame_count ) ) goto err_io; break; default: assert( 0 ); break; } } /* Let's return file pointer to the end of file just in case */ AW_Seek( ctx,tmppos ); } for( q = 0; q < AW_Idx_Plane_Count; q++ ) { free( ctx->idx[q] ); } ctx->magic = 0; free( ctx ); return AW_OK; err_io: for( q = 0; q < AW_Idx_Plane_Count; q++ ) { free( ctx->idx[q] ); } ctx->magic = 0; free( ctx ); return AW_ERR_FILE_IO; } AW_RET AW_UpdateAVIHeaderField( AW_CTX *ctx,AW_HDR_Fields fld,unsigned long value ) { if( !ctx ) return AW_ERR_PARAM; return AW_OK; } /* * typedef struct { * FOURCC fccType; * FOURCC fccHandler; * DWORD dwFlags; * WORD wPriority; * WORD wLanguage; * DWORD dwInitialFrames; * DWORD dwScale; * DWORD dwRate; // dwRate / dwScale == samples/second * DWORD dwStart; * DWORD dwLength; // In units above... * DWORD dwSuggestedBufferSize; * DWORD dwQuality; * DWORD dwSampleSize; * RECT rcFrame; * } AVIStreamHeader; */ static AW_BOOL AW_WriteAVIStreamHeader( AW_CTX *ctx, const unsigned char *fccType, const unsigned char *fccHandler, unsigned long scale, unsigned long rate, unsigned long width, unsigned long height) { return AW_WriteFourCC( ctx,LIST4cc ) && /* Size of strl LIST chunk, offset 4, fill later */ AW_WriteULONG( ctx,0 ) && AW_WriteFourCC( ctx,strl4cc ) && AW_WriteFourCC( ctx,strh4cc ) && /* strh chunk is always 56 bytes */ AW_WriteULONG( ctx,STRH_CHUNK_SIZE ) && /* fccType */ AW_WriteFourCC( ctx,fccType ) && /* fccHandler */ AW_WriteFourCC( ctx,fccHandler ) && /* dwFlags */ AW_WriteULONG( ctx,0 ) && /* wPriority */ AW_WriteUSHORT( ctx,0 ) && /* wLanguage */ AW_WriteUSHORT( ctx,0 ) && /* dwInitialFrames */ AW_WriteULONG( ctx,0 ) && /* dwScale */ AW_WriteULONG( ctx,scale ) && /* dwRate */ AW_WriteULONG( ctx,rate ) && /* dwStart */ AW_WriteULONG( ctx,0 ) && /* dwLength - have to be set later */ AW_WriteULONG( ctx,0 ) && /* dwSuggestedBufferSize */ AW_WriteULONG( ctx,width*height*3 ) && /* dwQuality */ AW_WriteULONG( ctx,0 ) && /* dwSampleSize */ AW_WriteULONG( ctx,0 ) && /* rcFrame */ AW_WriteUSHORT( ctx,0 ) && AW_WriteUSHORT( ctx,0 ) && AW_WriteUSHORT( ctx,width ) && AW_WriteUSHORT( ctx,height ); } static AW_BOOL AW_FinalizeStreamHeader( AW_CTX *ctx,const STREAM_CTX *cstream ) { unsigned long tmppos = ctx->write_pos; unsigned long strllen = tmppos - ( cstream->streamh_start + 8 ); if( AW_Seek( ctx,cstream->streamh_start + 4 ) && AW_WriteULONG( ctx,strllen ) && AW_Seek( ctx,tmppos ) ) { ctx->write_pos = tmppos; ctx->stream_count++; return AW_TRUE; } return AW_FALSE; } AW_RET AW_AddVideoStream( AW_CTX *ctx,const char *fourcc,int bitcount ) { STREAM_CTX *cstream; AW_UINT32 biCompression = 0; AW_UINT32 biClrUsed = 0; AW_UINT32 bmiColorsSize = 0; const void *bmiColors = NULL; if( !ctx ) return AW_ERR_PARAM; cstream = ctx->streams + ctx->stream_count; if( ctx->state != AW_StreamsConfig ) return AW_ERR_WRONG_STATE; if( ctx->stream_count >= AW_MAX_STREAMS ) return AW_ERR_STREAMS_LIMIT; memset( cstream,0,sizeof( STREAM_CTX )); cstream->streamh_start = ctx->write_pos; cstream->stype = AW_ST_Video; cstream->scale = 100; cstream->rate = 2997; /* 2997 / scale( 100 ) for NTSC 29.97 */ if (fourcc) { memcpy(&biCompression, fourcc, 4); memcpy( cstream->fourcc,fourcc,4 ); } if (!biCompression) { memcpy( cstream->fourcc,DIB4cc,4 ); switch (bitcount) { case 4: /* This one is not played by most players */ bmiColors = aw_palette_4bpp; bmiColorsSize = sizeof(aw_palette_4bpp); biClrUsed = 1 << bitcount; break; case 8: bmiColors = aw_palette_8bpp; bmiColorsSize = sizeof(aw_palette_8bpp); biClrUsed = 1 << bitcount; break; case 16: biCompression = 3 /* BI_BITFIELDS */; bmiColors = aw_mask_rgb16; bmiColorsSize = sizeof(aw_mask_rgb16); break; case 32: /* This one is not played by most players */ biCompression = 3 /* BI_BITFIELDS */; bmiColors = aw_mask_rgb32; bmiColorsSize = sizeof(aw_mask_rgb32); break; } } if( AW_WriteAVIStreamHeader(ctx, vids4cc, cstream->fourcc, cstream->scale, cstream->rate, ctx->width, ctx->height) && /* "strf" start" */ AW_WriteFourCC( ctx,strf4cc ) && /* Size of strf chunk */ AW_WriteULONG( ctx,STRF_VIDEO_CHUNK_SIZE + bmiColorsSize ) && /* * typedef struct { * DWORD biSize; * LONG biWidth; * LONG biHeight; * WORD biPlanes; * WORD biBitCount; * DWORD biCompression; * DWORD biSizeImage; * LONG biXPelsPerMeter; * LONG biYPelsPerMeter; * DWORD biClrUsed; * DWORD biClrImportant; * } BITMAPINFOHEADER; */ /* biSize */ AW_WriteULONG( ctx,STRF_VIDEO_CHUNK_SIZE ) && /* biWidth */ AW_WriteULONG( ctx,ctx->width ) && /* biHeight */ AW_WriteULONG( ctx,ctx->height ) && /* biPlanes */ AW_WriteUSHORT( ctx,1 ) && /* biBitCount */ AW_WriteUSHORT( ctx,bitcount ) && /* biCompression */ AW_WriteULONG( ctx,biCompression ) && /* biSizeImage */ AW_WriteULONG( ctx,ctx->width * ctx->height * bitcount / 8 ) && /* biXPelsPerMeter */ AW_WriteULONG( ctx,0 ) && /* biYPelsPerMeter */ AW_WriteULONG( ctx,0 ) && /* biClrUsed */ AW_WriteULONG( ctx,biClrUsed ) && /* biClrImportant */ AW_WriteULONG( ctx,0 ) && /* bmiColors */ AW_FWRITE( ctx->f,bmiColors,bmiColorsSize,&ctx->write_pos ) && /* Finalize stream list */ AW_FinalizeStreamHeader( ctx,cstream ) ) { return AW_OK; } ctx->state = AW_StreamError; return AW_ERR_FILE_IO; } AW_RET AW_AddAudioStreamPCM( AW_CTX *ctx,int freq,int bits,int channels ) { STREAM_CTX *cstream = ctx->streams + ctx->stream_count; if( !ctx ) return AW_ERR_PARAM; if( ctx->state != AW_StreamsConfig ) return AW_ERR_WRONG_STATE; if( ctx->stream_count >= AW_MAX_STREAMS ) return AW_ERR_STREAMS_LIMIT; memset( cstream,0,sizeof( STREAM_CTX )); cstream->streamh_start = ctx->write_pos; cstream->stype = AW_ST_Audio; cstream->scale = 1; cstream->rate = freq; if( AW_WriteAVIStreamHeader(ctx, auds4cc, cstream->fourcc, cstream->scale, cstream->rate, 0, 0) && /* "strf" start" */ AW_WriteFourCC( ctx,strf4cc ) && /* Size of strf chunk, 18 for PCM audio */ AW_WriteULONG( ctx,18 ) && /* * typedef struct { * WORD wFormatTag; * WORD nChannels; * DWORD nSamplesPerSec; * DWORD nAvgBytesPerSec; * WORD nBlockAlign; * WORD wBitsPerSample; * WORD cbSize; * } WAVEFORMATEX; */ /* wFormatTag */ AW_WriteUSHORT( ctx, 1 /* WAVE_FORMAT_PCM */ ) && /* nChannels */ AW_WriteUSHORT( ctx,channels ) && /* nSamplesPerSec */ AW_WriteULONG( ctx,freq ) && /* nAvgBytesPerSec */ AW_WriteULONG( ctx,freq*channels*bits/8 ) && /* nBlockAlign */ AW_WriteUSHORT( ctx,channels*bits/8 ) && /* wBitsPerSample */ AW_WriteUSHORT( ctx,bits ) && /* cbSize */ AW_WriteUSHORT( ctx,0 ) && /* Finalize stream list */ AW_FinalizeStreamHeader( ctx,cstream ) ) { return AW_OK; } ctx->state = AW_StreamError; return AW_ERR_FILE_IO; } AW_RET AW_UpdateStreamHeaderField( AW_CTX *ctx,int stream,AW_SHDR_Fields fld,unsigned long value ) { STREAM_CTX *s = NULL; int hdr_offs = 0; if( !ctx ) return AW_ERR_PARAM; if( stream >= ctx->stream_count ) return AW_ERR_PARAM; s = ctx->streams + stream; switch( fld ) { case AW_SHDR_Scale: s->scale = value; hdr_offs = 20; break; case AW_SHDR_Rate: s->rate = value; hdr_offs = 24; break; default: assert( 0 ); break; } if (hdr_offs) { const unsigned long tmppos = ctx->write_pos; if( AW_Seek( ctx,s->streamh_start + 20 + hdr_offs ) && AW_WriteULONG( ctx,value ) && /* Reposition back to the file end */ AW_Seek( ctx,tmppos ) ) { return AW_OK; } } ctx->state = AW_StreamError; return AW_ERR_FILE_IO; } AW_RET AW_StartStreamsData( AW_CTX *ctx ) { if( !ctx ) return AW_ERR_PARAM; if( ctx->state != AW_StreamsConfig ) return AW_ERR_WRONG_STATE; /* Align to CD sector size */ if( AW_Align( ctx,2048 ) ) { /* Finalize header list */ const unsigned long tmppos = ctx->write_pos; const unsigned long hdrllen = tmppos - 20; if( AW_Seek( ctx,16 ) && AW_WriteULONG( ctx,hdrllen ) && /* update dwStreams, offset hdrl + 24 = 56 */ AW_Seek( ctx,AVIH_CHUNK_OFFSET + AVIH_CHUNK_STREAM_COUNT_OFFSET ) && AW_WriteULONG( ctx,ctx->stream_count ) && /* Reposition back to the file end */ AW_Seek( ctx,tmppos ) && AW_WriteFourCC( ctx,LIST4cc ) && /* Size of movi LIST chunk, offset 4 from movi list start, fill later */ AW_WriteULONG( ctx,0 ) && AW_WriteFourCC( ctx,movi4cc ) ) { ctx->movi_ch_start = tmppos; ctx->state = AW_FramesAdd; return AW_OK; } } ctx->state = AW_StreamError; return AW_ERR_FILE_IO; } #define AW_KEYFRAME_FLAG 0x00000010 AW_RET AW_AddFrame( AW_CTX *ctx,int stream,unsigned char *frame,unsigned long frame_len,int keyframe ) { unsigned char chunkId[4] = "00dc"; if( !ctx ) return AW_ERR_PARAM; if( ctx->state != AW_FramesAdd ) return AW_ERR_WRONG_STATE; if( stream > ctx->stream_count ) return AW_ERR_PARAM; if( ctx->streams[stream].stype != AW_ST_Video ) return AW_ERR_PARAM; assert( ctx->stream_count < 100 ); chunkId[0] = '0' + (char)( stream / 10 ); chunkId[1] = '0' + (char)( stream % 10 ); if( AW_AddIdx( ctx,chunkId,keyframe ? AW_KEYFRAME_FLAG : 0, ctx->write_pos - ( ctx->movi_ch_start + 8 ), frame_len ) != AW_OK ) { ctx->state = AW_StreamError; return AW_ERR_INTERNAL_LIMIT; } if( AW_WriteFourCC( ctx,chunkId ) && AW_WriteULONG( ctx,frame_len ) && AW_FWRITE( ctx->f,frame,frame_len,&ctx->write_pos ) ) { ctx->streams[stream].frame_count++; return AW_OK; } ctx->state = AW_StreamError; return AW_ERR_FILE_IO; } AW_RET AW_AddAudioChunk( AW_CTX *ctx,int stream,unsigned char *data,unsigned long len) { unsigned char chunkId[4] = "00wb"; if( !ctx ) return AW_ERR_PARAM; if( ctx->state != AW_FramesAdd ) return AW_ERR_WRONG_STATE; if( stream > ctx->stream_count ) return AW_ERR_PARAM; if( ctx->streams[stream].stype != AW_ST_Audio ) return AW_ERR_PARAM; assert( ctx->stream_count < 100 ); chunkId[0] = '0' + (char)( stream / 10 ); chunkId[1] = '0' + (char)( stream % 10 ); if( AW_AddIdx( ctx,chunkId, AW_KEYFRAME_FLAG, ctx->write_pos - ( ctx->movi_ch_start + 8 ), len ) != AW_OK ) { ctx->state = AW_StreamError; return AW_ERR_INTERNAL_LIMIT; } if( AW_WriteFourCC( ctx,chunkId ) && AW_WriteULONG( ctx,len ) && AW_FWRITE( ctx->f,data,len,&ctx->write_pos ) ) { ctx->streams[stream].frame_count++; return AW_OK; } ctx->state = AW_StreamError; return AW_ERR_FILE_IO; } /* * Local Variables: * c-basic-offset: 4 * indent-tabs-mode: nil * End: */
29,662
C
31.740618
102
0.564662
adegirmenci/HBL-ICEbot/epiphan/codec/avi_writer/avi_writer.h
/**************************************************************************** * * $Id: avi_writer.h 15560 2012-02-01 16:27:42Z pzeldin $ * * Copyright (C) 2007-2009 Epiphan Systems Inc. All rights reserved. * * Platform-independent library for creating AVI files. * ****************************************************************************/ #ifndef __AVI_WRITER_H__ #define __AVI_WRITER_H__ #include <stdio.h> #define AW_MAX_STREAMS 2 typedef enum { AW_OK, AW_ERR_MEMORY, AW_ERR_PARAM, AW_ERR_FILE_IO, AW_ERR_WRONG_STATE, AW_ERR_STREAMS_LIMIT, AW_ERR_INTERNAL_LIMIT } AW_RET; typedef enum { AW_HDR_MicroSecPerFrame, AW_HDR_MaxBytesPerSec, AW_HDR_TotalFrames, AW_HDR_Flags, AW_HDR_Streams, AW_HDR_SuggestedBufferSize, AW_HDR_Length } AW_HDR_Fields; typedef enum { AW_SHDR_Scale, AW_SHDR_Rate } AW_SHDR_Fields; typedef FILE * AW_FHANDLE; typedef struct __AW_CTX AW_CTX; #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ AW_RET AW_FInit( AW_CTX **ctx,AW_FHANDLE f,unsigned long width,unsigned long height ); AW_RET AW_FDone( AW_CTX *ctx ); AW_RET AW_UpdateAVIHeaderField( AW_CTX *ctx,AW_HDR_Fields fld,unsigned long value ); AW_RET AW_AddVideoStream( AW_CTX *ctx,const char *fourcc,int bitcount ); AW_RET AW_AddAudioStreamPCM( AW_CTX *ctx,int freq,int bits,int channels ); /* Scale and rate stream fields will be used for calculation of stream playback length in stream header and average frame duration in avi header on close in AW_FDone */ AW_RET AW_UpdateStreamHeaderField( AW_CTX *ctx,int stream,AW_SHDR_Fields fld,unsigned long value ); AW_RET AW_StartStreamsData( AW_CTX *ctx ); /* Starts movi chunk */ AW_RET AW_AddFrame( AW_CTX *ctx,int stream,unsigned char *frame,unsigned long frame_len,int keyframe ); AW_RET AW_AddAudioChunk( AW_CTX *ctx,int stream,unsigned char *data,unsigned long len); #ifdef __cplusplus } /* end of extern "C" */ #endif /* __cplusplus */ #endif /* __AVI_WRITER_H__ */
2,006
C
27.267605
108
0.64008
adegirmenci/HBL-ICEbot/epiphan/include/v2u_version.h
/**************************************************************************** * * $Id: v2u_version.h 22900 2013-07-04 18:43:09Z monich $ * * Copyright (C) 2004-2013 Epiphan Systems Inc. All rights reserved. * * Version information * ****************************************************************************/ #ifndef _VGA2USB_VERSION_H_ #define _VGA2USB_VERSION_H_ 1 #ifndef V2U_COMPANY_NAME #define V2U_COMPANY_NAME "Epiphan Systems Inc." #endif /* V2U_COMPANY_NAME */ #ifndef V2U_COMPANY_URL #define V2U_COMPANY_URL "http://www.epiphan.com" #endif /* V2U_COMPANY_URL */ #ifndef V2U_REGISTRATION_URL #define V2U_REGISTRATION_URL V2U_COMPANY_URL "/register/" #endif /* V2U_REGISTRATION_URL */ #ifndef V2U_COPYRIGHT_YEARS #define V2U_COPYRIGHT_YEARS "2004-2013" #endif /* V2U_COPYRIGHT_YEARS */ #ifndef V2U_PRODUCT_COPYRIGHT #define V2U_PRODUCT_COPYRIGHT V2U_COPYRIGHT_YEARS " " V2U_COMPANY_NAME #endif /* V2U_PRODUCT_COPYRIGHT */ #ifndef V2U_PRODUCT_NAME #define V2U_PRODUCT_NAME "Epiphan Capture" #endif /* V2U_PRODUCT_NAME */ #define V2U_VERSION_MAJOR 3 #define V2U_VERSION_MINOR 28 #define V2U_VERSION_MICRO 0 #define V2U_VERSION_NANO 9 #endif /* _VGA2USB_VERSION_H_*/
1,247
C
27.363636
78
0.605453
adegirmenci/HBL-ICEbot/epiphan/include/v2u_dshow.h
/**************************************************************************** * * $Id: v2u_dshow.h 22128 2013-05-12 06:46:41Z monich $ * * Copyright (C) 2009-2013 Epiphan Systems Inc. All rights reserved. * * VGA2USB driver for Windows. * Declaration of VGA2USB proprietary property set * ****************************************************************************/ #ifndef _VGA2USB_V2U_DSHOW_H_ #define _VGA2USB_V2U_DSHOW_H_ 1 /* {9B2C649F-CAE6-4745-8D09-413DF0562C4B} */ #define STATIC_PROPSETID_V2U_PROPSET \ 0x9b2c649fL, 0xcae6, 0x4745, 0x8d, 0x09, 0x41, 0x3d, 0xf0, 0x56, 0x2c, 0x4b /* * Map between DirectShow PROP_GET properties and V2U properties. * This map is full. */ #define V2U_DSHOW_PROP_MAP(m) \ m( V2U_DSHOW_PROP_GET_DSFLAGS, V2UKey_DirectShowFlags ) \ m( V2U_DSHOW_PROP_GET_DSFIXRES, V2UKey_DirectShowFixRes ) \ m( V2U_DSHOW_PROP_GET_DSBITMAP, V2UKey_DirectShowDefaultBmp ) \ m( V2U_DSHOW_PROP_GET_DSSCALEMODE, V2UKey_DirectShowScaleMode ) \ m( V2U_DSHOW_PROP_GET_DSMAXRATE, V2UKey_DirectShowMaxFps ) \ m( V2U_DSHOW_PROP_GET_USERDATA, V2UKey_UserData ) \ m( V2U_DSHOW_PROP_GET_PROD_ID, V2UKey_UsbProductID ) \ m( V2U_DSHOW_PROP_GET_PROD_TYPE, V2UKey_ProductType ) \ m( V2U_DSHOW_PROP_GET_PROD_NAME, V2UKey_ProductName ) \ m( V2U_DSHOW_PROP_GET_VGAMODE_INFO, V2UKey_ModeMeasurmentsDump ) \ m( V2U_DSHOW_PROP_GET_HW_COMPRESSION, V2UKey_HardwareCompression ) \ m( V2U_DSHOW_PROP_GET_ADJ_RANGE, V2UKey_AdjustmentsRange ) \ m( V2U_DSHOW_PROP_GET_VERSION, V2UKey_Version ) \ m( V2U_DSHOW_PROP_GET_EDID, V2UKey_EDID ) \ m( V2U_DSHOW_PROP_GET_KVM_SUPPORT, V2UKey_KVMCapable ) \ m( V2U_DSHOW_PROP_GET_VGAMODE_ENTRY, V2UKey_VGAMode ) \ m( V2U_DSHOW_PROP_GET_VGAMODE, V2UKey_CurrentVGAMode ) \ m( V2U_DSHOW_PROP_GET_MEASURE_INTERVAL, V2UKey_ModeMeasureInterval ) \ m( V2U_DSHOW_PROP_GET_EDID_SUPPORT, V2UKey_EDIDSupport ) \ m( V2U_DSHOW_PROP_GET_TUNE_INTERVAL, V2UKey_TuneInterval ) \ m( V2U_DSHOW_PROP_GET_SN, V2UKey_SerialNumber ) \ m( V2U_DSHOW_PROP_GET_SIGNAL_TYPE, V2UKey_InputSignalType ) \ m( V2U_DSHOW_PROP_GET_DVIMODE_DETECT, V2UKey_DigitalModeDetect ) \ m( V2U_DSHOW_PROP_GET_NOISE_FILTER, V2UKey_NoiseFilter ) \ m( V2U_DSHOW_PROP_GET_HSYNC_THRESHOLD, V2UKey_HSyncThreshold ) \ m( V2U_DSHOW_PROP_GET_VSYNC_THRESHOLD, V2UKey_VSyncThreshold ) \ m( V2U_DSHOW_PROP_GET_DEVICE_CAPS, V2UKey_DeviceCaps ) \ m( V2U_DSHOW_PROP_GET_DSBITMAP2, V2UKey_DirectShowDefaultBmp2) \ m( V2U_DSHOW_PROP_GET_BUS_TYPE, V2UKey_BusType ) \ m( V2U_DSHOW_PROP_GET_GRABBER_ID, V2UKey_GrabberId ) \ m( V2U_DSHOW_PROP_GET_VIDEO_FORMAT, V2UKey_VideoFormat ) /* * Second range of properties (add new ones to the end) */ #define V2U_DSHOW_PROP_MAP2(m) \ m( V2U_DSHOW_PROP_GET_DSHOW_COMPAT_MODE, V2UKey_DShowCompatMode ) \ m( V2U_DSHOW_PROP_GET_EEDID, V2UKey_EEDID ) /* We have run out of these */ #define V2U_DSHOW_PROP_RESERVE(r) /* More reserved slots before V2U_DSHOW_PROP_GET_DSHOW_COMPAT_MODE */ #define V2U_DSHOW_PROP_RESERVE2(r) \ r( V2U_DSHOW_PROP_RESERVED_1, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_2, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_3, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_4, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_5, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_6, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_7, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_8, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_9, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_10, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_11, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_12, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_13, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_14, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_15, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_16, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_17, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_18, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_19, -1 ) \ r( V2U_DSHOW_PROP_RESERVED_20, -1 ) /** * Property IDs */ #undef V2U_DSHOW_PROP_DEFINE_ID #define V2U_DSHOW_PROP_DEFINE_ID(id,key) id, typedef enum _V2U_DSHOW_PROP { V2U_DSHOW_PROP_DETECT_VIDEO_MODE, /* V2U_VideoMode */ V2U_DSHOW_PROP_SET_PROPERTY, /* Any property */ V2U_DSHOW_PROP_MAP(V2U_DSHOW_PROP_DEFINE_ID) V2U_DSHOW_PROP_RESERVE(V2U_DSHOW_PROP_DEFINE_ID) V2U_DSHOW_PROP_GRAB_PARAMETERS, /* V2U_GrabParameters */ V2U_DSHOW_PROP_DSHOW_ACTIVE_COMPAT_MODE,/* V2UKey_DShowActiveCompatMode */ V2U_DSHOW_PROP_RESERVE2(V2U_DSHOW_PROP_DEFINE_ID) V2U_DSHOW_PROP_MAP2(V2U_DSHOW_PROP_DEFINE_ID) V2U_DSHOW_PROP_COUNT /* Not a valid value! */ } V2U_DSHOW_PROP; #undef V2U_DSHOW_PROP_DEFINE_ID #endif /* _VGA2USB_V2U_DSHOW_H_ */
5,164
C
44.307017
79
0.588304
adegirmenci/HBL-ICEbot/epiphan/include/v2u_ioctl.h
/**************************************************************************** * * $Id: v2u_ioctl.h 19092 2012-10-31 02:04:10Z monich $ * * Copyright (C) 2003-2012 Epiphan Systems Inc. All rights reserved. * * Defines IOCTL interface to the VGA2USB driver. Included by the driver * and by the user level code. * ****************************************************************************/ #ifndef _VGA2USB_IOCTL_H_ #define _VGA2USB_IOCTL_H_ 1 #include "v2u_defs.h" /* Platform specific magic */ #ifdef _WIN32 # define FILE_DEVICE_VGA2USB FILE_DEVICE_UNKNOWN # define _IOCTL_VGA2USB(x,a) CTL_CODE(FILE_DEVICE_VGA2USB,x,METHOD_NEITHER,a) # define IOCTL_VGA2USB(x) _IOCTL_VGA2USB(x,FILE_ANY_ACCESS) # define IOCTL_VGA2USB_R(x,type) _IOCTL_VGA2USB(x,FILE_READ_ACCESS) # define IOCTL_VGA2USB_W(x,type) _IOCTL_VGA2USB(x,FILE_WRITE_ACCESS) # define IOCTL_VGA2USB_WR(x,type) _IOCTL_VGA2USB(x,FILE_ANY_ACCESS) #else /* Unix */ # define IOCTL_VGA2USB(x) _IO('V',x) # define IOCTL_VGA2USB_R(x,type) _IOR('V',x,type) # define IOCTL_VGA2USB_W(x,type) _IOW('V',x,type) # define IOCTL_VGA2USB_WR(x,type) _IOWR('V',x,type) #endif /* Unix */ /* IOCTL definitions */ /* * IOCTL_VGA2USB_VIDEOMODE * * Detects video mode. If cable is disconnected, width and height are zero. * Note that the vertical refresh rate is measured in milliHertz. * That is, the number 59900 represents 59.9 Hz. * * Support: Linux, Windows, MacOS X */ #define IOCTL_VGA2USB_VIDEOMODE IOCTL_VGA2USB_R(9,V2U_VideoMode) /* * IOCTL_VGA2USB_GETPARAMS * IOCTL_VGA2USB_SETPARAMS * * Support: Linux, Windows, MacOS X */ /* Legacy flags names */ #define GRAB_BMP_BOTTOM_UP V2U_GRAB_BMP_BOTTOM_UP #define GRAB_PREFER_WIDE_MODE V2U_GRAB_PREFER_WIDE_MODE #define GRAB_YCRCB V2U_GRAB_YCRCB #define IOCTL_VGA2USB_GETPARAMS IOCTL_VGA2USB_R(6,V2U_GrabParameters) #define IOCTL_VGA2USB_SETPARAMS IOCTL_VGA2USB_W(8,V2U_GrabParameters) /* * IOCTL_VGA2USB_GRABFRAME * * For pixel format check V2U_GRABFRAME_FORMAT_XXX constants in v2u_defs.h * * Support: Linux, Windows, MacOS X */ #define IOCTL_VGA2USB_GRABFRAME IOCTL_VGA2USB_WR(10,V2U_GrabFrame) #define IOCTL_VGA2USB_GRABFRAME2 IOCTL_VGA2USB_WR(20,V2U_GrabFrame2) /* * IOCTL_VGA2USB_GETSN * * Support: Windows, Linux, MacOS X */ typedef struct ioctl_getsn { char sn[V2U_SN_BUFSIZ]; /* OUT serial number string */ } V2U_PACKED V2U_GetSN; #define IOCTL_VGA2USB_GETSN IOCTL_VGA2USB_R(7,V2U_GetSN) /* * IOCTL_VGA2USB_SENDPS2 (KVM2USB capable products only) * * Support: Windows, Linux, MacOS X */ #define IOCTL_VGA2USB_SENDPS2 IOCTL_VGA2USB_W(16,V2U_SendPS2) /* * IOCTL_VGA2USB_GET_PROPERTY * IOCTL_VGA2USB_SET_PROPERTY * * Get or set the value of the specified property. * * Support: Windows, Linux, MacOS X * Required driver version: 3.6.22 or later. */ #define IOCTL_VGA2USB_GET_PROPERTY IOCTL_VGA2USB_WR(18,V2U_Property) #define IOCTL_VGA2USB_SET_PROPERTY IOCTL_VGA2USB_W(19,V2U_Property) #endif /* _VGA2USB_IOCTL_H_ */
3,098
C
28.235849
84
0.656553
adegirmenci/HBL-ICEbot/epiphan/include/v2u_defs.h
/**************************************************************************** * * $Id: v2u_defs.h 22124 2013-05-11 19:36:54Z monich $ * * Copyright (C) 2003-2013 Epiphan Systems Inc. All rights reserved. * * VGA2USB common defines and types * ****************************************************************************/ #ifndef _VGA2USB_DEFS_H_ #define _VGA2USB_DEFS_H_ 1 /* Required system headers */ #if !defined(__KERNEL__) && !defined(__C51__) && !defined(__FX3__) # ifdef _WIN32 # include <windows.h> # include <winioctl.h> # else /* Unix */ # include <stdint.h> # include <sys/ioctl.h> # endif /* Unix */ #endif /* __KERNEL__ */ /* Structure packing */ #ifdef _WIN32 # include <pshpack1.h> #endif #ifndef V2U_PACKED # if defined(_WIN32) || defined(__C51__) # define V2U_PACKED # else # define V2U_PACKED __attribute__((packed)) # endif #endif /* Basic data types */ #ifdef _WIN32 typedef __int8 V2U_INT8; typedef unsigned __int8 V2U_UINT8; typedef __int16 V2U_INT16; typedef unsigned __int16 V2U_UINT16; typedef __int32 V2U_INT32; typedef unsigned __int32 V2U_UINT32; typedef __int64 V2U_INT64; typedef unsigned __int64 V2U_UINT64; #elif defined(__C51__) typedef char V2U_INT8; typedef unsigned char V2U_UINT8; typedef short V2U_INT16; typedef unsigned short V2U_UINT16; typedef long V2U_INT32; typedef unsigned long V2U_UINT32; /* V2U_INT64 and V2U_UINT64 should not be used on FX2 microcontroller */ typedef BYTE V2U_INT64[8]; typedef BYTE V2U_UINT64[8]; #else typedef int8_t V2U_INT8; typedef uint8_t V2U_UINT8; typedef int16_t V2U_INT16; typedef uint16_t V2U_UINT16; typedef int32_t V2U_INT32; typedef uint32_t V2U_UINT32; typedef int64_t V2U_INT64; typedef uint64_t V2U_UINT64; #endif typedef const char* V2U_STR; typedef V2U_UINT8 V2U_BYTE; typedef V2U_UINT16 V2U_UCS2; typedef V2U_INT32 V2U_BOOL; #if !defined(__C51__) typedef V2U_INT64 V2U_TIME; #endif #define V2U_TRUE 1 #define V2U_FALSE 0 typedef struct v2u_size { V2U_INT32 width; V2U_INT32 height; } V2U_PACKED V2USize; typedef struct v2u_rect { V2U_INT32 x; V2U_INT32 y; V2U_INT32 width; V2U_INT32 height; } V2U_PACKED V2URect; typedef struct v2u_str_ucs2 { V2U_UCS2* buffer; /* not necessarily NULL-terminated */ V2U_UINT32 len; /* string length, in characters */ V2U_UINT32 maxlen; /* buffer size, in characters */ } V2U_PACKED V2UStrUcs2; /* * V2U_VideoMode * * Video mode descriptor. * * Note that the vertical refresh rate is measured in milliHertz. * That is, the number 59900 represents 59.9 Hz. */ typedef struct ioctl_videomode { V2U_INT32 width; /* screen width, pixels */ V2U_INT32 height; /* screen height, pixels */ V2U_INT32 vfreq; /* vertical refresh rate, mHz */ } V2U_PACKED V2U_VideoMode, V2UVideoMode; /* * V2U_GrabParameters * * VGA capture parameters. * * Gain = Contrast * Offset = Brightness */ typedef struct ioctl_setparams { V2U_UINT32 flags; /* Validity flags for fields below */ /* When any of the fields below is used, */ /* corresponding V2U_FLAG_VALID_* flag is set */ /* otherwise the field is ignored */ V2U_INT32 hshift; /* Shifts image left (<0) or right(>0). */ /* Valid range depends on the video mode. */ /* Invalid values are rounded to the nearest */ /* valid value */ V2U_UINT8 phase; /* Pixel sampling phase, [0,31] */ V2U_UINT8 gain_r; /* Gain for the red channel, [0,255] */ V2U_UINT8 gain_g; /* Gain for the green channel, [0,255] */ V2U_UINT8 gain_b; /* Gain for the blue channel, [0,255] */ V2U_UINT8 offset_r; /* Offset for the red channel, [0,63] */ V2U_UINT8 offset_g; /* Offset for the green channel, [0,63] */ V2U_UINT8 offset_b; /* Offset for the blue channel, [0,63] */ V2U_UINT8 reserved; /* added for alignment, don't use */ V2U_INT32 vshift; /* Shifts image up or down */ /* Valid range depends on the video mode. */ /* Invalid values are rounded to the nearest */ /* valid value */ V2U_INT32 pllshift; /* Adjusts the PLL value */ V2U_UINT32 grab_flags; /* Sets grab_flags V2U_GRAB_* */ V2U_UINT32 grab_flags_mask; /* Marks which bits from grab_flags are used */ } V2U_PACKED V2U_GrabParameters, V2UGrabParameters; /* Indicates that hshift field is used */ #define V2U_FLAG_VALID_HSHIFT 0x0001 /* Indicates that phase field is used */ #define V2U_FLAG_VALID_PHASE 0x0002 /* Indicates that all gain_{rgb} and offset_{rgb} fields are used */ #define V2U_FLAG_VALID_OFFSETGAIN 0x0004 /* Indicates that vshift field is used */ #define V2U_FLAG_VALID_VSHIFT 0x0008 /* Indicates that pllshift field is used */ #define V2U_FLAG_VALID_PLLSHIFT 0x0010 /* Indicates that grab_flags and grab_flags_mask are used */ #define V2U_FLAG_VALID_GRABFLAGS 0x0020 /* Flags allowed in grab_flags and grab_flags_mask fields */ /* Grab image upside-down */ #define V2U_GRAB_BMP_BOTTOM_UP 0x10000 /* Sometimes 4:3 and wide modes with the same height are indistinguishable, * so this flag can force choosing wide mode */ #define V2U_GRAB_PREFER_WIDE_MODE 0x20000 /* We have no way to distinguish Component Video (YCrCb) from RGB+Sync-on-Green, * so this flag can force YCrCb->RGB conversion on input */ #define V2U_GRAB_YCRCB 0x40000 /* * The ranges below are obsolete. They depend on the frame grabber model * as well as the video mode. Use V2UKey_AdjustmentsRange property to get * the ranges that are valid for the parcular frame grabber and current * video mode. */ #define V2U_MIN_PHASE 0 #define V2U_MAX_PHASE 31 #define V2U_MIN_GAIN 0 #define V2U_MAX_GAIN 255 #define V2U_MIN_OFFSET 0 #define V2U_MAX_OFFSET 63 /* * V2U_SendPS2 * * PS/2 packet descriptor. */ typedef struct ioctl_sendps2 { V2U_INT16 addr; V2U_INT16 len; V2U_BYTE buf[64]; } V2U_PACKED V2U_SendPS2, V2USendPS2; #define V2U_PS2ADDR_KEYBOARD 0x01 #define V2U_PS2ADDR_MOUSE 0x02 /* * Serial number length. */ #define V2U_SN_BUFSIZ 32 /* * Product type. */ typedef enum v2u_product_type { V2UProductOther, V2UProductVGA2USB, V2UProductKVM2USB, V2UProductDVI2USB, V2UProductVGA2USBPro, V2UProductVGA2USBLR, V2UProductDVI2USBSolo, V2UProductDVI2USBDuo, V2UProductKVM2USBPro, V2UProductKVM2USBLR, V2UProductDVI2USBRespin, V2UProductVGA2USBHR, V2UProductVGA2USBLRRespin, V2UProductVGA2USBHRRespin, V2UProductVGA2USBProRespin, V2UProductVGA2FIFO, V2UProductKVM2FIFO, V2UProductDVI2FIFO, V2UProductDVI2Davinci1, V2UProductVGA2PCI, V2UProductGioconda, V2UProductDVI2PCI, V2UProductKVM2USBLRRespin, V2UProductHDMI2PCI, V2UProductDVI2PCIStd, V2UProductDVI2USB3, V2UProductDVI2PCIGen2, V2UProductCount /* Number of known product types */ } V2UProductType; /* * Resize algorithms. */ typedef enum v2u_scale_mode { V2UScaleNone, /* No scaling */ V2UScaleModeNearestNeighbor, /* Nearest neighbor algorithm */ V2UScaleModeWeightedAverage, /* Weighted average algorithm */ V2UScaleModeFastBilinear, /* Fast bilinear */ V2UScaleModeBilinear, /* Bilinear */ V2UScaleModeBicubic, /* Bicubic */ V2UScaleModeExperimental, /* Experimental */ V2UScaleModePoint, /* Nearest neighbour# 2 */ V2UScaleModeArea, /* Weighted average */ V2UScaleModeBicubLin, /* Luma bicubic, chroma bilinear */ V2UScaleModeSinc, /* Sinc */ V2UScaleModeLanczos, /* Lanczos */ V2UScaleModeSpline, /* Natural bicubic spline */ V2UScaleModeHardware, /* Scale in hardware, if supported */ V2UScaleModeCount /* Number of valid modes */ } V2UScaleMode; /* Macros to translate V2UScaleMode to capture flags and back */ #define V2U_SCALE_MODE_TO_FLAGS(_m) \ (((_m) << 16) & V2U_GRABFRAME_SCALE_MASK) #define V2U_SCALE_FLAGS_TO_MODE(_f) \ ((V2UScaleMode)(((_f) & V2U_GRABFRAME_SCALE_MASK) >> 16)) typedef enum v2u_rotation_mode { V2URotationNone, /* V2U_GRABFRAME_ROTATION_NONE */ V2URotationLeft90, /* V2U_GRABFRAME_ROTATION_LEFT90 */ V2URotationRight90, /* V2U_GRABFRAME_ROTATION_RIGHT90 */ V2URotation180, /* V2U_GRABFRAME_ROTATION_180 */ V2URotationCount /* Number of valid rotation types */ } V2URotationMode; /* Macros to translate V2URotationMode to capture flags and back */ #define V2U_ROTATION_MODE_TO_FLAGS(_m) \ (((_m) << 20) & V2U_GRABFRAME_ROTATION_MASK) #define V2U_ROTATION_FLAGS_TO_MODE(_f) \ ((V2URotationMode)(((_f) & V2U_GRABFRAME_ROTATION_MASK) >> 20)) typedef struct v2u_adjustment_range { V2U_UINT32 flags; V2U_UINT32 valid_flags; V2U_INT16 hshift_min; V2U_INT16 hshift_max; V2U_INT16 phase_min; V2U_INT16 phase_max; V2U_INT16 offset_min; V2U_INT16 offset_max; V2U_INT16 gain_min; V2U_INT16 gain_max; V2U_INT16 vshift_min; V2U_INT16 vshift_max; V2U_INT16 pll_min; V2U_INT16 pll_max; } V2U_PACKED V2UAdjRange; /* Video mode descriptor */ typedef struct vesa_videomode { V2U_UINT32 VerFrequency; /* mHz */ V2U_UINT16 HorAddrTime; /* pixels */ V2U_UINT16 HorFrontPorch; /* pixels */ V2U_UINT16 HorSyncTime; /* pixels */ V2U_UINT16 HorBackPorch; /* pixels */ V2U_UINT16 VerAddrTime; /* lines */ V2U_UINT16 VerFrontPorch; /* lines */ V2U_UINT16 VerSyncTime; /* lines */ V2U_UINT16 VerBackPorch; /* lines */ V2U_UINT32 Type; /* flags, see below */ #define VIDEOMODE_TYPE_VALID 0x01 #define VIDEOMODE_TYPE_ENABLED 0x02 #define VIDEOMODE_TYPE_SUPPORTED 0x04 #define VIDEOMODE_TYPE_DUALLINK 0x08 #define VIDEOMODE_TYPE_DIGITAL 0x10 #define VIDEOMODE_TYPE_INTERLACED 0x20 #define VIDEOMODE_TYPE_HSYNCPOSITIVE 0x40 #define VIDEOMODE_TYPE_VSYNCPOSITIVE 0x80 #define VIDEOMODE_TYPE_TOPFIELDFIRST 0x100 } V2U_PACKED V2UVideoModeDescr; typedef const V2UVideoModeDescr* V2UVideoModeDescrCPtr; /* Maximum number of custom videomodes */ #define V2U_CUSTOM_VIDEOMODE_COUNT 8 /* * The first 8 (V2U_CUSTOM_VIDEOMODE_COUNT) entries in the video mode table * are reserved for custom video modes. The remaining entries are standard * video modes. */ typedef struct custom_videomode { V2U_INT32 idx; V2UVideoModeDescr vesa_mode; } V2U_PACKED V2UVGAMode; typedef struct v2u_version { V2U_INT32 major; V2U_INT32 minor; V2U_INT32 micro; V2U_INT32 nano; } V2U_PACKED V2UVersion; /* * Property keys and types */ /* V2UKey_DirectShowFlags */ #define V2U_DSHOW_LIMIT_FPS 0x200 #define V2U_DSHOW_FLIP_VERTICALLY 0x400 #define V2U_DSHOW_FIX_FPS 0x800 /* V2UKey_DShowCompatMode */ /* V2UKey_DShowActiveCompatMode */ typedef enum v2u_dshow_compat_mode { V2UDShowCompatMode_Invalid = -1, /* Invalid value */ V2UDShowCompatMode_Auto, /* Automatic action (default) */ V2UDShowCompatMode_None, /* No tweaks */ V2UDShowCompatMode_Skype, /* Skype compatiblity */ V2UDShowCompatMode_WebEx, /* WebEx compatibility */ V2UDShowCompatMode_Count /* Number of valid values */ } V2UDShowCompatMode; /* Type of video input (V2UKey_InputSignalType) */ #define V2U_INPUT_NONE 0x00 #define V2U_INPUT_ANALOG 0x01 #define V2U_INPUT_DIGITAL 0x02 #define V2U_INPUT_SOG 0x04 #define V2U_INPUT_COMPOSITE 0x08 /* V2UKey_DigitalModeDetect */ typedef enum v2u_digital_mode_detect { V2UDigitalMode_AutoDetect, /* Automatic detection (default) */ V2UDigitalMode_SingleLink, /* Force single link */ V2UDigitalMode_DualLink, /* Force dual link */ V2UDigitalMode_Count /* Not a valid value */ } V2UDigitalModeDetect; /* V2UKey_NoiseFilter */ typedef enum v2u_noise_filter { V2UNoiseFilter_Auto, /* Automatic configuration (default) */ V2UNoiseFilter_None, /* Disable noise filter */ V2UNoiseFilter_Low, /* Good for Apple */ V2UNoiseFilter_Moderate, V2UNoiseFilter_High, V2UNoiseFilter_Extreme, /* Good for black and white */ V2UNoiseFilter_Count /* Not a valid value */ } V2UNoiseFilter; /* V2UKey_BusType */ typedef enum v2u_bus_type { V2UBusType_Other, /* Doesn't fall into any known category */ V2UBusType_USB, /* USB bus */ V2UBusType_PCI, /* PCI (Express) bus */ V2UBusType_VPFE, /* Davinci platform bus */ V2UBusType_Count /* Not a valid value */ } V2UBusType; /* H/VSync threshold values */ #define V2U_MIN_SYNC_THRESHOLD 0 #define V2U_MAX_SYNC_THRESHOLD 255 #define V2U_DEFAULT_SYNC_THRESHOLD 128 /* ResetADC options */ #define ResetADC_Reset 0x01 #define ResetADC_PowerDown 0x02 #define ResetADC_PowerUp 0x03 /* Divide the value of V2UKey_DirectShowMaxFps by 100 to get the fps value */ #define V2U_FPS_DENOMINATOR 100 /* Device capabilities for V2UKey_DeviceCaps */ #define V2U_CAPS_VGA_CAPTURE 0x0001 /* Captures VGA signal */ #define V2U_CAPS_DVI_CAPTURE 0x0002 /* Captures DVI single-link */ #define V2U_CAPS_DVI_DUAL_LINK 0x0004 /* Captures DVI dual-link */ #define V2U_CAPS_KVM 0x0008 /* KVM functionality */ #define V2U_CAPS_EDID 0x0010 /* Programmable EDID */ #define V2U_CAPS_HW_COMPRESSION 0x0020 /* On-board compression */ #define V2U_CAPS_SYNC_THRESHOLD 0x0040 /* Adjustable sync thresholds */ #define V2U_CAPS_HW_SCALE 0x0080 /* Hardware scale */ #define V2U_CAPS_SIGNATURE 0x0100 /* Signed hardware */ #define V2U_CAPS_SD_VIDEO 0x0200 /* Captures SD video */ #define V2U_CAPS_MULTIGRAB 0x0400 /* Several grabbers on board */ #define V2U_CAPS_AUDIO_CAPTURE 0x0800 /* Captures audio */ /* V2UKey_VideoFormat. For grabbers with V2U_CAPS_SD_VIDEO capability */ typedef enum { V2UVideoFormat_Unknown = -1, V2UVideoFormat_SVideo, V2UVideoFormat_Composite, V2UVideoFormat_Count } V2UVideoFormat; typedef enum v2u_property_access { V2UPropAccess_NO, /* unaccesible */ V2UPropAccess_RO, /* Read only */ V2UPropAccess_RW, /* Read/Write */ V2UPropAccess_WO, /* Write only */ } V2UPropertyAccess; typedef enum v2u_property_type { V2UPropType_Invalid = -1, /* Not a valid type */ V2UPropType_Int8, /* int8 - First valid type (zero) */ V2UPropType_Int16, /* int16 */ V2UPropType_Int32, /* int32 - Also used for enums */ V2UPropType_Boolean, /* boolean */ V2UPropType_Size, /* size */ V2UPropType_Rect, /* rect */ V2UPropType_Version, /* version */ V2UPropType_Binary, /* blob */ V2UPropType_EDID, /* edid */ V2UPropType_AdjustRange, /* adj_range */ V2UPropType_VGAMode, /* vgamode */ V2UPropType_String, /* str */ V2UPropType_StrUcs2, /* wstr */ V2UPropType_Uint8, /* uint8 */ V2UPropType_Uint16, /* uint16 */ V2UPropType_Uint32, /* uint32 */ V2UPropType_Reserved, /* not being used */ V2UPropType_UserData, /* userdata */ V2UPropType_Int64, /* int64 */ V2UPropType_Uint64, /* uint64 */ V2UPropType_VESAMode, /* vesa_mode */ V2UPropType_String2, /* str2 */ V2UPropType_Count /* Number of valid types */ } V2UPropertyType; #define V2UPropType_Enum V2UPropType_Int32 #define V2UKey_UsbProductID V2UKey_ProductID #define V2U_PROPERTY_LIST(property) \ property( V2UKey_ProductID, \ "Product id", \ V2UPropType_Int16, \ V2UPropAccess_RO) \ property( V2UKey_ProductType, \ "Product type", \ V2UPropType_Enum, \ V2UPropAccess_RO) \ property( V2UKey_DirectShowFixRes, /* Windows only */\ "DS Fix Resolution", \ V2UPropType_Size, \ V2UPropAccess_RW) \ property( V2UKey_DirectShowFlags, /* Windows only */\ "DS Flags", \ V2UPropType_Int32, \ V2UPropAccess_RW) \ property( V2UKey_DirectShowDefaultBmp, /* Windows only */\ "DS Default BMP", \ V2UPropType_StrUcs2, \ V2UPropAccess_RW) \ property( V2UKey_ModeMeasurmentsDump, \ "Mode Measurments dump", \ V2UPropType_Binary, \ V2UPropAccess_RO) \ property( V2UKey_ResetADC, /* Not really a property */\ "Reset ADC", \ V2UPropType_Int32, \ V2UPropAccess_WO) \ property( V2UKey_DirectShowScaleMode, /* Windows only */\ "DirectShow Scale Mode", \ V2UPropType_Enum, \ V2UPropAccess_RW) \ property( V2UKey_HardwareCompression, \ "Hardware Compression", \ V2UPropType_Boolean, \ V2UPropAccess_RO) \ property( V2UKey_AdjustmentsRange, \ "Adjustments Range", \ V2UPropType_AdjustRange, \ V2UPropAccess_RO) \ property( V2UKey_Version, \ "Version", \ V2UPropType_Version, \ V2UPropAccess_RO) \ property( V2UKey_EDID, \ "EDID", \ V2UPropType_EDID, \ V2UPropAccess_RW) \ property( V2UKey_DirectShowMaxFps, /* Windows only */\ "DS Max fps", \ V2UPropType_Int32, \ V2UPropAccess_RW) \ property( V2UKey_KVMCapable, \ "KVM capable", \ V2UPropType_Boolean, \ V2UPropAccess_RO) \ property( V2UKey_VGAMode, \ "VGA mode", \ V2UPropType_VGAMode, \ V2UPropAccess_RW) \ property( V2UKey_CurrentVGAMode, /* Since 3.24.6 */\ "Current VGA mode", \ V2UPropType_VESAMode, \ V2UPropAccess_RO) \ property( V2UKey_ModeMeasureInterval, \ "Mode Measure interval", \ V2UPropType_Int32, \ V2UPropAccess_RW) \ property( V2UKey_EDIDSupport, \ "EDID support", \ V2UPropType_Boolean, \ V2UPropAccess_RO) \ property( V2UKey_ProductName, \ "Product name", \ V2UPropType_String, \ V2UPropAccess_RO) \ property( V2UKey_TuneInterval, /* ms */\ "Tune interval", \ V2UPropType_Uint32, \ V2UPropAccess_RW) \ property( V2UKey_UserData, \ "User data", \ V2UPropType_UserData, \ V2UPropAccess_RW) \ property( V2UKey_SerialNumber, \ "Serial number", \ V2UPropType_String, \ V2UPropAccess_RO) \ property( V2UKey_InputSignalType, /* Since 3.23.7.3 */\ "Input signal type", \ V2UPropType_Uint32, \ V2UPropAccess_RO) \ property( V2UKey_DigitalModeDetect, /* Since 3.24.5 */\ "Digital mode detection", \ V2UPropType_Enum, \ V2UPropAccess_RW) \ property( V2UKey_NoiseFilter, /* Since 3.24.6 */\ "Noise filter", \ V2UPropType_Enum, \ V2UPropAccess_RW) \ property( V2UKey_HSyncThreshold, /* Since 3.24.6 */\ "Hsync threshold", \ V2UPropType_Uint8, \ V2UPropAccess_RW) \ property( V2UKey_VSyncThreshold, /* Since 3.24.6 */\ "Vsync threshold", \ V2UPropType_Uint8, \ V2UPropAccess_RW) \ property( V2UKey_DeviceCaps, /* Since 3.24.6 */\ "Device capabilities", \ V2UPropType_Uint32, \ V2UPropAccess_RO) \ property( V2UKey_DirectShowDefaultBmp2, /* Since 3.24.9.4, Windows */\ "DS Default BMP", \ V2UPropType_String2, \ V2UPropAccess_RW) \ property( V2UKey_BusType, /* Since 3.24.9.5 */\ "Grabber bus type", \ V2UPropType_Enum, \ V2UPropAccess_RO) \ property( V2UKey_GrabberId, /* Since 3.27.4 */\ "Grabber ID", \ V2UPropType_String, \ V2UPropAccess_RO) \ property( V2UKey_VideoFormat, /* Since 3.27.4 */\ "Video input format", \ V2UPropType_Enum, \ V2UPropAccess_RW) \ property( V2UKey_DShowCompatMode, /* Since 3.27.10, Windows */\ "DShow compatiblity mode", \ V2UPropType_Enum, \ V2UPropAccess_RW) \ property( V2UKey_DShowActiveCompatMode, /* Since 3.27.10, Windows */\ "Active compatiblity mode", \ V2UPropType_Enum, \ V2UPropAccess_RO) \ property( V2UKey_EEDID, /* Since 3.27.14.6 */\ "E-EDID", \ V2UPropType_Binary, \ V2UPropAccess_RW) /* Define V2UPropertyKey enum */ typedef enum v2u_property_key { #define V2U_PROPERTY_KEY_ENUM(key,name,type,access) key, V2U_PROPERTY_LIST(V2U_PROPERTY_KEY_ENUM) #undef V2U_PROPERTY_KEY_ENUM V2UKey_Count /* Number of known properties */ } V2UPropertyKey; #define V2U_USERDATA_LEN 8 typedef union v2u_property_value { V2U_INT8 int8; V2U_UINT8 uint8; V2U_INT16 int16; V2U_UINT16 uint16; V2U_INT32 int32; V2U_UINT32 uint32; V2U_INT64 int64; V2U_UINT64 uint64; V2U_BOOL boolean; V2UProductType product_type; V2USize size; V2URect rect; V2UStrUcs2 wstr; V2UAdjRange adj_range; V2UVersion version; V2UVGAMode vgamode; V2UVideoModeDescr vesa_mode; char str[256]; V2U_UCS2 str2[128]; V2U_UINT8 edid[128]; V2U_UINT8 blob[256]; V2U_UINT8 userdata[V2U_USERDATA_LEN]; } V2UPropertyValue; typedef struct v2u_ioctl_property { V2UPropertyKey key; /* IN property key */ V2UPropertyValue value; /* IN/OUT property value */ } V2U_PACKED V2U_Property, V2UProperty; /* * V2U_GrabFrame * * Frame buffer. */ typedef struct ioctl_grabframe { #define V2U_GrabFrame_Fields(pointer) \ pointer pixbuf; /* IN should be filled by user process */\ V2U_UINT32 pixbuflen; /* IN should be filled by user process */\ V2U_INT32 width; /* OUT width in pixels */\ V2U_INT32 height; /* OUT height in pixels */\ V2U_UINT32 bpp; /* IN pixel format */ V2U_GrabFrame_Fields(void*) } V2U_PACKED V2U_GrabFrame, V2UGrabFrame; typedef struct ioctl_grabframe2 { #define V2U_GrabFrame2_Fields(pointer) \ pointer pixbuf; /* IN should be filled by user process */\ V2U_UINT32 pixbuflen; /* IN should be filled by user process */\ V2U_UINT32 palette; /* IN pixel format */\ V2URect crop; /* IN/OUT cropping area; all zeros = full frame */\ V2U_VideoMode mode; /* OUT VGA mode */\ V2U_UINT32 imagelen; /* OUT size of the image stored in pixbuf */\ V2U_INT32 retcode; /* OUT return/error code */ V2U_GrabFrame2_Fields(void*) } V2U_PACKED V2U_GrabFrame2, V2UGrabFrame2; /* * Error codes */ #define V2UERROR_OK 0 /* Success */ #define V2UERROR_FAULT 1 /* Unspecified error */ #define V2UERROR_INVALARG 2 /* Invalid argument */ #define V2UERROR_SMALLBUF 3 /* Insufficient buffer size */ #define V2UERROR_OUTOFMEMORY 4 /* Out of memory */ #define V2UERROR_NOSIGNAL 5 /* No signal detected */ #define V2UERROR_UNSUPPORTED 6 /* Unsupported video mode */ #define V2UERROR_TIMEOUT 7 /* grab timeout */ /* * The following flags can be OR'ed with V2U_GrabFrame::bpp or * V2U_GrabFrame2::palette field. The flags are preserved on return. * * V2U_GRABFRAME_BOTTOM_UP_FLAG * This flag requests the bitmap data to be sent in bottom-up format. * By default, the bitmap data are stored in the top-down order. * * V2U_GRABFRAME_KEYFRAME_FLAG * This flag only makes sense when the data are requested in compressed * format (V2U_GRABFRAME_FORMAT_CRGB24 and such). If this flag is set, the * driver updates and returns a full frame (i.e. keyframe). */ #define V2U_GRABFRAME_RESERVED 0x0f000000 /* These are ignored */ #define V2U_GRABFRAME_FLAGS_MASK 0xf0000000 /* Bits reserved for flags */ #define V2U_GRABFRAME_BOTTOM_UP_FLAG 0x80000000 /* Invert order of lines */ #define V2U_GRABFRAME_KEYFRAME_FLAG 0x40000000 /* Full frame is requested */ #define V2U_GRABFRAME_ADDR_IS_PHYS 0x20000000 /* Buffer addr is physical */ #define V2U_GRABFRAME_DEINTERLACE 0x10000000 /* De-interlace image, if it is interlaced */ /* * Image rotation mode * * V2U_GRABFRAME_ROTATION_NONE * No rotation, image is grabbed in its original orientation. * * V2U_GRABFRAME_ROTATION_LEFT90 * Grab the image rotated 90 degrees to the left with respect * to its original orientation. * * V2U_GRABFRAME_ROTATION_RIGHT90 * Grab the image rotated 90 degrees to the right with respect * to its original orientation. * * V2U_GRABFRAME_ROTATION_180 * Grab the image rotated 180 degrees with respect to its * original orientation. */ #define V2U_GRABFRAME_ROTATION_MASK 0x00300000 /* Bits reserved for mode */ #define V2U_GRABFRAME_ROTATION_NONE 0x00000000 /* No rotation */ #define V2U_GRABFRAME_ROTATION_LEFT90 0x00100000 /* 90 degrees to the left */ #define V2U_GRABFRAME_ROTATION_RIGHT90 0x00200000 /* 90 degrees to the right */ #define V2U_GRABFRAME_ROTATION_180 0x00300000 /* Rotation 180 degrees */ /* If a valid algoruthm code is set, the image will be scaled image to * width/height in V2U_GrabFrame or crop.width/crop.height in V2U_GrabFrame2. * If no bits in V2U_GRABFRAME_SCALE_MASK are set, no scaling is performed. * If an unknown algorithm code is specified, a default one will be used. * Scaling works for the following capture formats: * * V2U_GRABFRAME_FORMAT_Y8 * V2U_GRABFRAME_FORMAT_RGB4 * V2U_GRABFRAME_FORMAT_RGB8 * V2U_GRABFRAME_FORMAT_RGB16 * V2U_GRABFRAME_FORMAT_BGR16 * V2U_GRABFRAME_FORMAT_RGB24 * V2U_GRABFRAME_FORMAT_ARGB32 * V2U_GRABFRAME_FORMAT_BGR24 * V2U_GRABFRAME_FORMAT_YUY2 * V2U_GRABFRAME_FORMAT_2VUY * V2U_GRABFRAME_FORMAT_YV12 * V2U_GRABFRAME_FORMAT_I420 * V2U_GRABFRAME_FORMAT_NV12 * * Scaling is available since version 3.10.9 * * Note that V2U_GRABFRAME_SCALE_AVERAGE scale mode is EXPERIMENTAL and * currently only works for RGB24 and BGR24 images. */ #define V2U_GRABFRAME_SCALE_MASK 0x000F0000 /* Scale algorithm mask */ #define V2U_GRABFRAME_SCALE_NEAREST 0x00010000 /* Nearest neighbour */ #define V2U_GRABFRAME_SCALE_AVERAGE 0x00020000 /* Weighted average */ #define V2U_GRABFRAME_SCALE_FAST_BILINEAR 0x00030000 /* Fast bilinear */ #define V2U_GRABFRAME_SCALE_BILINEAR 0x00040000 /* Bilinear */ #define V2U_GRABFRAME_SCALE_BICUBIC 0x00050000 /* Bicubic */ #define V2U_GRABFRAME_SCALE_EXPERIMENTAL 0x00060000 /* Experimental */ #define V2U_GRABFRAME_SCALE_POINT 0x00070000 /* Nearest neighbour */ #define V2U_GRABFRAME_SCALE_AREA 0x00080000 /* Weighted average */ #define V2U_GRABFRAME_SCALE_BICUBLIN 0x00090000 /* Lum bicub,Chr bilinear*/ #define V2U_GRABFRAME_SCALE_SINC 0x000A0000 /* Sinc */ #define V2U_GRABFRAME_SCALE_LANCZOS 0x000B0000 /* Lanczos */ #define V2U_GRABFRAME_SCALE_SPLINE 0x000C0000 /* Natural bicubic spline*/ #define V2U_GRABFRAME_SCALE_HW 0x000D0000 /* Hardware provided */ #define V2U_GRABFRAME_SCALE_MAX_MODE 0x000D0000 /* Maximum valid mode */ /* Bits that define image format */ #define V2U_GRABFRAME_FORMAT_MASK 0x0000ffff /* Image format mask */ #define V2U_GRABFRAME_FORMAT_RGB_MASK 0x0000001f /* Mask for RGB formats */ #define V2U_GRABFRAME_FORMAT_RGB4 0x00000004 #define V2U_GRABFRAME_FORMAT_RGB8 0x00000008 /* R2:G3:B3 */ #define V2U_GRABFRAME_FORMAT_RGB16 0x00000010 #define V2U_GRABFRAME_FORMAT_RGB24 0x00000018 #define V2U_GRABFRAME_FORMAT_YUY2 0x00000100 /* Same as YUV422 */ #define V2U_GRABFRAME_FORMAT_YV12 0x00000200 #define V2U_GRABFRAME_FORMAT_2VUY 0x00000300 #define V2U_GRABFRAME_FORMAT_BGR16 0x00000400 #define V2U_GRABFRAME_FORMAT_Y8 0x00000500 #define V2U_GRABFRAME_FORMAT_CRGB24 0x00000600 /* Compressed RGB24 */ #define V2U_GRABFRAME_FORMAT_CYUY2 0x00000700 /* Compressed YUY2 */ #define V2U_GRABFRAME_FORMAT_BGR24 0x00000800 #define V2U_GRABFRAME_FORMAT_CBGR24 0x00000900 /* Compressed BGR24 */ #define V2U_GRABFRAME_FORMAT_I420 0x00000A00 /* Same as YUV420P */ #define V2U_GRABFRAME_FORMAT_ARGB32 0x00000B00 #define V2U_GRABFRAME_FORMAT_NV12 0x00000C00 #define V2U_GRABFRAME_FORMAT_C2VUY 0x00000D00 /* Compressed 2VUY */ /* Old flag names, defined here for backward compatibility */ #define V2U_GRABFRAME_PALETTE_MASK V2U_GRABFRAME_FORMAT_MASK #define V2U_GRABFRAME_PALETTE_RGB_MASK V2U_GRABFRAME_FORMAT_RGB_MASK #define V2U_GRABFRAME_PALETTE_RGB4 V2U_GRABFRAME_FORMAT_RGB4 #define V2U_GRABFRAME_PALETTE_RGB8 V2U_GRABFRAME_FORMAT_RGB8 #define V2U_GRABFRAME_PALETTE_RGB16 V2U_GRABFRAME_FORMAT_RGB16 #define V2U_GRABFRAME_PALETTE_RGB24 V2U_GRABFRAME_FORMAT_RGB24 #define V2U_GRABFRAME_PALETTE_ARGB32 V2U_GRABFRAME_FORMAT_ARGB32 #define V2U_GRABFRAME_PALETTE_YUY2 V2U_GRABFRAME_FORMAT_YUY2 #define V2U_GRABFRAME_PALETTE_YV12 V2U_GRABFRAME_FORMAT_YV12 #define V2U_GRABFRAME_PALETTE_I420 V2U_GRABFRAME_FORMAT_I420 #define V2U_GRABFRAME_PALETTE_2VUY V2U_GRABFRAME_FORMAT_2VUY #define V2U_GRABFRAME_PALETTE_BGR16 V2U_GRABFRAME_FORMAT_BGR16 #define V2U_GRABFRAME_PALETTE_Y8 V2U_GRABFRAME_FORMAT_Y8 #define V2U_GRABFRAME_PALETTE_BGR24 V2U_GRABFRAME_FORMAT_BGR24 #define V2U_GRABFRAME_PALETTE_NV12 V2U_GRABFRAME_FORMAT_NV12 #define V2U_GRABFRAME_FORMAT(p) ((p) & V2U_GRABFRAME_FORMAT_MASK) /* Macro to determine bpp (bits per pixel) for particular grab format */ #define V2UPALETTE_2_BPP(p) \ (((p) & V2U_GRABFRAME_FORMAT_RGB_MASK) ? \ ((V2U_UINT8)((p) & V2U_GRABFRAME_FORMAT_RGB_MASK)) : \ (((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_BGR16) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_YUY2) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_2VUY) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CYUY2) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_C2VUY)) ? 16 :\ (((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_YV12) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_NV12) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_I420)) ? 12 : \ (((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_Y8) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_RGB8)) ? 8 : \ (((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CRGB24) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CBGR24) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_BGR24)) ? 24 : \ ((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_ARGB32) ? 32 : 0)))))) /* Macro to determine whether frame data is compressed */ #define V2UPALETTE_COMPRESSED(p) \ ((V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CRGB24) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CBGR24) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_CYUY2) || \ (V2U_GRABFRAME_FORMAT(p) == V2U_GRABFRAME_FORMAT_C2VUY)) /* * Restore previous packing */ #ifdef _WIN32 # include <poppack.h> #endif #endif /* _VGA2USB_DEFS_H_ */
34,431
C
39.603774
96
0.596178
adegirmenci/HBL-ICEbot/epiphan/include/v2u_compression.h
/**************************************************************************** * * $Id: v2u_compression.h 8063 2009-11-19 23:11:46Z rekjanov $ * * Copyright (C) 2007-2009 Epiphan Systems Inc. All rights reserved. * * Defines and implements decompression library for EPIPHAN VGA2USB compression * ****************************************************************************/ #ifndef _VGA2USB_COMPRESSION_H_ #define _VGA2USB_COMPRESSION_H_ 1 #include "v2u_defs.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef V2UDEC_API #ifdef _WIN32 #ifdef V2UDEC_EXPORTS #define V2UDEC_API __declspec(dllexport) #else #define V2UDEC_API __declspec(dllimport) #endif #else #define V2UDEC_API #endif #endif /** * Error codes used as a part of compression SDK */ #ifndef EPROTO # define EPROTO 105 #endif #ifndef ENOSR # define ENOSR 106 #endif #ifndef EOK # define EOK 0 #endif /**************************************************************************** * * * Public interface to the decompression engine * * ****************************************************************************/ /** * Version of the library and files generatated by the compression algorithm */ #define V2U_COMPRESSION_LIB_VERSION 0x00000100 /** * Context of the files sequence * Compression algorithm internaly keeps key frame. Therefore to decode * sequence of frames common context must be created and used during decoding * of consiquently captured frames */ typedef struct v2udec_ctx* V2U_DECOMPRESSION_LIB_CONTEXT; V2UDEC_API V2U_DECOMPRESSION_LIB_CONTEXT v2udec_init_context( void ); V2UDEC_API void v2udec_deinit_context( V2U_DECOMPRESSION_LIB_CONTEXT uctx ); /** * Functions to obtain information about the compressed frame */ /** * Minimum header size. * Useful when reading in bytestream. After receiving this number of bytes * additional information about the frame can be obtained from * v2udec_get_framelen() et al. * This value can be different for different versions of V2U libraries. */ V2UDEC_API V2U_UINT32 v2udec_get_minheaderlen(V2U_DECOMPRESSION_LIB_CONTEXT uctx); /** * Actual header size. * Add this to v2udec_get_framelen() to obtain required buffer size to * hold one compressed frame. * @return 0 on error. */ V2UDEC_API V2U_UINT32 v2udec_get_headerlen( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen); /** Timestamp (in milliseconds) of the frame in the framebuf */ V2UDEC_API V2U_TIME v2udec_get_timestamp( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen); // Length of the single compressed frame in the framebuf (excluding compression // header) V2UDEC_API V2U_UINT32 v2udec_get_framelen( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen); // Size of the buffer required to decompress the frame in the framebuf // (function of frame resolution and palette) V2UDEC_API int v2udec_get_decompressed_framelen( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen); // Palette of the frame in the framebuf (currently RGB24 or YUY2) V2UDEC_API V2U_UINT32 v2udec_get_palette( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen); // Palette of the frame in the framebuf before decompression V2UDEC_API V2U_UINT32 v2udec_get_cpalette( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen); // Set desired palette for the frame in the framebuf V2UDEC_API V2U_BOOL v2udec_set_palette( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen, V2U_UINT32 palette); // Resolution of the frame in the framebuf V2UDEC_API void v2udec_get_frameres( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen, V2URect * rect); // Video mode of the frame in the framebuf, // that is width and height before cropping // and vertical refresh rate. V2UDEC_API void v2udec_get_videomode( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen, V2U_VideoMode * vmode); // Keyframe if not 0 V2UDEC_API int v2udec_is_keyframe( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen); // Ordered if not 0 V2UDEC_API int v2udec_is_ordered( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen); /** * Decompression functions */ V2UDEC_API int v2udec_decompress_frame( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen, unsigned char * bufout, // user-allocated buffer for decompressed frame int bufoutlen); V2UDEC_API int v2udec_decompress_frame2( V2U_DECOMPRESSION_LIB_CONTEXT uctx, const unsigned char * framebuf, int framebuflen, unsigned char * bufout, int bufoutlen, const unsigned char *prev_frame, int prev_frame_len, int just_key_data); #ifdef __cplusplus } /* end of extern "C" */ #endif /* __cplusplus */ #endif //_VGA2USB_COMPRESSION_H_
5,192
C
24.455882
79
0.684707
adegirmenci/HBL-ICEbot/epiphan/include/v2u_id.h
/**************************************************************************** * * $Id: v2u_id.h 21957 2013-04-29 19:18:29Z monich $ * * Copyright (C) 2003-2013 Epiphan Systems Inc. All rights reserved. * * Defines vendor and product ids of VGA2USB hardware. Included by the * driver and by the user level code. * ****************************************************************************/ #ifndef _VGA2USB_ID_H_ #define _VGA2USB_ID_H_ 1 /** * Vendor and product ids. * * NOTE: if you are adding a new product ID, don't forget to update * V2U_PRODUCT_MAP macro below. */ #define EPIPHAN_VENDORID 0x5555 #define VGA2USB_VENDORID EPIPHAN_VENDORID #define VGA2USB_PRODID_VGA2USB 0x1110 #define VGA2USB_PRODID_KVM2USB 0x1120 #define VGA2USB_PRODID_DVI2USB 0x2222 #define VGA2USB_PRODID_VGA2USB_LR 0x3340 #define VGA2USB_PRODID_VGA2USB_HR 0x3332 #define VGA2USB_PRODID_VGA2USB_PRO 0x3333 #define VGA2USB_PRODID_VGA2USB_LR_RESPIN 0x3382 #define VGA2USB_PRODID_KVM2USB_LR_RESPIN 0x3383 #define VGA2USB_PRODID_VGA2USB_HR_RESPIN 0x3392 #define VGA2USB_PRODID_VGA2USB_PRO_RESPIN 0x33A2 #define VGA2USB_PRODID_DVI2USB_RESPIN 0x3380 #define VGA2USB_PRODID_KVM2USB_LR 0x3344 #define VGA2USB_PRODID_KVM2USB_PRO 0x3337 #define VGA2USB_PRODID_DVI2USB_SOLO 0x3411 #define VGA2USB_PRODID_DVI2USB_DUO 0x3422 #define VGA2USB_PRODID_DVI2USB3 0x3500 #define VGA2USB_PRODID_VGA2FIFO 0x4000 #define VGA2USB_PRODID_KVM2FIFO 0x4004 #define VGA2USB_PRODID_DVI2FIFO 0x4080 #define VGA2USB_PRODID_DAVINCI1 0x5000 #define VGA2USB_PRODID_VGA2PCI 0x3A00 #define VGA2USB_PRODID_DVI2PCI 0x3B00 #define VGA2USB_PRODID_DVI2PCI_STD 0x3B10 #define VGA2USB_PRODID_HDMI2PCI 0x3C00 #define VGA2USB_PRODID_DVI2PCI2 0x3D00 #define VGA2USB_PRODID_GIOCONDA 0x5100 #define VGA2USB_PRODID_ORNITHOPTER 0x5200 /** * Macros for detecting VGA2USB hardware */ #define VGA2USB_IS_VGA2USB(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_KVM2USB(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_KVM2USB && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_DVI2USB(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_DVI2USB && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_VGA2USB_PRO(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_PRO && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_VGA2USB_HR(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_HR && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_VGA2USB_LR(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_LR && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_VGA2USB_LR_RESPIN(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_LR_RESPIN && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_VGA2USB_HR_RESPIN(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_HR_RESPIN && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_VGA2USB_PRO_RESPIN(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_VGA2USB_PRO_RESPIN && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_KVM2USB_LR(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_KVM2USB_LR && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_KVM2USB_PRO(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_KVM2USB_PRO && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_DVI2USB_SOLO(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_DVI2USB_SOLO && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_DVI2USB_DUO(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_DVI2USB_DUO && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_DVI2USB_RESPIN(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID &&(idProduct)==VGA2USB_PRODID_DVI2USB_RESPIN &&\ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_KVM2USB_LR_RESPIN(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_KVM2USB_LR_RESPIN && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_DVI2USB3(idVendor,idProduct,iProduct,iMfg) \ ((idVendor)==VGA2USB_VENDORID && (idProduct)==VGA2USB_PRODID_DVI2USB3 && \ ((iProduct)>0 || (iMfg)>0)) #define VGA2USB_IS_ANY(idVendor,idProduct,iProduct,iMfg) \ (VGA2USB_IS_VGA2USB(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_KVM2USB(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_DVI2USB(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_DVI2USB_SOLO(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_DVI2USB_DUO(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_DVI2USB_RESPIN(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_VGA2USB_PRO(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_VGA2USB_HR(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_VGA2USB_LR(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_VGA2USB_LR_RESPIN(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_VGA2USB_HR_RESPIN(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_VGA2USB_PRO_RESPIN(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_KVM2USB_PRO(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_KVM2USB_LR(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_KVM2USB_LR_RESPIN(idVendor,idProduct,iProduct,iMfg) || \ VGA2USB_IS_DVI2USB3(idVendor,idProduct,iProduct,iMfg)) /** * Windows device name format. Used by user level code on Windows to open * a handle to the VGA2USB driver. */ #define VGA2USB_WIN_DEVICE_FORMAT "EpiphanVga2usb%lu" /** * This macro helps to map VGA2USB product ids into product names */ #define V2U_PRODUCT_MAP(map) \ map( VGA2USB_PRODID_VGA2USB, V2UProductVGA2USB, "VGA2USB" )\ map( VGA2USB_PRODID_KVM2USB, V2UProductKVM2USB, "KVM2USB" )\ map( VGA2USB_PRODID_DVI2USB, V2UProductDVI2USB, "DVI2USB" )\ map( VGA2USB_PRODID_VGA2USB_LR, V2UProductVGA2USBLR, "VGA2USB LR" )\ map( VGA2USB_PRODID_VGA2USB_HR, V2UProductVGA2USBHR, "VGA2USB HR" )\ map( VGA2USB_PRODID_VGA2USB_PRO, V2UProductVGA2USBPro, "VGA2USB Pro" )\ map( VGA2USB_PRODID_VGA2USB_LR_RESPIN,V2UProductVGA2USBLRRespin,"VGA2USB LR")\ map( VGA2USB_PRODID_VGA2USB_HR_RESPIN,V2UProductVGA2USBHRRespin,"VGA2USB HR")\ map( VGA2USB_PRODID_VGA2USB_PRO_RESPIN,V2UProductVGA2USBProRespin,"VGA2USB Pro")\ map( VGA2USB_PRODID_DVI2USB_RESPIN,V2UProductDVI2USBRespin,"DVI2USB" )\ map( VGA2USB_PRODID_KVM2USB_LR, V2UProductKVM2USBLR, "KVM2USB LR" )\ map( VGA2USB_PRODID_KVM2USB_LR_RESPIN, V2UProductKVM2USBLRRespin, "KVM2USB LR")\ map( VGA2USB_PRODID_KVM2USB_PRO, V2UProductKVM2USBPro, "KVM2USB Pro" )\ map( VGA2USB_PRODID_DVI2USB_SOLO, V2UProductDVI2USBSolo, "DVI2USB Solo")\ map( VGA2USB_PRODID_DVI2USB_DUO, V2UProductDVI2USBDuo, "DVI2USB Duo" )\ map( VGA2USB_PRODID_DVI2USB3, V2UProductDVI2USB3, "DVI2USB 3.0" )\ map( VGA2USB_PRODID_VGA2FIFO, V2UProductVGA2FIFO, "VGA2FIFO" )\ map( VGA2USB_PRODID_KVM2FIFO, V2UProductKVM2FIFO, "KVMFIFO" )\ map( VGA2USB_PRODID_DVI2FIFO, V2UProductDVI2FIFO, "DVI2FIFO" )\ map( VGA2USB_PRODID_DAVINCI1, V2UProductDVI2Davinci1, "DVI2Davinci" )\ map( VGA2USB_PRODID_VGA2PCI, V2UProductVGA2PCI, "VGA2PCI" )\ map( VGA2USB_PRODID_GIOCONDA, V2UProductGioconda, "Gioconda" )\ map( VGA2USB_PRODID_DVI2PCI, V2UProductDVI2PCI, "DVI2PCI" )\ map( VGA2USB_PRODID_DVI2PCI_STD, V2UProductDVI2PCIStd, "DVI2PCI Std" )\ map( VGA2USB_PRODID_DVI2PCI2, V2UProductDVI2PCIGen2, "DVI2PCI Gen2")\ map( VGA2USB_PRODID_HDMI2PCI, V2UProductHDMI2PCI, "HDMI2PCI" ) #endif /* _VGA2USB_ID_H_ */
8,369
C
46.288135
86
0.68933
adegirmenci/HBL-ICEbot/DataLoggerWidget/dataloggerwidget.cpp
#include "dataloggerwidget.h" #include "ui_dataloggerwidget.h" DataLoggerWidget::DataLoggerWidget(QWidget *parent) : QWidget(parent), ui(new Ui::DataLoggerWidget) { ui->setupUi(this); m_worker = new DataLoggerThread; m_worker->moveToThread(&m_thread); connect(&m_thread, &QThread::finished, m_worker, &QObject::deleteLater); m_thread.start(); // connect widget signals to worker slots connect(this, SIGNAL(initializeDataLogger(std::vector<int>,std::vector<QString>)), m_worker, SLOT(initializeDataLogger(std::vector<int>,std::vector<QString>))); connect(this, SIGNAL(setRootDir(QString)), m_worker, SLOT(setRootDirectory(QString))); connect(this, SIGNAL(closeLogFiles()), m_worker, SLOT(closeLogFiles())); connect(this, SIGNAL(startLogging()), m_worker, SLOT(startLogging())); connect(this, SIGNAL(stopLogging()), m_worker, SLOT(stopLogging())); connect(this, SIGNAL(logNote(QTime,QString)), m_worker, SLOT(logNote(QTime,QString))); // connect worker signals to widget slots connect(m_worker, SIGNAL(statusChanged(int)), this, SLOT(workerStatusChanged(int))); connect(m_worker, SIGNAL(fileStatusChanged(unsigned short,int)), this, SLOT(workerFileStatusChanged(unsigned short,int))); m_statusList.push_back(ui->EMstatusLabel); m_statusList.push_back(ui->ECGstatusLabel); m_statusList.push_back(ui->EPOSstatusLabel); m_statusList.push_back(ui->FrmGrabStatusLabel); m_statusList.push_back(ui->LogStatusLabel); m_statusList.push_back(ui->ErrorStatusLabel); m_statusList.push_back(ui->NotesStatusLabel); m_statusList.push_back(ui->ControlStatusLabel); m_fileNameList.push_back(ui->EMpathLineEdit); m_fileNameList.push_back(ui->ECGpathLineEdit); m_fileNameList.push_back(ui->EPOSpathLineEdit); m_fileNameList.push_back(ui->FrmGrabPathLineEdit); m_fileNameList.push_back(ui->LogPathLineEdit); m_fileNameList.push_back(ui->ErrorPathLineEdit); m_fileNameList.push_back(ui->NotesPathLineEdit); m_fileNameList.push_back(ui->ControlPathLineEdit); m_checkBoxList.push_back(ui->EMcheckBox); m_checkBoxList.push_back(ui->ECGcheckBox); m_checkBoxList.push_back(ui->EPOScheckBox); m_checkBoxList.push_back(ui->FrmGrabCheckBox); m_checkBoxList.push_back(ui->LogCheckBox); m_checkBoxList.push_back(ui->ErrorCheckBox); m_checkBoxList.push_back(ui->NotesCheckBox); m_checkBoxList.push_back(ui->ControlCheckBox); m_writeCount.resize(DATALOG_NUM_FILES, 0); } DataLoggerWidget::~DataLoggerWidget() { m_thread.quit(); m_thread.wait(); qDebug() << "DataLogger thread quit."; delete ui; } void DataLoggerWidget::workerStatusChanged(int status) { switch(status) { case DATALOG_INITIALIZE_BEGIN: ui->widgetStatusLineEdit->setText("Initializing"); ui->initFilesButton->setEnabled(false); ui->dataDirLineEdit->setReadOnly(true); ui->dataDirPushButton->setEnabled(false); ui->startLoggingButton->setEnabled(true); ui->stopLoggingButton->setEnabled(false); ui->closeFilesButton->setEnabled(false); ui->logNoteButton->setEnabled(false); for(size_t i = 0; i < m_checkBoxList.size(); i++) { m_fileNameList[i]->setReadOnly(true); m_checkBoxList[i]->setEnabled(false); } break; case DATALOG_INITIALIZE_FAILED: ui->widgetStatusLineEdit->setText("Failed!"); ui->initFilesButton->setEnabled(true); ui->dataDirLineEdit->setReadOnly(false); ui->dataDirPushButton->setEnabled(true); ui->startLoggingButton->setEnabled(false); ui->stopLoggingButton->setEnabled(false); ui->closeFilesButton->setEnabled(false); ui->logNoteButton->setEnabled(false); for(size_t i = 0; i < m_checkBoxList.size(); i++) { m_fileNameList[i]->setReadOnly(false); m_checkBoxList[i]->setEnabled(true); } break; case DATALOG_INITIALIZED: ui->widgetStatusLineEdit->setText("Initialized"); ui->initFilesButton->setEnabled(false); ui->dataDirLineEdit->setReadOnly(true); ui->dataDirPushButton->setEnabled(false); ui->startLoggingButton->setEnabled(true); ui->stopLoggingButton->setEnabled(false); ui->closeFilesButton->setEnabled(true); ui->logNoteButton->setEnabled(true); for(size_t i = 0; i < m_checkBoxList.size(); i++) { m_fileNameList[i]->setReadOnly(true); m_checkBoxList[i]->setEnabled(false); } break; case DATALOG_LOGGING_STARTED: ui->widgetStatusLineEdit->setText("Logging"); ui->initFilesButton->setEnabled(false); ui->dataDirLineEdit->setReadOnly(true); ui->dataDirPushButton->setEnabled(false); ui->startLoggingButton->setEnabled(false); ui->stopLoggingButton->setEnabled(true); ui->closeFilesButton->setEnabled(false); ui->logNoteButton->setEnabled(true); break; case DATALOG_LOGGING_STOPPED: ui->widgetStatusLineEdit->setText("Stopped"); ui->initFilesButton->setEnabled(false); ui->dataDirLineEdit->setReadOnly(true); ui->dataDirPushButton->setEnabled(false); ui->startLoggingButton->setEnabled(true); ui->stopLoggingButton->setEnabled(false); ui->closeFilesButton->setEnabled(true); ui->logNoteButton->setEnabled(true); break; case DATALOG_CLOSED: ui->widgetStatusLineEdit->setText("Closed"); ui->initFilesButton->setEnabled(true); ui->dataDirLineEdit->setReadOnly(false); ui->dataDirPushButton->setEnabled(true); ui->startLoggingButton->setEnabled(false); ui->stopLoggingButton->setEnabled(false); ui->closeFilesButton->setEnabled(false); ui->logNoteButton->setEnabled(false); for(size_t i = 0; i < m_checkBoxList.size(); i++) { m_fileNameList[i]->setReadOnly(false); m_checkBoxList[i]->setEnabled(true); } break; default: qDebug() << "Unrecognized status."; break; } } void DataLoggerWidget::workerFileStatusChanged(const unsigned short fileID, int status) { switch(status) { case DATALOG_FILE_OPENED: m_statusList[fileID]->setText("Opened"); m_statusList[fileID]->setStyleSheet("QLabel { background-color : green;}"); break; case DATALOG_FILE_CLOSED: m_statusList[fileID]->setText("Closed"); m_statusList[fileID]->setStyleSheet("QLabel { background-color : yellow;}"); break; case DATALOG_FILE_ERROR: m_statusList[fileID]->setText("ERROR!"); m_statusList[fileID]->setStyleSheet("QLabel { background-color : red;}"); break; case DATALOG_FILE_DATA_LOGGED: m_writeCount[fileID] += 1; // data written break; default: qDebug() << "Worker status not recognized!"; break; } } void DataLoggerWidget::on_dataDirPushButton_clicked() { QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "../ICEbot_QT_v1/LoggedData", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); ui->dataDirLineEdit->setText(dir); ui->initFilesButton->setEnabled(true); // enable initialize button } void DataLoggerWidget::on_initFilesButton_clicked() { std::vector<int> enableMask; std::vector<QString> fileNames; QString rootDir = ui->dataDirLineEdit->text(); QString datetime = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz"); rootDir.append("/"); rootDir.append(datetime); ui->subdirLineEdit->setText(tr("/")+datetime); emit setRootDir(rootDir); for(int i = 0; i < DATALOG_NUM_FILES; i++) { enableMask.push_back(m_checkBoxList[i]->isChecked()); QString fname = rootDir; fname.append("/"); fname.append(datetime); fname.append("_"); fname.append(m_fileNameList[i]->text()); fileNames.push_back(fname); } emit initializeDataLogger(enableMask, fileNames); } void DataLoggerWidget::on_closeFilesButton_clicked() { for(size_t i = 0; i < DATALOG_NUM_FILES; i++) qDebug() << m_writeCount[i] << "records written to" << m_fileNameList[i]->text(); // reset counts m_writeCount.clear(); m_writeCount.resize(DATALOG_NUM_FILES, 0); emit closeLogFiles(); } void DataLoggerWidget::on_startLoggingButton_clicked() { emit startLogging(); } void DataLoggerWidget::on_stopLoggingButton_clicked() { emit stopLogging(); } void DataLoggerWidget::on_logNoteButton_clicked() { emit logNote(QTime::currentTime(), ui->noteTextEdit->toPlainText()); ui->noteTextEdit->clear(); }
8,985
C++
34.377953
90
0.650751
adegirmenci/HBL-ICEbot/DataLoggerWidget/dataloggerthread.cpp
#include "dataloggerthread.h" DataLoggerThread::DataLoggerThread(QObject *parent) : QObject(parent) { qRegisterMetaType< std::vector<int> >("std::vector<int>"); qRegisterMetaType< std::vector<QString> >("std::vector<QString>"); m_isEpochSet = false; m_isReady = false; m_keepLogging = false; m_mutex = new QMutex(QMutex::Recursive); // for (int i = 0; i < DATALOG_NUM_FILES; i++) // { // m_files.push_back(std::shared_ptr<QFile>(new QFile()) ); // m_TextStreams.push_back(std::shared_ptr<QTextStream>(new QTextStream())); // m_DataStreams.push_back(std::shared_ptr<QTextStream>(new QTextStream())); // } m_files.resize(DATALOG_NUM_FILES); m_TextStreams.resize(DATALOG_NUM_FILES); m_DataStreams.resize(DATALOG_NUM_FILES); //qRegisterMetaType<DOUBLE_POSITION_MATRIX_TIME_Q_RECORD>("DOUBLE_POSITION_MATRIX_TIME_Q_RECORD"); } DataLoggerThread::~DataLoggerThread() { closeLogFiles(); qDebug() << "Ending DataLoggerThread - ID: " << reinterpret_cast<int>(QThread::currentThreadId()) << "."; delete m_mutex; emit finished(); } // ------------------------------ // SLOTS IMPLEMENTATION // ------------------------------ void DataLoggerThread::setEpoch(const QDateTime &epoch) { QMutexLocker locker(m_mutex); if(!m_keepLogging) { m_epoch = epoch; m_isEpochSet = true; // TODO: Implement generic logEventWithMessage slot //emit logEventWithMessage(SRC_DATALOGGER, LOG_INFO, QTime::currentTime(), DATALOG_EPOCH_SET, // m_epoch.toString("dd/MM/yyyy - hh:mm:ss.zzz")); } else emit logEvent(SRC_DATALOGGER, LOG_INFO, QTime::currentTime(), DATALOG_EPOCH_SET_FAILED); } void DataLoggerThread::setRootDirectory(QString rootDir) { QMutexLocker locker(m_mutex); // check if the directory exists, if not, create it QDir dir; if( ! dir.exists(rootDir) ) { if( dir.mkpath(rootDir) ) { qDebug() << "Folder created: " << rootDir; QDir imgDir; if( imgDir.mkpath(rootDir + QString("/images")) ) qDebug() << "Folder created: " << "/images"; } else { qDebug() << "Folder creation failed: " << rootDir; emit statusChanged(DATALOG_FOLDER_ERROR); } } else { QDir imgDir; if(! dir.exists(rootDir+ QString("/images")) ) { if( imgDir.mkpath(rootDir + QString("/images")) ) qDebug() << "Folder created: " << "/images"; } } qDebug() << "Root dir: " << rootDir; m_rootDirectory = rootDir; } void DataLoggerThread::initializeDataLogger(std::vector<int> enableMask, std::vector<QString> fileNames) { QMutexLocker locker(m_mutex); emit statusChanged(DATALOG_INITIALIZE_BEGIN); if(enableMask.size() == DATALOG_NUM_FILES) // within bounds { for (size_t i = 0; i < enableMask.size(); i++) // iterate through items { if(enableMask[i]) // user wants to log this { bool status = true; m_files[i].reset(new QFile()); m_files[i]->setFileName(fileNames[i]); // set filename of QFile if(m_files[i]->open(QIODevice::WriteOnly | QIODevice::Append)) // opened successfuly { if( DATALOG_EM_ID == i) { m_DataStreams[i].reset(new QDataStream()); m_DataStreams[i]->setDevice(&(*m_files[i])); (*m_DataStreams[i]) << QDateTime::currentMSecsSinceEpoch(); } else { m_TextStreams[i].reset(new QTextStream()); m_TextStreams[i]->setDevice(&(*m_files[i])); (*m_TextStreams[i]) << "File opened at: " << getCurrDateTimeStr() << '\n'; } emit fileStatusChanged(i, DATALOG_FILE_OPENED); } else // can't open { qDebug() << "File could not be opened: " << m_files[i]->fileName(); status = false; emit fileStatusChanged(i, DATALOG_FILE_ERROR); } } else // user doesn't want { emit fileStatusChanged(i, DATALOG_FILE_CLOSED); } } emit statusChanged(DATALOG_INITIALIZED); m_isReady = true; } else emit statusChanged(DATALOG_INITIALIZE_FAILED); //error! } // This is for writing to EM file as text //void DataLoggerThread::logEMdata(QTime timeStamp, // int sensorID, // DOUBLE_POSITION_MATRIX_TIME_STAMP_RECORD data) //{ // QDateTime ts; // ts.setMSecsSinceEpoch(data.time*1000); // // Data Format // // | Sensor ID | Time Stamp | x | y | z | r11 | r12 | ... | r33 | // QString output; // output.append(QString("%1\t%2\t%3\t%4\t%5\t%6\t%7\t%8\t%9\t%10\t%11\t%12\t%13\t%14\n") // .arg(sensorID) // .arg(QString::number(data.x,'f',m_prec)) // .arg(QString::number(data.y,'f',m_prec)) // .arg(QString::number(data.z,'f',m_prec)) // .arg(QString::number(data.s[0][0],'f',m_prec)) // .arg(QString::number(data.s[0][1],'f',m_prec)) // .arg(QString::number(data.s[0][2],'f',m_prec)) // .arg(QString::number(data.s[1][0],'f',m_prec)) // .arg(QString::number(data.s[1][1],'f',m_prec)) // .arg(QString::number(data.s[1][2],'f',m_prec)) // .arg(QString::number(data.s[2][0],'f',m_prec)) // .arg(QString::number(data.s[2][1],'f',m_prec)) // .arg(QString::number(data.s[2][2],'f',m_prec)) // .arg(QString::number(data.time*1000,'f',m_prec))); // //.arg(ts.toString("hh:mm:ss:zzz"))); // QMutexLocker locker(m_mutex); // if(m_files[DATALOG_EM_ID]->isOpen()) // { // (*m_TextStreams[DATALOG_EM_ID]) << output; // // // emit fileStatusChanged(DATALOG_EM_ID, DATALOG_FILE_DATA_LOGGED); // } // else // qDebug() << "File is closed."; //} void DataLoggerThread::logEMdata(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data) { // Data Format // | Sensor ID | Time Stamp | x | y | z | q1 | q2 | q3 | q4 | quality | // | int | double | ... double ... | QMutexLocker locker(m_mutex); if(m_isReady && m_files[DATALOG_EM_ID]->isOpen()) { (*m_DataStreams[DATALOG_EM_ID]) << sensorID << data.time*1000 << data.x << data.y << data.z << data.s[0][0] << data.s[0][1] << data.s[0][2] << data.s[1][0] << data.s[1][1] << data.s[1][2] << data.s[2][0] << data.s[2][1] << data.s[2][2] << data.quality; // << data.q[0] // << data.q[1] // << data.q[2] // << data.q[3] // emit fileStatusChanged(DATALOG_EM_ID, DATALOG_FILE_DATA_LOGGED); } else qDebug() << "File is closed."; } // save image and write details to text file void DataLoggerThread::logFrmGrabImage(std::shared_ptr<Frame> frm) { QDateTime imgTime; imgTime.setMSecsSinceEpoch(frm->timestamp_); // file name of frame QString m_imgFname = imgTime.toString("ddMMyyyy_hhmmsszzz"); // populate m_imgFname with index m_imgFname.append( QString("_%1.jpg").arg(frm->index_) ); QString m_DirImgFname = m_rootDirectory; m_DirImgFname.append("/images/"); m_DirImgFname.append(m_imgFname); // save frame //state = frame->image_.save(m_imgFname, "JPG", 100); std::vector<int> compression_params; compression_params.push_back(CV_IMWRITE_JPEG_QUALITY); compression_params.push_back(100); cv::imwrite(m_DirImgFname.toStdString().c_str(), frm->image_, compression_params); // write frame QMutexLocker locker(m_mutex); // output to text if(m_isReady && m_files[DATALOG_FrmGrab_ID]->isOpen()) { (*m_TextStreams[DATALOG_FrmGrab_ID]) << m_imgFname << "\t" << QString::number(frm->timestamp_, 'f', 1) << '\n'; // emit fileStatusChanged(DATALOG_FrmGrab_ID, DATALOG_FILE_DATA_LOGGED); } else qDebug() << "FrmGrab text file closed."; } void DataLoggerThread::logLabJackData(qint64 timeStamp, std::vector<double> data) { QString output = QString("%1").arg(timeStamp); for(const double &d : data) { output.append("\t"); output.append(QString::number(d, 'f', 6)); } QMutexLocker locker(m_mutex); if(m_isReady && m_files[DATALOG_ECG_ID]->isOpen()) { // (*m_TextStreams[DATALOG_ECG_ID]) << timeStamp.toString("HH:mm:ss.zzz") << "\t" << QString::number(data, 'f', 6) << '\n'; (*m_TextStreams[DATALOG_ECG_ID]) << output << '\n'; // emit fileStatusChanged(DATALOG_ECG_ID, DATALOG_FILE_DATA_LOGGED); } else ;//qDebug() << "File is closed."; } void DataLoggerThread::logEPOSdata(QTime timeStamp, int dataType, const int motID, long data) { QString output = QString("%1\t").arg(timeStamp.msecsSinceStartOfDay()); switch(dataType) { case EPOS_COMMANDED: output.append("CMND\t"); break; case EPOS_READ: output.append("READ\t"); break; } output.append(QString("%1\t%2\n").arg(motID).arg(data)); QMutexLocker locker(m_mutex); if(m_isReady && m_files[DATALOG_EPOS_ID]->isOpen()) { (*m_TextStreams[DATALOG_EPOS_ID]) << output; // emit fileStatusChanged(DATALOG_EPOS_ID, DATALOG_FILE_DATA_LOGGED); } else ;//qDebug() << "File is closed."; } void DataLoggerThread::logEPOSdata(QTime timeStamp, int dataType, std::vector<long> data) { QString output; for(size_t i = 0; i < data.size(); i++) { output.append(QString("%1\t").arg(timeStamp.msecsSinceStartOfDay())); switch(dataType) { case EPOS_COMMANDED: output.append("CMND\t"); break; case EPOS_READ: output.append("READ\t"); break; } output.append(QString("%1\t%2\n").arg(i).arg(data[i])); } QMutexLocker locker(m_mutex); if(m_isReady && m_files[DATALOG_EPOS_ID]->isOpen()) { (*m_TextStreams[DATALOG_EPOS_ID]) << output << '\n'; // emit fileStatusChanged(DATALOG_EPOS_ID, DATALOG_FILE_DATA_LOGGED); } else ;//qDebug() << "File is closed."; } void DataLoggerThread::logControllerData(QTime timeStamp, int loopIdx, int dataType, std::vector<double> data) { // CONTROLLER_DXYZPSI = 0, // 4 values // CONTROLLER_USER_XYZDXYZPSI, // 7 values // CONTROLLER_CURR_PSY_GAMMA, // 2 values // CONTROLLER_T_BB_CT_curTipPos, // 16 values // CONTROLLER_CURR_TASK, // 4 values // CONTROLLER_PERIOD, // 1 value // CONTROLLER_BIRD4_MODEL_PARAMS, // 19 = 10 polar + 9 rect // CONTROLLER_RESETBB, // 16 values // CONTROLLER_MODES, // 6 values // CONTROLLER_USANGLE // 1 value QString output; output.append(QString("%1\t%2\t").arg(loopIdx).arg(timeStamp.msecsSinceStartOfDay())); switch(dataType) { case CONTROLLER_DXYZPSI: // 4 values output.append(QString("DXYZPSI\t%1\t%2\t%3\t%4") .arg(QString::number(data[0],'f',m_prec2)) .arg(QString::number(data[1],'f',m_prec2)) .arg(QString::number(data[2],'f',m_prec2)) .arg(QString::number(data[3],'f',m_prec2))); break; case CONTROLLER_USER_XYZDXYZPSI: // 7 values output.append(QString("USERXYZDXYZPSI\t%1\t%2\t%3\t%4\t%5\t%6\t%7") .arg(QString::number(data[0],'f',2)) .arg(QString::number(data[1],'f',2)) .arg(QString::number(data[2],'f',2)) .arg(QString::number(data[3],'f',2)) .arg(QString::number(data[4],'f',2)) .arg(QString::number(data[5],'f',2)) .arg(QString::number(data[6],'f',2))); break; case CONTROLLER_CURR_PSY_GAMMA: // 2 values output.append(QString("CURRPSYGAMMA\t%1\t%2") .arg(QString::number(data[0],'f',m_prec2)) .arg(QString::number(data[1],'f',m_prec2))); break; case CONTROLLER_T_BB_CT_curTipPos: // 16 values output.append(QString("T_BB_CT\t%1\t%2\t%3\t%4\t%5\t%6\t%7\t%8\t%9\t%10\t%11\t%12\t%13\t%14\t%15\t%16") .arg(QString::number(data[0],'f',m_prec2)) .arg(QString::number(data[1],'f',m_prec2)) .arg(QString::number(data[2],'f',m_prec2)) .arg(QString::number(data[3],'f',m_prec2)) .arg(QString::number(data[4],'f',m_prec2)) .arg(QString::number(data[5],'f',m_prec2)) .arg(QString::number(data[6],'f',m_prec2)) .arg(QString::number(data[7],'f',m_prec2)) .arg(QString::number(data[8],'f',m_prec2)) .arg(QString::number(data[9],'f',m_prec2)) .arg(QString::number(data[10],'f',m_prec2)) .arg(QString::number(data[11],'f',m_prec2)) .arg(QString::number(data[12],'f',m_prec2)) .arg(QString::number(data[13],'f',m_prec2)) .arg(QString::number(data[14],'f',m_prec2)) .arg(QString::number(data[15],'f',m_prec2))); break; case CONTROLLER_CURR_TASK: // 4 values output.append(QString("CURRTASK\t%1\t%2\t%3\t%4") .arg(QString::number(data[0],'f',m_prec2)) .arg(QString::number(data[1],'f',m_prec2)) .arg(QString::number(data[2],'f',m_prec2)) .arg(QString::number(data[3],'f',m_prec2))); break; case CONTROLLER_PERIOD: // 1 value output.append(QString("PERIOD\t%1") .arg(QString::number(data[0],'f',m_prec))); break; case CONTROLLER_BIRD4_MODEL_PARAMS: // 19 = 10 polar + 9 rect output.append(QString("BIRD4MODELPARAMS\t%1\t%2\t%3\t%4\t%5\t%6\t%7\t%8\t%9\t%10\t%11\t%12\t%13\t%14\t%15\t%16\t%17\t%18\t%19") .arg(QString::number(data[0],'f',m_prec2)) .arg(QString::number(data[1],'f',m_prec2)) .arg(QString::number(data[2],'f',m_prec2)) .arg(QString::number(data[3],'f',m_prec2)) .arg(QString::number(data[4],'f',m_prec2)) .arg(QString::number(data[5],'f',m_prec2)) .arg(QString::number(data[6],'f',m_prec2)) .arg(QString::number(data[7],'f',m_prec2)) .arg(QString::number(data[8],'f',m_prec2)) .arg(QString::number(data[9],'f',m_prec2)) .arg(QString::number(data[10],'f',m_prec2)) .arg(QString::number(data[11],'f',m_prec2)) .arg(QString::number(data[12],'f',m_prec2)) .arg(QString::number(data[13],'f',m_prec2)) .arg(QString::number(data[14],'f',m_prec2)) .arg(QString::number(data[15],'f',m_prec2)) .arg(QString::number(data[16],'f',m_prec2)) .arg(QString::number(data[17],'f',m_prec2)) .arg(QString::number(data[18],'f',m_prec2))); break; case CONTROLLER_RESETBB: // 16 values output.append(QString("RESETBB\t%1\t%2\t%3\t%4\t%5\t%6\t%7\t%8\t%9\t%10\t%11\t%12\t%13\t%14\t%15\t%16") .arg(QString::number(data[0],'f',m_prec2)) .arg(QString::number(data[1],'f',m_prec2)) .arg(QString::number(data[2],'f',m_prec2)) .arg(QString::number(data[3],'f',m_prec2)) .arg(QString::number(data[4],'f',m_prec2)) .arg(QString::number(data[5],'f',m_prec2)) .arg(QString::number(data[6],'f',m_prec2)) .arg(QString::number(data[7],'f',m_prec2)) .arg(QString::number(data[8],'f',m_prec2)) .arg(QString::number(data[9],'f',m_prec2)) .arg(QString::number(data[10],'f',m_prec2)) .arg(QString::number(data[11],'f',m_prec2)) .arg(QString::number(data[12],'f',m_prec2)) .arg(QString::number(data[13],'f',m_prec2)) .arg(QString::number(data[14],'f',m_prec2)) .arg(QString::number(data[15],'f',m_prec2))); break; case CONTROLLER_MODES: // 6 values output.append(QString("MODES\t%1\t%2\t%3\t%4\t%5\t%6") .arg(QString::number(data[0],'f',1)) .arg(QString::number(data[1],'f',1)) .arg(QString::number(data[2],'f',1)) .arg(QString::number(data[3],'f',1)) .arg(QString::number(data[4],'f',1)) .arg(QString::number(data[5],'f',1))); break; case CONTROLLER_USANGLE: // 1 value output.append(QString("USANGLE\t%1") .arg(QString::number(data[0],'f',m_prec))); break; case CONTROLLER_SWEEP_START: // 4 values output.append(QString("SWEEP\t%1\t%2\t%3\t%4") .arg(QString::number(data[0],'f',1)) // nSteps_ .arg(QString::number(data[1],'f',m_prec)) // stepAngle_ .arg(QString::number(data[2],'f',m_prec)) // convLimit_ .arg(QString::number(data[3],'f',1))); // imgDuration_ break; case CONTROLLER_NEXT_SWEEP: // 1 value output.append(QString("SWEEPNEXT\t%1") .arg(QString::number(data[0],'f',m_prec))); break; case CONTROLLER_SWEEP_CONVERGED: // 1 value output.append(QString("SWEEPCONVD\t%1") .arg(QString::number(data[0],'f',m_prec))); break; default: output.append(QString("UNKNOWN")); break; } QMutexLocker locker(m_mutex); // output to text if(m_isReady && m_files[DATALOG_Control_ID]->isOpen()) { (*m_TextStreams[DATALOG_Control_ID]) << output << '\n'; // emit fileStatusChanged(DATALOG_Control_ID, DATALOG_FILE_DATA_LOGGED); } else ;//qDebug() << "Controller text file closed."; } void DataLoggerThread::logEvent(int source, int logType, QTime timeStamp, int eventID) { // Data Format // | Time Stamp | Log Type | Source | eventID | QString output = timeStamp.toString("HH:mm:ss.zzz"); switch(logType) { case LOG_INFO: output.append(" INFO "); break; case LOG_WARNING: output.append(" WARNING "); break; case LOG_ERROR: output.append(" ERROR "); break; case LOG_FATAL: output.append(" FATAL "); break; default: output.append(" UNKNOWN "); break; } switch(source) { case SRC_CONTROLLER: output.append("CONTROLLER "); break; case SRC_EM: output.append("EM "); break; case SRC_EPOS: output.append("EPOS "); break; case SRC_FRMGRAB: output.append("FRMGRAB "); break; case SRC_EPIPHAN: output.append("EPIPHAN "); break; case SRC_LABJACK: output.append("LABJACK "); break; case SRC_OMNI: output.append("OMNI "); break; case SRC_GUI: output.append("GUI "); break; case SRC_UNKNOWN: output.append("UNKNOWN "); break; default: output.append("UNKNOWN "); break; } output.append(QString("%1\n").arg(eventID)); QMutexLocker locker(m_mutex); if(m_isReady && m_files[DATALOG_Log_ID]->isOpen()) { (*m_TextStreams[DATALOG_Log_ID]) << output; emit fileStatusChanged(DATALOG_Log_ID, DATALOG_FILE_DATA_LOGGED); } else qDebug() << "Event logger: File is closed!"; } void DataLoggerThread::logError(int source, int logType, QTime timeStamp, int errCode, QString message) { // Data Format // | Time Stamp | Log Type | Source | eventID | QString output = timeStamp.toString("HH:mm:ss.zzz"); switch(logType) { case LOG_INFO: output.append(" INFO "); break; case LOG_WARNING: output.append(" WARNING "); break; case LOG_ERROR: output.append(" ERROR "); break; case LOG_FATAL: output.append(" FATAL "); break; default: output.append(" UNKNOWN "); break; } switch(source) { case SRC_CONTROLLER: output.append("CONTROLLER "); break; case SRC_EM: output.append("EM "); break; case SRC_EPOS: output.append("EPOS "); break; case SRC_FRMGRAB: output.append("FRMGRAB "); break; case SRC_EPIPHAN: output.append("EPIPHAN "); break; case SRC_LABJACK: output.append("LABJACK "); break; case SRC_OMNI: output.append("OMNI "); break; case SRC_GUI: output.append("GUI "); break; case SRC_UNKNOWN: output.append("UNKNOWN "); break; default: output.append("UNKNOWN "); break; } output.append(QString("%1 ").arg(errCode)); output.append(message); QMutexLocker locker(m_mutex); if(m_isReady && m_files[DATALOG_Error_ID]->isOpen()) { (*m_TextStreams[DATALOG_Error_ID]) << output << '\n'; emit fileStatusChanged(DATALOG_Error_ID, DATALOG_FILE_DATA_LOGGED); } else qDebug() << "Error logger: File is closed!"; } void DataLoggerThread::startLogging() { QMutexLocker locker(m_mutex); // make connections emit statusChanged(DATALOG_LOGGING_STARTED); } void DataLoggerThread::stopLogging() { QMutexLocker locker(m_mutex); // sever connections emit statusChanged(DATALOG_LOGGING_STOPPED); } void DataLoggerThread::logNote(QTime timeStamp, QString note) { if(m_files[DATALOG_Note_ID]->isOpen()) { (*m_TextStreams[DATALOG_Note_ID]) << "[" << timeStamp.toString("HH:mm:ss.zzz") << "] " << note << endl; emit fileStatusChanged(DATALOG_Note_ID, DATALOG_FILE_DATA_LOGGED); } } void DataLoggerThread::closeLogFile(const unsigned short fileID) { QMutexLocker locker(m_mutex); // pointer not null and file is open if(m_files[fileID] && m_files[fileID]->isOpen()) { if( DATALOG_EM_ID != fileID ) { (*m_TextStreams[fileID]) << "File closed at: " << getCurrDateTimeStr() << '\n'; m_TextStreams[fileID]->flush(); //m_DataStreams[fileID]->flush(); // no need to flush, data is not buffered } m_files[fileID]->close(); emit fileStatusChanged(fileID, DATALOG_FILE_CLOSED); } } void DataLoggerThread::closeLogFiles() { QMutexLocker locker(m_mutex); for (unsigned short i = 0; i < DATALOG_NUM_FILES; i++) // iterate through items { closeLogFile(i); } emit statusChanged(DATALOG_CLOSED); m_isReady = false; } // Helper functions inline const QString getCurrDateTimeFileStr() { return QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz"); } inline const QString getCurrDateTimeStr() { return QDateTime::currentDateTime().toString("yyyy/MM/dd - hh:mm:ss.zzz"); }
25,116
C++
33.501374
135
0.508321
adegirmenci/HBL-ICEbot/DataLoggerWidget/dataloggerwidget.h
#ifndef DATALOGGERWIDGET_H #define DATALOGGERWIDGET_H #include <QWidget> #include <QThread> #include <QFileDialog> #include <QLabel> #include <QLineEdit> #include <QCheckBox> #include "dataloggerthread.h" namespace Ui { class DataLoggerWidget; } class DataLoggerWidget : public QWidget { Q_OBJECT public: explicit DataLoggerWidget(QWidget *parent = 0); ~DataLoggerWidget(); DataLoggerThread *m_worker; signals: void initializeDataLogger(std::vector<int> enableMask, std::vector<QString> fileNames); void setRootDir(QString dir); void closeLogFiles(); void startLogging(); void stopLogging(); void logNote(QTime timeStamp, QString note); private slots: void workerStatusChanged(int status); void workerFileStatusChanged(const unsigned short fileID, int status); void on_dataDirPushButton_clicked(); void on_initFilesButton_clicked(); void on_closeFilesButton_clicked(); void on_startLoggingButton_clicked(); void on_stopLoggingButton_clicked(); void on_logNoteButton_clicked(); private: Ui::DataLoggerWidget *ui; QThread m_thread; // Data Logger Thread will live in here std::vector<QLabel*> m_statusList; std::vector<QLineEdit*> m_fileNameList; std::vector<QCheckBox*> m_checkBoxList; std::vector<unsigned int> m_writeCount; }; #endif // DATALOGGERWIDGET_H
1,372
C
20.453125
91
0.723761
adegirmenci/HBL-ICEbot/DataLoggerWidget/dataloggerthread.h
#ifndef DATALOGGERTHREAD_H #define DATALOGGERTHREAD_H #include <QObject> #include <QMutex> #include <QMutexLocker> #include <QThread> //#include <QWaitCondition> #include <QString> #include <QFile> #include <QDataStream> #include <QTextStream> #include <QDir> #include <QTime> #include <QTimer> #include <QDebug> #include <vector> #include <memory> #include "../icebot_definitions.h" #include "../AscensionWidget/3DGAPI/ATC3DG.h" #include "../FrmGrabWidget/frmgrabthread.h" //Q_DECLARE_METATYPE(DOUBLE_POSITION_MATRIX_TIME_Q_RECORD) Q_DECLARE_METATYPE(std::vector<int>) class DataLoggerThread : public QObject { Q_OBJECT public: explicit DataLoggerThread(QObject *parent = 0); ~DataLoggerThread(); signals: void statusChanged(int event); void fileStatusChanged(const unsigned short fileID, int status); void finished(); // emit upon termination public slots: // Widget slots void setEpoch(const QDateTime &epoch); void setRootDirectory(QString rootDir); void initializeDataLogger(std::vector<int> enableMask, std::vector<QString> fileNames); void startLogging(); void stopLogging(); void closeLogFile(const unsigned short fileID); void closeLogFiles(); void logNote(QTime timeStamp, QString note); // EM slots void logEMdata(QTime timeStamp, int sensorID, DOUBLE_POSITION_MATRIX_TIME_Q_RECORD data); void logFrmGrabImage(std::shared_ptr<Frame> frm); void logLabJackData(qint64 timeStamp, std::vector<double> data); void logEPOSdata(QTime timeStamp, int dataType, // EPOS_DATA_IDS const int motID, long data); void logEPOSdata(QTime timeStamp, int dataType, // EPOS_DATA_IDS std::vector<long> data); // void logEvent(LOG_TYPES logType, // QTime timeStamp, // EM_EVENT_IDS eventID); // void logEventWithMessage(LOG_TYPES logType, // QTime timeStamp, // EM_EVENT_IDS eventID, // QString &message); // void logError(LOG_TYPES logType, // QTime timeStamp, // EM_ERROR_CODES, // QString &message); // void logData(QTime timeStamp, // EPOS_DATA_IDS dataType, // const int motID, // long data); // void logData(QTime timeStamp, // EPOS_DATA_IDS dataType, // std::vector<long> data); void logControllerData(QTime timeStamp, int loopIdx, int dataType, std::vector<double> data); void logEvent(int source, int logType, // LOG_TYPES QTime timeStamp, int eventID); // log error and log event with message can be combined void logError(int source, // LOG_SOURCE int logType, // LOG_TYPE QTime timeStamp, int errCode, // EPOS_ERROR_CODES QString message); // void logEventWithMessage(LOG_TYPES logType, // QTime timeStamp, // EPOS_EVENT_IDS eventID, // QString &message); // void logError(LOG_TYPES logType, // QTime timeStamp, // EPOS_ERROR_CODES, // QString &message); private: // Instead of using "m_mutex.lock()" // use "QMutexLocker locker(&m_mutex);" // this will unlock the mutex when the locker goes out of scope mutable QMutex *m_mutex; // Epoch for time stamps // During initializeDataLogger(), check 'isEpochSet' flag // If Epoch is set externally from MainWindow, the flag will be true // Otherwise, Epoch will be set internally QDateTime m_epoch; bool m_isEpochSet; // Flag to indicate if DataLogger is ready for data logging // True if InitializeDataLogger was successful bool m_isReady; // Flag to tell the run() loop to keep logging data bool m_keepLogging; // Root directory for creating files QString m_rootDirectory; // QFile m_EMfile; // QFile m_ECGfile; // QFile m_EPOSfile; // QFile m_FrameFile; // QFile m_LogFile; // QFile m_ErrorFile; // QFile m_NoteFile; // QTextStream m_textStream; const int m_prec = 4; // precision for print operations const int m_prec2 = 6; std::vector< std::shared_ptr<QFile> > m_files; std::vector< std::shared_ptr<QTextStream> > m_TextStreams; std::vector< std::shared_ptr<QDataStream> > m_DataStreams; }; inline const QString getCurrTimeStr(); inline const QString getCurrDateTimeStr(); #endif // DATALOGGERTHREAD_H
4,771
C
30.394737
91
0.608258
liamczm/OmniverseExtensionDev/README.md
# OmniverseExtensionDev
23
Markdown
22.999977
23
0.913043
liamczm/OmniverseExtensionDev/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
liamczm/OmniverseExtensionDev/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
liamczm/OmniverseExtensionDev/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_ui_model.py
__all__ = ["PrimPathUIModel"] from pxr import Tf,Usd,UsdGeom,UsdLux import omni.ui as ui import omni.usd class PathValueItem(ui.AbstractItem): """单个Item,决定类型""" def __init__(self): super().__init__() self.path_model = ui.SimpleStringModel() self.path_children = [] class PrimPathUIModel(ui.AbstractItemModel): """代表名称-数值表的model""" def __init__(self): super().__init__() # 示例参数 self._children = PathValueItem() def get_item_children(self, item): """当widget询问时返回所有子项""" if item is not None: return [] # return self._children # return item.children def get_item_value_model_count(self, item): """列数""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.path_model class TreeViewLayout(omni.ext.IExt): """灯光TreeView""" def __init__(self): super().__init__() # self._usd_context = omni.usd.get_context() # self._selection = self._usd_context.get_selection() # self._events = self._usd_context.get_stage_event_stream() # self._stage_event_sub = self._events.create_subscription_to_pop( # self._on_stage_event, name="customdataview" # ) # self._selected_primpath_model = ui.SimpleStringModel("-") def InitLayout(self): with ui.VStack(): with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="LtTreeView", ): self._model = PrimPathUIModel() ui.TreeView(self._model, root_visible=False, style={"margin": 0.5})
2,010
Python
31.967213
84
0.572637
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/extension.py
import omni.ext import omni.ui as ui import omni.usd import carb import omni.kit.commands from omni.kit.viewport.utility import get_active_viewport_window # 加载viewport_scene from .viewport_scene import ViewportLtInfo from .my_light_model import LtStartSceneModel from .my_light_ui_model import PrimPathUIModel from .my_light_ui_manipulator import Layout as layt from .my_light_ui_model import TreeViewLayout as tVlt from .my_light_list_model import LightListModel as lst class MyExtension(omni.ext.IExt): def on_startup(self, ext_id): # 得到当前usd context self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() # 注册事件 self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="customdataview" ) # self._customdata_model = CustomDataAttributesModel() self._selected_primpath_model = ui.SimpleStringModel("-") self._selected_Prim_Family = ui.SimpleStringModel() self._window = ui.Window("ipolog Selection Info", width=300, height=200) # 得到当前stage self.current_stage = self._usd_context.get_stage() #self.list_model = lst(str(self.current_stage)) # 得到当前激活的视口 viewport_window = get_active_viewport_window() # 如果没有视口记录错误 if not viewport_window: carb.log_error(f"No Viewport to add {ext_id} scene to") return # 建立scene(覆盖默认的) self._viewport_scene = ViewportLtInfo(viewport_window,ext_id) self._window = ui.Window("HNADI Light Studio", width=300, height=300) #窗口UI with self._window.frame: with ui.VStack(): with ui.HStack(height=35): # Pic 占位 ui.Circle( name = "iconHolder", radius = 20, size_policy = ui.CircleSizePolicy.FIXED, alignment = ui.Alignment.CENTER, ) with ui.VStack(): ui.Label("LightType") self._selected_Prim_Family = ui.StringField(model=self._selected_primpath_model,height=20, read_only=True) self._selectedPrimName = ui.StringField(model=self._selected_primpath_model, height=20, read_only=True) with ui.VStack(): ui.Label("Profiles:", height=20) #tVlt.InitLayout(self) #ui.TreeView(self.list_model,root_visible = False) with ui.VStack(): ui.Label("Lights", height=20) layt.InitLayout(self) # 创建按钮 with ui.HStack(): ui.Button("Create a set of lights",clicked_fn=lambda: click_lt()) ui.Button("Select",clicked_fn=lambda:select_type()) def click_lt(): omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', attributes={}) omni.kit.commands.execute('CreatePrim', prim_type='RectLight', attributes={'width': 100, 'height': 100, 'intensity': 15000}) omni.kit.commands.execute('MovePrim', path_from='/World/RectLight_01', path_to='/World/Xform/RectLight_01') def select_type(self): selection = self._selection.get_selected_prim_paths() sel_type = selection.select_all_prims(self,type_names="") # tree_view = ui.TreeView( # self._customdata_model, # root_visible=False, # header_visible=False, # columns_resizable=True, # column_widths=[ui.Fraction(0.4), ui.Fraction(0.6)], # style={"TreeView.Item": {"margin": 4}}, # ) def _on_stage_event(self, event): """只跟踪选取变动""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): """选择变动后读取信息""" selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() # print(f"== selection changed with {len(selection)} items") if selection and stage: #-- set last selected element in property model if len(selection) > 0: path = selection[-1] family = selection self._selected_primpath_model.set_value(path) self._selected_Prim_Family.set_value(family) def on_shutdown(self): #清空自定义scene if self._viewport_scene: self._viewport_scene.destroy() self._viewport_scene = None print("[my.light.start] MyExtension shutdown")
5,093
Python
40.414634
130
0.549185
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/viewport_scene.py
from omni.ui import scene as sc import omni.ui as ui from .my_light_manipulator import LtStartSceneManipulator from .my_light_model import LtStartSceneModel class ViewportLtInfo(): def __init__(self,viewportWindow,ext_id) -> None: self.sceneView = None self.viewportWindow = viewportWindow with self.viewportWindow.get_frame(ext_id): self.sceneView = sc.SceneView() # 向SceneView中加载Manipulator with self.sceneView.scene: LtStartSceneManipulator(model = LtStartSceneModel()) self.viewportWindow.viewport_api.add_scene_view(self.sceneView) def __del__(self): self.destroy() def destroy(self): if self.sceneView: self.sceneView.scene.clear() if self.viewportWindow: self.viewportWindow.viewport_api.remove_scene_view(self.sceneView) self.viewportWindow = None self.sceneView = None
958
Python
28.968749
82
0.653445
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_list_model.py
import omni.ui as ui class LightListItem(ui.AbstractItem): def __init__(self,text:str): super().__init__() self.sub_model = ui.SimpleStringModel(text) class LightListModel(ui.AbstractItemModel): def __init__(self,*args): super().__init__() self._children = [LightListItem(t) for t in args] def get_item_children(self,item): if item is not None: return[] else: return self._children def get_item_value_model_count(self,item): return 1 def get_item_value_model(self,item,id): return item.sub_model
540
Python
24.761904
51
0.675926
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_manipulator.py
from omni.ui import scene as sc import omni.ui as ui from warp.types import transform from omni.ui import color as cl class LtStartSceneManipulator(sc.Manipulator): # 包含model作为参数 def on_build(self): """model变动即呼起,重建整个manipulator""" # 没有model返回 if not self.model: return # 没有选择返回 if self.model.get_item("name") == "": return # 更新位置信息(通过model) position = self.model.get_as_floats(self.model.get_item("position")) with sc.Transform(transform = sc.Matrix44.get_translation_matrix(*position)): # 屏幕上显示名称信息 with sc.Transform(scale_to = sc.Space.SCREEN): sc.Label(f"Path:{self.model.get_item('name')}",color=cl("#76b900"),size = 20) #sc.Label(f"Path:{self.model.get_item('intensity')}") #sc.Label(f"Path:{self.model.get_item('name')}") def on_model_updated(self,item): """model中某项目更新呼起该方法,核心,重建Manipulator""" # manipulator自带的方法,删除旧的重新执行on_build生成新的manipulator self.invalidate()
1,067
Python
33.451612
93
0.613871
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_model.py
from pxr import Tf,Usd,UsdGeom,UsdLux import omni.ui as ui from omni.ui import scene as sc import omni.usd class LtStartSceneModel(sc.AbstractManipulatorModel): def __init__(self)->None: super().__init__() self.prim = None self.current_path=None self.stage_listener = None self.position = LtStartSceneModel.PositionItem() self.intensity = LtStartSceneModel.IntensityItem() # 保存当前UsdContext self.usd_context = omni.usd.get_context() # self._light = None # 追踪选择变动 self.events = self.usd_context.get_stage_event_stream() # 自定义on_stage_event self.stage_event_delegate = self.events.create_subscription_to_pop( self.on_stage_event,name = "Light Selection Update" ) def on_stage_event(self,event): """事件方法,只包含了选择变动""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): # 若选择变动,得到新选中物体的路径 prim_path = self.usd_context.get_selection().get_selected_prim_paths() if not prim_path: self.current_path = "" # 如果没有路径,返回_item_changed self._item_changed(self.position)#_item_changed是自带方法,代表item改变 return # 得到当前stage内选中的prim stage = self.usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path[0]) # 如果选中的prim不是Imageable激活stage_listener继续监听选择变动 if not prim.IsA(UsdGeom.Imageable): self.prim = None if self.stage_listener: self.stage_listener.Revoke() self.stage_listener = None return # TODO 是啥?自定义notice_changed if not self.stage_listener: self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged,self.notice_changed,stage) self.prim = prim self.current_path = prim_path[0] # 位置变动,新选中物体有新位置 self._item_changed(self.position) class PositionItem(sc.AbstractManipulatorItem): """该model item代表位置""" def __init__(self) -> None: super().__init__() self.value = [0,0,0] class IntensityItem(sc.AbstractManipulatorItem): """该model item代表灯光强度""" def __init__(self) -> None: super().__init__() self.value = 0.0 def get_item(self,identifier): """根据标识符得到数据项目""" if identifier == "name": return self.current_path elif identifier == "position": return self.position elif identifier == "intensity": return self.intensity def get_as_floats(self,item): """引用自定义方法得到项目数据为浮点数""" if item == self.position: # 索取位置 return self.get_position() elif item == self.intensity: # 索取强度 return self.get_intensity() # TODO 不懂 if item: # 直接从item得到数值 return item.value return [] def get_position(self): """得到当前选中物体位置的方法,用来作为信息显示的位置""" # 得到当前stage stage = self.usd_context.get_stage() if not stage or self.current_path == "": return [0,0,0] # 直接从USD得到位置 prim = stage.GetPrimAtPath(self.current_path) position = prim.GetAttribute('xformOp:translate').Get() return position # 得到强度待定 def get_intensity(self,time:Usd.TimeCode): """得到灯光强度""" stage = self.usd_context.get_stage() if not stage or self.current_path == "": return prim = stage.GetPrimAtPath(self.current_path) intensity = prim.GetIntensityAttr().Get(time) #intensity = self._light.GetIntensityAttr().Get(time) return intensity # 循环所有通知直到找到选中的 def notice_changed(self,notice:Usd.Notice,stage:Usd.Stage)->None: """Tf.Notice呼起,当选中物体变化""" #TODO 为什么只改动位置 for p in notice.GetChangedInfoOnlyPaths(): if self.current_path in str(p.GetPrimPath()): self._item_changed(self.position) def destroy(self): self.events = None self.stage_event_delegate.unsubscribe()
4,208
Python
31.882812
109
0.573194
liamczm/OmniverseExtensionDev/exts/my.light.start/my/light/start/my_light_ui_manipulator.py
import omni.ui as ui import omni.usd field = ui.StringField() class Layout(omni.ext.IExt): """TreeView示例""" def InitLayout(self): with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._model = Model("Root", "Items") ui.TreeView(self._model, root_visible=False, style={"margin": 0.5}) # model = MyStringModel() # field.model = model # ui.StringField(field.model) class Item(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) self.children = None class Model(ui.AbstractItemModel): def __init__(self, *args): super().__init__() self._children = [Item(t) for t in args] # # 编辑时的颜色 # def begin_edit(self): # custom_treeview.set_style({"color":0xFF00B976}) # def end_edit(self): # custom_treeview.set_style({"color":0xFFCCCCC}) def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: if not item.children: item.children = [Item(f"Child #{i}") for i in range(5)] return item.children return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model # class MyStringModel(ui.SimpleStringModel): # def __init__(self): # super().__init__() # # 开始编辑时变色 # def begin_edit(self): # field.set_style({"color":0xFF00B976}) # def end_edit(self): # field.set_style({"color":0xFFCCCCC})
2,072
Python
29.940298
80
0.590734
liamczm/OmniverseExtensionDev/exts/my.light.start/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "My Revit View Project" description="The Revit View Tools, View revit infomations in viewport" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "WorkByHendrix" # Keywords for the extension keywords = ["kit", "revit","Scene Modifier"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import my.light.start". [[python.module]] name = "my.light.start"
779
TOML
25.896551
103
0.736842
terrylincn/omniskeleton/README.md
# omniskeleton this project is not maintained, use terrylincn/cn.appincloud.skeleton stead.
92
Markdown
29.99999
76
0.826087
terrylincn/omniskeleton/cn/appincloud/skeleton/hand_tracker.py
import filecmp import cv2 import mediapipe as mp import sys def hand_process(cam_id=0): mp_drawing = mp.solutions.drawing_utils mp_drawing_styles = mp.solutions.drawing_styles mp_hands = mp.solutions.hands # For webcam input: cap = cv2.VideoCapture(cam_id) with mp_hands.Hands( model_complexity=0, min_detection_confidence=0.5, min_tracking_confidence=0.5) as hands: while cap.isOpened(): success, image = cap.read() if not success: print("Ignoring empty camera frame.") # If loading a video, use 'break' instead of 'continue'. continue # To improve performance, optionally mark the image as not writeable to # pass by reference. image.flags.writeable = False image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = hands.process(image) # Draw the hand annotations on the image. image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: print(hand_landmarks) mp_drawing.draw_landmarks( image, hand_landmarks, mp_hands.HAND_CONNECTIONS, mp_drawing_styles.get_default_hand_landmarks_style(), mp_drawing_styles.get_default_hand_connections_style()) # Flip the image horizontally for a selfie-view display. cv2.imshow('MediaPipe Hands', cv2.flip(image, 1)) if cv2.waitKey(5) & 0xFF == 27: break cap.release() def landmark2text(landmark): txt = "" for mark in landmark: one = "{} {} {}".format(mark.x,mark.y,mark.z) if txt != "": txt += " " txt += one return txt + "\n" def handpose2kpts(videofile): txt = "" mp_drawing = mp.solutions.drawing_utils mp_drawing_styles = mp.solutions.drawing_styles mp_hands = mp.solutions.hands # For webcam input: cap = cv2.VideoCapture(videofile) with mp_hands.Hands( model_complexity=0, min_detection_confidence=0.5, min_tracking_confidence=0.5) as hands: while cap.isOpened(): success, image = cap.read() if not success: print("Ignoring empty camera frame.") # If loading a video, use 'break' instead of 'continue'. break # To improve performance, optionally mark the image as not writeable to # pass by reference. image.flags.writeable = False image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = hands.process(image) # Draw the hand annotations on the image. image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) if results.multi_hand_landmarks: handedness = [ handedness.classification[0].label for handedness in results.multi_handedness ] if "Left" not in handedness: continue index = 0 for hand_landmarks in results.multi_hand_landmarks: #only output right hand if handedness.index("Left") == index: txt += landmark2text(hand_landmarks.landmark) index += 1 cap.release() return txt class HandTracker: def __init__(self): mp_hands = mp.solutions.hands self._hands = mp_hands.Hands( model_complexity=0, min_detection_confidence=0.5, min_tracking_confidence=0.5) def process(self, image): left_hand = None right_hand = None image.flags.writeable = False image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = self._hands.process(image) if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: print(hand_landmarks) return left_hand, right_hand if __name__ == "__main__": #cam_id = int(sys.argv[1]) #hand_process(cam_id) filepath = sys.argv[1] outfile = sys.argv[2] txt = handpose2kpts(filepath) with open(outfile, "w") as fp: fp.write(txt)
4,731
Python
35.4
94
0.5316
terrylincn/omniskeleton/cn/appincloud/skeleton/extension.py
import omni.ext import omni.ui as ui from .skeletonutils import addRootToUsd, copyAnim, copyAnimToUsd, copyRotation, copySkel import uuid import carb import os from pxr import Usd,UsdSkel,AnimationSchema from omni.kit.window.popup_dialog import MessageDialog # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[cn.appincloud.skeleton] MyExtension startup") self._window = ui.Window("Avatar convert", width=300, height=300) with self._window.frame: with ui.VStack(): ui.Label("add root joint to skeleton") def on_add_joint_click(): print("add clicked!") self._on_assign_selected() def _copy_skel_click(): print("copy skel clicked!") self._copy_skel() def _copy_anim_click(): print("copy anim clicked!") self._copy_anim() def _copy_rot_click(): print("copy rot clicked!") self._copy_rot() ui.Button("Add Root Joint", clicked_fn=lambda: on_add_joint_click()) ui.Button("Copy Skeleton", clicked_fn=lambda: _copy_skel_click()) ui.Button("Copy Animation", clicked_fn=lambda: _copy_anim_click()) ui.Button("Copy Rotation", clicked_fn=lambda: _copy_rot_click()) def on_shutdown(self): print("[cn.appincloud.skeleton] MyExtension shutdown") def _on_assign_selected(self): # find currently seleced joint usd_context = omni.usd.get_context() stage = usd_context.get_stage() selection = usd_context.get_selection() selected_prims = selection.get_selected_prim_paths() skeleton = None if len(selected_prims) > 0: prim = stage.GetPrimAtPath(selected_prims[0]) print(prim) if AnimationSchema.SkelJoint(prim): skeleton, joint_token = AnimationSchema.SkelJoint(prim).GetJoint() elif UsdSkel.Skeleton(prim): print("skeleton") #skeleton = UsdSkel.Skeleton(prim) #addJoint(skeleton) #print(skeleton.GetRestTransformsAttr().Get()) elif UsdSkel.Root(prim): print("skeleton root", selected_prims[0]) file_url = usd_context.get_stage_url() prim_url = omni.usd.get_url_from_prim(prim) print(file_url, prim_url) if prim_url is not None and file_url != prim_url: usd_context.open_stage(prim_url) stage = usd_context.get_stage() prim_path = "/World/Hips0" prim = stage.GetPrimAtPath(prim_path) else: prim_url = file_url if prim_url is None or prim_url.startswith("omniverse:"): tmp_dir = carb.tokens.get_tokens_interface().resolve("${shared_documents}/capture/temp") tmp_fname = "stage_test_" + str(uuid.uuid4()) + ".usda" tmp_fpath = os.path.normpath(os.path.abspath(os.path.join(tmp_dir, tmp_fname))) else: tmp_fpath = prim_url.replace(".usd",".usda") root = UsdSkel.Root(prim) prims = prim.GetChildren() for subprim in prims: if UsdSkel.Skeleton(subprim): skel = UsdSkel.Skeleton(subprim) addRootToUsd(skel, tmp_fpath) #stage = Usd.Stage.Open(tmp_fpath) print("loading...") stage = usd_context.open_stage(tmp_fpath) usd_context.attach_stage_with_callback(stage) break else: dialog = MessageDialog(title="no prim selected", message="please select a prim", disable_okay_button=True, disable_cancel_button=False) dialog.show() def _copy_skel(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() selection = usd_context.get_selection() selected_prims = selection.get_selected_prim_paths() skeleton = None if len(selected_prims) > 1: prim1 = stage.GetPrimAtPath(selected_prims[0]) prim2 = stage.GetPrimAtPath(selected_prims[1]) print(prim1, prim2) copySkel(prim1, prim2) def _copy_anim(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() selection = usd_context.get_selection() selected_prims = selection.get_selected_prim_paths() if len(selected_prims) > 1: _source_skeleton = UsdSkel.Skeleton(stage.GetPrimAtPath(selected_prims[0])) _target_skeleton = UsdSkel.Skeleton(stage.GetPrimAtPath(selected_prims[1])) copyAnim(_source_skeleton, _target_skeleton, "/World/testanim") else: return def _copy_rot(self): usd_context = omni.usd.get_context() stage = usd_context.get_stage() selection = usd_context.get_selection() selected_prims = selection.get_selected_prim_paths() if len(selected_prims) > 0: _source_skeleton = UsdSkel.Skeleton(stage.GetPrimAtPath(selected_prims[0])) copyRotation(_source_skeleton, "/World/testanim") else: return
5,939
Python
44.343511
147
0.572319
terrylincn/omniskeleton/cn/appincloud/skeleton/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
terrylincn/omniskeleton/cn/appincloud/skeleton/skeletonutils.py
import omni from pxr import Usd, UsdSkel, Vt, Gf import numpy as np import copy from omni.anim.retarget.core.scripts.utils import ( convert_matrix_to_trans_rots, convert_trans_rots_to_pxr ) import carb import os import uuid root_rest_translations = ((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1)) def addJoint(skel): def translation2transform(vec): t = np.eye(4) t[:-1, -1] = vec return t.T skel_cache = UsdSkel.Cache() skel_query = skel_cache.GetSkelQuery(skel) joint_tokens = skel.GetJointsAttr().Get()#skel_query.GetJointOrder() root_t = copy.deepcopy(root_rest_translations) rest_translations = [root_t] + np.asarray(skel.GetRestTransformsAttr().Get()) bind_translations = [root_t] + np.asarray(skel.GetBindTransformsAttr().Get()) rest_transforms = Vt.Matrix4dArray.FromNumpy( rest_translations #np.array([translation2transform(x) for x in rest_translations]) ) bind_transforms = Vt.Matrix4dArray.FromNumpy( bind_translations #np.array([translation2transform(x) for x in bind_translations]) ) joint_tokens = ["root"] + ["root/" + token for token in joint_tokens] skel_cache.Clear() skel.GetRestTransformsAttr().Set(rest_transforms) skel.GetBindTransformsAttr().Set(bind_transforms) skel.GetJointsAttr().Set(joint_tokens) """ anim = UsdSkel.Animation.Define(stage, root_path + "/Skeleton/Anim") anim.GetJointsAttr().Set(joint_tokens) binding = UsdSkel.BindingAPI.Apply(skel.GetPrim()) binding.CreateAnimationSourceRel().SetTargets([anim.GetPrim().GetPath()]) binding = UsdSkel.BindingAPI.Apply(skel_root.GetPrim()) binding.CreateSkeletonRel().SetTargets([skel.GetPrim().GetPath()]) """ def save_as_usda(fpath): omni.usd.get_context().save_as_stage(fpath) def add_root(content, skelroot="Hips0", joint="Hips"): content = content.replace(skelroot, "skelroot") content = content.replace(joint, "Root/" + joint) content = content.replace("uniform matrix4d[] restTransforms = [", "uniform matrix4d[] restTransforms = [((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1)),") content = content.replace("uniform matrix4d[] bindTransforms = [", "uniform matrix4d[] bindTransforms = [((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1)),") content = content.replace('uniform token[] joints = [', 'uniform token[] joints = ["Root",') return content def load_usda(fpath): with open(fpath, 'r') as fp: content = fp.read() return content def save_usda(fpath, content): with open(fpath, 'w') as fp: fp.write(content) def addRootToUsd(skel, fpath): save_as_usda(fpath) content = load_usda(fpath) content = add_root(content) save_usda(fpath, content) def copySkel(source_prim, target_prim): #interpolation = "vertex" elementSize = 4 source_binding = UsdSkel.BindingAPI.Apply(source_prim) target_binding = UsdSkel.BindingAPI.Apply(target_prim) joints = source_binding.GetJointsAttr() target_binding.CreateJointsAttr().Set(joints.Get()) jointIndices = source_binding.GetJointIndicesAttr() target_binding.CreateJointIndicesAttr().Set(jointIndices.Get()) target_binding.CreateJointIndicesPrimvar(constant=False,elementSize=elementSize) jointWeights = source_binding.GetJointWeightsAttr() target_binding.CreateJointWeightsAttr().Set(jointWeights.Get()) target_binding.CreateJointWeightsPrimvar(constant=False,elementSize=elementSize) geomBind = source_binding.GetGeomBindTransformAttr() target_binding.CreateGeomBindTransformAttr().Set(geomBind.Get()) skelRel = source_binding.GetSkeletonRel().GetTargets() target_binding.CreateSkeletonRel().SetTargets(skelRel) def convert_to_trans_rots(translations1, rotations1): translations: List[carb.Float3] = [] rotations: List[carb.Float4] = [] for trans in translations1: translations.append(carb.Float3(trans[0], trans[1], trans[2])) for quat in rotations1: rotations.append(carb.Float4(quat.imaginary[0], quat.imaginary[1], quat.imaginary[2], quat.real)) return translations, rotations def copyAnim(source_skeleton, target_skeleton, prim_path): retarget_controller = omni.anim.retarget.core.RetargetController( "", source_skeleton.GetPath().pathString, target_skeleton.GetPath().pathString ) if (source_skeleton and target_skeleton): stage = omni.usd.get_context().get_stage() time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond() # copy source transform source_skel_cache = UsdSkel.Cache() source_skel_query = source_skel_cache.GetSkelQuery(source_skeleton) source_transforms = source_skel_query.ComputeJointLocalTransforms(time_code) source_translations, source_rotations = convert_matrix_to_trans_rots(source_transforms) joint_tokens = target_skeleton.GetJointsAttr().Get() #skel_cache = UsdSkel.Cache() #skel_query = skel_cache.GetSkelQuery(target_skeleton) target_translations, target_rotations = retarget_controller.retarget(source_translations, source_rotations) t1, t2, t3 =convert_trans_rots_to_pxr(target_translations, target_rotations) """ this only gets one source_binding = UsdSkel.BindingAPI.Apply(source_skeleton.GetPrim()) source_prim = source_binding.GetAnimationSource() source_anim = UsdSkel.Animation.Get(stage, source_prim.GetPath()) source_translations = source_anim.GetTranslationsAttr().Get() source_rotations = source_anim.GetRotationsAttr().Get() source_translations, source_rotations = convert_to_trans_rots(source_translations, source_rotations) """ suurce_anim_query = source_skel_query.GetAnimQuery() #source_skel_anim = UsdSkel.Animation(suurce_anim_query.GetPrim()) jtt = suurce_anim_query.GetJointTransformTimeSamples() prim = suurce_anim_query.GetPrim() prim_path = prim.GetPath().pathString + "_target" carb.log_info("jtt:{}".format(jtt)) target_anim = UsdSkel.Animation.Define(stage, prim_path) target_anim.CreateJointsAttr().Set(joint_tokens) transAttr = target_anim.CreateTranslationsAttr() rotAttr = target_anim.CreateRotationsAttr() scalAttr = target_anim.CreateScalesAttr() tt1 = {} tt2 = {} for jt in jtt: source_transforms = suurce_anim_query.ComputeJointLocalTransforms(Usd.TimeCode(jt)) source_translations, source_rotations = convert_matrix_to_trans_rots(source_transforms) carb.log_info("time:{} source_translations:{} source_rotations:{}".format(jt, source_translations, source_rotations)) # retarget target_translations: List[carb.Float3] = [] target_rotations: List[carb.Float4] = [] target_translations, target_rotations = retarget_controller.retarget(source_translations, source_rotations) tt1[jt] = target_translations tt2[jt] = target_rotations target_translations, target_rotations, target_scales = convert_trans_rots_to_pxr(target_translations, target_rotations) transAttr.Set(target_translations, Usd.TimeCode(jt)) rotAttr.Set(target_rotations, Usd.TimeCode(jt)) scalAttr.Set(target_scales, Usd.TimeCode(jt)) """ omni.usd.get_context().new_stage() new_stage = omni.usd.get_context().get_stage() target_anim = UsdSkel.Animation.Define(new_stage, "/World") target_anim.CreateJointsAttr().Set(joint_tokens) target_anim.CreateTranslationsAttr().Set(t1) target_anim.CreateRotationsAttr().Set(t2) target_anim.CreateScalesAttr().Set(t3) """ return tt1, tt2 def add_timesamples(translations, rotations, content): content = content.replace('SkelAnimation "World"', 'SkelAnimation "World"(apiSchemas = ["AnimationSkelBindingAPI"])') txt1 = '\nfloat3[] translations.timeSamples = {' for key, translation in translations.items(): txt1 += '{}:{},\n'.format(key, translation).replace("carb.Float3","") txt1 += '}\n' txt2 = '\nquatf[] rotations.timeSamples = {' for key, rotation in rotations.items(): txt2 += '{}:{},\n'.format(key, rotation).replace("carb.Float4","") txt2 += '}\n' carb.log_info(txt1) carb.log_info(txt2) newcontent = content[:content.rfind("}")-1] + txt1 + txt2 + '}' return newcontent def copyAnimToUsd(source_skeleton, target_skeleton, prim_path): tmp_dir = carb.tokens.get_tokens_interface().resolve("${shared_documents}/capture/temp") tmp_fname = "stage_test_" + str(uuid.uuid4()) + ".usda" fpath = os.path.normpath(os.path.abspath(os.path.join(tmp_dir, tmp_fname))) tt1, tt2 = copyAnim(source_skeleton, target_skeleton, prim_path) save_as_usda(fpath) content = load_usda(fpath) content = add_timesamples(tt1, tt2, content) save_usda(fpath, content) def extract_transforms(source_transforms): source_translations = [] source_rotations = [] for source_transform in source_transforms: source_translations.append(source_transform.ExtractTranslation()) source_rotations.append(source_transform.ExtractRotation()) return source_translations, source_rotations def copyRotation(source_skeleton, prim_path): if (source_skeleton): stage = omni.usd.get_context().get_stage() time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond() # copy source transform source_skel_cache = UsdSkel.Cache() source_skel_query = source_skel_cache.GetSkelQuery(source_skeleton) #source_transforms = source_skel_query.ComputeJointLocalTransforms(time_code) #source_translations, source_rotations = convert_matrix_to_trans_rots(source_transforms) source_transforms = source_skeleton.GetBindTransformsAttr().Get() source_transforms = source_skeleton.GetRestTransformsAttr().Get() source_translations, source_rotations = convert_matrix_to_trans_rots(source_transforms) source_translations, source_rotations, source_scales = convert_trans_rots_to_pxr(source_translations, source_rotations) joint_tokens = source_skeleton.GetJointsAttr().Get() target_anim = UsdSkel.Animation.Define(stage, prim_path) target_anim.CreateJointsAttr().Set(joint_tokens) target_anim.CreateTranslationsAttr().Set(source_translations) target_anim.CreateRotationsAttr().Set(source_rotations) target_anim.CreateScalesAttr().Set(source_scales)
11,078
Python
45.746835
153
0.66447
terrylincn/omniskeleton/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Simple UI Extension Template" description="The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "cn.appincloud.skeleton"
805
TOML
26.793103
105
0.742857
tangkangqi/omnivese-ai-kit-IAT-course/README.md
[# omnivese-ai-kit-IAT-course 课程目标 本课程旨在向开发者介绍如何使用NVIDIA Omniverse Kit开发AI扩展插件。通过学习Kit的基础概念、API以及环境配置、微服务、调用AI应用、插件发布等知识,学员将能够开发出自己的AI文生贴图插件。 课程时长 总时长:2小时 课程安排 第一部分:Kit基础概念 (30分钟) - Kit核心组件、架构概览 (10分钟) - Kit API介绍 (10分钟) - Kit USD介绍 (10分钟) 第二部分:Kit开发 (45分钟) - Kit UI交互开发 (15分钟) - 演示如何开发用户界面,包括基本的UI组件和交互逻辑。 - Extension.toml介绍 (10分钟) - 介绍如何使用Extension.toml文件配置和管理Kit扩展 - 使用AI功能 (20分钟) - Kit如何安装python pip包 (5分钟) - 介绍在Kit环境中安装和管理Python依赖。 - Kit微服务开发 (5分钟) - 如何开发和使用Kit微服务,以支持复杂的AI功能。 - 创建和导入Kit插件 (10分钟) - 演示如何创建Kit插件,并将其导入到Omniverse中使用 第三部分:案例:AI文生贴图插件开发 (45分钟) - SDXL文生图代码介绍 (10分钟) - 介绍如何利用AI生成图像。 - Kit 新建Object和贴图 (10分钟) - 演示如何使用Kit Python API新建对象和应用贴图。 - 插件UI开发和调试 (15分钟) - 文本生图插件发布 (10分钟) 请注意,课程内容和时间分配可能根据实际情况进行调整。 学员将获得相关的学习材料和代码示例 附录:课程运行环境详细配置 为了确保课程的顺利进行,以下是详细的环境配置要求: 系统环境: - 操作系统:Windows 10 - GPU驱动:版本 537.13 - CUDA版本:12.3 - Omniverse环境: - OVE已安装 - Omniverse USD Composer版本为2023.2.0 - 开发环境: - Visual Studio Code (Vscode),安装日期为2024年3月12日的最新版本 AI开发环境: - Python环境管理: - Miniconda,安装日期为2024年3月12日的最新版本 - 在Miniconda中创建Python 3.12环境 - 深度学习库: - 安装PyTorch 2.2.0及相关库, 参考安装指南:PyTorch Get Started - Previous Versions - 文生图模型下载: - 从Huggingface下载LCM模型。模型链接:LCM_Dreamshaper_v7 网络环境: - 需要能够访问Google的网络环境,以便于AI代码运行时能够高速访问GitHub、Huggingface和pip官方源。 注意事项: - 确保在安装和配置环境之前,您的系统满足上述所有要求。 - 安装CUDA和GPU驱动时,请遵循官方指南,确保版本兼容性。 - 在配置Python环境时,确保使用的是Miniconda创建的指定版本环境,以避免版本冲突。 - 在下载和使用Huggingface模型时,请确保遵守相关使用协议和条件。 - 确保网络环境稳定,以便于顺利完成模型下载和库安装。 附录: 课程运行环境: Windows 10 系统 GPU Driver: 537.13 CUDA版本: 12.3 OVE 已安装,Omniverse USD Composer 2023.2.0 Vscode , 安装24/3/12 最新版本 AI 环境: - Miniconda, 安装24/3/12 最新版本 - Miniconda 中创建python 3.12 环境: - 安装torch2.2.0, 参考: https://pytorch.org/get-started/previous-versions/ - pip install torch==2.2.0 torchvision==0.17.0 torchaudio==2.2.0 --index-url https://download.pytorch.org/whl/cu121 - Huggingface 下载LCM 模型:https://huggingface.co/SimianLuo/LCM_Dreamshaper_v7/tree/main 能够访问google的网络环境 ( AI 代码运行,需要github,huggingface, pip 官方源高速访问) ](https://vj0y7kxa0d.feishu.cn/docx/TKqKdBqHioxUFvx36j9cjZpOnFd)
2,068
Markdown
22.781609
115
0.765474
tangkangqi/omnivese-ai-kit-IAT-course/exts/iat.diffuser/iat/diffuser/extension.py
import omni.ext import omni.ui as ui from pathlib import Path import omni.kit.viewport.utility as vp_utils from PIL import Image import omni.kit.notification_manager as notifier from pxr import UsdGeom, UsdShade, UsdLux, Vt, Gf, Sdf, Usd, UsdUtils, Tf import asyncio import requests import numpy as np import shutil import os SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__)) import random import string import logging logger = logging.getLogger(__name__) logger.info("123") logger.warning("456") # import omni.kit.pipapi # omni.kit.pipapi.install("requests") # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[iat.diffuser] some_public_function was called with x: ", x) return x ** x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class IatDiffuserExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def __init__(self) -> None: super().__init__() self._name = 'IATDiffuser' self._path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self.outdir = Path(self._path) / '_output_images' self.outdir.mkdir(exist_ok=True, parents=True) self.cachedir = Path(self._path) / '_model_cache' self.cachedir.mkdir(exist_ok=True, parents=True) self.model_id = '' self.prev_imgpath = Path(self._path) / "data/dummy.png" self.imgpath = Path(self._path) / "data/dummy.png" self._image_shape = (512, 512) self.prev_texture_image = None self.texture_batch = [] self.texture_image = self._load_image_from_file(self.imgpath) self.texture_mask = None self.diffuser_pipe = None self._seamless = True self._loaded_scene = False # self._loaded_scene = True self._logged_in = False self._image_provider = ui.ByteImageProvider() self.i2i_strength = 0.5 self.batch_size = 4 self.mini_image_providers = [ui.ByteImageProvider() for _ in range(self.batch_size)] self.imgpath_batch = ['' for _ in range(self.batch_size)] self._usd_context = omni.usd.get_context() self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event ) def on_startup(self, ext_id): # ext_id is the current extension id. It can be used with the extension manager to query additional information, # such as where this extension is located in the filesystem. print(f"{self} startup", flush=True) self._window = ui.Window(self._name, width=500, height=500) self.build_ui() def on_shutdown(self): print("[iat.diffuser] iat diffuser shutdown") def build_ui(self): with self._window.frame: with ui.VStack(): with ui.Frame(height=50): with ui.VStack(): self.text_box = ui.StringField(style={'font_size': 30}) self.text_box.model.set_value('an old tree bark') with ui.HStack(): generate_button = ui.Button('Text to Image', height=40) generate_button.set_clicked_fn(self.inference) i2i_button = ui.Button('Image to Image', height=40) i2i_button.set_clicked_fn(self.i2i_inference) undo_button = ui.Button('Undo', height=40) undo_button.set_clicked_fn(self._on_undo_click) with ui.HStack(): ui.Label("diffusion service url:", style={'font_size': 15}) self.url_box = ui.StringField(style={'font_size': 20}, width=450) self.url_box.model.set_value('http://127.0.0.1:8000') ui.Spacer(height=5) with ui.HStack(): ui.Label('Scale') ui.Spacer(width=5) ui.Label('Strength') ui.Spacer(width=5) ui.Label('Batch size') with ui.Frame(height=50): with ui.VStack(): # ui.Spacer(height=10) with ui.HStack(): model_button = ui.Button(f"Load models", height=40) model_button.set_clicked_fn(self._load_model) ui.Spacer(width=10) image_button = ui.Button(f"Select image", height=40) image_button.set_clicked_fn(self._on_select_image_click) with ui.Frame(height=450): with ui.VStack(): image_provider = ui.ImageWithProvider(self._image_provider) #, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT) self.set_image_provider(self.texture_image) ### STAGE & USD ### def _on_stage_event(self, evt): if evt.type == int(omni.usd.StageEventType.OPENED): print(f"{self} Stage opened") self._on_stage_opened() elif evt.type == int(omni.usd.StageEventType.ASSETS_LOADED): self._hide_stage_defaults() def _on_stage_opened(self): self._load_scene() def _load_scene(self): if self._loaded_scene: return self._usd_context = omni.usd.get_context() stage = self._usd_context.get_stage() preset_path = str(Path(self._path) / "data/scene.usd") root_layer = stage.GetRootLayer() root_layer.subLayerPaths = [preset_path] # HACK: move prims to /World (default prim) from /Environment to allow changes to visibility cube = stage.GetPrimAtPath("/Environment/Cube") if cube: omni.kit.commands.execute("MovePrimCommand", path_from="/Environment/Cube", path_to="/World/Cube") cube = stage.GetPrimAtPath("/World/Cube") cube.GetAttribute("visibility").Set("inherited") sphere = stage.GetPrimAtPath("/Environment/Sphere") if cube: omni.kit.commands.execute("MovePrimCommand", path_from="/Environment/Sphere", path_to="/World/Sphere") sphere = stage.GetPrimAtPath("/World/Sphere") sphere.GetAttribute("visibility").Set("inherited") vp = vp_utils.get_active_viewport() vp.set_active_camera("/World/Camera") self._loaded_scene = True def _hide_stage_defaults(self): stage = omni.usd.get_context().get_stage() ground_plane = stage.GetPrimAtPath("/Environment/GroundPlane") if ground_plane: print(f"{self} hiding /Environment/GroundPlane") ground_plane.GetAttribute("visibility").Set("invisible") # hide ground plane ground_plane = stage.GetPrimAtPath("/Environment/Plane") if ground_plane: print(f"{self} hiding /Environment/Plane") ground_plane.GetAttribute("visibility").Set("invisible") # hide ground plane ## Update Materials def _update_material(self, material_path, params): stage = self._usd_context.get_stage() # ctx = omni.usd.get_context() # stage = ctx.get_stage() # selection = ctx.get_selection().get_selected_prim_paths() material = stage.GetPrimAtPath(material_path) logger.warn((f"{self} material: {material}")) shader = UsdShade.Shader(omni.usd.get_shader_from_material(material.GetPrim(), True)) logger.warn(f"{self} shader: {shader}") # For each parameter, write to material for param, value in params.items(): logger.warn(f"{self} creating & getting input: {param}") shader.CreateInput(param, Sdf.ValueTypeNames.Asset) shader.GetInput(param).Set(value) ## Click select image def _on_select_image_click(self): """Show filepicker after load image is clicked""" self._filepicker = omni.kit.window.filepicker.FilePickerDialog( f"{self}/Select Image", click_apply_handler=lambda f, d: asyncio.ensure_future(self._on_image_selection(f, d)), ) try: self._filepicker.navigate_to(os.path.expanduser("~/")) except Exception: print(f"could not find {os.path.expanduser('~')}") self._filepicker.refresh_current_directory() omni.kit.window.filepicker def _on_undo_click(self): print(self.imgpath) print(self.prev_imgpath) self.imgpath = self.prev_imgpath self.texture_image = self._load_image_from_file(self.imgpath) self.set_image_provider(self.texture_image) self._update_material('/Environment/Looks/OmniPBR', {"diffuse_texture": str(self.imgpath) }) def _on_model_select_click(self): pass async def _on_image_selection(self, filename, dirname): """Load the selected image.""" selections = self._filepicker.get_current_selections() if os.path.isfile(selections[0]): self.imgpath = selections[0] else: print('Select a valid image file.') return print(f"{self} Loading image from: {self.imgpath}") self.texture_image = self._load_image_from_file(self.imgpath) self.set_image_provider(self.texture_image) self._update_material('/Environment/Looks/OmniPBR', {"diffuse_texture": str(self.imgpath) }) self._filepicker.hide() self._window.frame.rebuild() def _load_image_from_file(self, imgpath): img = Image.open(imgpath) # w, h = img.size # min_size = min(w, h) img = img.resize(self._image_shape) return img def refresh_image(self): self.image_box.set_style({'image_url': str(self.imgpath)}) ### MODEL ### def _load_model(self, new_model_id=None, new_model_inpaint_id=None): pass def i2i_inference(self): pass def generate(self, prompt): base_url = self.url_box.model.get_value_as_string() url = "%s/txt2img/%s"%(base_url, prompt) # res = {'file_name': 'res.jpg', 'prompt': 'how are you', 'time': 11.930987119674683} res = requests.get(url).json() print(res) im_url = "%s/download/%s"%(base_url, res["file_name"]) r = requests.get(im_url) open(os.path.join(SCRIPT_PATH, "data", "res.jpg"), "wb").write(r.content) # shutil.copy(os.path.join(SCRIPT_PATH, "data", "res.jpg"), os.path.join(self.outdir, res["file_name"])) # random_name_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) image_num = len(os.listdir(self.outdir)) fpath = os.path.join(self.outdir, "%04d-%s"%(image_num, res["file_name"])) shutil.copy(os.path.join(SCRIPT_PATH, "data", "res.jpg"), fpath) return r.content def inference(self): prompt = self.text_box.model.get_value_as_string() print(f"{self} {prompt}") # self.texture_batch = self.diffuser_pipe([prompt]*self.batch_size).images self.texture_batch = self.generate(prompt=prompt) # texture update self.prev_imgpath = self.imgpath self.imgpath = os.path.join(SCRIPT_PATH, "data", "res.jpg") self.texture_image = self._load_image_from_file(os.path.join(SCRIPT_PATH, "data", "res.jpg")) logger.warn("diffusion images: %s"%(self.imgpath)) self._load_scene() self._update_material('/Environment/Looks/OmniPBR', {"diffuse_texture": str(self.imgpath) }) self.set_image_provider(self.texture_image) def set_image_provider(self, img): if isinstance(img, Image.Image): img = np.asarray(img, dtype=np.uint8) elif isinstance(img, np.ndarray): pass else: print('Unknown image format.') # Create alpha channel since ImageProvider expects a 4-channel image alpha_channel = np.ones_like(img[:,:,[0]], dtype=np.uint8) * 255 if img.shape[2] == 3 : img = np.concatenate([img, alpha_channel], axis=2) print('updating image provider') self._image_provider.set_data_array(img, (img.shape[0], img.shape[1]))
12,784
Python
40.644951
141
0.59332
tangkangqi/omnivese-ai-kit-IAT-course/exts/iat.diffuser/iat/diffuser/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
tangkangqi/omnivese-ai-kit-IAT-course/exts/iat.diffuser/iat/diffuser/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
tangkangqi/omnivese-ai-kit-IAT-course/exts/iat.diffuser/iat/diffuser/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import iat.diffuser # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = iat.diffuser.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,660
Python
34.340425
142
0.680723
tangkangqi/omnivese-ai-kit-IAT-course/exts/iat.diffuser/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "iat diffuser" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" requirements = [ "requests", "numpy" ] # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.ngsearch" = {} "omni.kit.window.popup_dialog" = {} # Main python module this extension provides, it will be publicly available as "import iat.diffuser". [[python.module]] name = "iat.diffuser" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,672
TOML
28.874999
118
0.733254
tangkangqi/omnivese-ai-kit-IAT-course/exts/iat.diffuser/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
tangkangqi/omnivese-ai-kit-IAT-course/exts/iat.diffuser/docs/README.md
# Python Extension Example [iat.diffuser] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
171
Markdown
33.399993
126
0.783626
tangkangqi/omnivese-ai-kit-IAT-course/exts/iat.diffuser/docs/index.rst
iat.diffuser ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"iat.diffuser" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
325
reStructuredText
14.523809
43
0.609231
tangkangqi/omnivese-ai-kit-IAT-course/iat_diffuser_server/pipline.py
from fastapi import FastAPI from fastapi import File, UploadFile from fastapi.responses import FileResponse import time import shutil import torch from diffusers import DiffusionPipeline app = FastAPI() def load_lcm_pipe(): pipe = DiffusionPipeline.from_pretrained("SimianLuo/LCM_Dreamshaper_v7") # To save GPU memory, torch.float16 can be used, but it may compromise image quality. pipe.to(torch_device="cuda", torch_dtype=torch.float32) return pipe pipe = load_lcm_pipe() @app.get("/download/{name_file}") def download_file(name_file: str): return FileResponse(path= "data/" + name_file, media_type='application/octet-stream', filename=name_file) def gen_image(prompt): num_inference_steps = 4 images = pipe(prompt=prompt, num_inference_steps=num_inference_steps, guidance_scale=8.0, lcm_origin_steps=50, output_type="pil").images print(len(images)) image = images[0] fname = "%s.jpg"%("-".join(prompt.split(" "))) image.save("data/" + fname) shutil.copy("data/" + fname, "data/res.jpg") return fname def test_infer(self): prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k" gen_image(prompt) @app.get("/txt2img/{prompt}") def get_image(prompt: str): t0 = time.time() fname = gen_image(prompt) return {"file_name": fname, "prompt": prompt, "time": time.time() - t0}
1,376
Python
30.295454
140
0.699128
jonasmaximilian/orbit.test/pyproject.toml
[build-system] requires = ["setuptools", "toml"] build-backend = "setuptools.build_meta" [tool.isort] atomic = true profile = "black" line_length = 120 py_version = 310 skip_glob = ["docs/*", "logs/*", "_orbit/*", "_isaac_sim/*"] group_by_package = true sections = [ "FUTURE", "STDLIB", "THIRDPARTY", "ORBITPARTY", "FIRSTPARTY", "LOCALFOLDER", ] extra_standard_library = [ "numpy", "h5py", "open3d", "torch", "tensordict", "bpy", "matplotlib", "gymnasium", "gym", "scipy", "hid", "yaml", "prettytable", "toml", "trimesh", "tqdm", ] known_thirdparty = [ "omni.isaac.core", "omni.replicator.isaac", "omni.replicator.core", "pxr", "omni.kit.*", "warp", "carb", ] known_orbitparty = [ "omni.isaac.orbit", "omni.isaac.orbit_tasks", "omni.isaac.orbit_assets" ] # Modify the following to include the package names of your first-party code known_firstparty = "orbit.ext_template" known_local_folder = "config" [tool.pyright] exclude = [ "**/__pycache__", "**/_isaac_sim", "**/_orbit", "**/docs", "**/logs", ".git", ".vscode", ] typeCheckingMode = "basic" pythonVersion = "3.10" pythonPlatform = "Linux" enableTypeIgnoreComments = true # This is required as the CI pre-commit does not download the module (i.e. numpy, torch, prettytable) # Therefore, we have to ignore missing imports reportMissingImports = "none" # This is required to ignore for type checks of modules with stubs missing. reportMissingModuleSource = "none" # -> most common: prettytable in mdp managers reportGeneralTypeIssues = "none" # -> raises 218 errors (usage of literal MISSING in dataclasses) reportOptionalMemberAccess = "warning" # -> raises 8 errors reportPrivateUsage = "warning"
1,823
TOML
20.458823
103
0.633022
jonasmaximilian/orbit.test/setup.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Installation script for the 'orbit.ext_template' python package.""" import os import toml from setuptools import setup # Obtain the extension data from the extension.toml file EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__)) # Read the extension.toml file EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml")) # Minimum dependencies required prior to installation INSTALL_REQUIRES = [ # NOTE: Add dependencies "psutil", ] # Installation operation setup( # TODO: Change your package naming # ----------------------------------------------------------------- name="orbit.ext_template", packages=["orbit.ext_template"], # ----------------------------------------------------------------- author=EXTENSION_TOML_DATA["package"]["author"], maintainer=EXTENSION_TOML_DATA["package"]["maintainer"], maintainer_email=EXTENSION_TOML_DATA["package"]["maintainer_email"], url=EXTENSION_TOML_DATA["package"]["repository"], version=EXTENSION_TOML_DATA["package"]["version"], description=EXTENSION_TOML_DATA["package"]["description"], keywords=EXTENSION_TOML_DATA["package"]["keywords"], install_requires=INSTALL_REQUIRES, license="BSD-3-Clause", include_package_data=True, python_requires=">=3.10", classifiers=[ "Natural Language :: English", "Programming Language :: Python :: 3.10", "Isaac Sim :: 2023.1.0-hotfix.1", "Isaac Sim :: 2023.1.1", ], zip_safe=False, )
1,647
Python
31.959999
89
0.631451
jonasmaximilian/orbit.test/README.md
# Extension Template for Orbit [![IsaacSim](https://img.shields.io/badge/IsaacSim-2023.1.1-silver.svg)](https://docs.omniverse.nvidia.com/isaacsim/latest/overview.html) [![Orbit](https://img.shields.io/badge/Orbit-0.2.0-silver)](https://isaac-orbit.github.io/orbit/) [![Python](https://img.shields.io/badge/python-3.10-blue.svg)](https://docs.python.org/3/whatsnew/3.10.html) [![Linux platform](https://img.shields.io/badge/platform-linux--64-orange.svg)](https://releases.ubuntu.com/20.04/) [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://pre-commit.com/) ## Overview This repository serves as a template for building projects or extensions based on Orbit. It allows you to develop in an isolated environment, outside of the core Orbit repository. Furthermore, this template serves three use cases: - **Python Package** Can be installed into Isaac Sim's Python environment, making it suitable for users who want to integrate their extension to `Orbit` as a python package. - **Project Template** Ensures access to `Isaac Sim` and `Orbit` functionalities, which can be used as a project template. - **Omniverse Extension** Can be used as an Omniverse extension, ideal for projects that leverage the Omniverse platform's graphical user interface. **Key Features:** - `Isolation` Work outside the core Orbit repository, ensuring that your development efforts remain self-contained. - `Flexibility` This template is set up to allow your code to be run as an extension in Omniverse. **Keywords:** extension, template, orbit ### License The source code is released under a [BSD 3-Clause license](https://opensource.org/licenses/BSD-3-Clause). **Author: The ORBIT Project Developers<br /> Affiliation: [The AI Institute](https://theaiinstitute.com/)<br /> Maintainer: Nico Burger, [email protected]** ## Setup Depending on the use case defined [above](#overview), follow the instructions to set up your extension template. Start with the [Basic Setup](#basic-setup), which is required for either use case. ### Basic Setup #### Dependencies This template depends on Isaac Sim and Orbit. For detailed instructions on how to install these dependencies, please refer to the [installation guide](https://isaac-orbit.github.io/orbit/source/setup/installation.html). - [Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/index.html) - [Orbit](https://isaac-orbit.github.io/orbit/) #### Configuration Decide on a name for your project or extension. This guide will refer to this name as `<your_extension_name>`. - Create a new repository based off this template [here](https://github.com/new?owner=isaac-orbit&template_name=orbit.ext_template&template_owner=isaac-orbit). Name your forked repository using the following convention: `"orbit.<your_extension_name>"`. - Clone your forked repository to a location **outside** the orbit repository. ```bash git clone <your_repository_url> ``` - To tailor this template to your needs, customize the settings in `config/extension.toml` and `setup.py` by completing the sections marked with TODO. - Rename your source folder. ```bash cd orbit.<your_extension_name> mv orbit/ext_template orbit/<your_extension_name> ``` - Define the following environment variable to specify the path to your Orbit installation: ```bash # Set the ORBIT_PATH environment variable to point to your Orbit installation directory export ORBIT_PATH=<your_orbit_path> ``` #### Set Python Interpreter Although using a virtual environment is optional, we recommend using `conda` (detailed instructions [here](https://isaac-orbit.github.io/orbit/source/setup/installation.html#setting-up-the-environment)). If you decide on using Isaac Sim's bundled Python, you can skip these steps. - If you haven't already: create and activate your `conda` environment, followed by installing extensions inside Orbit: ```bash # Create conda environment ${ORBIT_PATH}/orbit.sh --conda # Activate conda environment conda activate orbit # Install all Orbit extensions in orbit/source/extensions ${ORBIT_PATH}/orbit.sh --install ``` - Set your `conda` environment as the default interpreter in VSCode by opening the command palette (`Ctrl+Shift+P`), choosing `Python: Select Interpreter` and selecting your `conda` environment. Once you are in the virtual environment, you do not need to use `${ORBIT_PATH}/orbit.sh -p` to run python scripts. You can use the default python executable in your environment by running `python` or `python3`. However, for the rest of the documentation, we will assume that you are using `${ORBIT_PATH}/orbit.sh -p` to run python scripts. #### Set up IDE To setup the IDE, please follow these instructions: 1. Open the `orbit.<your_extension_template>` directory on Visual Studio Code IDE 2. Run VSCode Tasks, by pressing `Ctrl+Shift+P`, selecting `Tasks: Run Task` and running the `setup_python_env` in the drop down menu. When running this task, you will be prompted to add the absolute path to your Orbit installation. If everything executes correctly, it should create a file .python.env in the .vscode directory. The file contains the python paths to all the extensions provided by Isaac Sim and Omniverse. This helps in indexing all the python modules for intelligent suggestions while writing code. ### Setup as Python Package / Project Template From within this repository, install your extension as a Python package to the Isaac Sim Python executable. ```bash ${ORBIT_PATH}/orbit.sh -p -m pip install --upgrade pip ${ORBIT_PATH}/orbit.sh -p -m pip install -e . ``` ### Setup as Omniverse Extension To enable your extension, follow these steps: 1. **Add the search path of your repository** to the extension manager: - Navigate to the extension manager using `Window` -> `Extensions`. - Click on the **Hamburger Icon** (☰), then go to `Settings`. - In the `Extension Search Paths`, enter the path that goes up to your repository's location without actually including the repository's own directory. For example, if your repository is located at `/home/code/orbit.ext_template`, you should add `/home/code` as the search path. - If not already present, in the `Extension Search Paths`, enter the path that leads to your local Orbit directory. For example: `/home/orbit/source/extensions` - Click on the **Hamburger Icon** (☰), then click `Refresh`. 2. **Search and enable your extension**: - Find your extension under the `Third Party` category. - Toggle it to enable your extension. ## Usage ### Python Package Import your python package within `Isaac Sim` and `Orbit` using: ```python import orbit.<your_extension_name> ``` ### Project Template We provide an example for training and playing a policy for ANYmal on flat terrain. Install [RSL_RL](https://github.com/leggedrobotics/rsl_rl) outside of the orbit repository, e.g. `home/code/rsl_rl`. ```bash git clone https://github.com/leggedrobotics/rsl_rl.git cd rsl_rl ${ORBIT_PATH}/orbit.sh -p -m pip install -e . ``` Train a policy. ```bash cd <path_to_your_extension> ${ORBIT_PATH}/orbit.sh -p scripts/rsl_rl/train.py --task Template-Velocity-Flat-Anymal-D-v0 --num_envs 4096 --headless ``` Play the trained policy. ```bash ${ORBIT_PATH}/orbit.sh -p scripts/rsl_rl/play.py --task Template-Velocity-Flat-Anymal-D-Play-v0 --num_envs 16 ``` ### Omniverse Extension We provide an example UI extension that will load upon enabling your extension defined in `orbit/ext_template/ui_extension_example.py`. For more information on UI extensions, enable and check out the source code of the `omni.isaac.ui_template` extension and refer to the introduction on [Isaac Sim Workflows 1.2.3. GUI](https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html#gui). ## Pre-Commit Pre-committing involves using a framework to automate the process of enforcing code quality standards before code is actually committed to a version control system, like Git. This process involves setting up hooks that run automated checks, such as code formatting, linting (checking for programming errors, bugs, stylistic errors, and suspicious constructs), and running tests. If these checks pass, the commit is allowed; if not, the commit is blocked until the issues are resolved. This ensures that all code committed to the repository adheres to the defined quality standards, leading to a cleaner, more maintainable codebase. To do so, we use the [pre-commit](https://pre-commit.com/) module. Install the module using: ```bash pip install pre-commit ``` Run the pre-commit with: ```bash pre-commit run --all-files ``` ## Finalize You are all set and no longer need the template instructions - The `orbit/ext_template` and `scripts/rsl_rl` directories act as a reference template for your convenience. Delete them if no longer required. - When ready, use this `README.md` as a template and customize where appropriate. ## Docker / Cluster We are currently working on a docker and cluster setup for this template. In the meanwhile, please refer to the current setup provided in the Orbit [documentation](https://isaac-orbit.github.io/orbit/source/deployment/index.html). ## Troubleshooting ### Docker Container When running within a docker container, the following error has been encountered: `ModuleNotFoundError: No module named 'orbit'`. To mitigate, please comment out the docker specific environment definitions in `.vscode/launch.json` and run the following: ```bash echo -e "\nexport PYTHONPATH=\$PYTHONPATH:/workspace/orbit.<your_extension_name>" >> ~/.bashrc source ~/.bashrc ``` ## Bugs & Feature Requests Please report bugs and request features using the [Issue Tracker](https://github.com/isaac-orbit/orbit.ext_template/issues).
9,829
Markdown
46.033493
724
0.760301
jonasmaximilian/orbit.test/scripts/rsl_rl/play.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Script to play a checkpoint if an RL agent from RSL-RL.""" """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.orbit.app import AppLauncher # local imports import cli_args # isort: skip # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import os import torch from rsl_rl.runners import OnPolicyRunner import omni.isaac.orbit_tasks # noqa: F401 from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import ( RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, export_policy_as_onnx, ) # Import extensions to set up environment tasks import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name> def main(): """Play with RSL-RL agent.""" # parse configuration env_cfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs) agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Loading experiment from directory: {log_root_path}") resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # load previously trained model ppo_runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) ppo_runner.load(resume_path) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # obtain the trained policy for inference policy = ppo_runner.get_inference_policy(device=env.unwrapped.device) # export policy to onnx export_model_dir = os.path.join(os.path.dirname(resume_path), "exported") export_policy_as_onnx(ppo_runner.alg.actor_critic, export_model_dir, filename="policy.onnx") # reset environment obs, _ = env.get_observations() # simulate environment while simulation_app.is_running(): # run everything in inference mode with torch.inference_mode(): # agent stepping actions = policy(obs) # env stepping obs, _, _, _ = env.step(actions) # close the simulator env.close() if __name__ == "__main__": # run the main execution main() # close sim app simulation_app.close()
3,483
Python
32.5
101
0.706001
jonasmaximilian/orbit.test/scripts/rsl_rl/cli_args.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import argparse from typing import TYPE_CHECKING if TYPE_CHECKING: from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlOnPolicyRunnerCfg def add_rsl_rl_args(parser: argparse.ArgumentParser): """Add RSL-RL arguments to the parser. Args: parser: The parser to add the arguments to. """ # create a new argument group arg_group = parser.add_argument_group("rsl_rl", description="Arguments for RSL-RL agent.") # -- experiment arguments arg_group.add_argument( "--experiment_name", type=str, default=None, help="Name of the experiment folder where logs will be stored." ) arg_group.add_argument("--run_name", type=str, default=None, help="Run name suffix to the log directory.") # -- load arguments arg_group.add_argument("--resume", type=bool, default=None, help="Whether to resume from a checkpoint.") arg_group.add_argument("--load_run", type=str, default=None, help="Name of the run folder to resume from.") arg_group.add_argument("--checkpoint", type=str, default=None, help="Checkpoint file to resume from.") # -- logger arguments arg_group.add_argument( "--logger", type=str, default=None, choices={"wandb", "tensorboard", "neptune"}, help="Logger module to use." ) arg_group.add_argument( "--log_project_name", type=str, default=None, help="Name of the logging project when using wandb or neptune." ) def parse_rsl_rl_cfg(task_name: str, args_cli: argparse.Namespace) -> RslRlOnPolicyRunnerCfg: """Parse configuration for RSL-RL agent based on inputs. Args: task_name: The name of the environment. args_cli: The command line arguments. Returns: The parsed configuration for RSL-RL agent based on inputs. """ from omni.isaac.orbit_tasks.utils.parse_cfg import load_cfg_from_registry # load the default configuration rslrl_cfg: RslRlOnPolicyRunnerCfg = load_cfg_from_registry(task_name, "rsl_rl_cfg_entry_point") # override the default configuration with CLI arguments if args_cli.seed is not None: rslrl_cfg.seed = args_cli.seed if args_cli.resume is not None: rslrl_cfg.resume = args_cli.resume if args_cli.load_run is not None: rslrl_cfg.load_run = args_cli.load_run if args_cli.checkpoint is not None: rslrl_cfg.load_checkpoint = args_cli.checkpoint if args_cli.run_name is not None: rslrl_cfg.run_name = args_cli.run_name if args_cli.logger is not None: rslrl_cfg.logger = args_cli.logger # set the project name for wandb and neptune if rslrl_cfg.logger in {"wandb", "neptune"} and args_cli.log_project_name: rslrl_cfg.wandb_project = args_cli.log_project_name rslrl_cfg.neptune_project = args_cli.log_project_name return rslrl_cfg
2,981
Python
38.759999
117
0.688695
jonasmaximilian/orbit.test/scripts/rsl_rl/train.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Script to train RL agent with RSL-RL.""" """Launch Isaac Sim Simulator first.""" import argparse import os from omni.isaac.orbit.app import AppLauncher # local imports import cli_args # isort: skip # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import gymnasium as gym import os import torch from datetime import datetime from rsl_rl.runners import OnPolicyRunner import omni.isaac.orbit_tasks # noqa: F401 from omni.isaac.orbit.envs import RLTaskEnvCfg from omni.isaac.orbit.utils.dict import print_dict from omni.isaac.orbit.utils.io import dump_pickle, dump_yaml from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper # Import extensions to set up environment tasks import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name> torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = False def main(): """Train with RSL-RL agent.""" # parse configuration env_cfg: RLTaskEnvCfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs) agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli) # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Logging experiment in directory: {log_root_path}") # specify directory for logging runs: {time-stamp}_{run_name} log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if agent_cfg.run_name: log_dir += f"_{agent_cfg.run_name}" log_dir = os.path.join(log_root_path, log_dir) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) # wrap for video recording if args_cli.video: video_kwargs = { "video_folder": os.path.join(log_dir, "videos"), "step_trigger": lambda step: step % args_cli.video_interval == 0, "video_length": args_cli.video_length, "disable_logger": True, } print("[INFO] Recording videos during training.") print_dict(video_kwargs, nesting=4) env = gym.wrappers.RecordVideo(env, **video_kwargs) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # create runner from rsl-rl runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device) # write git state to logs runner.add_git_repo_to_log(__file__) # save resume path before creating a new log_dir if agent_cfg.resume: # get path to previous checkpoint resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # load previously trained model runner.load(resume_path) # set seed of the environment env.seed(agent_cfg.seed) # dump the configuration into log-directory dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg) dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg) dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg) dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg) # run training runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) # close the simulator env.close() if __name__ == "__main__": # run the main execution main() # close sim app simulation_app.close()
4,924
Python
37.779527
117
0.703696
jonasmaximilian/orbit.test/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # Description category = "orbit" readme = "README.md" # TODO: Change your package specifications # ----------------------------------------------------------------- title = "Extension Template" author = "ORBIT Project Developers" maintainer = "Nico Burger" maintainer_email = "[email protected]" description="Extension Template for Orbit" repository = "https://github.com/isaac-orbit/orbit.ext_template.git" keywords = ["extension", "template", "orbit"] # ----------------------------------------------------------------- [dependencies] "omni.isaac.orbit" = {} "omni.isaac.orbit_assets" = {} "omni.isaac.orbit_tasks" = {} # NOTE: Add additional dependencies here [[python.module]] # TODO: Change your package name # ----------------------------------------------------------------- name = "orbit.ext_template" # -----------------------------------------------------------------
972
TOML
29.406249
68
0.52572
jonasmaximilian/orbit.test/orbit/ext_template/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """ Python module serving as a project/extension template. """ # Register Gym environments. from .tasks import * # Register UI extensions. from .ui_extension_example import *
300
Python
19.066665
56
0.743333
jonasmaximilian/orbit.test/orbit/ext_template/ui_extension_example.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause import omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[orbit.ext_template] some_public_function was called with x: ", x) return x**x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class ExampleExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[orbit.ext_template] startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Add", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[orbit.ext_template] shutdown")
1,650
Python
33.395833
119
0.609697
jonasmaximilian/orbit.test/orbit/ext_template/tasks/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Package containing task implementations for various robotic environments.""" import os import toml # Conveniences to other module directories via relative paths ORBIT_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../")) """Path to the extension source directory.""" ORBIT_TASKS_METADATA = toml.load(os.path.join(ORBIT_TASKS_EXT_DIR, "config", "extension.toml")) """Extension metadata dictionary parsed from the extension.toml file.""" # Configure the module-level variables __version__ = ORBIT_TASKS_METADATA["package"]["version"] ## # Register Gym environments. ## from omni.isaac.orbit_tasks.utils import import_packages # The blacklist is used to prevent importing configs from sub-packages _BLACKLIST_PKGS = ["utils"] # Import all configs in this package import_packages(__name__, _BLACKLIST_PKGS)
968
Python
30.258064
95
0.744835
jonasmaximilian/orbit.test/orbit/ext_template/tasks/locomotion/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Locomotion environments for legged robots.""" from .velocity import * # noqa
205
Python
21.888886
56
0.731707
jonasmaximilian/orbit.test/orbit/ext_template/tasks/locomotion/velocity/velocity_env_cfg.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import math from dataclasses import MISSING import omni.isaac.orbit.sim as sim_utils from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg from omni.isaac.orbit.envs import RLTaskEnvCfg from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm from omni.isaac.orbit.managers import RandomizationTermCfg as RandTerm from omni.isaac.orbit.managers import RewardTermCfg as RewTerm from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm from omni.isaac.orbit.scene import InteractiveSceneCfg from omni.isaac.orbit.sensors import ContactSensorCfg, RayCasterCfg, patterns from omni.isaac.orbit.terrains import TerrainImporterCfg from omni.isaac.orbit.utils import configclass from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise import orbit.ext_template.tasks.locomotion.velocity.mdp as mdp ## # Pre-defined configs ## from omni.isaac.orbit.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip ## # Scene definition ## @configclass class MySceneCfg(InteractiveSceneCfg): """Configuration for the terrain scene with a legged robot.""" # ground terrain terrain = TerrainImporterCfg( prim_path="/World/ground", terrain_type="generator", terrain_generator=ROUGH_TERRAINS_CFG, max_init_terrain_level=5, collision_group=-1, physics_material=sim_utils.RigidBodyMaterialCfg( friction_combine_mode="multiply", restitution_combine_mode="multiply", static_friction=1.0, dynamic_friction=1.0, ), visual_material=sim_utils.MdlFileCfg( mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl", project_uvw=True, ), debug_vis=False, ) # robots robot: ArticulationCfg = MISSING # sensors height_scanner = RayCasterCfg( prim_path="{ENV_REGEX_NS}/Robot/base", offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)), attach_yaw_only=True, pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]), debug_vis=False, mesh_prim_paths=["/World/ground"], ) contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) # lights light = AssetBaseCfg( prim_path="/World/light", spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), ) sky_light = AssetBaseCfg( prim_path="/World/skyLight", spawn=sim_utils.DomeLightCfg(color=(0.13, 0.13, 0.13), intensity=1000.0), ) ## # MDP settings ## @configclass class CommandsCfg: """Command specifications for the MDP.""" base_velocity = mdp.UniformVelocityCommandCfg( asset_name="robot", resampling_time_range=(10.0, 10.0), rel_standing_envs=0.02, rel_heading_envs=1.0, heading_command=True, heading_control_stiffness=0.5, debug_vis=True, ranges=mdp.UniformVelocityCommandCfg.Ranges( lin_vel_x=(-1.0, 1.0), lin_vel_y=(-1.0, 1.0), ang_vel_z=(-1.0, 1.0), heading=(-math.pi, math.pi) ), ) @configclass class ActionsCfg: """Action specifications for the MDP.""" joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True) @configclass class ObservationsCfg: """Observation specifications for the MDP.""" @configclass class PolicyCfg(ObsGroup): """Observations for policy group.""" # observation terms (order preserved) base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1)) base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2)) projected_gravity = ObsTerm( func=mdp.projected_gravity, noise=Unoise(n_min=-0.05, n_max=0.05), ) velocity_commands = ObsTerm(func=mdp.generated_commands, params={"command_name": "base_velocity"}) joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5)) actions = ObsTerm(func=mdp.last_action) height_scan = ObsTerm( func=mdp.height_scan, params={"sensor_cfg": SceneEntityCfg("height_scanner")}, noise=Unoise(n_min=-0.1, n_max=0.1), clip=(-1.0, 1.0), ) def __post_init__(self): self.enable_corruption = True self.concatenate_terms = True # observation groups policy: PolicyCfg = PolicyCfg() @configclass class RandomizationCfg: """Configuration for randomization.""" # startup physics_material = RandTerm( func=mdp.randomize_rigid_body_material, mode="startup", params={ "asset_cfg": SceneEntityCfg("robot", body_names=".*"), "static_friction_range": (0.8, 0.8), "dynamic_friction_range": (0.6, 0.6), "restitution_range": (0.0, 0.0), "num_buckets": 64, }, ) add_base_mass = RandTerm( func=mdp.add_body_mass, mode="startup", params={"asset_cfg": SceneEntityCfg("robot", body_names="base"), "mass_range": (-5.0, 5.0)}, ) # reset base_external_force_torque = RandTerm( func=mdp.apply_external_force_torque, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", body_names="base"), "force_range": (0.0, 0.0), "torque_range": (-0.0, 0.0), }, ) reset_base = RandTerm( func=mdp.reset_root_state_uniform, mode="reset", params={ "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, "velocity_range": { "x": (-0.5, 0.5), "y": (-0.5, 0.5), "z": (-0.5, 0.5), "roll": (-0.5, 0.5), "pitch": (-0.5, 0.5), "yaw": (-0.5, 0.5), }, }, ) reset_robot_joints = RandTerm( func=mdp.reset_joints_by_scale, mode="reset", params={ "position_range": (0.5, 1.5), "velocity_range": (0.0, 0.0), }, ) # interval push_robot = RandTerm( func=mdp.push_by_setting_velocity, mode="interval", interval_range_s=(10.0, 15.0), params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}}, ) @configclass class RewardsCfg: """Reward terms for the MDP.""" # -- task track_lin_vel_xy_exp = RewTerm( func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) track_ang_vel_z_exp = RewTerm( func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) # -- penalties lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0) ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05) dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5) dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7) action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01) feet_air_time = RewTerm( func=mdp.feet_air_time, weight=0.125, params={ "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"), "command_name": "base_velocity", "threshold": 0.5, }, ) undesired_contacts = RewTerm( func=mdp.undesired_contacts, weight=-1.0, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0}, ) # -- optional penalties flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0) dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0) @configclass class TerminationsCfg: """Termination terms for the MDP.""" time_out = DoneTerm(func=mdp.time_out, time_out=True) base_contact = DoneTerm( func=mdp.illegal_contact, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0}, ) @configclass class CurriculumCfg: """Curriculum terms for the MDP.""" terrain_levels = CurrTerm(func=mdp.terrain_levels_vel) ## # Environment configuration ## @configclass class LocomotionVelocityRoughEnvCfg(RLTaskEnvCfg): """Configuration for the locomotion velocity-tracking environment.""" # Scene settings scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5) # Basic settings observations: ObservationsCfg = ObservationsCfg() actions: ActionsCfg = ActionsCfg() commands: CommandsCfg = CommandsCfg() # MDP settings rewards: RewardsCfg = RewardsCfg() terminations: TerminationsCfg = TerminationsCfg() randomization: RandomizationCfg = RandomizationCfg() curriculum: CurriculumCfg = CurriculumCfg() def __post_init__(self): """Post initialization.""" # general settings self.decimation = 4 self.episode_length_s = 20.0 # simulation settings self.sim.dt = 0.005 self.sim.disable_contact_processing = True self.sim.physics_material = self.scene.terrain.physics_material # update sensor update periods # we tick all the sensors based on the smallest update period (physics update period) if self.scene.height_scanner is not None: self.scene.height_scanner.update_period = self.decimation * self.sim.dt if self.scene.contact_forces is not None: self.scene.contact_forces.update_period = self.sim.dt # check if terrain levels curriculum is enabled - if so, enable curriculum for terrain generator # this generates terrains with increasing difficulty and is useful for training if getattr(self.curriculum, "terrain_levels", None) is not None: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = True else: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = False
10,649
Python
32.596214
118
0.626538