void IBClient::execDetails(int reqId, const Contract &contract, const Execution &execution)
{
    auto exec = createDictionary(std::map<std::string, K> {
        { "execId",         ks((S)execution.execId.c_str()) },
        { "time",           kp((S)execution.time.c_str()) }, // TODO: Convert
        { "acctNumber",     ks((S)execution.acctNumber.c_str()) },
        { "exchange",       ks((S)execution.exchange.c_str()) },
        { "side",           ks((S)execution.side.c_str()) },
        { "shares",         ki(execution.shares) },
        { "price",          kf(execution.price) },
        { "permId",         ki(execution.permId) },
        { "clientId",       kj(execution.clientId) },
        { "orderId",        kj(execution.orderId) },
        { "liquidation",    ki(execution.liquidation) },
        { "cumQty",         ki(execution.cumQty) },
        { "avgPrice",       kf(execution.avgPrice) },
        { "evRule",         kp((S)execution.evRule.c_str()) },
        { "evMultiplier",   kf(execution.evMultiplier) }
    });
    receiveData("execDetails", knk(3, ki(reqId), kj(contract.conId), exec));
}
예제 #2
0
QT_BEGIN_NAMESPACE

QV4ProfilerAdapter::QV4ProfilerAdapter(QQmlProfilerService *service, QV4::ExecutionEngine *engine) :
    QQmlAbstractProfilerAdapter(service)
{
    engine->enableProfiler();
    connect(this, SIGNAL(profilingEnabled(quint64)),
            engine->profiler, SLOT(startProfiling(quint64)));
    connect(this, SIGNAL(profilingEnabledWhileWaiting(quint64)),
            engine->profiler, SLOT(startProfiling(quint64)), Qt::DirectConnection);
    connect(this, SIGNAL(profilingDisabled()), engine->profiler, SLOT(stopProfiling()));
    connect(this, SIGNAL(profilingDisabledWhileWaiting()), engine->profiler, SLOT(stopProfiling()),
            Qt::DirectConnection);
    connect(this, SIGNAL(dataRequested()), engine->profiler, SLOT(reportData()));
    connect(this, SIGNAL(referenceTimeKnown(QElapsedTimer)),
            engine->profiler, SLOT(setTimer(QElapsedTimer)));
    connect(engine->profiler, SIGNAL(dataReady(QList<QV4::Profiling::FunctionCallProperties>,
                                               QList<QV4::Profiling::MemoryAllocationProperties>)),
            this, SLOT(receiveData(QList<QV4::Profiling::FunctionCallProperties>,
                                   QList<QV4::Profiling::MemoryAllocationProperties>)));
}
예제 #3
0
void Messenger::reset()
{
    m_packetNo = 1;

    if (socket) {
        socket->close();
        delete socket;
        socket = NULL;
    }

    socket = new QUdpSocket(this);

    if (!socket->bind(UDP_PORT))
    {
        QMessageBox::critical(0, tr("Connection Error"), tr("Could not bind, perhaps port %1 is being used by another application.").arg(UDP_PORT));
        exit(1);
    }

    refreshSettings();
    connect(socket, SIGNAL(readyRead()), this, SLOT(receiveData()));
}
예제 #4
0
void SDRuReceiver_stepImpl(testMACReceiverStackData *SD, const emlrtStack *sp,
  const comm_SDRuReceiver *obj, creal_T y[5120])
{
  real_T fc;
  real_T loOffset;
  real_T gain;
  real_T decim;
  int32_T errMsg_size[2];
  char_T errMsg_data[1024];
  UsrpErrorCapiEnumT errStatus;
  uint32_T overrun;
  uint32_T dataLen;
  int32_T i;
  emlrtStack st;
  st.prev = sp;
  st.tls = sp->tls;
  fc = obj->CenterFrequency;
  loOffset = obj->LocalOscillatorOffset;
  gain = obj->Gain;
  decim = obj->DecimationFactor;
  st.site = &ml_emlrtRSI;
  receiveData(&st, obj->pDriverHandle, fc, loOffset, gain, decim,
              SD->u1.f5.yTemp, &dataLen, &overrun, &errStatus, errMsg_data,
              errMsg_size);
  if (errStatus != UsrpDriverSuccess) {
    st.site = &ml_emlrtRSI;
    error(&st, errMsg_data, errMsg_size);
  }

  for (i = 0; i < 5120; i++) {
    y[i].re = SD->u1.f5.yTemp[i].re;
    y[i].im = SD->u1.f5.yTemp[i].im;
  }

  for (i = 0; i < 5120; i++) {
    fc = y[i].im;
    y[i].re *= 3.0518509475997192E-5;
    y[i].im = 3.0518509475997192E-5 * fc;
  }
}
예제 #5
0
int main(int argc, const char * argv[])
{
    char commandBuffer[512];
    ssize_t commandLength;
    int socketHandle = -1;
    int countDown = MAX_ATTEMPTS_WITHOUT_STATUS;
    
    while (true)
    {
        if (socketHandle < 0) {
            socketHandle = connectToServer(SERVER_ADDRESS, SERVER_PORT);
        }
        
        if (socketConnected(socketHandle)) {
            int available = dataAvailable(socketHandle, 30);
            if (available > 0) {
                commandLength = receiveData(socketHandle, commandBuffer, sizeof(commandBuffer));
                if (commandLength > 0) {
                    countDown = MAX_ATTEMPTS_WITHOUT_STATUS;
                    std::cout << "Received: " <<  commandBuffer << std::endl;
                    handleCommand(socketHandle, commandBuffer, commandLength);
                }
            }
            else if ((countDown <= 0) || (available < 0)) {
                // socket must have broke, let's close and re-attempt
                close(socketHandle);
                socketHandle = -1;
                countDown = MAX_ATTEMPTS_WITHOUT_STATUS;
            }
            else {
                countDown -= 1;
            }
        }
        else {
            sleep(20);
        }
    }
    
    return 0;
}
예제 #6
0
파일: Socket.cpp 프로젝트: ogidow/TCPEvent
void Socket::receiving()
{
	
	ParsedData *parsedData = new ParsedData();
	while (1){
		if (status == 0) break;
		
		receiveData(parsedData);
		
		
		if (parsedData->eventName != ""){
			if (eventList.count(parsedData->eventName) != 0){
				eventList[parsedData->eventName](parsedData->data);
				parsedData->eventName.clear();
				parsedData->data.clear();
			}
		} else {
			close();
		}
	}

}
예제 #7
0
/*----------------------------------------------------------------------
 * i3dmgx3_captureGyroBias	0xCD
 *
 * parameters   portNum    : the number of the sensor device (1..n)
 *              Bresponse    : pointer to a buffer containing returned values
 *
 * returns:     errorCode : I3DMGX3_OK if succeeded, otherwise returns 
 *                          an error code.
 *--------------------------------------------------------------------*/
