Example #1
0
bool QCAN::init()
{
    s_BOARD Board = {(char*)port, (char*)"125K"};

    /* Define callback functions */
    mData->classObject = this;
    mData->initialisation = &QCAN::initialisation;
    mData->preOperational = &QCAN::preOperational;
    mData->operational = &QCAN::operational;
    mData->stopped = &QCAN::stopped;
    mData->post_sync = &QCAN::post_sync;
    mData->post_TPDO = &QCAN::post_TPDO;
    mData->post_SlaveBootup = &QCAN::post_SlaveBootup;

    mPort = canOpen(&Board, mData);
    if(!mPort)
        return false;

    // Defining the node Id
    setNodeId(mData, mNodeID);
    setState(mData, Initialisation);
//    masterSendNMTstateChange(mData, mNodeID, NMT_Reset_Node);

    return true;
}
Example #2
0
void CANUi::on_pushButton_Open_clicked()
{
    if(m_CANState){
        ui->textBrowser->append("already opened !");
        return;
    }

    if(!canOpen(m_masterBoard, &master_Data)){
        ui->textBrowser->append("open failed !");
        return;
    }

    m_CANState = true;
    ui->textBrowser->append("open success !");

    connect(m_canThread, SIGNAL(message(QString)),
            this, SLOT(messageShow(QString)));

    connect(m_canThread, SIGNAL(message(QCanBusFrame)),
            this, SLOT(messageShow(QCanBusFrame)));

    m_canThread->mStart(false);//open canport and close canopen

    ui->textBrowser->append(tr("ObjdictSize: %1").arg(*master_Data.ObjdictSize));


    ui->pushButton_Open->setEnabled(false);
    ui->pushButton_Close->setEnabled(true);

    ui->Checkb_CANopen->setEnabled(true);//canopen open
    ui->pushButton_Send->setEnabled(true);


}
Example #3
0
int NodeInit(int NodeID, int NodeType)
{
	if(NodeType)
		CANOpenShellOD_Data = &CANOpenShellMasterOD_Data;
	else
		CANOpenShellOD_Data = &CANOpenShellSlaveOD_Data;

	/* Load can library */
	LoadCanDriver(LibraryPath);

	/* Define callback functions */
	CANOpenShellOD_Data->initialisation = CANOpenShellOD_initialisation;
	CANOpenShellOD_Data->preOperational = CANOpenShellOD_preOperational;
	CANOpenShellOD_Data->operational = CANOpenShellOD_operational;
	CANOpenShellOD_Data->stopped = CANOpenShellOD_stopped;
	CANOpenShellOD_Data->post_sync = CANOpenShellOD_post_sync;
	CANOpenShellOD_Data->post_TPDO = CANOpenShellOD_post_TPDO;
	CANOpenShellOD_Data->post_SlaveBootup=CANOpenShellOD_post_SlaveBootup;

	/* Open the Peak CANOpen device */
	if(!canOpen(&Board,CANOpenShellOD_Data)) return INIT_ERR;

	/* Defining the node Id */
	setNodeId(CANOpenShellOD_Data, NodeID);
	/* Start Timer thread */
	StartTimerLoop(&Init);
	return 0;
}
Example #4
0
void ShiptoEdit::sNew()
{
  if (canOpen())
  {
    if (!_x_privileges->check(_newPriv))
      return;

    ParameterList params;
    params.append("mode", "new");
    params.append("cust_id", _custid);

    QWidget* w = 0;
    if (parentWidget()->window())
    {
      if (parentWidget()->window()->isModal())
        w = _guiClientInterface->openWindow(_uiName, params, parentWidget()->window() , Qt::WindowModal, Qt::Dialog);
      else
        w = _guiClientInterface->openWindow(_uiName, params, parentWidget()->window() , Qt::NonModal, Qt::Window);
    }

    if (w->inherits("QDialog"))
    {
      QDialog* newdlg = qobject_cast<QDialog*>(w);
      int id = newdlg->exec();
      if (id != QDialog::Rejected)
      {
        silentSetId(id);
        emit newId(_id);
        emit valid(_id != -1);
      }
    }
  }
}
Example #5
0
void VirtualClusterLineEdit::sUpdateMenu()
{
  if (! _x_privileges)
    return;

  _listAct->setEnabled(isEnabled());
  _searchAct->setEnabled(isEnabled());
  _aliasAct->setEnabled(isEnabled());
  _infoAct->setEnabled(_id != -1);
  _openAct->setEnabled((_x_privileges->check(_editPriv) ||
                        _x_privileges->check(_viewPriv)) &&
                       _id != -1);
  _newAct->setEnabled(_x_privileges->check(_newPriv) &&
                      isEnabled());

  if (canOpen())
  {
    if (!menu()->actions().contains(_openAct))
      menu()->addAction(_openAct);

    if (!menu()->actions().contains(_newAct) &&
        !_newPriv.isEmpty())
      menu()->addAction(_newAct);
  }
  else
  {
    if (menu()->actions().contains(_openAct))
      menu()->removeAction(_openAct);

    if (menu()->actions().contains(_newAct))
      menu()->removeAction(_newAct);
  }
}
Example #6
0
  Molecule * OpenbabelWrapper::openFile(const QString &fileName,
                                        const QString &fileType,
                                        const QString &fileOptions)
  {
    // Check that the file can be read from disk
    if (!canOpen(fileName, QFile::ReadOnly | QFile::Text))
      return 0;

    // Construct the OpenBabel objects, set the file type
    OBConversion conv;
    OBFormat *inFormat;
    if (!fileType.isEmpty() && !conv.SetInFormat(fileType.toAscii().data()))
      // Input format not supported
      return 0;
    else {
      inFormat = conv.FormatFromExt(fileName.toAscii().data());
      if (!conv.SetInFormat(inFormat))
        // Input format not supported
        return 0;
    }

    // set any options
    if (!fileOptions.isEmpty()) {
      foreach(const QString &option,
              fileOptions.split('\n', QString::SkipEmptyParts)) {
        conv.AddOption(option.toAscii().data(), OBConversion::INOPTIONS);
      }
    }
Example #7
0
void ContactClusterLineEdit::sNew()
{
  if (canOpen())
  {
    // virtualCluster performs priv checking??
    //if (!_x_privileges->check(_editPriv))
    //  return;

    ParameterList params;
    params.append("mode", "new");
    if (_searchAcctId != -1)
      params.append("crmacct_id", _searchAcctId);
    if (_newAddr.count())
    {
      params.append("addr_line1", _newAddr.at(0));
      params.append("addr_line2", _newAddr.at(1));
      params.append("addr_line3", _newAddr.at(2));
      params.append("addr_city", _newAddr.at(3));
      params.append("addr_state", _newAddr.at(4));
      params.append("addr_postalcode", _newAddr.at(5));
      params.append("addr_country", _newAddr.at(6));
    }

    QDialog* newdlg = (QDialog*)_guiClientInterface->openWindow(_uiName, params, parentWidget(),Qt::WindowModal);

    int id = newdlg->exec();
    if (id != QDialog::Rejected)
      setId(id);
    return;
  }
}
    bool CCWorldCompletionGate::openInner() {
        if (canOpen()) {
            forceOpen(true);
            return true;
        }

        return false;
    }
Example #9
0
int TestMasterSlave_start (void)
{
	TimerInit();

	if(strcmp(SlaveBoard.baudrate, "none")){
		
		TestSlave_Data.heartbeatError = TestSlave_heartbeatError;
		TestSlave_Data.initialisation = TestSlave_initialisation;
		TestSlave_Data.preOperational = TestSlave_preOperational;
		TestSlave_Data.operational = TestSlave_operational;
		TestSlave_Data.stopped = TestSlave_stopped;
		TestSlave_Data.post_sync = TestSlave_post_sync;
		TestSlave_Data.post_TPDO = TestSlave_post_TPDO;
		TestSlave_Data.storeODSubIndex = TestSlave_storeODSubIndex;
		TestSlave_Data.post_emcy = TestSlave_post_emcy;

		if(!canOpen(&SlaveBoard,&TestSlave_Data)){
			eprintf("Cannot open Slave Board (%s,%s)\n",SlaveBoard.busname, SlaveBoard.baudrate);
			return 1;
		}
	}
	if(strcmp(MasterBoard.baudrate, "none")){
		
		TestMaster_Data.heartbeatError = TestMaster_heartbeatError;
		TestMaster_Data.initialisation = TestMaster_initialisation;
		TestMaster_Data.preOperational = TestMaster_preOperational;
		TestMaster_Data.operational = TestMaster_operational;
		TestMaster_Data.stopped = TestMaster_stopped;
		TestMaster_Data.post_sync = TestMaster_post_sync;
		TestMaster_Data.post_TPDO = TestMaster_post_TPDO;
		TestMaster_Data.post_emcy = TestMaster_post_emcy;
		TestMaster_Data.post_SlaveBootup=TestMaster_post_SlaveBootup;
		
		if(!canOpen(&MasterBoard,&TestMaster_Data)){
			eprintf("Cannot open Master Board (%s,%s)\n",MasterBoard.busname, MasterBoard.baudrate);
			if(strcmp(MasterBoard.baudrate, "none")) canClose(&TestMaster_Data);
			return 1;
		}
	}

	// Start timer thread
	StartTimerLoop(&InitNodes);

	return 0;
}
Example #10
0
    bool CCRecordGate::openInner() {
        if (canOpen()) {
            // There's nothing to do here... If the DesiredRecord was reached then the gate is just open.
            forceOpen(true);
            return true;
        }

        return false;
    }
    bool CCSocialLikeGate::openInner() {
        if (canOpen()) {

            CCSoomlaProfile::getInstance()->like(getProvider(), getPageName()->getCString(), NULL, NULL);

            return true;
        }

        return false;
    }
Example #12
0
/** @return List of {@link CaptureDeviceInfo} */
void V4LCaptureSystem::getCaptureDeviceInfoList(list<CaptureDeviceInfo> &result) /*throws CaptureException*/
{
	// TODO: if one of the devices is busy, it won't open and won't be in the list, even if it is valid.
	for (int i = 0; i < NUM_VIDEO_DEVICE_PATHS; ++i)
	{
		const char *path = wchar_t_to_char_array_alloc(videoDevicePaths[i]);
		const int openResult = canOpen(path);
		delete path;
		if (openResult)
			result.push_back(CaptureDeviceInfo(videoDevicePaths[i], videoDevicePaths[i]));	// TODO: deal with memory allocation issues.
	}

}
Example #13
0
int32_t initNTCAN(uint32_t baud,  uint32_t flags,
                  int32_t ID[], 	 int32_t net,
                  int32_t rxSize, int32_t rxTime,
                  int32_t txSize, int32_t txTime)
{
    NTCAN_HANDLE		handle;    	//
    NTCAN_RESULT		result;    	// Used for checking for error
    int32_t		i;       	  		// Index for multiple objects
    int32_t		timeout=0;   		// Current number of timeouts
    /* Open can */
    result = canOpen(net,flags,txSize,rxSize,   // Opens device
                     txTime,rxTime,&handle);
    if(errorCheck(CAN_OPEN,result) != 0)  			// Error check
    {
        return 0xFFFF;    // returns 1 if error
    }
//   printf("canOpen() success\n");
    /* Setting baudrate */
    result = canSetBaudrate(handle,baud);   		// sets baudrate
    if(errorCheck(CAN_SET_BAUDRATE,result) != 0) // Error check
    {
        return 0xFFFF;    // returns 1 if error
    }
    result = canGetBaudrate(handle,&baud);  		// Reads buadrate
//   printf("canSetBaudrate() success. Baudrate is %d\n",baud);
    /* Adding an ID */
    for(i=1; i<ID[0]; i++) {
        do  {
            result = canIdAdd(handle,ID[i]); 	// Adds ID to handle
            timeout++; 									// reapeat if Timeout
            if(timeout>MAX_TIMEOUT) {
                printf("Max timeout out reached, Aborting addID\n");
                return 0xFFFF;
            }  // return if repeated error
        } while( errorCheck(CAN_ID_ADD,result) == 2);
        if(errorCheck(CAN_ID_ADD,result) != 0) 	// error check
        {
            return 0xFFFF;
        }
//   printf("canIdAdd() successful\n");
    }
    printf("Initializing sucessfull\n");
    /* Flushing FIFO buffer */
    result = canIoctl(handle,NTCAN_IOCTL_FLUSH_RX_FIFO,NULL);
    if(errorCheck(CAN_IO_CTL,result) != 0) 		// flushing FIFO
    {
        return 0xFFFF;    // error check
    }
//   printf("System flushed, device ready to use\n");
    return handle; // returns handle for NTCAN device
}
Example #14
0
//-----------------------------------------------
CanESD::CanESD(int iIniBaudRate, int iNrNet)
{
	//initial values
	int net=1; /* logical net number (here: 0) */
	uint32_t mode=0; /* mode used for canOpen() */
	int32_t txqueuesize=100; /* size of transmit queue */
	int32_t rxqueuesize=100; /* size of receive queue */
	int32_t txtimeout=0; /* timeout for transmit operations in ms */
	int32_t rxtimeout=0; /* timeout for receive operations in ms */
	NTCAN_RESULT retvalue; /* return values of NTCAN API calls */
	//uint32_t baud=2; /* configured CAN baudrate (here: 500 kBit/s.) */
	CMSG cmsg[8]; /* can message buffer */
	int rtr=0; /* rtr bit */
	int32_t len; /* # of CAN messages */

	retvalue = canOpen(iNrNet, mode, txqueuesize, rxqueuesize, txtimeout, rxtimeout, &m_Handle);
	if (retvalue != NTCAN_SUCCESS)
	{
		LOGINFO("canOpen() failed: " << getErrorMessage(retvalue));
	}
	Sleep(300);
	retvalue = canSetBaudrate(m_Handle, getBaudRate(iIniBaudRate));
	if (retvalue != 0)
	{
		LOGINFO("canSetBaudrate() failed: " << getErrorMessage(retvalue)); 
		canClose(m_Handle);
	}
	else 
	{
		LOGINFO("Baudrate set to " << getBaudRate(iIniBaudRate));	
	}
	Sleep(300);
	
	//set Amtek Arm IDs
	int i;
	for(i=1; i < 2048; i++)
	{
		retvalue = canIdAdd(m_Handle, i);
		if (retvalue != NTCAN_SUCCESS)
		{
			LOGERROR("canIdAdd() failed: " << getErrorMessage(retvalue)); 
		}
	}

	Sleep(300);

	m_LastID = -1;
}
void CrmClusterLineEdit::sUpdateMenu()
{
  if (! _x_privileges)
    return;

  _listAct->setEnabled(isEnabled());
  _searchAct->setEnabled(isEnabled());
  _aliasAct->setEnabled(isEnabled());
  _infoAct->setEnabled(_id != -1);
  _openAct->setEnabled((_x_privileges->check(_editPriv) ||
                        _x_privileges->check(_viewPriv) ||
                        (_x_privileges->check(_editOwnPriv) && (_owner == _x_username || _assignto == _x_username)) ||
                        (_x_privileges->check(_viewOwnPriv) && (_owner == _x_username || _assignto == _x_username))) &&
                        _id != -1);
  _copyAct->setEnabled((_x_privileges->check(_editPriv) ||
                        _x_privileges->check(_viewPriv) ||
                        (_x_privileges->check(_editOwnPriv) && (_owner == _x_username || _assignto == _x_username)) ||
                        (_x_privileges->check(_viewOwnPriv) && (_owner == _x_username || _assignto == _x_username))) &&
                       _id != -1 && isEnabled() && _uiName == "project");
  _newAct->setEnabled((_x_privileges->check(_newPriv) || _x_privileges->check(_editOwnPriv)) &&
                      isEnabled());

  if (canOpen())
  {
    if (!menu()->actions().contains(_openAct))
      menu()->addAction(_openAct);

    if (!menu()->actions().contains(_copyAct))
      menu()->addAction(_copyAct);
    
    if (!menu()->actions().contains(_newAct) &&
        !_newPriv.isEmpty())
      menu()->addAction(_newAct);
  }
  else
  {
    if (menu()->actions().contains(_openAct))
      menu()->removeAction(_openAct);

    if (menu()->actions().contains(_copyAct))
      menu()->removeAction(_copyAct);
    
    if (menu()->actions().contains(_newAct))
      menu()->removeAction(_newAct);
  }
}
Example #16
0
bool QCan::init()
{
    if (!LoadCanDriver("/usr/local/lib/libcanfestival_can_vscom.so"))
        return false;

    TimerInit();
    StartTimerLoop(Init);

    s_BOARD Board = {(char*)"/dev/ttyUSB0", (char*)"125K"};
    mPort = canOpen(&Board, mData);
    if(!mPort)
        return false;

    setState(mData, Initialisation);
    masterSendNMTstateChange(mData, 0, NMT_Reset_Node);

    return true;
}
Example #17
0
INTEGER8 InitCANdevice( UNS8 bus, UNS32 baudrate, UNS8 node )
{ 
char busName[2];
char baudRate[7];
s_BOARD board;

    sprintf(busName, "%u", bus);
    sprintf(baudRate, "%u", baudrate);
    board.busname = busName;
    board.baudrate = baudRate;

    slaveNode = node;

    SillySlave_Data.heartbeatError = SillySlave_heartbeatError;
    SillySlave_Data.initialisation = SillySlave_initialisation;
    SillySlave_Data.preOperational = SillySlave_preOperational;
    SillySlave_Data.operational = SillySlave_operational;
    SillySlave_Data.stopped = SillySlave_stopped;
    SillySlave_Data.post_sync = SillySlave_post_sync;
    SillySlave_Data.post_TPDO = SillySlave_post_TPDO;
    SillySlave_Data.storeODSubIndex = SillySlave_storeODSubIndex;
    SillySlave_Data.post_emcy = SillySlave_post_emcy;
    
    if(!canOpen(&board, &SillySlave_Data))
    {
        printf("\n\aInitCANdevice() CAN bus %s opening error, baudrate=%s\n",board.busname, board.baudrate);
        return -1;
    }


    printf("\nInitCANdevice(), canOpen() OK, starting timer loop...\n");

    /* Start timer thread */
    StartTimerLoop(&InitNode); 
    
	/* wait Ctrl-C */
	pause();
	printf("\nFinishing.\n");
	
	/* Stop timer thread */
	StopTimerLoop(&Exit);
    return 0;
}
Example #18
0
void ContactClusterLineEdit::sNew()
{
  if (canOpen())
  {
    if (!_x_privileges->check(_editPriv))
      return;

    ParameterList params;
    params.append("mode", "new");
    if (_searchAcctId != -1)
      params.append("crmacct_id", _searchAcctId);

    QDialog* newdlg = (QDialog*)_guiClientInterface->openDialog(_uiName, params, parentWidget(),Qt::WindowModal);

    int id = newdlg->exec();
    if (id != QDialog::Rejected)
      setId(id);
    return;
  }
}
Example #19
0
void openAllCAN(int vCan) {
	for ( size_t i = 0; i < 2; i ++ ) {
		int r = canOpen( i, //net
				 0, // flags
				 10, //txqueue
				 10, //rxqueue
				 100, //txtimeout
				 100, //rxtimeout
				 &hubo_socket[i] //handle
			);
		if( NTCAN_SUCCESS != r ) {
			fprintf(stderr, "Unable to open CAN %d: %s\n", i, canResultString(r));
			exit( EXIT_FAILURE );
		}

		r = canSetBaudrate( hubo_socket[i], NTCAN_BAUD_1000 );
		if( NTCAN_SUCCESS != r ) {
			fprintf(stderr, "Unable to set CAN %d baud: %s\n", i, canResultString(r));
			exit( EXIT_FAILURE );
		}
	}

}
Example #20
0
//****************************************************************************
//***************************  MAIN  *****************************************
//****************************************************************************
int
main_can (s_BOARD SlaveBoard, char *LibraryPath)
{
#if !defined(WIN32) && !defined(__CYGWIN__)
	//TimerInit();
#endif	
	TimerInit();
	printf ("Bus name: %s        Freq: %s       Driver: %s\n",
	  SlaveBoard.busname, SlaveBoard.baudrate, LibraryPath);

#ifndef NOT_USE_DYNAMIC_LOADING
  if (LoadCanDriver (LibraryPath) == NULL)
    *textLog << wxT ("Unable to load library\n");
#endif
  // Open CAN devices

  ObjDict_Data.heartbeatError = Call_heartbeatError;
  ObjDict_Data.initialisation = Call_initialisation;
  ObjDict_Data.preOperational = Call_preOperational;
  ObjDict_Data.operational = Call_operational;
  ObjDict_Data.stopped = Call_stopped;
  ObjDict_Data.post_sync = Call_post_sync;
  ObjDict_Data.post_TPDO = Call_post_TPDO;
  ObjDict_Data.storeODSubIndex = Call_storeODSubIndex;

  if (!canOpen (&SlaveBoard, &ObjDict_Data))
    {
      printf ("Cannot open Slave Board (%s,%s)\n", SlaveBoard.busname,
	      SlaveBoard.baudrate);
      return (1);
    }

  StartTimerLoop (&InitNodes);

  return 0;
}
Example #21
0
int PBGameInfo::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    
#ifndef QT_NO_PROPERTIES
     if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< QString*>(_v) = gameId(); break;
        case 1: *reinterpret_cast< QString*>(_v) = tableId(); break;
        case 2: *reinterpret_cast< QString*>(_v) = tourneyTableId(); break;
        case 3: *reinterpret_cast< QString*>(_v) = siteId(); break;
        case 4: *reinterpret_cast< int*>(_v) = canJoin(); break;
        case 5: *reinterpret_cast< QString*>(_v) = gameFamily(); break;
        case 6: *reinterpret_cast< double*>(_v) = smallBlind(); break;
        case 7: *reinterpret_cast< double*>(_v) = bigBlind(); break;
        case 8: *reinterpret_cast< int*>(_v) = maxSeats(); break;
        case 9: *reinterpret_cast< QString*>(_v) = driver(); break;
        case 10: *reinterpret_cast< int*>(_v) = canOpen(); break;
        case 11: *reinterpret_cast< int*>(_v) = openedTablesCount(); break;
        case 12: *reinterpret_cast< int*>(_v) = tablesMax(); break;
        case 13: *reinterpret_cast< int*>(_v) = tableOpened(); break;
        case 14: *reinterpret_cast< int*>(_v) = tourneyOpened(); break;
        case 15: *reinterpret_cast< int*>(_v) = gameComplete(); break;
        }
        _id -= 16;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setGameId(*reinterpret_cast< QString*>(_v)); break;
        case 1: setTableId(*reinterpret_cast< QString*>(_v)); break;
        case 2: setTourneyTableId(*reinterpret_cast< QString*>(_v)); break;
        case 3: setSiteId(*reinterpret_cast< QString*>(_v)); break;
        case 4: setCanJoin(*reinterpret_cast< int*>(_v)); break;
        case 5: setGameFamily(*reinterpret_cast< QString*>(_v)); break;
        case 6: setSmallBlind(*reinterpret_cast< double*>(_v)); break;
        case 7: setBigBlind(*reinterpret_cast< double*>(_v)); break;
        case 8: setMaxSeats(*reinterpret_cast< int*>(_v)); break;
        case 9: setDriver(*reinterpret_cast< QString*>(_v)); break;
        case 10: setCanOpen(*reinterpret_cast< int*>(_v)); break;
        case 11: setOpenedTablesCount(*reinterpret_cast< int*>(_v)); break;
        case 12: setTablesMax(*reinterpret_cast< int*>(_v)); break;
        case 13: setTableOpened(*reinterpret_cast< int*>(_v)); break;
        case 14: setTourneyOpened(*reinterpret_cast< int*>(_v)); break;
        case 15: setGameComplete(*reinterpret_cast< int*>(_v)); break;
        }
        _id -= 16;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 16;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 16;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 16;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 16;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 16;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 16;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
