Exemplo n.º 1
0
int main(int argc, char **argv)
{
  kern_return_t       result;
  
  result = IOMasterPort(bootstrap_port, &masterPort);
  if (result != KERN_SUCCESS) {
    errx(1, "Error getting the IOMaster port: %s",
         mach_error_string(result));
  }
  
  gPlatform = IORegistryEntryFromPath(masterPort, "IODeviceTree:/efi/platform");
  if (gPlatform == 0) {
    errx(1, "EFI is not supported on this system");
  }
  
  CFTypeRef data;
  result = GetOFVariable("Settings", &data);
  if (result != KERN_SUCCESS) {
    errx(1, "Clover absent or too old : %s",
         mach_error_string(result));
  }
  
  PrintConfig(data);
  CFRelease(data);
  
  IOObjectRelease(gPlatform);
  
  return 0;
}
Exemplo n.º 2
0
void load_config_from_local(Configuration &config)
{
    map<string,string> conf_map;
    if(!ReadConfig(CONFIG_FILE,conf_map))
    {
        puts("[error 01] load config from local file failed.");
        exit(-1);
    }
    init_conf(conf_map,config);
    PrintConfig(conf_map);
}
Exemplo n.º 3
0
/*------------------------------------------------------------------------------------------------------------*/
void cgi_eemem( void * pStruct )
{
	struct HTTP_REQUEST * http_request;
	http_request = (struct HTTP_REQUEST *) pStruct;

	cgi_PrintHttpheaderStart();

	printf_P( PSTR(	"<pre>"));

	PrintConfig ();

	printf_P( PSTR( "</pre>" ));

	cgi_PrintHttpheaderEnd();

}
Exemplo n.º 4
0
inline void Args::HandleBuild( ostream& os ) const
{
    string build = "--build";
    char** arg = std::find( argv_, argv_+argc_, build );
    const bool foundBuild = ( arg != argv_+argc_ );
    if( foundBuild )
    {
        if( mpi::WorldRank() == 0 )
        {
            PrintVersion();
            PrintConfig();
            PrintCCompilerInfo();
            PrintCxxCompilerInfo();
        }
        throw ArgException();
    }
}
Exemplo n.º 5
0
int cmd_eemem( int argc, char ** argv )
{
	int ERROR = -1;
	char string[ 32 ];

	
	if ( argc == 2 )
	{
		if ( !strcmp_P( argv[1], PSTR("protect") ) )
		{
			strcpy_P( string, PSTR("ON"));
			changeConfig_P( PSTR("WRITE_PROTECT"), string );
			setprotectConfig( PROTECT );
			ERROR = 0; 
		}
		if ( !strcmp_P( argv[1], PSTR("unprotect") ) )
		{
			setprotectConfig( UNPROTECT );
			strcpy_P( string, PSTR("OFF"));
			changeConfig_P( PSTR("WRITE_PROTECT"), string );
			printf_P( PSTR("unprotectet\r\n"));
			ERROR = 0; 
		}
		if ( !strcmp_P( argv[1], PSTR("print") ) )
		{
			PrintConfig();
			ERROR = 0; 
		}
		if ( !strcmp_P( argv[1], PSTR("clean") ) )
		{
			makeConfig();
			ERROR = 0; 
		}
	}

	if ( ERROR == -1 )
		printf_P( PSTR("eemem <protect>|<unprotect> <print> <clean>\r\n"));
}
Exemplo n.º 6
0
LOCAL_C TInt WavRecord()
	{
	// Parse the commandline and get a filename to use
	TLex l(CommandLine);
	TParse destinationName;
	if (destinationName.SetNoWild(l.NextToken(),0,0)!=KErrNone)
		{
		Test.Printf(_L("No arg, skipping\r\n"));
		return(KErrArgument);
		}
	Test.Next(_L("Record Wav file"));

	// Open the file for writing
	TInt r;
	RFile destination;
	r = destination.Replace(Fs,destinationName.FullName(),EFileWrite);
	if (r!=KErrNone)
		{
		Test.Printf(_L("Open file for write failed(%d)\n"), r);
		return(r);
		}		
	Test.Printf(_L("File opened for write\r\n"));
	
	Test.Next(_L("Preparing to record"));
	
	// Get the rate
	TLex cl(l.NextToken());
	TUint32 tmpRate;
	TSoundRate rate;
	r = cl.Val(tmpRate,EDecimal);
	if (r == KErrNone && (r=SamplesPerSecondToRate(tmpRate,rate))==KErrNone)
		{
		Test.Printf(_L("Parsed rate: %d\r\n"), tmpRate);
		RecordFormatBuf().iRate = rate;
		}
	else
		{
		Test.Printf(_L("Parse rate failed(%d)\r\n"),r);
		RecordFormatBuf().iRate = ESoundRate32000Hz;
		}

	// Get number of channels
	TLex cl_chan(l.NextToken());
	TUint32 tmpChannels;
	r = cl_chan.Val(tmpChannels,EDecimal);
	if (r == KErrNone)
		{
		Test.Printf(_L("Parsed %d channels\r\n"),tmpChannels);
		RecordFormatBuf().iChannels = tmpChannels;
		}
	else
		{
		Test.Printf(_L("Parse channels failed(%d)\r\n"), r);
		RecordFormatBuf().iChannels = 2;
		}

	RecordFormatBuf().iEncoding = ESoundEncoding16BitPCM;
	
	// Set the record buffer configuration.
	RChunk chunk;
	TTestSharedChunkBufConfig bufferConfig;
	bufferConfig.iNumBuffers=4;
	bufferConfig.iBufferSizeInBytes=RecordBufferSizeInBytes(RecordFormatBuf());
	if (RecordCapsBuf().iRequestMinSize)
		bufferConfig.iBufferSizeInBytes&=~(RecordCapsBuf().iRequestMinSize-1); 	// Keep the buffer length valid for the driver.
	bufferConfig.iFlags=0;	
	PrintBufferConf(bufferConfig,Test);
	TPckg<TTestSharedChunkBufConfig> bufferConfigBuf(bufferConfig);
	r=RxSoundDevice.SetBufferChunkCreate(bufferConfigBuf,chunk);
	if (r!=KErrNone)
		{
		Test.Printf(_L("Buffer configuration not supported(%d)\r\n"),r);
		return(r);
		}
	
	// Set the audio record configuration.
	RxSoundDevice.SetVolume(KSoundMaxVolume);
	PrintConfig(RecordFormatBuf(),Test);
	r=RxSoundDevice.SetAudioFormat(RecordFormatBuf);
	if (r!=KErrNone)
		{
		Test.Printf(_L("Format not supported\r\n"));
		return(r);
		}

	// Get length in seconds
	TLex cl_seconds(l.NextToken());
	TUint32 tmpSeconds;
	r = cl_seconds.Val(tmpSeconds,EDecimal);
	if (r == KErrNone)
		{
		Test.Printf(_L("Parsed %d seconds\r\n"),tmpSeconds);
		}
	else
		{
		Test.Printf(_L("Parse seconds failed(%d)\r\n"),r);
		tmpSeconds=10;
		}
	TInt bytesToRecord = BytesPerSecond(RecordFormatBuf())*tmpSeconds;	
		
	Test.Next(_L("Recording..."));
	
	// Lay down a file header
	WAVEheader header;
	TPtr8 headerDes((TUint8 *)&header, sizeof(struct WAVEheader), sizeof(struct WAVEheader));

	// "RIFF"
	header.ckID[0] = 'R'; header.ckID[1] = 'I';
	header.ckID[2] = 'F'; header.ckID[3] = 'F';
	// "WAVE"
	header.wave_ckID[0] = 'W'; header.wave_ckID[1] = 'A';
	header.wave_ckID[2] = 'V'; header.wave_ckID[3] = 'E';
	// "fmt "
	header.fmt_ckID[0] = 'f'; header.fmt_ckID[1] = 'm';
	header.fmt_ckID[2] = 't'; header.fmt_ckID[3] = ' ';
	// "data"
	header.data_ckID[0] = 'd'; header.data_ckID[1] = 'a';
	header.data_ckID[2] = 't'; header.data_ckID[3] = 'a';

	header.nChannels		= (TUint16)RecordFormatBuf().iChannels;
	header.nSamplesPerSec	= RateInSamplesPerSecond(RecordFormatBuf().iRate);
	header.nBitsPerSample	= 16;
	header.nBlockAlign		= TUint16((RecordFormatBuf().iChannels == 2) ? 4 : 2);
	header.formatTag		= 1;	// type 1 is PCM
	header.fmt_ckSize		= 16;
	header.nAvgBytesPerSec	= BytesPerSecond(RecordFormatBuf());
	header.data_ckSize		= bytesToRecord;
	header.ckSize			= bytesToRecord + sizeof(struct WAVEheader) - 8;

	Test.Printf(_L("Header rate:%d channels:%d tag:%d bits:%d (%d bytes/s) align %d datalen:%d fmt_ckSize:%d ckSize:%d\r\n"),
			header.nSamplesPerSec, header.nChannels, header.formatTag, header.nBitsPerSample,
			header.nAvgBytesPerSec, header.nBlockAlign, header.data_ckSize, header.fmt_ckSize, header.ckSize, sizeof(struct WAVEheader));

	r = destination.Write(headerDes);

	TRequestStatus stat;
	TInt length;
	TPtrC8 buf;

	TTime startTime;
	startTime.HomeTime();
	
	// Start off by issuing a record request.
	TTime starttime;
	starttime.HomeTime();
	TInt bytesRecorded = 0;
	RxSoundDevice.RecordData(stat,length);

	TInt pausesToDo = 10;
	pausesToDo = 0;
	FOREVER
		{
		// Wait for the outstanding record request to complete.
        User::After(6000);

		User::WaitForAnyRequest();
		if (stat==KRequestPending)
			return(KErrGeneral);

		TTime currentTime;
		currentTime.HomeTime();
		TInt64 elapsedTime = currentTime.Int64()-startTime.Int64();	// us
		TTimeIntervalMicroSecondsBuf timeRecordedBuf;
		if(RxSoundDevice.TimeRecorded(timeRecordedBuf) == KErrNone)
			{
			// Compare TimeRecorded with the actual elapsed time. They should be different, but not drift apart too badly...
			TInt32 offset = TInt32(elapsedTime - timeRecordedBuf().Int64());
			Test.Printf(_L("\telapsedTime - TimeRecorded = %d ms\n"), offset/1000);
			}		
			
		// Check whether the record request was succesful.
		TInt retOffset=stat.Int();
		if (retOffset<0)
			{
			Test.Printf(_L("Record failed(%d)\r\n"),retOffset);
			return(retOffset);
			}
		
		// Successfully recorded another buffer so write the recorded data to the record file and release the buffer.
		buf.Set((const TUint8*)(chunk.Base()+retOffset),length);
		r=destination.Write(buf);
		if (r!=KErrNone)
			{
			Test.Printf(_L("File write failed(%d)\r\n"),r);
			return(r);
			}
		r=RxSoundDevice.ReleaseBuffer(retOffset);
		if (r!=KErrNone)
			{
			Test.Printf(_L("Release buffer failed(%d)\r\n"),r);
			return(r);
			}
		
		Test.Printf(_L("Recorded %d more bytes - %d\r\n"),length,retOffset);

		if((pausesToDo > 0) && (bytesRecorded > bytesToRecord/2))
			{
			--pausesToDo;
			Test.Printf(_L("Pause\r\n"));
			RxSoundDevice.Pause();
			Test.Printf(_L("Paused, sleeping for 0.5 seconds\r\n"));
			User::After(500*1000);
            Test.Printf(_L("Resume\r\n"));
			RxSoundDevice.Resume();
			}
		
		// Check whether we have now recorded all the data. If more to record then queue a further request
		bytesRecorded+=length;
		if (bytesRecorded<bytesToRecord)
		    {
            Test.Printf(_L("RecordData\r\n"));
			RxSoundDevice.RecordData(stat,length);
		    }
		else
			break;
		}
	
	RxSoundDevice.CancelRecordData();	// Stop the driver from recording.
	
	TTime endtime;
	endtime.HomeTime();

	TInt64 elapsedTime = endtime.Int64()-starttime.Int64();	// us
	Test.Printf(_L("Delta time = %d\r\n"),I64LOW(elapsedTime));
	Test.Printf(_L("Seconds in buffer: %d (%d)\r\n"), bytesRecorded / header.nAvgBytesPerSec, (bytesRecorded / header.nAvgBytesPerSec)*1000000);

	if (I64LOW(elapsedTime) <= (bytesRecorded / header.nAvgBytesPerSec)*1000000)
		{
		Test.Printf(_L("Time travelling; record took less time than it should have done\r\n"));
		return(KErrGeneral);
		}
	
	chunk.Close();
	destination.Close();

	Test.Printf(_L("Record finished\r\n"));
	return(KErrNone);
	}