int i3dmgx3_captureGyroBias(int portNum, short sampt, BYTE *BiasBuff, unsigned char *Bresponse) {
    unsigned char cmd = CMD_CAPTURE_GYRO_BIAS; //0xCD
	unsigned short wChecksum = 0;
    unsigned short wCalculatedCheckSum = 0;
	int responseLength = 19;
    int status;
	int i = 0;
	unsigned char Coutbuff[5];
	
	/* initialize send buffer to obtain gyro bias */
	Coutbuff[0] = 0xCD;   //Command code for Gyro Bias
	Coutbuff[1] = 0xC1;   // Required identifier
    Coutbuff[2] = 0x29;   // Required identifier
    Coutbuff[3] = (sampt & MSB_MASK) >> 8;  //sample time with mask
	Coutbuff[4] =  sampt & LSB_MASK; 
	
	printf("...one %d/ms moment while gyro bias values are retrieved\n", sampt);

	status = sendBuffData(portNum, &Coutbuff[0], 5);
    if (DEBUG) printf(" Capture Gyro Bias  Send struct status is %d\n", status);
	if (status == I3DMGX3_COMM_OK) {
		    status = receiveData(portNum, &Bresponse[0], responseLength);
			if (DEBUG) printf(" Capture Gyro Bias Receive  status is %d\n", status);
			if (status == I3DMGX3_COMM_OK) {
			    wChecksum = convert2ushort(&Bresponse[responseLength-2]);
	            wCalculatedCheckSum = i3dmgx3_Checksum(&Bresponse[0], responseLength-2); //calculate the checkusm, 29 = 31-2 don't include the checksum bytes
				if(wChecksum != wCalculatedCheckSum)
					return status = I3DMGX3_CHECKSUM_ERROR;
	        }else
			    return status = I3DMGX3_COMM_READ_ERROR;        			
			
			for (i=0; i<12; i++)
				BiasBuff[i] = Bresponse[1 +i];
	}else
		return status = I3DMGX3_COMM_WRITE_ERROR;
	return status;

}
예제 #8
0
CommClient::CommClient(QObject* parent) :
    QObject(parent)
{
    QString path = QDir::homePath();
    path.append("/ISL_workspace/src/configISL.json");

    robotID = 0;

    if( !readConfigFile(path) ){
        qDebug()<< "Read Config File Failed!!!";
    }
    else
    {
       qDebug() << "robotID is: "<< robotID;
    }


    socket = new QTcpSocket(this);

    socket->setReadBufferSize(0);

    connect(socket,SIGNAL(readyRead()),this,SLOT(receiveData()));

    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displaySocketError(QAbstractSocket::SocketError)));

    qDebug() << "Client IP is: " << IP;

    socket->connectToHost(IP,4012);

    if(socket->waitForConnected(5000)){
        qDebug()<<"Connected";
    }
    else
    {
        qDebug()<<"Error timeout";
    }
}
예제 #9
0
int i3dmgx3_getFirmwareVersion(int portNum, char *firmware) {
    unsigned char cmd = (char) CMD_FIRWARE_VERSION;
    unsigned char Bresponse[7] = {0}; 
	unsigned short wChecksum = 0;
    unsigned short wCalculatedCheckSum = 0;
	
	short firmwareNum=0;
    short majorNum, minorNum, buildNum;
    int status;
	int responseLength = 7; 
	  	
    status = sendBuffData(portNum, &cmd, 1);
    if (DEBUG) printf("FirmWare_send: tx status : %d\n", status);
	if (status == I3DMGX3_COMM_OK) {
		if (responseLength>0) {
    		status = receiveData(portNum, &Bresponse[0], responseLength);
            if (DEBUG) printf("FirmWare i3dmgx3_send: rx status : %d and responseLength %d\n", status, responseLength);
    		if (status==I3DMGX3_COMM_OK) {
                wChecksum = convert2ushort(&Bresponse[responseLength-2]);
	            wCalculatedCheckSum = i3dmgx3_Checksum(&Bresponse[0], responseLength-2); //calculate the checkusm, 29 = 31-2 don't include the checksum bytes
					if(wChecksum != wCalculatedCheckSum)
						return	status = I3DMGX3_CHECKSUM_ERROR;
			}else
					return status = I3DMGX3_COMM_READ_ERROR;
		}

		firmwareNum = convert2short(&Bresponse[3]);
		if (firmwareNum > 0) {
			/* format for firmware number is #.#.## */
	        majorNum = firmwareNum / 1000;
		    minorNum = (firmwareNum % 1000) / 100;
			buildNum = firmwareNum % 100;
		    sprintf(firmware, "%d.%d.%d", majorNum, minorNum, buildNum);
		} 
		return I3DMGX3_OK;
	}else return status;
}
예제 #10
0
/*----------------------------------------------------------------------
 * i3dmgx3_AccAngMagRate	0xCB
 *
 * parameters   portNum    : the number of the sensor device (1..n)
 *              mag       : array which will contain mag data 
 *                         (3 elements X Y and Z)
 *              accel     : array which will contain acceleration data 
 *                         (3 elements X Y and Z)
 *              angRate   : array which will contain angular rate data 
 *                         (3 elements X Y and Z)
 *              
 *
 * returns:     errorCode : I3DMGX3_OK if succeeded, otherwise returns
 *                          an error code.
 *--------------------------------------------------------------------*/
