예제 #1
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
void VstPlugin::rotateProgram( int offset )
{
	lock();
	sendMessage( message( IdVstRotateProgram ).addInt( offset ) );
	waitForMessage( IdVstRotateProgram, true );
	unlock();
}
예제 #2
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
void VstPlugin::loadProgramNames()
{
	lock();
	sendMessage( message( IdVstProgramNames ) );
	waitForMessage( IdVstProgramNames, true );
	unlock();
}
예제 #3
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
void VstPlugin::savePreset( )
{
	QString presName = currentProgramName().isEmpty() ? tr(": default") : currentProgramName();
	presName.replace(tr("\""), tr("'")); // QFileDialog unable to handle double quotes properly

	FileDialog sfd( NULL, tr( "Save Preset" ), presName.section(": ", 1, 1) + tr(".fxp"),
		tr( "Vst Plugin Preset (*.fxp *.fxb)" ) );

	if( p_name != "" ) // remember last directory
	{
		sfd.setDirectory( QFileInfo( p_name ).absolutePath() );
	}

	sfd.setAcceptMode( FileDialog::AcceptSave );
	sfd.setFileMode( FileDialog::AnyFile );
	if( sfd.exec () == QDialog::Accepted &&
				!sfd.selectedFiles().isEmpty() && sfd.selectedFiles()[0] != "" )
	{
		QString fns = sfd.selectedFiles()[0];
		p_name = fns;

		if ((fns.toUpper().indexOf(tr(".FXP")) == -1) && (fns.toUpper().indexOf(tr(".FXB")) == -1))
			fns = fns + tr(".fxb");
		else fns = fns.left(fns.length() - 4) + (fns.right( 4 )).toLower();
		lock();
		sendMessage( message( IdSavePresetFile ).
			addString(
				QSTR_TO_STDSTR(
					QDir::toNativeSeparators( fns ) ) )
			);
		waitForMessage( IdSavePresetFile, true );
		unlock();
	}
}
예제 #4
0
/** Requests a device's MAC Address (64-bit IEEE Address) given a short address.
@param shortAddress the short address to locate
@param requestType must be SINGLE_DEVICE_RESPONSE or INCLUDE_ASSOCIATED_DEVICES. 
If SINGLE_DEVICE_RESPONSE is selected, then only information about the requested device will be returned. 
If INCLUDE_ASSOCIATED_DEVICES is selected, then the short addresses of the selected device's children will be returned too.
@param startIndex If INCLUDE_ASSOCIATED_DEVICES was selected, then there may be too many children to 
fit in one ZDO_IEEE_ADDR_RSP message. So, use startIndex to get the next set of children's short addresses.
@post An ZDO_IEEE_ADDR_RSP message will be received, with one or more entries.
@post znpResult contains the error code, or ZNP_SUCCESS if success.
*/
void zdoRequestIeeeAddress(unsigned int shortAddress, unsigned char requestType, unsigned char startIndex)
{
    if ((requestType != SINGLE_DEVICE_RESPONSE) && (requestType != INCLUDE_ASSOCIATED_DEVICES))
    {
        znpResult = -1;
        return;
    }
#ifdef AF_ZDO_VERBOSE     
    printf("Requesting IEEE Address for short address %04X, requestType %s, startIndex %u\r\n", 
           shortAddress, (requestType == 0) ? "Single" : "Extended", startIndex);
#endif 
    
    znpBuf[0] = ZDO_IEEE_ADDR_REQ_PAYLOAD_LEN;
    znpBuf[1] = MSB(ZDO_IEEE_ADDR_REQ);
    znpBuf[2] = LSB(ZDO_IEEE_ADDR_REQ);      
    
    znpBuf[3] = LSB(shortAddress);
    znpBuf[4] = MSB(shortAddress);
    znpBuf[5] = requestType;
    znpBuf[6] = startIndex;
    
    znpResult = sendMessage();
    if (znpResult != 0)     
        return;
    
    znpResult = waitForMessage(ZDO_IEEE_ADDR_RSP, 5);
    if (znpResult != 0)
        return;
    if (znpBuf[SRSP_PAYLOAD_START] != SRSP_STATUS_SUCCESS) //verify status is succes
    {
        znpResult = -2;
        return;
    }    
}
예제 #5
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
void VstPlugin::setProgram( int index )
{
	lock();
	sendMessage( message( IdVstSetProgram ).addInt( index ) );
	waitForMessage( IdVstSetProgram, true );
	unlock();
}
예제 #6
0
/** Requests a device's Short Address for a given long address.
@param ieeeAddress the long address to locate
@param requestType must be SINGLE_DEVICE_RESPONSE or INCLUDE_ASSOCIATED_DEVICES. 
If SINGLE_DEVICE_RESPONSE is selected, then only information about the requested device will be returned. 
If INCLUDE_ASSOCIATED_DEVICES is selected, then the short addresses of the selected device's children will be returned too.
@param startIndex If INCLUDE_ASSOCIATED_DEVICES was selected, then there may be 
too many children to fit in one ZDO_NWK_ADDR_RSP message. 
So, use startIndex to get the next set of children's short addresses.
@note DOES NOT WORK FOR SLEEPING END DEVICES
@post An ZDO_NWK_ADDR_RSP message will be received, with one or more entries.
@return a pointer to the beginning of the payload, or a pointer to indeterminate data if error.
@post znpResult contains the error code, or ZNP_SUCCESS if success.
*/
unsigned char* zdoNetworkAddressRequest(unsigned char* ieeeAddress, unsigned char requestType, unsigned char startIndex)
{
    if ((requestType != SINGLE_DEVICE_RESPONSE) && (requestType != INCLUDE_ASSOCIATED_DEVICES)) 
    {
        znpResult = -1;
        return 0;
    }
#ifdef AF_ZDO_VERBOSE     
    printf("Requesting Network Address for long address ");
    printHexBytes(ieeeAddress, 8);
    printf("requestType %s, startIndex %u\r\n", (requestType == 0) ? "Single" : "Extended", startIndex);
#endif
    
    znpBuf[0] = ZDO_NWK_ADDR_REQ_PAYLOAD_LEN;
    znpBuf[1] = MSB(ZDO_NWK_ADDR_REQ);
    znpBuf[2] = LSB(ZDO_NWK_ADDR_REQ);      

    memcpy(znpBuf+3, ieeeAddress, 8);
    znpBuf[11] = requestType;
    znpBuf[12] = startIndex;

    znpResult = sendMessage();

    if (znpResult != 0)     
        return 0;
    znpResult = waitForMessage(ZDO_NWK_ADDR_RSP, 5);
    if (znpResult != 0)
        return 0;
    if (znpBuf[SRSP_PAYLOAD_START] != SRSP_STATUS_SUCCESS) //verify status is succes
    {
        znpResult = -2;
        return 0;
    }
    return (znpBuf + SRSP_PAYLOAD_START);
}
예제 #7
0
파일: GameManager.cpp 프로젝트: lukhio/aic
void GameManager :: play(){
    Message m;
    for(size_t a=0; a<phase.size(); a+=1){
        phase[a]->begin0();
        waitForMessage(phase[a]);
        phase[a]->end0();
    }
}
예제 #8
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
void VstPlugin::updateSampleRate()
{
	lock();
	sendMessage( message( IdSampleRateInformation ).
			addInt( Engine::mixer()->processingSampleRate() ) );
	waitForMessage( IdInformationUpdated, true );
	unlock();
}
예제 #9
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
int VstPlugin::currentProgram()
{
	lock();
	sendMessage( message( IdVstCurrentProgram ) );
	waitForMessage( IdVstCurrentProgram, true );
	unlock();

	return m_currentProgram;
}
예제 #10
0
void ClientInterface::updateKeyframe(int frameCount){
	
	bool done= false;

	while(!done){
		//wait for the next message
		waitForMessage();

		//check we have an expected message
		NetworkMessageType networkMessageType= getNextMessageType();

		switch(networkMessageType){
			case nmtCommandList:{
				//make sure we read the message
				NetworkMessageCommandList networkMessageCommandList;
				while(!receiveMessage(&networkMessageCommandList)){
					sleep(waitSleepTime);
				}

				//check that we are in the right frame
				if(networkMessageCommandList.getFrameCount()!=frameCount){
					throw runtime_error("Network synchronization error, frame counts do not match");
				}

				// give all commands
				for(int i= 0; i<networkMessageCommandList.getCommandCount(); ++i){
					pendingCommands.push_back(*networkMessageCommandList.getCommand(i));
				}				

				done= true;
			}
			break;

			case nmtQuit:{
				NetworkMessageQuit networkMessageQuit;
				if(receiveMessage(&networkMessageQuit)){
					quit= true;
				}
				done= true;
			}
			break;

			case nmtText:{
				NetworkMessageText networkMessageText;
				if(receiveMessage(&networkMessageText)){
					chatText= networkMessageText.getText();
					chatSender= networkMessageText.getSender();
					chatTeamIndex= networkMessageText.getTeamIndex();
				}
			}
			break;

			default:
				throw runtime_error("Unexpected message in client interface: " + intToStr(networkMessageType));
		}
	}
}
예제 #11
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
const QMap<QString, QString> & VstPlugin::parameterDump()
{
	lock();
	sendMessage( IdVstGetParameterDump );
	waitForMessage( IdVstParameterDump, true );
	unlock();

	return m_parameterDump;
}
예제 #12
0
std::auto_ptr<ArgumentDecoder> Connection::sendSyncMessage(MessageID messageID, uint64_t syncRequestID, std::auto_ptr<ArgumentEncoder> encoder, double timeout)
{
    // First send the message.
    if (!sendMessage(messageID, encoder))
        return std::auto_ptr<ArgumentDecoder>();

    // Now wait for a reply and return it.
    return waitForMessage(MessageID(CoreIPCMessage::SyncMessageReply), syncRequestID, timeout);
}
예제 #13
0
	RemoteZynAddSubFx( int _shm_in, int _shm_out ) :
		RemotePluginClient( _shm_in, _shm_out ),
		LocalZynAddSubFx(),
		m_guiSleepTime( 100 ),
		m_guiExit( false )
	{
		setInputCount( 0 );
		sendMessage( IdInitDone );
		waitForMessage( IdInitDone );

		pthread_mutex_init( &m_guiMutex, NULL );
		pthread_create( &m_guiThreadHandle, NULL, guiThread, this );
	}