Exemplo n.º 7
0
LOCAL_C TInt WavPlay()
	{
	RChunk chunk;
	
	// Parse the commandline and get a filename to use
	TLex l(CommandLine);
	TFileName thisfile=RProcess().FileName();
	TPtrC token=l.NextToken();
	if (token.MatchF(thisfile)==0)
		token.Set(l.NextToken());

	if (token.Length()==0)
		{
		// No args, skip to end
		Test.Printf(_L("Invalid configuration\r\n"));
		return(KErrArgument);
		}
		
	Test.Next(_L("Play Wav file"));

	// Assume that the argument is a WAV filename
	TFileName wavFilename=token;
	TInt r;
	RFile source;
	r = source.Open(Fs,wavFilename,EFileRead);
	if (r!=KErrNone)
		{
		Test.Printf(_L("Open failed(%d)\r\n"), r);
		return(r);
		}

	// Read the pcm header
	WAVEheader header;
	TPtr8 headerDes((TUint8 *)&header,sizeof(struct WAVEheader),sizeof(struct WAVEheader));
	r = source.Read(headerDes);
	if (r!=KErrNone)
		{
		source.Close();
		return(r);
		}
	Test.Printf(_L("Header Read %d bytes\r\n"),headerDes.Size());

	if (headerDes.Size() != sizeof(struct WAVEheader)) // EOF
		{
		Test.Printf(_L("Couldn't read a header(%d bytes)\r\n"),headerDes.Size());
		source.Close();
		return(KErrCorrupt);
		}

	Test.Printf(_L("Header rate:%d channels:%d tag:%d bits:%d (%d bytes/s) align %d datalen:%d fmt_ckSize:%d ckSize:%d\n"),
			header.nSamplesPerSec, header.nChannels, header.formatTag, header.nBitsPerSample,
			header.nAvgBytesPerSec, header.nBlockAlign, header.data_ckSize, header.fmt_ckSize, header.ckSize);

	if (header.formatTag != 1) // not pcm
		{
		Test.Printf(_L("Format not PCM(%d)\r\n"),header.formatTag);
		source.Close();
		return(KErrNotSupported);
		}

	if (header.nBitsPerSample != 16) // not 16 bit
		{
		Test.Printf(_L("Format not 16 bit PCM(%d bits)\r\n"),header.nBitsPerSample);
		source.Close();
		return(KErrNotSupported);
		}
		
	TSoundRate rate;	
	if (SamplesPerSecondToRate(header.nSamplesPerSec,rate)!=KErrNone)	
		{
		Test.Printf(_L("Format specifies a rate not supported(%d)\r\n"),header.nSamplesPerSec);
		source.Close();
		return(KErrNotSupported);
		}

	TxSoundDevice.AudioFormat(PlayFormatBuf);	// Read back the current setting which must be valid.
	PlayFormatBuf().iChannels = header.nChannels;
	PlayFormatBuf().iRate = rate;
	PlayFormatBuf().iEncoding = ESoundEncoding16BitPCM;
	
	// Set the play buffer configuration.
	TInt bufSize=BytesPerSecond(PlayFormatBuf())/8; 	// Large enough to hold 1/8th second of data.
	bufSize&=~(header.nBlockAlign-1);					// Keep the buffer length a multiple of the bytes per sample (assumes 16bitPCM, 1 or 2 chans).
	if (PlayCapsBuf().iRequestMinSize)
		bufSize&=~(PlayCapsBuf().iRequestMinSize-1); 	// Keep the buffer length valid for the driver.
	TTestSharedChunkBufConfig bufferConfig;
	bufferConfig.iNumBuffers=3;
	bufferConfig.iBufferSizeInBytes=bufSize;
	bufferConfig.iFlags=0;	
	PrintBufferConf(bufferConfig,Test);
	TPckg<TTestSharedChunkBufConfig> bufferConfigBuf(bufferConfig);
	r=TxSoundDevice.SetBufferChunkCreate(bufferConfigBuf,chunk);
	if (r!=KErrNone)
		{
		Test.Printf(_L("Buffer configuration not supported(%d)\r\n"),r);
		source.Close();
		return(r);
		}
	TxSoundDevice.GetBufferConfig(bufferConfigBuf);			// Read back the configuration - to get the buffer offsets
	CHECK(bufferConfig.iBufferSizeInBytes==bufSize);

	// Set the audio play configuration.
	TxSoundDevice.SetVolume(KSoundMaxVolume - (KSoundMaxVolume / 4)); // set volume to 75%
	PrintConfig(PlayFormatBuf(),Test);
	r=TxSoundDevice.SetAudioFormat(PlayFormatBuf);
	if (r!=KErrNone)
		{
		Test.Printf(_L("Format not supported\r\n"));
		source.Close();
		chunk.Close();
		return(r);
		}
	TxSoundDevice.ResetBytesTransferred();

	TInt32 bytesToPlay = header.data_ckSize;
	TTime starttime;
	starttime.HomeTime();

	TRequestStatus stat[3];
	TPtr8* tPtr[3];
	TInt i;
	for (i=0;i<3;i++)
		tPtr[i]=new TPtr8(NULL,0); 

	TTime startTime;
	startTime.HomeTime();
	
	// Start off by issuing a play request for each buffer (assuming that the file is long enough). Use the full size
	// of each buffer.
	TInt stillToRead=bytesToPlay;
	TInt stillNotPlayed=bytesToPlay;
	TUint flags;
	for (i=0 ; i<3 ; i++)
		{
		// Setup the descriptor for reading in the data from the file.
		tPtr[i]->Set(chunk.Base()+bufferConfig.iBufferOffsetList[i],0,bufSize); 
		
		// If there is still data to read to play then read this into the descriptor
		// and then write it to the driver.
		if (stillToRead)
			{
			r=source.Read(*tPtr[i],Min(stillToRead,bufSize));
			if (r!=KErrNone)
				{
				Test.Printf(_L("Initial file read error(%d)\r\n"),r);
				source.Close();
				chunk.Close();
				return(r);
				}
			stillToRead-=tPtr[i]->Length();
			flags=(stillToRead>0)?0:KSndFlagLastSample;
			TxSoundDevice.PlayData(stat[i],bufferConfig.iBufferOffsetList[i],tPtr[i]->Length(),flags);
			}
		else
			stat[i]=KRequestPending;	
		}	
		
	FOREVER
		{
		// Wait for any one of the outstanding play requests to complete.
		User::WaitForAnyRequest();

		TTime currentTime;
		currentTime.HomeTime();
		TInt64 elapsedTime = currentTime.Int64()-startTime.Int64();	// us
		TTimeIntervalMicroSecondsBuf timePlayedBuf;
		if(TxSoundDevice.TimePlayed(timePlayedBuf) == KErrNone)
			{
			// Compare TimePlayed with the actual elapsed time. They should be different, but not drift apart too badly...
			TInt32 offset = TInt32(elapsedTime - timePlayedBuf().Int64());
			Test.Printf(_L("\telapsedTime - TimePlayed = %d ms\n"), offset/1000);
			}		
	
		// Work out which buffer this applies to
		for (i=0 ; i<3 ; i++)
			{
			if (stat[i]!=KRequestPending)
				break;
			}
		if (i>=3)
			{
			Test.Printf(_L("I/O error\r\n"));
			source.Close();
			chunk.Close();
			return(KErrGeneral);
			}
	
		// Check that the transfer was succesful and whether we have now played all the file.
		if (stat[i]!=KErrNone)
			{
			Test.Printf(_L("Play error(%d)\r\n"),stat[i].Int());
			source.Close();
			chunk.Close();
			return(stat[i].Int());
			}
		Test.Printf(_L("Played %d bytes(%d) - %d\r\n"),tPtr[i]->Length(),i,stat[i].Int());
		stillNotPlayed-=tPtr[i]->Length();
		CHECK(stillNotPlayed>=0);
		if (!stillNotPlayed)
			break;
	
		// Still more to be played so read the next part of the file into the descriptor for this
		// buffer and then write it to the driver.
		if (stillToRead)
			{
			TInt len=Min(stillToRead,bufSize);
		
			// If we've got to the end of the file and the driver is particular about the request length then 
			// zero fill the entire buffer so we can play extra zeros after the last sample from the file.
			if (len<bufSize && PlayCapsBuf().iRequestMinSize)
				tPtr[i]->FillZ(bufSize);
		
			// Read the next part of the file 
			r=source.Read(*tPtr[i],len);			// This will alter the length of the descriptor
			if (r!=KErrNone)
				{
				Test.Printf(_L("File read error(%d)\r\n"),r);
				source.Close();
				chunk.Close();
				return(r);
				}
			stillToRead-=tPtr[i]->Length();
		
			// If we've got to the end of the file and the driver is particular about the request length then
			// round up the length to the next valid boundary. This is OK since we zero filled.
			if (tPtr[i]->Length() < bufSize && PlayCapsBuf().iRequestMinSize)
				{
				TUint m=PlayCapsBuf().iRequestMinSize-1;
				len=(tPtr[i]->Length() + m) & ~m;
				}
		
			// Write it to the driver.
			flags=(stillToRead>0)?0:KSndFlagLastSample;
			TxSoundDevice.PlayData(stat[i],bufferConfig.iBufferOffsetList[i],len,flags);
			}
		else
			stat[i]=KRequestPending;		
		}
	
	// Delete all the variables again.	
	for (i=0 ; i<3 ; i++)
		delete tPtr[i];
	
	TTime endtime;
	endtime.HomeTime();

	Test.Printf(_L("Done playing\r\n"));
	Test.Printf(_L("Bytes played = %d\r\n"),TxSoundDevice.BytesTransferred());
	Test.Printf(_L("Delta time = %d\r\n"),endtime.Int64()-starttime.Int64());

	chunk.Close();
	source.Close();
	return(KErrNone);
	}