int i3dmgx3_AccAngMagRate(int portNum, unsigned char* Bresponse) {
	int responseLength = 43;
	int status = 0, i =0;
	unsigned short wChecksum = 0;
    unsigned short wCalculatedCheckSum = 0;
	unsigned char cmd = CMD_ACCEL_ANG_MAG_VECTO;  //0xCB
	
	status = sendBuffData(portNum, &cmd, 1);
    if (DEBUG) printf("Get Acc ang mag i3dmgx3_send: tx status : %d\n", status);
    if (status == I3DMGX3_COMM_OK) {
    		status = receiveData(portNum, &Bresponse[0], responseLength);
			if (DEBUG) printf("Accel ang mag rate i3dmgx3_send: rx status : %d and responseLength %d\n", status, responseLength); /* temp adj 8-1-08 */
    		if (status==I3DMGX3_COMM_OK) {
                wChecksum = convert2ushort(&Bresponse[responseLength-2]);
	            wCalculatedCheckSum = i3dmgx3_Checksum(&Bresponse[0], responseLength-2); //calculate the checkusm, 29 = 31-2 don't include the checksum bytes
	            if(wChecksum != wCalculatedCheckSum){
                    status = I3DMGX3_CHECKSUM_ERROR;
                }
            }else
                status = I3DMGX3_COMM_READ_ERROR;
    }else
		status = I3DMGX3_COMM_WRITE_ERROR;       
	return status;
}
예제 #11
0
파일: main.c 프로젝트: houbuyuan/BetterTest
/*******************************************************************************
* Function Name  : main
* Description    : the main function
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
int main(void)
{
	
	/********Config the Environment***********************/
	SYSTEM_Configuration(); 
	//delay_init(72);
	SYSTEM_Init();
	if(DEBUG) printf("Better Call boot successful.\r\n");
	/****************main loop **********************************/
	//delay_ms(100);
	
	while(1)
	{
		send_flag = 0;
		
		//loop_task();
		
		receiveData();
		if(DEBUG) printf("Better Call receive data done.\r\n");
		if(DEBUG)
		{
			printf("Better Call final data:%d%d%d%d %d%d%d%d %d%d%d%d\r\n",
			data_final[0],data_final[1],data_final[2],data_final[3],
			data_final[4],data_final[5],data_final[6],data_final[7],
			data_final[8],data_final[9],data_final[10],data_final[11]);
		}
		
		if(DEBUG) printf("Better Call waiting for sending data.\r\n");
		while(!send_flag);
		if(DEBUG) printf("Better Call sent data.\r\n");
		
		//send data
		//data_final[12]
		
	}
}
void IBClient::error(const int id, const int errorCode, const IBString errorString)
{
    std::string type;
    
    if (1100 <= errorCode && errorCode <= 1300) {
        type = "system";
    } else if (2100 <= errorCode && errorCode <= 2110) {
        type = "warning";
    } else {
        type = "error";
    }
    
    receiveData(type.c_str(), knk(3, kj(id), kj(errorCode), kp((S)errorString.c_str())));
    
    // "Connectivity between IB and TWS has been lost"
    if (id == -1 && errorCode == 1100) {
        disconnect();
    }
    
    // Exception caught while reading socket - Connection reset by peer
    if (id == -1 && errorCode == 509) {
        disconnect();
    }
}
예제 #13
0
/*----------------------------------------------------------------------
 * i3dmgx3_DeltaAngVel	0xD3
 *
 * parameters   portNum    : the number of the sensor device (1..n)
 *             I3dmgx3Set    : pointer to a struct containing the values 
 *                             gyro stab accel angR and Mag
 *              
 *
 * returns:     errorCode : I3DMGX3_OK if succeeded, otherwise returns
 *                          an error code.
 *--------------------------------------------------------------------*/
int i3dmgx3_DeltaAngVel(int portNum, unsigned char* Bresponse) {
    int responseLength = 43;
	int status;
	unsigned short wChecksum = 0;
    unsigned short wCalculatedCheckSum = 0;
	unsigned char cmd = CMD_DELTA_ANGVEL_MAGV; /* value is 0xD3 */
	int i = 0;
		
	status = sendBuffData(portNum, &cmd, 1);
    if (DEBUG) printf("DeltaAngVel i3dmgx3_send: tx status : %d\n", status);
    if (status == I3DMGX3_COMM_OK) {
    	status = receiveData(portNum, &Bresponse[0], responseLength);
        if (DEBUG) printf("DeltaAngVel i3dmgx3_send: rx status : %d and responseLength %d\n", status);
        if (status==I3DMGX3_COMM_OK) {
            wChecksum = convert2ushort(&Bresponse[responseLength-2]);
	        wCalculatedCheckSum = i3dmgx3_Checksum(&Bresponse[0], responseLength-2); //calculate the checkusm, 29 = 31-2 don't include the checksum bytes
			if(wChecksum != wCalculatedCheckSum)
			  return status = I3DMGX3_CHECKSUM_ERROR;
		}else
			return status = I3DMGX3_COMM_READ_ERROR;
    }else
		return status = I3DMGX3_COMM_WRITE_ERROR;
	return status;
 }
예제 #14
0
/*----------------------------------------------------------------------
 * i3dmgx3_EulerAngRate	0xCF
 *
 * parameters   portNum    : the number of the sensor device (1..n)
 *             I3dmgx3Set    : pointer to a struct containing the values 
 *                             for pitch angles in degrees and
 *							   Angle rates x y and z
 *
 * returns:     errorCode : I3DMGX3_OK if succeeded, otherwise returns
 *                          an error code.
 *--------------------------------------------------------------------*/
int i3dmgx3_EulerAngRate(int portNum, unsigned char* Bresponse) {
    int responseLength = 31;
	int status;
	unsigned short wChecksum = 0;
    unsigned short wCalculatedCheckSum = 0;
	unsigned char cmd = CMD_EULER_ANGLES_ANG_RT; /* value is 0xCF */
	int i = 0;
	
	status = sendBuffData(portNum, &cmd, 1);
    if (DEBUG) printf("i3dmgx3_send Euler and Ang Rate: tx status : %d\n", status);
    if (status == I3DMGX3_COMM_OK) { 
	   	status = receiveData(portNum, &Bresponse[0], responseLength);
        if (DEBUG) printf("Euler Ang Rate i3dmgx3_send: rx status : %d and responseLength %d\n", status, responseLength);
        if (status==I3DMGX3_COMM_OK) {
            wChecksum = convert2ushort(&Bresponse[responseLength-2]);
	        wCalculatedCheckSum = i3dmgx3_Checksum(&Bresponse[0], responseLength-2); //calculate the checkusm, 29 = 31-2 don't include the checksum bytes
			if(wChecksum != wCalculatedCheckSum)
				return status = I3DMGX3_CHECKSUM_ERROR;
		}else
			return status = I3DMGX3_COMM_READ_ERROR;
	} else
		return status = I3DMGX3_COMM_WRITE_ERROR;
	return status;
}
예제 #15
0
/*----------------------------------------------------------------------
 * i3dmgx3_ScaledMagVec	0xC7
 *
 * parameters   portNum : the number of the sensor device (1..n)
 *              pI3Record : struct to receive floating point values for
 *                          scaled Magnetometer Vectors (x,y,z)
 *
 * returns:     errorCode : I3DMGX3_OK if succeeded, otherwise returns 
 *                          an error code.
 *---------------------------------------------------------------------*/
int i3dmgx3_ScaledMagVec(int portNum, unsigned char* Bresponse) {
    int responseLength = 19;
	int status;
	unsigned short wChecksum = 0;
    unsigned short wCalculatedCheckSum = 0;
	unsigned char cmd = CMD_MAGNETROMETER_VECT; /* value is 0xC7 */
	int i = 0;
	
	status = sendBuffData(portNum, &cmd, 1);
    if (DEBUG) printf("Scaled Mag Vector i3dmgx3_send: tx status : %d\n", status);
    if (status == I3DMGX3_COMM_OK) {
      		status = receiveData(portNum, &Bresponse[0], responseLength);
            if (DEBUG) printf("Scaled Mag Vectorr i3dmgx3_send: rx status : %d and responseLength %d\n", status, responseLength);
    		if (status==I3DMGX3_COMM_OK) {
                wChecksum = convert2ushort(&Bresponse[responseLength-2]);
	            wCalculatedCheckSum = i3dmgx3_Checksum(&Bresponse[0], responseLength-2); //calculate the checkusm, 29 = 31-2 don't include the checksum bytes
					if(wChecksum != wCalculatedCheckSum)
						return	status = I3DMGX3_CHECKSUM_ERROR;
			}else
					return status = I3DMGX3_COMM_READ_ERROR;			
		}else
			status = I3DMGX3_COMM_WRITE_ERROR;
	return status;
}
예제 #16
0
/*----------------------------------------------------------------------
 * i3dmgx3_AccelAngOreint	0xC8
 *
 * parameters   portNum : the number of the sensor device (1..n)
 *              pI3Record : struct to receive floating point values for
 *                          Acceleration and Angular Rates (x,y,z)
 *                          and Orientation Matrix M1.1 - M1.2 ... M3.3
 *
 * returns:     errorCode : I3DMGX3_OK if succeeded, otherwise returns 
 *                          an error code.
 *--------------------------------------------------------------------*/