Example #22
0
void TraceProcess::traceMe() {
    struct user_regs_struct regs;

    DLOG(INFO) << pid << " trace_me\n";

    //the waitpid function will be interuppted by the SIGCHLD signal
    int wret;
#ifdef HAVE_WAIT4
	while((wret = wait4(this->pid, &status, 0, &process_usage)) > 0) {
		getusage = true;
#else
    while((wret = waitpid(this->pid, &status, 0)) > 0) {
#endif
        //DLOG(INFO) << pid << " waitpid return " << wret << "\n";

        if(WIFSIGNALED(status)) {
            DLOG(INFO) << "TraceProcess()::traceMe(): child was killed by signal\n";

            _exit = true;
            if(WTERMSIG(status) == SIGKILL && this->_result == -1) {
                this->_result = RUNTIME_ERROR;
            }
            break;
        }

        if(!WIFSTOPPED(status)) {
            //if(WEXITSTATUS(status)) {
            //    this->_result = RUNTIME_ERROR;
            //}
            _exit = true;
            break;
        }

        int sig = WSTOPSIG(status);
        if(sig != SIGTRAP) {
            DLOG(INFO) << "TraceProcess()::traceMe(): caught a signal " << sig << "\n";

            getRunningTime();
            getRunningMemory();

            switch(sig) {
            case SIGFPE:
                DLOG(INFO) << "TraceProcess()::traceMe(): SIGFPE\n";

                this->_result = FLOATING_POINT_ERROR;
                break;

            case SIGXCPU:
                DLOG(INFO) << "TraceProcess()::traceMe(): SIGXCPU\n";

                this->_result = TIME_LIMIT_EXCEEDED;
                break;

            case SIGBUS:
            case SIGSEGV:
                DLOG(INFO) << "TraceProcess()::traceMe(): SIGSEGV\n";

                this->_result = SEGMENTATION_FAULT;
                break;

            case SIGXFSZ:
                DLOG(INFO) << "TraceProcess()::traceMe(): SIGXFSZ\n";

                this->_result = OUTPUT_LIMIT_EXCEEDED;
                break;

            case SIGILL:
            case SIGKILL:
                DLOG(INFO) << "TraceProcess()::traceMe(): SIGKILL\n";

                if(this->_result == -1) {
                    this->_result = RUNTIME_ERROR;
                }
                break;

            case SIGALRM:
                ;
            }

            ptrace(PTRACE_SYSCALL, this->pid, NULL, sig);
            continue;
        }

        ptrace(PTRACE_GETREGS, this->pid, 0, &regs);
        
        switch(regs.ORIG_EAX) {
        case SYS_exit:
        case SYS_exit_group:
            DLOG(INFO) << "TraceProcess()::traceMe(): child sys_exit\n";

            getRunningTime();
            getRunningMemory();
            break;

        case SYS_execve:
            if(!first_exec) {
                first_exec = true;
                DLOG(INFO) << pid << " execve, ptrace it\n";

                ptrace(PTRACE_SYSCALL, this->pid, NULL, NULL);
                continue;
            }
            break;

        case SYS_brk:
            if(!insyscall) {
               brk = (unsigned long)regs.EBX;
               insyscall = true;
            }else{
                if(((unsigned long)regs.EAX) < brk) {
                    DLOG(INFO) << "TraceProcess()::traceMe(): brk request " << brk << " return " << regs.EAX << "\n";

                    this->_result = MEMORY_LIMIT_EXCEEDED;
                    ptrace(PTRACE_KILL, this->pid, 0, 0);
                    continue;
                }
                insyscall = false;
            }
            break;
        
        case SYS_open:
            if(!insyscall) {
                char path[FILENAME_MAX + 1];
                insyscall = true;
                getdata(regs.EBX, path, sizeof(path));
				DLOG(INFO) << "open file:" << path << "\n";
                if(!canOpen(path, regs.ECX)) {
					regs.ORIG_EAX = SYS_exit;
					regs.EBX = 1;
					ptrace(PTRACE_SETREGS, this->pid, 0, &regs);
                    this->_result = RUNTIME_ERROR;
					break;
                }
            }else{
                insyscall = false;
            }
            ptrace(PTRACE_SYSCALL, this->pid, 0, 0);
            continue;
        }

        if(regs.ORIG_EAX < sizeof(disabled_syscall) &&
            disabled_syscall[regs.ORIG_EAX]) {

            DLOG(INFO) << "TraceProcess()::traceMe(): Restricted syscall " << regs.ORIG_EAX << "\n";

            this->_result = RESTRICTED_FUNCTION;
            getRunningTime();
            getRunningMemory();

			regs.ORIG_EAX = SYS_exit;
			regs.EAX = SYS_exit;
			regs.EBX = 1;
			ptrace(PTRACE_SETREGS, this->pid, NULL, &regs);
            ptrace(PTRACE_KILL, this->pid, 0, 0);
			continue;
        }else{
            ptrace(PTRACE_SYSCALL, this->pid, 0, 0);
        }

        ptrace(PTRACE_SYSCALL, this->pid, NULL, NULL);
    }
}
Example #23
0
int main(int argc,char **argv)
{
	struct sigaction act;
	uint8_t nodeid = 2;

    // register handler on SIGINT signal 
    act.sa_handler=sortie;
    sigemptyset(&act.sa_mask);
    act.sa_flags=0;
    sigaction(SIGINT,&act,0);

    // Check that we have the right command line parameters
    if(argc != 3){
        display_usage(argv[0]);
        exit(1);
    }

    // get command line parameters
    nodeid = strtoul(argv[2], NULL, 10);
    SlaveBoard0.busname = argv[1];
    printf("Starting on %s with node id = %u\n", SlaveBoard0.busname, nodeid);

    // register the callbacks we use
    RegisterSetODentryCallBack(&slavedic_Data, 0x2001, 0, callback_on_position);
    slavedic_Data.initialisation=state_change;
    slavedic_Data.preOperational=state_change;
    slavedic_Data.operational=state_change;
    slavedic_Data.stopped=state_change;

	// Init Canfestival
	if (LoadCanDriver("./libcanfestival_can_socket.so") == NULL){
	    printf("Unable to load driver library\n");
        printf("please put file libcanfestival_can_socket.so in the current directory\n");
        exit(1);
    }
	if(!canOpen(&SlaveBoard0,&slavedic_Data)){
		printf("Cannot open can interface %s\n",SlaveBoard0.busname);
		exit(1);
	}

    TimerInit();
	setNodeId(&slavedic_Data, nodeid);
	setState(&slavedic_Data, Initialisation);

    printf("Canfestival initialisation done\n");
	Run = 1;
	while(Run)
	{
        sleep(1);
        EnterMutex();
        counter += nodeid;
        LeaveMutex();
	}

	// Stop timer thread
	StopTimerLoop(&Exit);
	// Close CAN devices (and can threads)
	canClose(&slavedic_Data);
	return 0;

}
Example #24
0
int main(int argc, char *argv[])
  {
   UNS8 node_id = 0;
   s_BOARD MasterBoard = {"1", "125K"};
   char* dll_file_name;

   /* process command line arguments */
   if (argc < 2)
      {
      printf("USAGE: win32test <node_id> [can driver dll filename [baud rate]]\n");
      return 1;
      }

   node_id = atoi(argv[1]);
   if (node_id < 2 || node_id > 127)
      {
      printf("ERROR: node_id shoule be >=2 and <= 127\n");
      return 1;
      }

   if (argc > 2)
      dll_file_name = argv[2];
   else
      dll_file_name = "can_uvccm_win32.dll";

   if (argc > 3)
      MasterBoard.baudrate = argv[3];

   // load can driver
   if (!LoadCanDriver(dll_file_name))
      {
      printf("ERROR: could not load diver %s\n", dll_file_name);
      return 1;
      }
   
   if (canOpen(&MasterBoard,&win32test_Data))
      {
      /* Defining the node Id */
      setNodeId(&win32test_Data, 0x01);

      /* init */
      setState(&win32test_Data, Initialisation);

      /****************************** START *******************************/
      /* Put the master in operational mode */
      setState(&win32test_Data, Operational);

      /* Ask slave node to go in operational mode */
      masterSendNMTstateChange (&win32test_Data, 0, NMT_Start_Node);

      printf("\nStarting node %d (%xh) ...\n",(int)node_id,(int)node_id);
      
      /* wait untill mode will switch to operational state*/
      if (GetChangeStateResults(node_id, Operational, 3000) != 0xFF)
         {
         /* modify Client SDO 1 Parameter */
         UNS32 COB_ID_Client_to_Server_Transmit_SDO = 0x600 + node_id;
         UNS32 COB_ID_Server_to_Client_Receive_SDO  = 0x580 + node_id;
         UNS32 Node_ID_of_the_SDO_Server = node_id;
         UNS8 ExpectedSize = sizeof (UNS32);

         if (OD_SUCCESSFUL ==  writeLocalDict(&win32test_Data, 0x1280, 1, &COB_ID_Client_to_Server_Transmit_SDO, &ExpectedSize, RW) 
              && OD_SUCCESSFUL ==  writeLocalDict(&win32test_Data, 0x1280, 2, &COB_ID_Server_to_Client_Receive_SDO, &ExpectedSize, RW) 
              && OD_SUCCESSFUL ==  writeLocalDict(&win32test_Data, 0x1280, 3, &Node_ID_of_the_SDO_Server, &ExpectedSize, RW))
            {
            UNS32 dev_type = 0;
            char device_name[64]="";
            char hw_ver[64]="";
            char sw_ver[64]="";   
            UNS32 vendor_id = 0;            
            UNS32 prod_code = 0;
            UNS32 ser_num = 0;
            UNS8 size;
            UNS8 res;

            printf("\nnode_id: %d (%xh) info\n",(int)node_id,(int)node_id);
            printf("********************************************\n");

            size = sizeof (dev_type);
            res = ReadSDO(node_id, 0x1000, 0, uint32, &dev_type, &size);
            printf("device type: %d\n",dev_type & 0xFFFF);
           
            size = sizeof (device_name);
            res = ReadSDO(node_id, 0x1008, 0, visible_string, device_name, &size);
            printf("device name: %s\n",device_name);

            size = sizeof (hw_ver);
            res = ReadSDO(node_id, 0x1009, 0, visible_string, hw_ver, &size);
            printf("HW version: %s\n",hw_ver);

            size = sizeof (sw_ver);
            res = ReadSDO(node_id, 0x100A, 0, visible_string, sw_ver, &size);
            printf("SW version: %s\n",sw_ver);            
            
            size = sizeof (vendor_id);
            res = ReadSDO(node_id, 0x1018, 1, uint32, &vendor_id, &size);
            printf("vendor id: %d\n",vendor_id);

            size = sizeof (prod_code);
            res = ReadSDO(node_id, 0x1018, 2, uint32, &prod_code, &size);
            printf("product code: %d\n",prod_code);

            size = sizeof (ser_num);
            res = ReadSDO(node_id, 0x1018, 4, uint32, &ser_num, &size);
            printf("serial number: %d\n",ser_num);
            
            printf("********************************************\n");
            } 
         else
            {
            printf("ERROR: Object dictionary access failed\n");
            }
         }
      else
         {
         printf("ERROR: node_id %d (%xh) is not responding\n",(int)node_id,(int)node_id);
         }
         
      masterSendNMTstateChange (&win32test_Data, 0x02, NMT_Stop_Node);

      setState(&win32test_Data, Stopped);
      
      canClose(&win32test_Data);
      }
   return 0;
  }
int CESDDevice::reinit(unsigned char ucBaudRateId)
{
	int i, iRetVal = 0;
	m_iErrorState = 0;
	if(!m_bInitFlag)
	{
		warning("device not initialized");
		m_iErrorState = ERRID_DEV_NOTINITIALIZED;
		return m_iErrorState;
	}
	switch(ucBaudRateId)
	{
		case BAUDRATEID_MOD_CAN_125K:
			m_iBaudRate = 125;
			break;
		case BAUDRATEID_MOD_CAN_250K:
			m_iBaudRate = 250;
			break;
		case BAUDRATEID_MOD_CAN_500K:
			m_iBaudRate = 500;
			break;
		case BAUDRATEID_MOD_CAN_1000K:
			m_iBaudRate = 1000;
			break;
	}
	iRetVal = canClose(m_hDevice);
	if(iRetVal != NTCAN_SUCCESS)
	{
		warning("can close failed Errorcode: %d", iRetVal);
		getDeviceError(iRetVal);
		m_iErrorState = ERRID_DEV_EXITERROR;
	}
	iRetVal = canClose(m_hSyncDevice);
	if(iRetVal != NTCAN_SUCCESS)
	{
		warning("can close failed Errorcode: %d", iRetVal);
		getDeviceError(iRetVal);
		m_iErrorState = ERRID_DEV_EXITERROR;
	}
	m_bInitFlag = false;
	iRetVal = canOpen(	
				m_iDeviceId,			// Net
				0,						// Mode
				m_uiQueueSize,			// TX Queue
				m_uiQueueSize,			// RX Queue
				20*m_uiTimeOut,			// Tx Timeout
				m_uiTimeOut,			// Rx Timeout
				&m_hDevice);
	if(iRetVal != NTCAN_SUCCESS)
	{
		warning("can open failed Errorcode: %d", iRetVal);
		getDeviceError(iRetVal);
		m_iErrorState = ERRID_DEV_INITERROR;
		return m_iErrorState;
	}
	/*iRetVal = canOpen(	
				m_iDeviceId,			// Net
				0,						// Mode
				1,						// TX Queue
				1,						// RX Queue
				600,					// Tx Timeout
				100,					// Rx Timeout
				&m_hSyncDevice);
	if(iRetVal != NTCAN_SUCCESS)
	{
		warning("can open failed Errorcode: %d", iRetVal);
		getDeviceError(iRetVal);
		m_iErrorState = ERRID_DEV_INITERROR;
		return m_iErrorState;
	}*/

	m_iErrorState = setBaudRate();
	if(m_iErrorState != 0)
		return m_iErrorState;

	for(i = 0; i <= m_iModuleCountMax; i++)
	{
		iRetVal = canIdAdd(m_hDevice, (MSGID_ACK + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
		iRetVal = canIdAdd(m_hDevice, (MSGID_STATE + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
	}

	for(i = 0; i < MAX_MP55; i++ )
	{
		iRetVal = canIdAdd(m_hDevice, (MSGID_MP55_RECV + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}

		iRetVal = canIdAdd(m_hDevice, (0x180 + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
	}

	for(i = 0; i < MAX_SCHUNK; i++ )
	{
		iRetVal = canIdAdd(m_hDevice, (MSGID_SCHUNK_RECV + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
	}

	iRetVal = canIdAdd(m_hSyncDevice, MSGID_ALL);
	if(iRetVal != NTCAN_SUCCESS)
	{
		warning("can add ID failed Errorcode: %d", iRetVal);
		getDeviceError(iRetVal);
		m_iErrorState = ERRID_DEV_INITERROR;
		return m_iErrorState;
	}

	m_iErrorState = clearReadQueue();
	if(m_iErrorState != 0)
		return m_iErrorState;

	if(m_iErrorState == 0)
		m_bInitFlag = true;

	updateModuleIdMap();
	return m_iErrorState;
}
int CESDDevice::init(const char* acInitString)
{
	InitializeCriticalSection(&m_csDevice);
	int i, iRetVal = 0;
	int txTimeOut = 0;
	char* pcToken;
	char acString[128];
	if(m_bInitFlag)
	{
		warning("device already initialized");
		m_iErrorState = ERRID_DEV_ISINITIALIZED;
		return m_iErrorState;
	}
	m_iDeviceId = -1;
	m_iErrorState = 0;
	strncpy(m_acInitString,acInitString,128);
	strncpy(acString,acInitString,128);
	pcToken = strtok( acString, ":" );
	if( !pcToken )
	{	m_iErrorState = ERRID_DEV_BADINITSTRING;
		return m_iErrorState;
	}
	if( strcmp( pcToken, "ESD" ) != 0 )
	{	m_iErrorState = ERRID_DEV_BADINITSTRING;
		return m_iErrorState;
	}
	pcToken = strtok( NULL, "," );
	if( !pcToken )
	{	m_iErrorState = ERRID_DEV_BADINITSTRING;
		return m_iErrorState;
	}
	m_iDeviceId = atoi(pcToken);

	pcToken = strtok( NULL, "," );
	if( !pcToken )
	{	m_iErrorState = ERRID_DEV_BADINITSTRING;
		return m_iErrorState;
	}
	m_iBaudRate = atoi(pcToken);

#if defined(__LINUX__)
	m_uiTimeOut = 6;
#endif
#if defined (_WIN32)
	switch( m_iBaudRate )
	{
	case 125:
	case 250:
		m_uiTimeOut = 4;
		break;
	case 500:
		m_uiTimeOut = 3;
		break;
	case 1000:
		m_uiTimeOut = 2;
		break;
	default:
		m_uiTimeOut = 10;
		break;
	}
#endif

	try
	{
		iRetVal = canOpen(	
					m_iDeviceId,			// Net
					0,						// Mode
					m_uiQueueSize,			// TX Queue
					m_uiQueueSize,			// RX Queue
					m_uiTimeOut,			// Tx Timeout
					m_uiTimeOut,			// Rx Timeout
					&m_hDevice);
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can open failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
		iRetVal = canOpen(	
					m_iDeviceId,			// Net
					0,						// Mode
					1,						// TX Queue
					1,						// RX Queue
					600,					// Tx Timeout
					100,					// Rx Timeout
					&m_hSyncDevice);
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can open failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
	}
	catch(...)
	{
			warning("init ESD device failed no library found");
			m_iErrorState = ERRID_DEV_NOLIBRARY;
			return m_iErrorState;
	}

	for(i = 0; i <= m_iModuleCountMax; i++)
	{
		iRetVal = canIdAdd(m_hDevice, (MSGID_ACK + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
		iRetVal = canIdAdd(m_hDevice, (MSGID_STATE + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
	}

	for(i = 0; i <= MAX_MP55; i++ )
	{
		iRetVal = canIdAdd(m_hDevice, (MSGID_MP55_RECV + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}

		iRetVal = canIdAdd(m_hDevice, (0x180 + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
		iRetVal = canIdAdd(m_hDevice, (0x600 + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
	}

	for(i = 0; i < MAX_SCHUNK; i++ )
	{
		iRetVal = canIdAdd(m_hDevice, (MSGID_SCHUNK_RECV + i));
		if(iRetVal != NTCAN_SUCCESS)
		{
			warning("can add ID failed Errorcode: %d", iRetVal);
			getDeviceError(iRetVal);
			m_iErrorState = ERRID_DEV_INITERROR;
			return m_iErrorState;
		}
	}
	
	iRetVal = canIdAdd(m_hSyncDevice, MSGID_ALL);
	if(iRetVal != NTCAN_SUCCESS)
	{
		warning("can add ID failed Errorcode: %d", iRetVal);
		getDeviceError(iRetVal);
		m_iErrorState = ERRID_DEV_INITERROR;
		return m_iErrorState;
	}

	m_iErrorState = setBaudRate();
	if(m_iErrorState != 0)
		return m_iErrorState;

	m_iErrorState = clearReadQueue();
	if(m_iErrorState != 0)
		return m_iErrorState;

	if(m_iErrorState == 0)
		m_bInitFlag = true;

	updateModuleIdMap();
	return m_iErrorState;
}
Example #27
0
//-----------------------------------------------
void CanESD::initIntern()
{	
	int ret=0;
/* Does this make any sense as the handle is opened somewhere later?!
	//m_Handle = 9;
	
	//m_Mutex.lock();

	//ret=canClose(m_Handle);

	if(ret == NTCAN_SUCCESS)
	{
		std::cout << "Can close ok ret = " << ret std::endl;
	}

	CAN_IF_STATUS *status;

	ret=canStatus(m_Handle,status);

	if(ret == NTCAN_SUCCESS)
	{
		std::cout << "Get status from can card ok ret = " << ret << std::endl;
	}
*/	
	ret = 0;
	int iCanNet = 1;
	//m_IniFile.GetKeyInt( "CanCtrl", "NetESD", &iCanNet, true);
	
	int iBaudrateVal = NTCAN_BAUD_250;
	//m_IniFile.GetKeyInt( "CanCtrl", "BaudrateVal", &iBaudrateVal, true);

	std::cout << "Initializing CAN network with id =" << iCanNet << ", baudrate=" << iBaudrateVal << std::endl;

	int iRet;
	if( m_bObjectMode )
		//iRet = canOpen(iCanNet, NTCAN_MODE_OBJECT, 10000, 10000, 0, 0, &m_Handle);
		iRet = canOpen(iCanNet, NTCAN_MODE_OBJECT, 10000, 10000, 1000, 0, &m_Handle);
	else
		//iRet = canOpen(iCanNet, 0, 10000, 10000, 0, 0, &m_Handle);
		iRet = canOpen(iCanNet, 0, 10000, 10000, 1000, 0, &m_Handle);
	sleep(0.3);

	if(iRet == NTCAN_SUCCESS)
		std::cout << "CanESD::CanESD(), init ok" << std::endl;
	else
		std::cout << "error in CANESD::receiveMsg: " << GetErrorStr(iRet) << std::endl;

/*	ret=canClose(m_Handle);
	if(ret == NTCAN_SUCCESS)
	{
		std::cout << "Can close ok ret = " << ret << std::endl;
		if( m_bObjectMode )
			iRet = canOpen(iCanNet, NTCAN_MODE_OBJECT, 10000, 10000, 0, 0, &m_Handle);
		else
			iRet = canOpen(iCanNet, 0, 10000, 10000, 0, 0, &m_Handle);
			Sleep(300);

		if(iRet == NTCAN_SUCCESS)
			std::cout << "CanESD::CanESD(), init ok" << ret << std::endl;
		else
			std::cout << "error in CANESD::receiveMsg: " << GetErrorStr(iRet) << std::endl;
	}
*/
	iRet = canSetBaudrate(m_Handle, iBaudrateVal);
	if(iRet == NTCAN_SUCCESS)
		std::cout << "CanESD::CanESD(), canSetBaudrate ok" << std::endl;
	else
		std::cout << "error in CANESD::receiveMsg: " << GetErrorStr(iRet) << std::endl;
	sleep(0.3);

	long lArg;
	iRet = canIoctl(m_Handle, NTCAN_IOCTL_FLUSH_RX_FIFO, NULL);
	//if( iRet == NTCAN_SUCCESS )
	//	std::cout << (int)(lArg) << " messages in CAN receive queue" << std::endl;

	// MMB/24.02.2006: Add all 11-bit identifiers as there is no loss in performance.
	for( int i=0; i<=0x7FF; ++i ) {
		iRet = canIdAdd( m_Handle, i );
		if(iRet != NTCAN_SUCCESS)
			std::cout << "error in CANESD::receiveMsg: " << GetErrorStr(iRet) << std::endl;
	}


	/*
	iRet = canIdAddGroup(m_Handle, 0x98);
	
	// for COB Arm
	iRet = canIdAdd(m_Handle, 0x100);
	iRet = canIdAdd(m_Handle, 0x101);
	iRet = canIdAdd(m_Handle, 0x200);
	iRet = canIdAdd(m_Handle, 0x201);
	iRet = canIdAdd(m_Handle, 0x300);
	iRet = canIdAdd(m_Handle, 0x301);
	iRet = canIdAdd(m_Handle, 0x400);
	iRet = canIdAdd(m_Handle, 0x401);
	iRet = canIdAdd(m_Handle, 0x500);
	iRet = canIdAdd(m_Handle, 0x501);
	iRet = canIdAdd(m_Handle, 0x600);
	iRet = canIdAdd(m_Handle, 0x601);
	
	// for CAN-Open Harmonica
	iRet = canIdAdd(m_Handle, 0x283);
	iRet = canIdAdd(m_Handle, 0x282);
	iRet = canIdAdd(m_Handle, 0x583);
	iRet = canIdAdd(m_Handle, 0x582);
	iRet = canIdAdd(m_Handle, 0x603);
	iRet = canIdAdd(m_Handle, 0x602);

	// for CAN-Open Harmonica and Cello Mimro
	iRet = canIdAdd(m_Handle, 0x18a);
	iRet = canIdAdd(m_Handle, 0x28a);
	iRet = canIdAdd(m_Handle, 0x194);
	iRet = canIdAdd(m_Handle, 0x294);
	iRet = canIdAdd(m_Handle, 0x19e);
	iRet = canIdAdd(m_Handle, 0x29e);
	
	// for RCS5000 arm
	iRet = canIdAdd(m_Handle, 0x111);
	iRet = canIdAdd(m_Handle, 0x112);
	iRet = canIdAdd(m_Handle, 0x113);
	iRet = canIdAdd(m_Handle, 0x114);
	iRet = canIdAdd(m_Handle, 0x115);
	iRet = canIdAdd(m_Handle, 0x116);
	iRet = canIdAdd(m_Handle, 0x788);
	iRet = canIdAdd(m_Handle, 0x789);
	iRet = canIdAdd(m_Handle, 0x78A);
	iRet = canIdAdd(m_Handle, 0x78B);
	iRet = canIdAdd(m_Handle, 0x78C);
	iRet = canIdAdd(m_Handle, 0x78D);
	iRet = canIdAdd(m_Handle, 0x78E);
	iRet = canIdAdd(m_Handle, 0x78F);

	iRet = canIdAddGroup(m_Handle, 0x00);
	iRet = canIdAddGroup(m_Handle, 0x08);
	iRet = canIdAddGroup(m_Handle, 0x10);
	iRet = canIdAddGroup(m_Handle, 0x18);
	iRet = canIdAddGroup(m_Handle, 0x20);
	iRet = canIdAddGroup(m_Handle, 0x28);
	iRet = canIdAddGroup(m_Handle, 0x30);
	iRet = canIdAddGroup(m_Handle, 0x38);
	iRet = canIdAddGroup(m_Handle, 0x40);
	iRet = canIdAddGroup(m_Handle, 0x48);
	iRet = canIdAddGroup(m_Handle, 0x50);
	iRet = canIdAddGroup(m_Handle, 0x58);
	iRet = canIdAddGroup(m_Handle, 0x60);
	iRet = canIdAddGroup(m_Handle, 0x68);
	iRet = canIdAddGroup(m_Handle, 0x98);

	// for Mimro drive ctrl
	iRet = canIdAdd(m_Handle, 0x123);
	*/

/*
	for(int i=0; i<2047; i++)
	{
		if (iRet != NTCAN_SUCCESS)
		{
			TRACE("canIdAdd: %x Error \n", i);
		}
	}
*/
	sleep(0.3);

	m_LastID = -1;

	//m_Mutex.unlock();
}
Example #28
0
int main(int argc,char **argv)
{

  int c;
  extern char *optarg;
  char* LibraryPath="libcanfestival_can_virtual.so";
  char *snodeid;
  while ((c = getopt(argc, argv, "-m:s:M:S:l:i:")) != EOF)
  {
    switch(c)
    {
      case 'm' :
        if (optarg[0] == 0)
        {
          help();
          exit(1);
        }
        MasterBoard.busname = optarg;
        break;
      case 'M' :
        if (optarg[0] == 0)
        {
          help();
          exit(1);
        }
        MasterBoard.baudrate = optarg;
        break;
      case 'l' :
        if (optarg[0] == 0)
        {
          help();
          exit(1);
        }
        LibraryPath = optarg;
        break;
      case 'i' :
        if (optarg[0] == 0)
        {
          help();
          exit(1);
        }
        snodeid = optarg;
		sscanf(snodeid,"%x",&slavenodeid);
        break;
      default:
        help();
        exit(1);
    }
  }

#if !defined(WIN32) || defined(__CYGWIN__)
  /* install signal handler for manual break */
	signal(SIGTERM, catch_signal);
	signal(SIGINT, catch_signal);
	TimerInit();
#endif

#ifndef NOT_USE_DYNAMIC_LOADING
	LoadCanDriver(LibraryPath);
#endif		

	TestMaster_Data.heartbeatError = TestMaster_heartbeatError;
	TestMaster_Data.initialisation = TestMaster_initialisation;
	TestMaster_Data.preOperational = TestMaster_preOperational;
	TestMaster_Data.operational = TestMaster_operational;
	TestMaster_Data.stopped = TestMaster_stopped;
	TestMaster_Data.post_sync = TestMaster_post_sync;
	TestMaster_Data.post_TPDO = TestMaster_post_TPDO;
	
	if(!canOpen(&MasterBoard,&TestMaster_Data)){
		eprintf("Cannot open Master Board\n");
		goto fail_master;
	}
	
	// Start timer thread
	StartTimerLoop(&InitNodes);

	// wait Ctrl-C
	pause();
	eprintf("Finishing.\n");
	
	// Reset the slave node for next use (will stop emitting heartbeat)
	masterSendNMTstateChange (&TestMaster_Data, slavenodeid, NMT_Reset_Node);
	
	// Stop master
	setState(&TestMaster_Data, Stopped);
	
	// Stop timer thread
	StopTimerLoop(&Exit);
	
fail_master:
	if(MasterBoard.baudrate) canClose(&TestMaster_Data);	

	TimerCleanup();
  	return 0;
}
Example #29
0
static long init_bi(
    struct biRecord *prec
) {
    static struct {
	char		*string;
	unsigned long	mask;
    } tipState[] = {
	{ "BUS_OFF",	PCA_SR_BS },
	{ "BUS_ERROR",	PCA_SR_ES },
	{ "DATA_OVERRUN",	PCA_SR_DO },
	{ "RECEIVING",	PCA_SR_RS },
	{ "RECEIVED",	PCA_SR_RBS },
	{ "SENDING",	PCA_SR_TS },
	{ "SENT", 	PCA_SR_TCS },
	{ "OK_TO_SEND",	PCA_SR_TBS },
	{ NULL,		0 }
    };

    char *canString;
    char *name;
    char separator;
    canBusID_t busID;
    int i;
    long status;

    /* bi.inp must be an INST_IO */
    if (prec->inp.type != INST_IO) goto error;

    canString = ((struct instio *)&(prec->inp.value))->string;

    /* Strip leading whitespace & non-alphanumeric chars */
    while (!isalnum(0xff & *canString)) {
	if (*canString++ == '\0') goto error;
    }

    /* First part of string is the bus name */
    name = canString;

    /* find the end of the busName */
    canString = strpbrk(canString, "/:");
    if (canString == NULL || *canString == '\0') goto error;

    /* Temporarily truncate string after name and look up t810 device */
    separator = *canString;
    *canString = '\0';
    status = canOpen(name, &busID);
    *canString++ = separator;
    if (status) goto error;

    /* After the bus name comes the name of the status bit we're after */
    prec->mask=0;
    for (i=0; tipState[i].string != NULL; i++)
	if (strcmp(canString, tipState[i].string) == 0)
	    prec->mask = tipState[i].mask;

    if (prec->mask) {
	prec->dpvt = busID;
	return 0;
    }

error:
    if (canSilenceErrors) {
	prec->pact = TRUE;
	return 0;
    } else {
	recGblRecordError(S_db_badField,(void *)prec,
			  "devBiTip810: Bad INP field type or value");
	return S_db_badField;
    }
}
int main()
{
  LIB_HANDLE driver;

  /* handles for additional CO-PCICAN functions */
  int (*get_fd_of_port)( CAN_PORT port );
  int (*co_pcican_enter_run_mode)( const int fd );
  int (*co_pcican_enter_config_mode)( const int fd );
  int (*co_pcican_select_channel)( const unsigned char channel, const unsigned int direction );
  int (*co_pcican_configure_selected_channel)( const int fd, s_BOARD *board, const unsigned int direction );

  s_BOARD  bd;
  CO_Data  myData;
  CAN_PORT port;
  Message myMessage;
  const char busname[]  = "/dev/co_pcican-0";
  const char baudrate[] = "1M";
  int fd;

  memset( &myData, 0x00, sizeof(CO_Data) );
  myData.CurrentCommunicationState.csSYNC = 1;
  myData.post_sync = mySyncHandler;
  bd.busname  = (char*)busname;
  bd.baudrate = (char*)baudrate;

  printf( "This example sends three SYNCs from port#%u to port#%u with a CO-PCICAN card\n", CHTX, CHRX );

  driver = LoadCanDriver( "/usr/local/lib/libcanfestival_can_copcican_linux.so" );

  if( driver == NULL )
  {
    /* something strange happenend */
    return 0;
  }

  /* dynamic load of additional library functions */
  get_fd_of_port = dlsym( driver, "get_fd_of_port" );
  co_pcican_enter_run_mode = dlsym( driver, "co_pcican_enter_run_mode" );
  co_pcican_enter_config_mode = dlsym( driver, "co_pcican_enter_config_mode" );
  co_pcican_select_channel = dlsym( driver, "co_pcican_select_channel" );
  co_pcican_configure_selected_channel = dlsym( driver, "co_pcican_configure_selected_channel" );

  /* direction: 0=RX, 1=TX */
  co_pcican_select_channel( CHRX, 0 );
  co_pcican_select_channel( CHTX, 1 );

  port = canOpen( &bd, &myData );

  if( port == NULL )
  {
    UnLoadCanDriver( driver );

    /* something strange happenend */
    return 0;
  }

  /* get file descriptor to control the opened device */
  fd = get_fd_of_port( port );

  co_pcican_enter_config_mode( fd );
  co_pcican_configure_selected_channel( fd, &bd, 0 );
  co_pcican_configure_selected_channel( fd, &bd, 1 );
  co_pcican_enter_run_mode( fd );

  memset( &myMessage, 0x00, sizeof(Message) );
  myMessage.cob_id = 0x80; /* SYNC message */
  myMessage.len = 1;
  myMessage.data[0] = 0xA5;

  /* SEND HERE */
  canSend( port, &myMessage );

  myMessage.data[0] = 0x5A;
  canSend( port, &myMessage );

  myMessage.data[0] = 0xA5;
  canSend( port, &myMessage );

  /* mySyncHandler() is called by the receive thread and shows a received SYNC message on console */
  usleep( 1*1000*1000 ); /* 1s */

  canClose( &myData );

  UnLoadCanDriver( driver );

  return 0;
}