Exemplo n.º 8
0
GLDEF_C TInt E32Main()

    {
	__UHEAP_MARK;

	Test.Title();

	TInt r;
	Test.Start(_L("Load sound PDD"));
	r=User::LoadPhysicalDevice(KSndPddFileName);
	if (r==KErrNotFound)
		{
		Test.Printf(_L("Shared chunk sound driver not supported - test skipped\r\n"));
		Test.End();
		Test.Close();
		__UHEAP_MARKEND;
		return(KErrNone);
		}
	Test(r==KErrNone || r==KErrAlreadyExists);
	
	Test.Next(_L("Load sound LDD"));
	r=User::LoadLogicalDevice(KSndLddFileName);
	Test(r==KErrNone || r==KErrAlreadyExists);
	
	/**	@SYMTestCaseID 		PBASE-T_SOUNDMCHAN-224
	@SYMTestCaseDesc 		Opening the channel - more than one channel
	@SYMTestPriority 		Critical
	@SYMTestActions			1)	With the LDD and PDD installed and with all channels closed on the device, 
								open a channel for playback on the device. 
							2)	Without closing the first playback channel, attempt to open a second channel 
								for playback on the same device. 
	@SYMTestExpectedResults	1)	KErrNone - Channel opens successfully. 
							2)	Should fail with KErrInUse.
	@SYMREQ					PREQ1073.4 */	
	
	__KHEAP_MARK;

	Test.Next(_L("Open a channel on the play device"));
	RSoundSc snddev;
	r=snddev.Open(KSoundScTxUnit0);
	Test(r==KErrNone);
	
	Test.Next(_L("Try opening the same unit a second time."));
	RSoundSc snddev2;
	r=snddev2.Open(KSoundScTxUnit0);
	Test(r==KErrInUse);
	
	Test.Next(_L("Query play formats supported"));
	TSoundFormatsSupportedV02Buf capsBuf;
	snddev.Caps(capsBuf);
	TSoundFormatsSupportedV02& caps=capsBuf();
	PrintCaps(caps,Test);
	
	Test.Next(_L("Try playing without setting the buffer config"));
	TRequestStatus pStat;
	snddev.PlayData(pStat,0,0x2000);	// 8K
	User::WaitForRequest(pStat);
	Test(pStat.Int()==KErrNotReady);

	Test.Next(_L("Configure the channel from a 2nd thread"));
	RThread thread;
	TRequestStatus tStat;
	SSecondaryThreadInfo sti;
	
	sti.iTestId=ESecThreadConfigPlayback;
	sti.iThreadId=RThread().Id();	// Get the ID of this thread
	sti.iDrvHandle=snddev.Handle();	// Pass the channel handle
	
	/**	@SYMTestCaseID 		PBASE-T_SOUNDMCHAN-225
	@SYMTestCaseDesc 		Opening the channel - sharing the handle between threads
	@SYMTestPriority 		Critical
	@SYMTestActions			1)	With the LDD and PDD installed and with all channels closed on the device, open a 
								channel for playback on the device. Now create a second thread. Resume this 
								thread - passing the handle to the playback channel to it. Wait for the second 
								thread to terminate.
							2)	In the second thread, duplicate the playback channel handle.
							3)	In the second thread, using the duplicated handle, issue a request to set the audio configuration. 
							4)	In the second thread, using the duplicated handle, issue a request to set the volume. 
							5)	In the second thread, close the handle and exit the thread.
							6)	In the first thread, read back the audio configuration.
							7)	In the first thread, set the buffer configuration, and then issue a request to play 
								audio data. 
							8)	In the first thread, close the channel. 
	@SYMTestExpectedResults	1)	KErrNone - Channel opens successfully. 
							2)	KErrNone - Duplication of the handle succeeds.
							3)	KErrNone - Audio configured successfully.
							4)	KErrNone - Volume set successfully.
							5)	No errors occur closing the channel and exiting the thread.
							6)	The audio configuration should correspond to that set by the second thread.
							7)	KErrNone - Setting the buffer configuration and issuing a play request.
							8)	No errors occur closing the channel.
	@SYMREQ					PREQ1073.4 */	
	
	r=thread.Create(_L("Thread"),secondaryThread,KDefaultStackSize,KHeapSize,KHeapSize,&sti); // Create secondary thread
	Test(r==KErrNone);
	thread.Logon(tStat);
	thread.Resume();
	User::WaitForRequest(tStat);
	Test(tStat.Int()==KErrNone);
//	Test.Printf(_L("Thread exit info: Cat:%S, Reason:%x, Type:%d\r\n"),&thread.ExitCategory(),thread.ExitReason(),thread.ExitType());
	Test(thread.ExitType()==EExitKill);
	thread.Close();
	User::After(10000);	// Wait 10ms
	
	Test.Next(_L("Read back the play configuration"));
	TCurrentSoundFormatV02Buf formatBuf;
	snddev.AudioFormat(formatBuf);
	TCurrentSoundFormatV02& format=formatBuf();
	PrintConfig(format,Test);
	
	Test.Next(_L("Set the buffer configuration"));
	RChunk chunk;
	TInt bufSize=BytesPerSecond(formatBuf()); 	 							// Large enough to hold 1 second of data.
	bufSize=ValidBufferSize(bufSize,caps.iRequestMinSize,formatBuf());		// Keep the buffer length valid for driver.
	TTestSharedChunkBufConfig bufferConfig;
	bufferConfig.iNumBuffers=1;
	bufferConfig.iBufferSizeInBytes=bufSize;
	bufferConfig.iFlags=0;	
	TPckg<TTestSharedChunkBufConfig> bufferConfigBuf(bufferConfig);
	r=snddev.SetBufferChunkCreate(bufferConfigBuf,chunk);
	Test(r==KErrNone);
	snddev.GetBufferConfig(bufferConfigBuf);
	PrintBufferConf(bufferConfig,Test);
	Test(bufferConfig.iBufferSizeInBytes==bufSize);
	
	Test.Next(_L("Start playing"));
	r=MakeSineTable(format);
	Test(r==KErrNone);
	r=SetToneFrequency(660,format);
	Test(r==KErrNone); 
	TPtr8 ptr(chunk.Base()+bufferConfig.iBufferOffsetList[0],bufSize);
	WriteTone(ptr,format);
	snddev.PlayData(pStat,bufferConfig.iBufferOffsetList[0],bufSize,KSndFlagLastSample);
	User::WaitForRequest(pStat);
	Test(tStat.Int()==KErrNone);
	
	Test.Next(_L("Close the drivers and the chunk"));
	chunk.Close();
	snddev.Close();
	
	__KHEAP_MARKEND;

	Test.Next(_L("Unload the drivers"));
	
	r=User::FreeLogicalDevice(KDevSoundScName);
	Test.Printf(_L("Unloading %S.LDD - %d\r\n"),&KDevSoundScName,r);
	Test(r==KErrNone);
	
	TName pddName(KDevSoundScName);
	_LIT(KPddWildcardExtension,".*");
	pddName.Append(KPddWildcardExtension);
	TFindPhysicalDevice findPD(pddName);
	TFullName findResult;
	r=findPD.Next(findResult);
	while (r==KErrNone)
		{
		r=User::FreePhysicalDevice(findResult);
		Test.Printf(_L("Unloading %S.PDD - %d\r\n"),&findResult,r);
		Test(r==KErrNone);
		findPD.Find(pddName); // Reset the find handle now that we have deleted something from the container.
		r=findPD.Next(findResult);
		} 
	
	Test.End();
	Test.Close();
	
	Cleanup();
	
	__UHEAP_MARKEND;

	return(KErrNone);
    }