int i3dmgx3_AccelAngOreint(int portNum, unsigned char* Bresponse) {
    int responseLength = 67;
	int status;
	unsigned short wChecksum = 0;
    unsigned short wCalculatedCheckSum = 0;
	unsigned char cmd = CMD_ACCEL_ANG_ORIENT; /* value is 0xC8 */
	int i = 0;
	
	status = sendBuffData(portNum, &cmd, 1);
    if (DEBUG) printf("Accel AngRate OrientMatx i3dmgx3_send: tx status : %d\n", status);
    if (status == I3DMGX3_COMM_OK) {
       		status = receiveData(portNum, &Bresponse[0], responseLength);
            if (DEBUG) printf("Accel Ang Orient i3dmgx3_send: rx status : %d and responseLength %d\n", status, responseLength);
    		if (status==I3DMGX3_COMM_OK) {
                wChecksum = convert2ushort(&Bresponse[responseLength-2]);
	            wCalculatedCheckSum = i3dmgx3_Checksum(&Bresponse[0], responseLength-2); //calculate the checkusm, 29 = 31-2 don't include the checksum bytes
					if(wChecksum != wCalculatedCheckSum)
						return	status = I3DMGX3_CHECKSUM_ERROR;
			}else
					return status = I3DMGX3_COMM_READ_ERROR;  	
	}else
			status = I3DMGX3_COMM_WRITE_ERROR;
	return status;
}
예제 #17
0
파일: rtl8139.c 프로젝트: else/xelix
static void rtl8139_intHandler(cpu_state_t *state)
{
	log(LOG_DEBUG, "rtl8139: Got interrupt \\o/\n");

	for (int i = 0; i < cards; ++i)
	{
		struct rtl8139_card *card = rtl8139_cards + i;
		uint16_t isr = int_in16(card, REG_INTERRUPT_STATUS);
		uint16_t new_isr = 0;

		if (isr & ISR_TRANSMIT_OK)
		{
			new_isr |= ISR_TRANSMIT_OK;
		}

		if (isr & ISR_RECEIVE_OK)
		{
			receiveData(card);
			new_isr |= ISR_RECEIVE_OK;
		}

		int_out16(card, REG_INTERRUPT_STATUS, new_isr);
	}
}
예제 #18
0
/*----------------------------------------------------------------------
 * i3dmgx3_GetFullMatrix 0xCC
 *  	
 * parameters   portNum    : the number of the sensor device (1..n)
 *              I3Record   : 18 positional stucture of defined type 
 *                           I3Record to capture data in floating point
 *							   
 * returns:     errorCode : I3DMGX3_OK if succeeded, otherwise returns
 *                          an error code.
 *--------------------------------------------------------------------*/
int i3dmgx3_GetFullMatrix(int portNum, unsigned char* Bresponse) {
	int responseLength = 79;
	int status;
	unsigned short wChecksum = 0;
    unsigned short wCalculatedCheckSum = 0;
	unsigned char cmd = CMD_ACEL_ANG_MAG_VEC_OR; /* value is 0xCC */
	int i=0;
	
	status = sendBuffData(portNum, &cmd, 1);
    if (DEBUG) printf("i3dmgx3_send: tx status : %d\n", status);
    if (status == I3DMGX3_COMM_OK) {
    		status = receiveData(portNum, &Bresponse[0], responseLength);
            if (DEBUG) printf("i3dmgx3_send: rx status : %d and responseLength %d\n", status, responseLength); /* temp adj 8-1-08 */
    		if (status==I3DMGX3_COMM_OK) {
                wChecksum = convert2ushort(&Bresponse[responseLength-2]);
	            wCalculatedCheckSum = i3dmgx3_Checksum(&Bresponse[0], responseLength-2); //calculate the checkusm, 29 = 31-2 don't include the checksum bytes
				if(wChecksum != wCalculatedCheckSum)
                   return status = I3DMGX3_CHECKSUM_ERROR;
				}else
				return status = I3DMGX3_COMM_READ_ERROR;
    }else
		status = I3DMGX3_COMM_WRITE_ERROR;  
	return status;
}
예제 #19
0
파일: mainwindow.cpp 프로젝트: guyuhu/Robot
MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    companyWebAddress ="explorer http://www.oschina.net/p/qtsharp";

    pingNet ="Ping www.baidu.com";   //实现ping值的实时测量
    getPing();
    QTimer *pingTimer=new QTimer(this);//此段作用是用一个定时器,每隔5s,查看一次当前ping值。
    connect(pingTimer,SIGNAL(timeout()),this,SLOT(pingTimeOut()));
    pingTimer->start(5000);

    bool ok=false;                      //定义声明一个服务器实体。
    getHostInformation();
    port=this->ui->editPort->text().toInt(&ok,10);
    tcpserver=new TcpServer(this,port);         //将server中的有用变量都复制到本函数中。
    robotHash=tcpserver->getRobotIDHash();
    robotNumberOnLine=tcpserver->getRobotNumber();
    showClientMessage();

    connect(tcpserver,SIGNAL(receiveDataSource(ProtocolFromClient2Server)),this,SLOT(receiveData(ProtocolFromClient2Server)));//接收数据槽函数。
    connect(this,SIGNAL(sendDataSource(QString,int)),this,SLOT(sendData(QString,int)));//发送数据槽函数。
}
uint8_t avsHeader::askFor(uint32_t cmd,uint32_t frame, uint32_t payloadsize,uint8_t *payload)
{
   
    if(!sendData(cmd,frame,0,NULL))
    {
        printf("[avsProxy]Send Cmd %u failed for frame %u\n",cmd,frame);
        return 0;
    }
    // Wait reply
    uint32_t size,reply,outframe;
    if(!receiveData(&reply,&outframe,&size,payload))
    {
        printf("[avsProxy]Rx Cmd %u failed for frame %u\n",cmd,frame);
        return 0;   
    }
  
    // Check!
    ADM_assert(outframe==frame);
    ADM_assert(reply==cmd+1);
    ADM_assert(size==payloadsize);
    aprintf("[avsProxy]Cmd %u on frame %u succeed\n",cmd,frame);
    return 1;
    
}
예제 #21
0
/*
* 	sendInstruction: Send Sensors Data to the external device
*	@param: String largeData - string to send 
*/
void SMBLEApplication::sendInstruction(String largeData){

		String dataCurDevice;
		String dataExtDevice;
		String position;
		position = _isRight ? "@" : "";
		
		largeData = "$" + largeData + "$";

		int jsonDataLength = largeData.length()/BLEFRAME;

			for(int i= 0;  i< jsonDataLength+1; i++){

				if(i == jsonDataLength){

					if(BLEFRAME%i != 0){
						//Check wether there are last data to send
						dataCurDevice =	position + largeData.substring(i*(BLEFRAME-1));
						sendData(dataCurDevice);
						Serial.println(dataCurDevice);
					}
					
				} else {

					dataCurDevice = position + largeData.substring(i*(BLEFRAME-1),(i+1)*(BLEFRAME-1));
					sendData(dataCurDevice);
					Serial.println(dataCurDevice);

				}

			}

		//Check if their is a request from the external device
		dataExtDevice = receiveData();
		_sessionStarted = true;//!dataExtDevice.equals(String(STOPSESSION));
}
예제 #22
0
int main(void)
{
		DDRA = 0xF0; PORTA = 0x0F;
		DDRB = 0x00;  PORTB = 0xFF;
		DDRC = 0xFF; PORTC = 0x00;
		DDRD = 0xFF; PORTD = 0x00;
		gameSelector = 0xFF;
		LINE_init();
	    TimerSet(1);
	    TimerOn();
	    srand(0);
	    InitADC();
		initUSART(1);
		
    while (1) 
    {
		if(SandM_period >= 10)
		{
			if(USART_HasReceived(1)){
				gameSelector = receiveData(1);
			}
			SandM_period = 0;
		}
		++SandM_period;
		
		if(gameSelector == 0x02)
		{
			if(TRLINES_period >= 9)
			{	       
				TRLINES_period = 0;
			}
			if(TRuser_period >= 80)
			{
				TunRun_ChkLoss();
				TunRun_JoyStk();
				TUNRUN_LINES();
				TunRun_Input();
				TRuser_period = 0;
			}
				displayMatrix();
				++TRLINES_period;
				++TRuser_period;
		}
		if(gameSelector == 0x04)
		{
			if(arrows_period >= 750)
			{
				DDR_arrows();
				if((arrow == 0) || (arrow == 2))
				{
					ADMUX = 0x40;
				}
				else
				{
					ADMUX = 0x41;
				}
				arrows_period = 0;
			}
			if(arrows_inputP >= 20)
			{
				DDR_Input();
				DDR_JoyStk();
				arrows_inputP = 0;
			}
			if(arrowsPeriod >= 250)
			{
				DDR_ChkLoss();
				arrowsPeriod = 0;
			}
			displayMatrix();
			++arrows_inputP;
			++arrows_period;
			++arrowsPeriod;
		}
		if(gameSelector == 0x03)
		{
			if(snakeJoystick > 30)
			{
				Snake_JoyStk();
				Snake_Input();
				snakeJoystick = 0;
			}
			if(body > body_period)
			{
				SnakeBody();
				Snake_Movement();
				body = 0;
			}
			++snakeJoystick;
			++joystick;
			++body;
			displayMatrix();
		}
		while(!TimerFlag);
		TimerFlag = 0;
    }
}
void ProtocolConnection::internOnFrameReceived(ProtocolParser::ProtocolParserStatus status, Frame *frame) {
	onFrameReceived(status, frame);
	receiveData();
}
/*Serve una richiesta client
 * Quattro messaggi al client e attende una risposta ... finchè il client non chiude la connessione
 */