예제 #14
0
void QJSDebugService::addEngine(QDeclarativeEngine *engine)
{
    Q_ASSERT(engine);
    Q_ASSERT(!m_engines.contains(engine));

    m_engines.append(engine);

    if (status() == Enabled && !m_engines.isEmpty() && !m_agent) {
        m_agent = new QJSDebuggerAgent(engine, engine);
        connect(m_agent, SIGNAL(stopped(bool,QString)),
                this, SLOT(executionStopped(bool,QString)));

        while (!m_agent->isInitialized()) {
            waitForMessage();
        }
    }
예제 #15
0
int SCoupler::sendMessage(const char* msg, int length)
{
	if(msg == NULL || length < 0)
		return 1;
	string checkSum;
	int size = length;
	checkSum = md5(string(msg, length));
	int bufSize = size+checkSum.length()+sizeof(size);
	char *buffer = new char[bufSize];
	/*cout << "Wysylam size: " << size << "\n";
	cout << "wysylam suma: \"" << checkSum << "\"\n";
	cout << "Wysylam msg: \"";
	for(int i = 0; i < length; ++i)
		cout << msg[i];
	cout << "\"\n";*/
	size = htonl(size);
	memcpy(buffer, &size, sizeof(size));
	memcpy(buffer+sizeof(size), checkSum.c_str(), checkSum.length());
	memcpy(buffer+sizeof(size)+checkSum.length(), msg, length);
	bool resend = true;
	char response[2];
	int counter = 0;
	while(resend)
	{
		if(write(buffer, bufSize) != 0)
			return WSAGetLastError();
		std::cout << "Czekam na odpowiedz\n";
		if(!read(response, 1))
			return WSAGetLastError();
		response[1] = '\0';
		cout << "Odebrano: " << response << "\n";
		if(strcmp(response, "0") == 0)
			resend = false;
		else
		{
			++counter;
			if(counter > 2)											// maksymalnie 3 razy ponawiamy próbê wys³ania
			{
				delete [] buffer;
				return 5;
			}
		}
	}
	int ret = waitForMessage();
	delete [] buffer;
	return ret;
}
예제 #16
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
QByteArray VstPlugin::saveChunk()
{
	QByteArray a;
	QTemporaryFile tf;
	if( tf.open() )
	{
		lock();
		sendMessage( message( IdSaveSettingsToFile ).
				addString(
					QSTR_TO_STDSTR(
						QDir::toNativeSeparators( tf.fileName() ) ) ) );
		waitForMessage( IdSaveSettingsToFile, true );
		unlock();
		a = tf.readAll();
	}

	return a;
}
예제 #17
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
void VstPlugin::loadChunk( const QByteArray & _chunk )
{
	QTemporaryFile tf;
	if( tf.open() )
	{
		tf.write( _chunk );
		tf.flush();

		lock();
		sendMessage( message( IdLoadSettingsFromFile ).
				addString(
					QSTR_TO_STDSTR(
						QDir::toNativeSeparators( tf.fileName() ) ) ).
				addInt( _chunk.size() ) );
		waitForMessage( IdLoadSettingsFromFile, true );
		unlock();
	}
}
예제 #18
0
/** Sends a message to another device over the Zigbee network using the AF command AF_DATA_REQUEST.
@param  destinationEndpoint which endpoint to send this to.
@param  sourceEndpoint which endpoint this message originated from on our device
@param  destinationShortAddress the short address of the destination, or ALL_DEVICES or ALL_ROUTERS_AND_COORDINATORS to broadcast the message.
@param  clusterId which cluster this message is for. User definable. Zigbee supports up to 2^16 clusters. 
A cluster is typically a particular command, e.g. "turn on lights" or "get temperature". 
If using a predefined Zigbee Alliance Application Profile then this cluster will follow the Zigbee Cluster Library.
@param  data is the data to send.
@param  dataLength is how many bytes of data to send. Must be less than MAXIMUM_PAYLOAD_LENGTH.
@note On a coordinator in a trivial test setup, it takes approximately 10mSec from sending 
AF_DATA_REQUEST to when we receive AF_DATA_CONFIRM.
@note   <code>transactionSequenceNumber</code> is an optional user-definable reference number to match AF_DATA_REQUEST messages with AF_DATA_CONFIRM messages. 
@note   The ZNP will automatically require an ACK from the next device on the route when sending data. 
To require an ACK from the final destination, change MAC_ACK to APS_ACK at the expense of increased network traffic.
@note   The <code>radius</code> is the maximum number of hops that this packet can travel through before it will be dropped.
Should be set to the maximum number of hops expected in the network.
@note   adjust AF_DATA_CONFIRM_INTERVAL_MS and AF_DATA_CONFIRM_TIMEOUT_MS based on network size, number of hops, etc.
@pre    the application was started successfully
@pre    there is another device on the network with short address of <code>destinationShortAddress</code> 
and that device has successfully started its application.
@post   srsp will contain a AF_DATA_REQUEST_SRSP. We will receive a AF_DATA_REQUEST_SRSP regardless of whether the message was successfully sent or not.
@post   we will receive a AF_DATA_CONFIRM if the message was successfully sent. 
@post znpResult contains the error code, or ZNP_SUCCESS if success.
*/
void afSendData(unsigned char destinationEndpoint, unsigned char sourceEndpoint, unsigned int destinationShortAddress, unsigned int clusterId, unsigned char* data, unsigned char dataLength)
{
    if (dataLength > MAXIMUM_PAYLOAD_LENGTH)
    {
        znpResult = -1;
        return;
    }
#ifdef AF_ZDO_VERBOSE     
    printf("Sending %u bytes to endpoint %u from endpoint %u with cluster %u (%04X) at Short Address %u (0x%04X)\r\n", 
           dataLength, destinationEndpoint, sourceEndpoint, clusterId, clusterId, destinationShortAddress, destinationShortAddress);
#endif  
    
    znpBuf[0] = AF_DATA_REQUEST_PAYLOAD_LEN + dataLength;
    znpBuf[1] = MSB(AF_DATA_REQUEST);
    znpBuf[2] = LSB(AF_DATA_REQUEST);      
    
    znpBuf[3] = LSB(destinationShortAddress); 
    znpBuf[4] = MSB(destinationShortAddress);
    znpBuf[5] = destinationEndpoint;
    znpBuf[6] = sourceEndpoint;
    znpBuf[7] = LSB(clusterId); 
    znpBuf[8] = MSB(clusterId); 
    znpBuf[9] = transactionSequenceNumber++;
    znpBuf[10] = MAC_ACK; //Could also use AF_APS_ACK;
    znpBuf[11] = DEFAULT_RADIUS;
    znpBuf[12] = dataLength; 
    
    memcpy(znpBuf+AF_DATA_REQUEST_PAYLOAD_LEN+3, data, dataLength);
    znpResult = sendMessage();
    if (znpResult != 0)
        return;
    
    //Now, wait for message, and verify that it's a AF_DATA_CONFIRM, else timeout.
    //NOTE: Do not print anything out here, or else you might miss the AF_DATA_CONFIRM!
    znpResult = waitForMessage(AF_DATA_CONFIRM, AF_DATA_CONFIRM_TIMEOUT);
    if (znpResult != 0)
        return;
    //note: znpBuf[4] = endpoint, znpBuf[5] = transaction sequence number
    if (znpBuf[SRSP_PAYLOAD_START] != SRSP_STATUS_SUCCESS) //verify status is succes
    {
        znpResult = -2;
        return;
    }
}
예제 #19
0
파일: VstPlugin.cpp 프로젝트: karmux/lmms
void VstPlugin::openPreset( )
{

	FileDialog ofd( NULL, tr( "Open Preset" ), "",
		tr( "Vst Plugin Preset (*.fxp *.fxb)" ) );
	ofd.setFileMode( FileDialog::ExistingFiles );
	if( ofd.exec () == QDialog::Accepted &&
					!ofd.selectedFiles().isEmpty() )
	{
		lock();
		sendMessage( message( IdLoadPresetFile ).
			addString(
				QSTR_TO_STDSTR(
					QDir::toNativeSeparators( ofd.selectedFiles()[0] ) ) )
			);
		waitForMessage( IdLoadPresetFile, true );
		unlock();
	}
}
예제 #20
0
/* Returns true if move was sucessful, false if we bumped into something */
bool Robot::move(int x, int y)
{
    // calculate new orientation
    double angle = acos(fabs(y - coords.second)
                        / sqrt(  pow(x - coords.first, 2)
                               + pow(y - coords.second, 2)));
    angle *= 180 / PI;

    if (y > coords.second && x > coords.first)
        angle = 180 - angle;
    else if (y > coords.second && x <= coords.first)
        angle = 180 + angle;
    else if (y <= coords.second && x <= coords.first)
        angle = 360 - angle;

    if(orientation != angle) {
        MessageTurn mTurn;
        mTurn.envObjID = 0;
        mTurn.degrees = angle;
        network->send(&mTurn);
        orientation = angle;
    }

    MessageMove m;
    m.envObjID = 0;
    m.coordX = x;
    m.coordY = y;
    network->send(&m);

    Message *msg = NULL;
    msg = waitForMessage();
    if (msg && msg->type == MsgBump) {
        MessageBump *m = static_cast<MessageBump *>(msg);
        coords = std::pair<int, int>(m->coordX, m->coordY);
        return false;
    } else {
        delete msg;
        coords = std::pair<int, int>(x, y);
        return true;
    }
}
예제 #21
0
std::vector<MessageObject> Robot::whoIsThere(unsigned int x, unsigned int y, unsigned int radius)
{
    MessageWhoIsThere m;
    m.envObjID = 0;
    m.coordX = x;
    m.coordY = y;
    m.radius = radius;
    network->send(&m);

    Message *msg = NULL;
    std::vector<MessageObject> results;
    msg = waitForMessage();
    if (msg && msg->type == MsgThereYouSee) {
        MessageThereYouSee *m = static_cast<MessageThereYouSee *>(msg);
        results.resize(m->objects.size());
        std::vector<MessageObject>::iterator it;
        for(it = m->objects.begin(); it < m->objects.end(); it++)
            results.push_back(*it);
    }
    return results;
}
예제 #22
0
파일: cmt2.cpp 프로젝트: jiapei100/mrpt
//////////////////////////////////////////////////////////////////////////////////////////
// Wait for a message to arrive.
XsensResultValue Cmt2s::waitForMessage(
	Message* rcv, const uint8_t msgId, uint32_t timeoutOverride,
	bool acceptErrorMessage)
{
	auto* hdr = (MessageHeader*)m_readBuffer;
	uint16_t pre = 0;
	uint32_t length = 0;
	uint32_t target;
	uint16_t i;
	bool extended;
	bool readsome = (m_readBufferCount > 0);
	uint32_t toRestore = m_toEnd;

	CMT2LOG(
		"L2: waitForMessage x%02x, TO=%u, TOend=%u, TOO=%u\n", (uint32_t)msgId,
		m_timeout, m_toEnd, timeoutOverride);

	// The end-time may be misinterpreted around midnight, where it may be
	// considered
	// expired even if this is not the case. However, this is extremely rare.
	if (m_toEnd == 0)
	{
		if (timeoutOverride != 0)
			m_toEnd = (getTimeOfDay() + (uint32_t)timeoutOverride) %
					  (XSENS_MS_PER_DAY);
		else
			m_toEnd =
				(getTimeOfDay() + (uint32_t)m_timeout) % (XSENS_MS_PER_DAY);
		if (m_toEnd == 0) m_toEnd = 1;
	}

	if (m_readBufferCount == 0)
		m_readBuffer[0] = (uint8_t)~CMT_PREAMBLE;  // create a value that is
	// definitely NOT a preamble

	do
	{
		// find preamble
		while (m_readBuffer[pre] != CMT_PREAMBLE)
		{
			if ((++pre) >= m_readBufferCount)
			{
				m_readBufferCount = 0;
				pre = 0;
				if (m_toEnd >= getTimeOfDay())
				{
					m_lastResult = m_cmt1s.readData(
						CMT_LEN_MSGHEADER, m_readBuffer, &length);
					m_readBufferCount = (uint16_t)length;
					if (m_readBufferCount > 0) readsome = true;
				}
			}
			if (m_toEnd < getTimeOfDay()) break;
		}
		// shift buffer to start
		if (pre)
		{
			m_readBufferCount -= pre;
			for (i = 0; i < m_readBufferCount; ++i)
			{
				m_readBuffer[i] = m_readBuffer[i + pre];
			}
		}

		pre = 1;  // make sure we skip the first item in the next iteration
		// read header
		while (m_readBufferCount < CMT_LEN_MSGHEADERCS &&
			   (m_toEnd >= getTimeOfDay()))
		{
			m_cmt1s.readData(
				CMT_LEN_MSGHEADERCS - m_readBufferCount,
				&m_readBuffer[m_readBufferCount], &length);
			m_readBufferCount += (uint16_t)length;
		}
		if ((m_readBufferCount < CMT_LEN_MSGHEADERCS) &&
			(m_toEnd < getTimeOfDay()))
		{
			CMT2LOG(
				"L2: waitForMessage timeout occurred trying to read header\n");
			break;
		}

		if (hdr->m_length == CMT_EXTLENCODE)
		{
			extended = true;
			while (m_readBufferCount < CMT_LEN_MSGEXTHEADERCS &&
				   (m_toEnd >= getTimeOfDay()))
			{
				m_cmt1s.readData(
					CMT_LEN_MSGEXTHEADERCS - m_readBufferCount,
					&m_readBuffer[m_readBufferCount], &length);
				m_readBufferCount += (uint16_t)length;
			}
			if ((m_readBufferCount < CMT_LEN_MSGEXTHEADERCS) &&
				(m_toEnd < getTimeOfDay()))
			{
				CMT2LOG(
					"L2: waitForMessage timeout occurred trying to read "
					"extended header\n");
				break;
			}
		}
		else
			extended = false;

		// check the reported size
		if (extended &&
			(((uint16_t)hdr->m_datlen.m_extended.m_length.m_high * 256 +
			  (uint16_t)hdr->m_datlen.m_extended.m_length.m_low) >
			 (uint16_t)CMT_MAXDATALEN))
			continue;

		// header seems to be ok, read until end and check checksum
		if (extended)
			target = ((uint16_t)hdr->m_datlen.m_extended.m_length.m_high * 256 +
					  (uint16_t)hdr->m_datlen.m_extended.m_length.m_low) +
					 CMT_LEN_MSGEXTHEADERCS;
		else
			target = hdr->m_length + CMT_LEN_MSGHEADERCS;

		// read the entire message
		while ((m_readBufferCount < target) && (m_toEnd >= getTimeOfDay()))
		{
			m_cmt1s.readData(
				target - m_readBufferCount, &m_readBuffer[m_readBufferCount],
				&length);
			m_readBufferCount += (uint16_t)length;
		}
		if ((m_readBufferCount < target) && (m_toEnd < getTimeOfDay()))
		{
			CMT2LOG("L2: waitForMessage timeout occurred\n");
			break;
		}

		// check the checksum
		// msg=new Message(m_readBuffer,(uint16_t) target, (uint16_t) target);
		if (rcv->loadFromString(m_readBuffer, (uint16_t)target) == XRV_OK)
		{
			CMT2LOG(
				"L2: waitForMessage received msg Id x%02x while expecting "
				"x%02x, msg size=%u\n",
				(uint32_t)rcv->getMessageId(), (uint32_t)msgId, target);
			if (m_onMessageReceived != nullptr)
			{
				auto* bytes = (CmtBinaryData*)malloc(sizeof(CmtBinaryData));
				bytes->m_size = target;
				bytes->m_portNr = m_cmt1s.getPortNr();
				//				bytes->m_type = CMT_CALLBACK_ONMESSAGERECEIVED;
				memcpy(bytes->m_data, m_readBuffer, target);
#ifdef _LOG_CALLBACKS
				CMTLOG(
					"C2: m_onMessageReceived(%d,(%d,%d),%p)\n",
					(int32_t)m_onMessageReceivedInstance,
					(int32_t)bytes->m_size, (int32_t)bytes->m_portNr,
					m_onMessageReceivedParam);
#endif
				m_onMessageReceived(
					m_onMessageReceivedInstance, CMT_CALLBACK_ONMESSAGERECEIVED,
					bytes, m_onMessageReceivedParam);
			}

			m_readBufferCount -= (uint16_t)target;
			if (m_readBufferCount)
			{
				for (i = 0; i < m_readBufferCount; ++i)
				{
					m_readBuffer[i] = m_readBuffer[i + target];
				}
			}

			if ((msgId == 0) || (msgId == rcv->getMessageId()) ||
				(acceptErrorMessage && rcv->getMessageId() == CMT_MID_ERROR))
			{
				m_toEnd = toRestore;
				return m_lastResult = XRV_OK;
			}
		}
		else
		{
			rcv->clear();
			CMT2LOG("L2: waitForMessage load from string failed\n");
		}
	} while (m_toEnd >= getTimeOfDay());

	// a timeout occurred
	if (readsome)
	{
		// check if the current data contains a valid message
		int32_t pos = findValidMessage(m_readBuffer, m_readBufferCount);

		if (pos != -1)
		{
			CMT2LOG("L2: waitForMessage found message in message\n");
			// shift data to start of buffer
			pre = (uint16_t)pos;
			m_readBufferCount -= pre;
			for (i = 0; i < m_readBufferCount; ++i)
			{
				m_readBuffer[i] = m_readBuffer[i + pre];
			}
			waitForMessage(
				rcv, msgId, 0, acceptErrorMessage);  // parse the message
			m_toEnd = toRestore;
			return m_lastResult;  // set by waitForMessage
		}

		m_lastResult = XRV_TIMEOUT;
	}
	else
		m_lastResult = XRV_TIMEOUTNODATA;
	m_toEnd = toRestore;
	return m_lastResult;
}
 bool getCurrentMessage(T& msg)
 {
   return waitForMessage(msg, 0);
 }
예제 #24
0
///The thread
void* ballThread(void* args) {
	BallThreadParameters* arg = (BallThreadParameters*)args ;
	int ID = arg->ID;
	float myMass = ball[ID]->getMass();
	float myRadius = ball[ID]->getRadius();
	
	#if defined(DEBUG) || defined(THREAD_DEBUG)
		cout << ID << " created \n";
	#endif

	while(true) {
		//Thread for exitting from the thread.
		pthread_mutex_lock(&vecMutexThreadTerminate[ID] );
			if(threadTerminate[ID]) {
				pthread_mutex_unlock(&vecMutexThreadTerminate[ID]);
				break;
			}
		pthread_mutex_unlock(&vecMutexThreadTerminate[ID] );

		//Functional Code.
		pthread_mutex_lock(&vecMutexBallPthreads[ID]);
		while(numBallUpdates == 0 || !vecShouldBallUpdate[ID] )
			pthread_cond_wait(&vecCondBallUpdateBegin[ID] , &vecMutexBallPthreads[ID]);
		while( (numBallUpdates > 0) && ( vecShouldBallUpdate[ID] ) ) {
			pthread_mutex_lock(&mutexStateVariableUpdate);
			numBallUpdates--;
			vecShouldBallUpdate[ID] = false;
			pthread_mutex_unlock(&mutexStateVariableUpdate);
			//Timer-related things have been started.

			///Generate N messages, and push them all.
			for(int i=0; i<NUM_BALLS; i++) {
				if ( i!= ID) {
					//Construct a message which contains present thread's data.
					BallDetailsMessage msg;
						msg.senderID = ID;
						msg.senderRadius = myRadius;
						msg.senderMass = myMass;
						msg.senderVelocity = ball[ID]->getVelocity();
						msg.senderPosition = addVectors(ball[ID]->getPosition() , ScalarMult( ball[ID]->getVelocity(), DELTA_T));
						msg.receiverID = i; 
						sendMessage(msg); //Send message to everyone.
				} //Message sent.
			}

			#if defined(DEBUG) || defined(THREAD_DEBUG)
				cout << "thread: " << ID <<	" will now begin waiting \n";		
			#endif
			//waitForMessages(ID); //Deprecated

			///Process messages received.
			for(int i = 1 ; i< NUM_BALLS; i++) { //Pop n-1 messages.
				pthread_mutex_lock(&vecMutexMailBox[ID]);	
				///Wait to receive atleast one message.
				waitForMessage(ID);
				//ASSERT : MailBox is not empty.
					BallDetailsMessage msg = mailBox[ID].front();
						mailBox[ID].pop();
					///BallToBall Collisions
					ball[ID]->handleBallCollision(msg.senderPosition , msg.senderVelocity , msg.senderMass , msg.senderRadius); //Changes the velocity,not the 
				
				pthread_mutex_unlock(&vecMutexMailBox[ID]);
			}
			
			//Ensure that ball isn't speeding
			float ratio = (ball[ID]->getSpeed() / MAX_VELOCITY);
			if ( ratio >= 1.0) {
				ball[ID]->slowDown(ratio);
			}

			//Self explanotry code follows
			ball[ID]->handleWallCollision(table);
			ball[ID]->displace(DELTA_T);

			//Updates have ended
			pthread_cond_signal(&condBallUpdateComplete);
		}
		pthread_mutex_unlock(&vecMutexBallPthreads[ID]);
	}
}
예제 #25
0
int Coupler::sendAndWait(const char* msg, int length)
{
	string checkSum;
	int size = length;
	checkSum = md5(msg);
	int bufSize = size+checkSum.length()+sizeof(size)+1;
	char *buffer = new char[bufSize];
	size = htonl(size);
	memcpy(buffer, &size, sizeof(size));
	memcpy(buffer+sizeof(size), checkSum.c_str(), checkSum.length());
	memcpy(buffer+sizeof(size)+checkSum.length(), msg, length);
	buffer[bufSize-1] = '\0';
	bool resend = true;
	char response[10];
	int counter = 0;
	while(resend)
	{
		/*std::cout << "Wysylam: (len = " << bufSize;
		for(int i = 0; i < bufSize; ++i)
			std::cout << buffer[i];
		std::cout << "\n";*/
		if(send(sock, buffer, bufSize, 0) == SOCKET_ERROR)
			return 1;
		fd_set fd;
		FD_ZERO(&fd);
		FD_SET(sock, &fd);
		std::cout << "Czekam na odpowiedz\n";
		int nError = select(0, &fd, NULL, NULL, &tv);				// czekamy a¿ bêdzie mo¿na coœ odczytaæ z socketa
		if (nError == 0)											// timeout
		{
			return 1;
		}

		if (nError == SOCKET_ERROR)									// winsock error
		{
			return 2;
		}
		int dataLength = recv(sock, response, sizeof(response), 0);
		if (dataLength == 0)										// client disconnected
		{
			return 3;
		}
		nError = WSAGetLastError(); 
		if (nError != 0)								// winsock error
		{
			return 4;
		}
		std::cout << "Odebrano odpowiedz: " << response << "\n";
		if(strcmp(response, "Ok") == 0)
			resend = false;
		else
		{
			++counter;
			if(counter > 2)											// maksymalnie 3 razy ponawiamy próbê wys³ania
			{
				delete [] buffer;
				return 5;
			}
		}
	}
	int ret = waitForMessage();
	delete [] buffer;
	return ret;
}
예제 #26
0
bool RemotePlugin::process( const sampleFrame * _in_buf,
						sampleFrame * _out_buf )
{
	const fpp_t frames = Engine::mixer()->framesPerPeriod();

	if( m_failed || !isRunning() )
	{
		if( _out_buf != NULL )
		{
			BufferManager::clear( _out_buf, frames );
		}
		return false;
	}

	if( m_shm == NULL )
	{
		// m_shm being zero means we didn't initialize everything so
		// far so process one message each time (and hope we get
		// information like SHM-key etc.) until we process messages
		// in a later stage of this procedure
		if( m_shmSize == 0 )
		{
			lock();
			fetchAndProcessAllMessages();
			unlock();
		}
		if( _out_buf != NULL )
		{
			BufferManager::clear( _out_buf, frames );
		}
		return false;
	}

	memset( m_shm, 0, m_shmSize );

	ch_cnt_t inputs = qMin<ch_cnt_t>( m_inputCount, DEFAULT_CHANNELS );

	if( _in_buf != NULL && inputs > 0 )
	{
		if( m_splitChannels )
		{
			for( ch_cnt_t ch = 0; ch < inputs; ++ch )
			{
				for( fpp_t frame = 0; frame < frames; ++frame )
				{
					m_shm[ch * frames + frame] =
							_in_buf[frame][ch];
				}
			}
		}
		else if( inputs == DEFAULT_CHANNELS )
		{
			memcpy( m_shm, _in_buf, frames * BYTES_PER_FRAME );
		}
		else
		{
			sampleFrame * o = (sampleFrame *) m_shm;
			for( ch_cnt_t ch = 0; ch < inputs; ++ch )
			{
				for( fpp_t frame = 0; frame < frames; ++frame )
				{
					o[frame][ch] = _in_buf[frame][ch];
				}
			}
		}
	}

	lock();
	sendMessage( IdStartProcessing );

	if( m_failed || _out_buf == NULL || m_outputCount == 0 )
	{
		unlock();
		return false;
	}

	waitForMessage( IdProcessingDone );
	unlock();

	const ch_cnt_t outputs = qMin<ch_cnt_t>( m_outputCount,
							DEFAULT_CHANNELS );
	if( m_splitChannels )
	{
		for( ch_cnt_t ch = 0; ch < outputs; ++ch )
		{
			for( fpp_t frame = 0; frame < frames; ++frame )
			{
				_out_buf[frame][ch] = m_shm[( m_inputCount+ch )*
								frames + frame];
			}
		}
	}
	else if( outputs == DEFAULT_CHANNELS )
	{
		memcpy( _out_buf, m_shm + m_inputCount * frames,
						frames * BYTES_PER_FRAME );
	}
	else
	{
		sampleFrame * o = (sampleFrame *) ( m_shm +
							m_inputCount*frames );
		// clear buffer, if plugin didn't fill up both channels
		BufferManager::clear( _out_buf, frames );

		for( ch_cnt_t ch = 0; ch <
				qMin<int>( DEFAULT_CHANNELS, outputs ); ++ch )
		{
			for( fpp_t frame = 0; frame < frames; ++frame )
			{
				_out_buf[frame][ch] = o[frame][ch];
			}
		}
	}

	return true;
}