Exemplo n.º 9
0
/*
 * Function: SMTP_ParseArgs(char *)
 *
 * Purpose: Process the preprocessor arguments from the rules file and 
 *          initialize the preprocessor's data struct.  This function doesn't
 *          have to exist if it makes sense to parse the args in the init 
 *          function.
 *
 * Arguments: args => argument list
 *
 * Returns: void function
 *
 */
void SMTP_ParseArgs(char *args)
{
    int ret = 0;
    char *arg;
    char *value;
    char errStr[ERRSTRLEN];
    int errStrLen = ERRSTRLEN;

    if (args == NULL)
    {
        return;
    }

    /*  Set config to defaults */
    memset(&_smtp_config, 0, sizeof(SMTPConfig));

    _smtp_config.ports[SMTP_DEFAULT_SERVER_PORT / 8]     |= 1 << (SMTP_DEFAULT_SERVER_PORT % 8);
    _smtp_config.ports[XLINK2STATE_DEFAULT_PORT / 8]     |= 1 << (XLINK2STATE_DEFAULT_PORT % 8);
    _smtp_config.ports[SMTP_DEFAULT_SUBMISSION_PORT / 8] |= 1 << (SMTP_DEFAULT_SUBMISSION_PORT % 8);
    _smtp_config.inspection_type = SMTP_STATELESS;
    _smtp_config.max_command_line_len = DEFAULT_MAX_COMMAND_LINE_LEN;
    _smtp_config.max_header_line_len = DEFAULT_MAX_HEADER_LINE_LEN;
    _smtp_config.max_response_line_len = DEFAULT_MAX_RESPONSE_LINE_LEN;
    _smtp_config.alert_xlink2state = 1;
    _smtp_config.print_cmds = 1;

    _smtp_cmd_config = (SMTPCmdConfig *)calloc(CMD_LAST, sizeof(SMTPCmdConfig));
    if (_smtp_cmd_config == NULL)
    {
        DynamicPreprocessorFatalMessage("%s(%d) => Failed to allocate memory for SMTP "
                                        "command structure\n", 
                                        *(_dpd.config_file), *(_dpd.config_line));
    }

    *errStr = '\0';

    arg = strtok(args, CONF_SEPARATORS);
    
    while ( arg != NULL )
    {
        if ( !strcasecmp(CONF_PORTS, arg) )
        {
            ret = ProcessPorts(errStr, errStrLen);
        }
        else if ( !strcasecmp(CONF_INSPECTION_TYPE, arg) )
        {
            value = strtok(NULL, CONF_SEPARATORS);
            if ( value == NULL )
            {
                return;
            }
            if ( !strcasecmp(CONF_STATEFUL, value) )
            {
                _smtp_config.inspection_type = SMTP_STATEFUL;
            }
            else
            {
                _smtp_config.inspection_type = SMTP_STATELESS;
            }
        }
        else if ( !strcasecmp(CONF_NORMALIZE, arg) )
        {
            value = strtok(NULL, CONF_SEPARATORS);
            if ( value == NULL )
            {
                return;
            }
            if ( !strcasecmp(CONF_NONE, value) )
            {
                _smtp_config.normalize = NORMALIZE_NONE;
            }
            else if ( !strcasecmp(CONF_ALL, value) )
            {
                _smtp_config.normalize = NORMALIZE_ALL;
            }
            else
            {
                _smtp_config.normalize = NORMALIZE_CMDS;
            }
        }
        else if ( !strcasecmp(CONF_IGNORE_DATA, arg) )
        {                    
            _smtp_config.ignore_data = 1;            
        }
        else if ( !strcasecmp(CONF_IGNORE_TLS_DATA, arg) )
        {
            _smtp_config.ignore_tls_data = 1;            
        }
        else if ( !strcasecmp(CONF_MAX_COMMAND_LINE_LEN, arg) )
        {
            char *endptr;

            value = strtok(NULL, CONF_SEPARATORS);
            if ( value == NULL )
            {
                return;
            }
            
            _smtp_config.max_command_line_len = strtol(value, &endptr, 10);
        }
        else if ( !strcasecmp(CONF_MAX_HEADER_LINE_LEN, arg) )
        {
            char *endptr;

            value = strtok(NULL, CONF_SEPARATORS);
            if ( value == NULL )
            {
                return;
            }
            
            _smtp_config.max_header_line_len = strtol(value, &endptr, 10);
        }
        else if ( !strcasecmp(CONF_MAX_RESPONSE_LINE_LEN, arg) )
        {
            char *endptr;

            value = strtok(NULL, CONF_SEPARATORS);
            if ( value == NULL )
            {
                return;
            }
            
            _smtp_config.max_response_line_len = strtol(value, &endptr, 10);
        }
        else if ( !strcasecmp(CONF_NO_ALERTS, arg) )
        {     
            _smtp_config.no_alerts = 1;
        }
        else if ( !strcasecmp(CONF_ALERT_UNKNOWN_CMDS, arg) )
        {
            _smtp_config.alert_unknown_cmds = 1;
        }
        else if ( !strcasecmp(CONF_INVALID_CMDS, arg) )
        {
            /* Parse disallowed commands */
            ret = ProcessCmds(errStr, errStrLen, ACTION_ALERT);
        }
        else if ( !strcasecmp(CONF_VALID_CMDS, arg) )
        {
            /* Parse allowed commands */
            ret = ProcessCmds(errStr, errStrLen, ACTION_NO_ALERT);   
        }
        else if ( !strcasecmp(CONF_NORMALIZE_CMDS, arg) )
        {
            /* Parse normalized commands */
            ret = ProcessCmds(errStr, errStrLen, ACTION_NORMALIZE);
        }
        else if ( !strcasecmp(CONF_ALT_MAX_COMMAND_LINE_LEN, arg) )
        {
            /* Parse max line len for commands */
            ret = ProcessAltMaxCmdLen(errStr, errStrLen);
        }
        else if ( !strcasecmp(CONF_XLINK2STATE, arg) )
        {
            ret = ProcessXlink2State(errStr, errStrLen);
        }

        else if ( !strcasecmp(CONF_PRINT_CMDS, arg) )
        {
            _smtp_config.print_cmds = 1;
        }
        else
        {
            DynamicPreprocessorFatalMessage("%s(%d) => Unknown SMTP configuration option %s\n", 
                                            *(_dpd.config_file), *(_dpd.config_line), arg);
        }        

        if (ret == -1)
        {
            /*
            **  Fatal Error, log error and exit.
            */
            if (*errStr)
            {
                DynamicPreprocessorFatalMessage("%s(%d) => %s\n", 
                                                *(_dpd.config_file), *(_dpd.config_line), errStr);
            }
            else
            {
                DynamicPreprocessorFatalMessage("%s(%d) => Undefined Error.\n", 
                                                *(_dpd.config_file), *(_dpd.config_line));
            }
        }

        /*  Get next token */
        arg = strtok(NULL, CONF_SEPARATORS);
    }

    PrintConfig();
}
Exemplo n.º 10
0
/**
 * Entry point 
 */