void* service(void* dss)
{
  int ret, i = 0;
  int ds_sockin = *((int*)dss);
  
  struct sigaction sigpipe;
  sigpipe.sa_handler = (void*)&connessione_senza_lettore;
  sigpipe.sa_mask = sig;
  sigaction(SIGPIPE, &sigpipe, NULL);
  
  sigemptyset(&sig);
  sigaddset(&sig, SIGINT);
  pthread_sigmask(SIG_BLOCK, &sig, NULL);

  char buffer[MESGSIZE];
  size_t receiveByte;
  
  while(1)
  {
    while(i < 4)
    {
      printf("Invia Messaggio %d:\n", i);
      fgets(buffer, MESGSIZE, stdin);
      usleep(10);
      ret = sendData(ds_sockin, buffer, MESGSIZE);
      
      if(ret == -1)
      {
	printf("Errore in scrittura sul socket\n");
	close(ds_sockin);
	pthread_exit(0);
      }
      i++;
    }
    i = 0;
       
    receiveByte = receiveData(ds_sockin, buffer, MESGSIZE);
    if(receiveByte == -1)
    {
      printf("Errore in lettura\n");
      close(ds_sockin);
      pthread_exit(0);
    }
    else if(receiveByte == 0)
    {
      printf("Il client ha chiuso la connessione\n");
      close(ds_sockin);
      pthread_exit(0);
    }
    
    if(strncmp(buffer, "quit", 4) == 0)
    {
      printf("Il client ha dato quit\n");
      break;
    }
      
    printf("Client: %s\n", buffer);
  }
  
  close(ds_sockin);
  pthread_exit(0);
}
예제 #25
0
파일: SM130.cpp 프로젝트: cperez36/RFIDuino
/**	Checks for availability of a valid response packet.
 *
 *	This function should always be called and return true prior to using results
 *	of a command.
 *
 *	@returns	true if a valid response packet is available
 */
boolean SM130::available()
{
	// If in SEEK mode and using DREADY pin, check the status
	if (cmd == CMD_SEEK_TAG && pinDREADY != 0xff)
	{
		if (!digitalRead(pinDREADY))
			return false;
	}

	// Set the maximum length of the expected response packet
	byte len;
	switch(cmd)
	{
	case CMD_ANTENNA_POWER:
	case CMD_AUTHENTICATE:
	case CMD_DEC_VALUE:
	case CMD_INC_VALUE:
	case CMD_WRITE_KEY:
	case CMD_HALT_TAG:
	case CMD_SLEEP:
		len = 4;
		break;
	case CMD_WRITE4:
	case CMD_WRITE_VALUE:
	case CMD_READ_VALUE:
		len = 8;
	case CMD_SEEK_TAG:
	case CMD_SELECT_TAG:
		len = 11;
		break;
	default:
		len = SIZE_PACKET;
	}

	// If valid data received, process the response packet
	if (receiveData(len) > 0)
	{
		// Init response variables
		tagType = tagLength = *tagString = 0;

		// If packet length is 2, the command failed. Set error code.
		errorCode = getPacketLength() < 3 ? data[2] : 0;

		// Process command response
		switch (getCommand())
		{
		case CMD_RESET:
		case CMD_VERSION:
			// RESET and VERSION commands produce the firmware version
			len = min(getPacketLength(), sizeof(versionString)) - 1;
			memcpy(versionString, data + 2, len);
			versionString[len] = 0;
			break;

		case CMD_SEEK_TAG:
		case CMD_SELECT_TAG:
			// If no error, get tag number
			if(errorCode == 0 && getPacketLength() >= 6)
			{
				tagLength = getPacketLength() - 2;
				tagType = data[2];
				memcpy(tagNumber, data + 3, tagLength);
				arrayToHex(tagString, tagNumber, tagLength);
			}
			break;

		case CMD_AUTHENTICATE:
			break;

		case CMD_READ16:
			break;

		case CMD_WRITE16:
		case CMD_WRITE4:
			break;

		case CMD_ANTENNA_POWER:
			errorCode = 0;
			antennaPower = data[2];
			break;

		case CMD_SLEEP:
			// If in SLEEP mode, no data is available
			return false;
		}

		// Data available
		return true;
	}
	// No data available
	return false;
}
예제 #26
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    conectar = new Conectar();
    conectar->show();

    connect(conectar, SIGNAL(accepted()), this, SLOT(connectServer()));

    ui->setupUi(this);

    timerLeitura = new QTimer(0);
    timerEscrita = new QTimer(0);

    threadLeitura = new QThread(this);
    threadEscrita = new QThread(this);

    timerLeitura->start(100);
    timerEscrita->start(100);

    timerLeitura->moveToThread(threadLeitura);
    connect(timerLeitura, SIGNAL(timeout()), this, SLOT(receiveData()));

    timerEscrita->moveToThread(threadEscrita);
    connect(timerEscrita, SIGNAL(timeout()), this, SLOT(sendData()));

    // Controlador P-I-D
    connect(ui->rb_constGanho,   SIGNAL(toggled(bool)),this,SLOT(UI_configControlador()));
    connect(ui->rb_constTempo,   SIGNAL(toggled(bool)),this,SLOT(UI_configControlador()));
    connect(ui->tipoControlador, SIGNAL(currentIndexChanged(int)),this,SLOT(UI_configControlador()));
    connect(ui->tipoControlador_2,SIGNAL(currentIndexChanged(int)),this,SLOT(UI_configControlador()));
    connect(ui->radioFechada,    SIGNAL(toggled(bool)), ui->tab_sinal_controle->widget(TAB_CONTROLE), SLOT(setEnabled(bool)));
    connect(ui->radioAberta,     SIGNAL(toggled(bool)), ui->tab_sinal_controle->widget(TAB_CONTROLE), SLOT(setDisabled(bool)));
    connect(ui->rb_constTempo,   SIGNAL(toggled(bool)),this,SLOT(UI_configConsControle()));
    connect(ui->rb_constGanho,   SIGNAL(toggled(bool)),this,SLOT(UI_configConsControle()));

    /// Habilitar Canais e Mostrar Canais no Gráfico
    connect(ui->canal_l0, SIGNAL(toggled(bool)), ui->cb_plot_canal0, SLOT(setEnabled(bool)));
    connect(ui->canal_l1, SIGNAL(toggled(bool)), ui->cb_plot_canal1, SLOT(setEnabled(bool)));
    connect(ui->canal_l2, SIGNAL(toggled(bool)), ui->cb_plot_canal2, SLOT(setEnabled(bool)));
    connect(ui->canal_l3, SIGNAL(toggled(bool)), ui->cb_plot_canal3, SLOT(setEnabled(bool)));
    connect(ui->canal_l4, SIGNAL(toggled(bool)), ui->cb_plot_canal4, SLOT(setEnabled(bool)));
    connect(ui->canal_l5, SIGNAL(toggled(bool)), ui->cb_plot_canal5, SLOT(setEnabled(bool)));
    connect(ui->canal_l6, SIGNAL(toggled(bool)), ui->cb_plot_canal6, SLOT(setEnabled(bool)));
    connect(ui->canal_l7, SIGNAL(toggled(bool)), ui->cb_plot_canal7, SLOT(setEnabled(bool)));
    connect(ui->canal_l0, SIGNAL(toggled(bool)), ui->cb_plot_canal0, SLOT(setChecked(bool)));
    connect(ui->canal_l1, SIGNAL(toggled(bool)), ui->cb_plot_canal1, SLOT(setChecked(bool)));
    connect(ui->canal_l2, SIGNAL(toggled(bool)), ui->cb_plot_canal2, SLOT(setChecked(bool)));
    connect(ui->canal_l3, SIGNAL(toggled(bool)), ui->cb_plot_canal3, SLOT(setChecked(bool)));
    connect(ui->canal_l4, SIGNAL(toggled(bool)), ui->cb_plot_canal4, SLOT(setChecked(bool)));
    connect(ui->canal_l5, SIGNAL(toggled(bool)), ui->cb_plot_canal5, SLOT(setChecked(bool)));
    connect(ui->canal_l6, SIGNAL(toggled(bool)), ui->cb_plot_canal6, SLOT(setChecked(bool)));
    connect(ui->canal_l7, SIGNAL(toggled(bool)), ui->cb_plot_canal7, SLOT(setChecked(bool)));

    //Grafico e Canais
    connect(ui->cb_plot_canal0, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_canal1, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_canal2, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_canal3, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_canal4, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_canal5, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_canal6, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_canal7, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_canalEscrita, SIGNAL(activated(int)), this, SLOT(UI_configPlotGraficosL()));

    // Grafico e Variavéis
    connect(ui->cb_plot_erro,           SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_setPoint,       SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_p,              SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_i,              SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_d,              SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_graf_sinalCalculado, SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosE()));
    connect(ui->cb_graf_sinalEnviado,   SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosE()));
    connect(ui->cb_SinalParcial,   SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosE()));
    //connect(ui->cb_plot_erro_2,           SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    //connect(ui->cb_plot_setPoint_2,       SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_p_2,        SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_i_2,        SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->cb_plot_d_2,        SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->checkErroObsTq01,   SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->checkErroObsTq02,   SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->checkObsTq01,       SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));
    connect(ui->checkObsTq02,       SIGNAL(toggled(bool)), this, SLOT(UI_configPlotGraficosL()));


    // Botões
    connect(ui->buttonAtualizar,SIGNAL(clicked(bool)),this,SLOT(data()));
    connect(ui->buttonStop,     SIGNAL(clicked(bool)),this,SLOT(zerarSinal()));

    // Tipo de Malha
    connect(ui->radioAberta,    SIGNAL(clicked(bool)),this,SLOT(UI_configMalha()));
    connect(ui->radioFechada,   SIGNAL(clicked(bool)),this,SLOT(UI_configMalha()));

    connect(ui->comboTipoSinal, SIGNAL(currentIndexChanged(int)),this,SLOT(UI_configSignal()));

    // Controlar o limite das entradas
    connect(ui->dSpinAmp,       SIGNAL(valueChanged(double)), this, SLOT(UI_limitRandInput()));
    connect(ui->dSpinPeriodo,   SIGNAL(valueChanged(double)), this, SLOT(UI_limitRandInput()));
    connect(ui->dSpinOffSet,    SIGNAL(valueChanged(double)), this, SLOT(UI_limitRandInput()));
    connect(ui->dSpinAux,       SIGNAL(valueChanged(double)), this, SLOT(UI_limitRandInput()));

    //Ordem do Sistema e comportamento do sistema
    connect(ui->radioFechada, SIGNAL(toggled(bool)), ui->frameOrdem, SLOT(setEnabled(bool)));
    connect(ui->rbSistemaO2, SIGNAL(toggled(bool)), ui->combo_Mp, SLOT(setEnabled(bool)));
    connect(ui->rbSistemaO2, SIGNAL(toggled(bool)), ui->combo_Tr, SLOT(setEnabled(bool)));
    connect(ui->rbSistemaO2, SIGNAL(toggled(bool)), ui->combo_Ts, SLOT(setEnabled(bool)));
    connect(ui->rbSistemaO2, SIGNAL(toggled(bool)), ui->canal_l1, SLOT(setChecked(bool)));
    connect(ui->rbSistemaO1, SIGNAL(toggled(bool)), ui->canal_l0, SLOT(setChecked(bool)));

    //Sistema de Segunda Ordem e Controle Simples e Cascata
    ui->gp_graf_pid_2->setVisible(false);
    ui->tabControlador->widget(TAB_ESCRAVO)->setEnabled(false);
    connect(ui->radioCascata, SIGNAL(toggled(bool)), this, SLOT(UI_tipo2Ordem_setEnable()));
    connect(ui->rbSistemaO2,  SIGNAL(toggled(bool)), this, SLOT(UI_tipo2Ordem_setEnable()));
    connect(ui->radioFechada, SIGNAL(toggled(bool)), this, SLOT(UI_tipo2Ordem_setEnable()));
    connect(ui->radioCascata, SIGNAL(toggled(bool)), this, SLOT(UI_connect_tipoDeSistema()));
    connect(ui->radioSimples, SIGNAL(toggled(bool)), this, SLOT(UI_connect_tipoDeSistema()));

    //Observador de Estado
    connect(ui->radioObservador,SIGNAL(toggled(bool)), this, SLOT(UI_connect_tipoDeSistema()));
    connect(ui->radioFechada,   SIGNAL(toggled(bool)), this, SLOT(UI_connect_tipoDeSistema()));
    connect(ui->rbSistemaO2,    SIGNAL(toggled(bool)), this, SLOT(UI_connect_tipoDeSistema()));
    connect(ui->dSpinL1_Obs, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_observador_LtoP()));
    connect(ui->dSpinL2_Obs, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_observador_LtoP()));
    connect(ui->dSpinP1Real_Obs, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_observador_PtoL()));
    connect(ui->dSpinP2Real_Obs, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_observador_PtoL()));
    connect(ui->dSpinComplexo_Obs, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_observador_PtoL()));

    //Seguidor de Referencia
    connect(ui->radioSeguidor, SIGNAL(toggled(bool)), this, SLOT(UI_connect_tipoDeSistema()));
    connect(ui->dSpinK1_Seg, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_seguidor_KtoP()));
    connect(ui->dSpinK2_Seg, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_seguidor_KtoP()));
    connect(ui->dSpinK3_Seg, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_seguidor_KtoP()));
    connect(ui->dSpinP1Real_Seg, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_seguidor_PtoK()));
    connect(ui->dSpinP2Real_Seg, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_seguidor_PtoK()));
    connect(ui->dSpinP3Real_Seg, SIGNAL(valueChanged(double)), this, SLOT(UI_connect_seguidor_PtoK()));
    connect(ui->dSpinP1Com_Seg,  SIGNAL(valueChanged(double)), this, SLOT(UI_connect_seguidor_PtoK()));


    UI_configPanel(); /* Método principal para setar o INIT da UI */

    matls = (double**)calloc(2, sizeof(double));

    matpolos = (double**)calloc(2, sizeof(double));

    for(int i=0; i<2; i++) {
        matpolos[i] = (double*)calloc(2, sizeof(double));
    }
    for(int i=0; i<2; i++) {
        matls[i] = (double*)calloc(1, sizeof(double));
    }
}
예제 #27
0
// *************************
//  Receive Thread
//
//  Input:
//    int *sckt = pointer of socket descriptor
//
void *receiveDataThread(void *arg)
{
  int recvLen;
  char recvBuffer[BUFFER_SIZE];
  int indexBuffer;
  int agentNumber;
  int i;
	RTDBconf_var rec;
	int life;
	struct _frameHeader frameHeader;

	int size;
	

	while(!end)
	{
		bzero(recvBuffer, BUFFER_SIZE);
		indexBuffer = 0;

		if((recvLen = receiveData(*(int*)arg, recvBuffer, BUFFER_SIZE)) > 0 )
		{

			memcpy (&frameHeader, recvBuffer + indexBuffer, sizeof(frameHeader));
			indexBuffer += sizeof(frameHeader);

			agentNumber = frameHeader.number;

      gettimeofday(&(agent[agentNumber].receiveTimeStamp), NULL);

      // receive from ourself
      // not supposed to occur. just to prevent!
  		if ((agentNumber == myNumber) && (nosend == 0))
				continue;

			// TODO
      // correction when frameCounter overflows
			if ((agent[agentNumber].lastFrameCounter + 1) != frameHeader.counter)
				lostPackets[agentNumber] = frameHeader.counter - (agent[agentNumber].lastFrameCounter + 1);
			agent[agentNumber].lastFrameCounter = frameHeader.counter;

      // state team view from received agent
			for (i = 0; i < MAX_AGENTS; i++)
				agent[agentNumber].stateTable[i] = frameHeader.stateTable[i];

			for(i = 0; i < frameHeader.noRecs; i++)
			{
				// id
				memcpy (&rec.id, recvBuffer + indexBuffer, sizeof(rec.id));
				indexBuffer += sizeof(rec.id);

				// size
				memcpy (&rec.size, recvBuffer + indexBuffer, sizeof(rec.size));
				indexBuffer += sizeof(rec.size);

				// life
				memcpy (&life, recvBuffer + indexBuffer, sizeof(life));
				indexBuffer += sizeof(life);

        life += COMM_DELAY_MS;

				// data
				if((size = DB_comm_put (agentNumber, rec.id, rec.size, recvBuffer + indexBuffer, life)) != (int)rec.size)
				{
					PERR("Error in frame/rtdb: from = %d, item = %d, received size = %d, local size = %d", agentNumber, rec.id, rec.size, size);
					break;
				}
				PDEBUG("Receive from %d\n", agentNumber);

				indexBuffer += rec.size;
			}

#ifndef UNSYNC
			sync_ratdma(agentNumber);
#endif

		}
	}

	return NULL;
}
예제 #28
0
int main(int argc, char *argv[])
{
  int sd;
  struct hostent *h;
  struct sockaddr_in sa;
  FILE *sock = 0;
  char *line = 0, *cmd = 0;
  size_t linelen = 0;
  unsigned int i, j;
  size_t dataSize;
  struct Matrix matrix;


  if (argc > 3 || argc < 2) {
    usage(argv[0]);
    exit(1);
  } else if (argc == 3) {
    if (!parseHostPort(argv[1]))
      exit(1);
    cmd = argv[2];
  } else 
    cmd = argv[1];

  if ( !(h = gethostbyname(host)) ) {
    herror("gethostbyname");
    exit(1);
  }
  
  if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 ) {
    perror("socket");
    exit(1);
  }

  sa.sin_family = AF_INET;
  sa.sin_port = htons(port);
  memcpy(&sa.sin_addr, h->h_addr_list[0], sizeof(struct in_addr));
  
  fprintf(stderr, "Connecting to %s port %hu\n", inet_ntoa(sa.sin_addr), port);

  if ( connect(sd, (struct sockaddr *)&sa, sizeof(sa)) ) {
    perror("connect");
    exit(1);
  }  
  
  if ( !(sock = fdopen(sd, "r+")) ) {
    perror("fdopen");
    exit(1);
  }
  
  fprintf(stderr, "Connected, sending '%s'\n", cmd);
  fprintf(sock, "%s\n", cmd);
  fflush(sock);
  
  matrixInit(&matrix);
  
  if ( getline(&line, &linelen, sock) == -1 
       || sscanf(line, "MATRIX %u %u", &matrix.m, &matrix.n) != 2) {
    if (strstr(line, "ERROR") == line) 
      fprintf(stderr, "Got ERROR response.. check the command and try again!\n");
    else
      fprintf(stderr, "Cannot parse matrix dimensions, bailing.\n");
    exit(1);
  }
  
  fprintf(stderr, "Ok, matrix is %ux%u.  Reading matrix data...\n", matrix.m, matrix.n);
  matrix.d = calloc(matrix.m*matrix.n, sizeof(double));  
  
  if (!matrix.d) {
    fprintf(stderr, "Cannot allocate memory.\n");
    exit(1);
  }

  fprintf(sock, "READY\n");
  fflush(sock);
  dataSize = matrix.m*matrix.n*sizeof(double);  
  
  if ( receiveData(matrix.d, dataSize, sock) != (ssize_t)dataSize )  {
    fprintf(stderr, "receive error when reading matrix data, bailing\n");
    exit(1);
  }

  fprintf(stderr, "%u bytes read, OK.\n", dataSize);
  
  if ( getline(&line, &linelen, sock) == -1 ) {
    fprintf(stderr, "Did not receive any response, exiting.\n");
    exit(1);
  } else if (strcmp(line, "OK\n")) {
    fprintf(stderr, "Got OK.\n");
    exit(1);
  }

  for(i = 0; i < matrix.m; ++i ) {
    for (j = 0; j < matrix.n; ++j) 
      fprintf(stdout, "%lf ", *at(&matrix, i, j));
    fprintf(stdout, "\n");
  }
 
  fprintf(sock, "EXIT\n");
  fflush(sock);
  free(line);
  free(matrix.d);
  shutdown(sd, SHUT_RDWR);
  fclose(sock);
  return 0;
}
예제 #29
0
void DataChannel::run()
{
	int transferId;
	if(!receiveData(m_Socket, (char*)&transferId, sizeof(transferId)))
	{
		emit errorHappend(ReceiveDataError);
		return;
	}
	transferId = ntohl(transferId);

	DataServerThread* dataServer = DataServerThread::createDataServer();

	DataTransfer* dataTransfer;
	try{
		dataTransfer = dataServer->getAndPopTransfer(transferId);
	}catch(...)
	{
		qDebug()<<tr("无法找到对应的传送数据ID");
		return;
	}

	unsigned long fileStatusCode; //客户端的文件是否存在等信息
	if(!getFourByte(m_Socket, fileStatusCode))
	{
		qDebug()<<tr("得到远程文件信息出错");
		return;
	}

	unsigned long responseCode = 0;
	if(fileStatusCode == 0x1) //文件已经存在
	{

		if(Parameters::transferExistsFileHandleCode == 0) //需要询问
		{
			dataTransfer->setSomethingHappended(fileStatusCode); //通过GUI询问是否继续覆盖
			dataTransfer->waitFor();
			responseCode = dataTransfer->getResponseCode();
		}
		else if(Parameters::transferExistsFileHandleCode == 1) //覆盖
		{
			//不处理
			responseCode = 1;
		}
		else if(Parameters::transferExistsFileHandleCode == 2) //跳过
		{
			responseCode = 2;
			dataTransfer->setCancelled();
		}
		else if(Parameters::transferExistsFileHandleCode == 3) //续传
		{
			responseCode = 3;
		}
	}

	unsigned long tmpResponseCode = responseCode;

	if(!sendData(m_Socket, FBtoNetworkCharP(responseCode), sizeof(responseCode)))
	{
		qDebug()<<tr("回传是否覆盖文件代码出错!");
		return;
	}

	if(tmpResponseCode == 3)//续传需要接受已有文件大小
	{
		unsigned long lowPart,highPart;
		if(!getFourByte(m_Socket, lowPart))
		{
			qDebug()<<tr("得到已有文件的大小的低字节部分出错!");
			return;
		}
		if(!getFourByte(m_Socket, highPart))
		{
			qDebug()<<tr("得到已有文件的大小的高字节部分出错!");
			return;
		}

		long long fileExistsSize = lowPart | ( (long long)highPart << 32);

		dataTransfer->setPointer(fileExistsSize);
	}

	if(dataTransfer->isCancelled())
	{
		return;
	}

	dataTransfer->setSomethingHappended(0x00); // 发送传送文件已经开始的信号

	const unsigned long bufferSize = 20000;
	char* buffer = new char[bufferSize];
	boost::scoped_array<char> bufferContainer(buffer);

	long long dataSize = dataTransfer->dataSize();
	long long sendedSize = dataTransfer->getSendedSize(); //如果是续传这个值不会为0
	long long remainedSize = dataSize - sendedSize;
	while(sendedSize < dataSize)
	{
		if(dataTransfer->isCancelled())
		{
			break;
		}

		long long oneTimeSize = remainedSize < bufferSize ? remainedSize : bufferSize;
		long long readedSize = dataTransfer->readData(buffer, oneTimeSize);

		if(!sendData(m_Socket, buffer, readedSize))
		{
			dataTransfer->setFailed();
			emit errorHappend(SendDataError);
			return ;
		}
		sendedSize += readedSize;
		remainedSize -= readedSize;

		dataTransfer->setSendedSize(sendedSize);
	}
	closesocket(m_Socket);

}
예제 #30
0
파일: ssl.cpp 프로젝트: ewduong/ScheduleIt
int SSL_read(SSL* ssl, void* buffer, int sz)
{
    Data data(min(sz, MAX_RECORD_SIZE), static_cast<opaque*>(buffer));
    return receiveData(*ssl, data);
}