int
main(int argc, char** argv )
{
  // TODO ([email protected]) put init settings in ctor
  ApplicationConfig config;
  config.print_debug = false;
  config.is_logging = true;

  SetSignalHandlers();

#ifdef LOG
      logging_init(createTimestampedLogFilename(PANTHEIOS_FE_PROCESS_IDENTITY).c_str());
#endif

  if (capk::InitializeZMQPublisher(&g_zmq_context, &g_pub_socket) != 0) {
#ifdef LOG
    pan::log_CRITICAL("Can't init ZMQ - exiting");
#endif
    return (-1);
  }

  // Must call this to use protobufs
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  // First read command line
  if (ReadCommandLineParams(argc, argv, &config) != 0) {
#ifdef LOG
    pan::log_CRITICAL("Aborting due to missing parameters.");
#endif
    return (-1);
  }

  // Read the symbols to subscribe to from file
  std::vector<std::string> symbols = capk::readSymbolsFile(config.symbol_file_name);
  if (symbols.size() <= 0) {
#ifdef LOG
    pan::log_CRITICAL("No symbols set in:", config.symbol_file_name.c_str());
#endif
    return (-1);
  }

  try {
    FIX::SessionSettings settings(config.config_file_name);
    std::set<FIX::SessionID> sessions = settings.getSessions();
    assert(sessions.size() == 1);
    FIX::SessionID sessionId = *(sessions.begin());
    const FIX::Dictionary& dict = settings.get(sessionId);


    // Get additional config settings from FIX config file
    if (ReadFIXConfig(&config, dict) != 0) {
      fprintf(stderr, "Can't read local config file - exiting\n");
      return (-1);
    }

    if (config.venue_config_file_name == "") {
      // Get config settings from config server
      if (ReadRemoteConfig(&config) != 0) {
        fprintf(stderr, "Can't read remote configuration - exiting\n");
        return (-1);
      }
    }
    else {
      // Get config settings from local ini file
      if (ReadLocalVenueConfig(config.venue_config_file_name, &config) != 0) {
        fprintf(stderr, "Can't read local venue configuration - exiting\n");
        return (-1);
      }
    }

    PrintConfig(&config);

    // Create the FIX application instance
    Application application(config);
    g_papplication = &application;
    application.addSymbols(symbols);

    // Create the output directories for orderbooks, log, and store if needed.
    // Note that actual log directories are created in the location specified
    // with -o arg each time the program starts
    // @TODO ([email protected]) Maybe better to put
    // each log in the dated directory rather than have store and
    // log on same level as dated tick dirs
    if (config.root_output_dir.length() > 0) {
      fs::path argPath = fs::path(config.root_output_dir);
      if (!fs::exists(argPath)) {
        fs::create_directories(argPath);
      }

      fs::path fix_log_path = argPath / fs::path("log");
      if (!fs::exists(fix_log_path)) {
        fs::create_directory(fix_log_path);
      }
      config.fix_log_output_dir = fix_log_path.string();

      fs::path store_path = argPath / fs::path("store");
      if (!fs::exists(store_path)) {
        fs::create_directory(store_path);
      }
      config.fix_store_output_dir = store_path.string();
    }

    pid_t pid = getpid();
    pid_t ppid = getppid();

#ifdef LOG
    pan::log_DEBUG("pid: ", pan::integer(pid), " ppid: ", pan::integer(ppid));
#endif
    if (WritePidFile(argv[0], config.mic_string.c_str(), pid, ppid) != 0) {
#ifdef LOG
      pan::log_CRITICAL("Can't write pid file - exiting");
#endif
      return (-1);
    }

    // Set ZMQ parameters in Application 
    if (config.is_publishing) {
      zmq_bind(g_pub_socket, config.publishing_addr.c_str());
      application.setZMQContext(g_zmq_context);
      application.setZMQSocket(g_pub_socket);
    }


    if (config.is_logging) {
      std::cout << "Logging with FileStoreFactory" << std::endl;
      FIX::FileStoreFactory fileStoreFactory(config.fix_store_output_dir);
      FIX::FileLogFactory logFactory(config.fix_log_output_dir);
      g_pinitiator = new FIX::SocketInitiator(application,
                                              fileStoreFactory,
                                              settings,
                                              logFactory);
      assert(g_pinitiator);
    } else {
      std::cout << "Logging with NullStoreFactory" << std::endl;
      FIX::NullStoreFactory nullStoreFactory;
      g_pinitiator = new FIX::SocketInitiator(application,
                                              nullStoreFactory,
                                              settings);
      assert(g_pinitiator);
    }

    std::cout << "Starting initiator" << std::endl;
    g_pinitiator->start();

    char x;
    std::cout << "Type 'q' to disconnect and exit" << std::endl;
    while (std::cin >> x) {
      if (x == 'q') {
        break;
      }
    }
    std::cout << "Cleaning up" << std::endl;
    g_pinitiator->stop();
    return 0;
  } catch(FIX::Exception& e) {
    std::cerr << e.what();
    return 1;
  }
}