コード例 #1
0
ファイル: lists.c プロジェクト: billev/literacybridge
char *getCurrentList(ListItem *list) {
	char *ret;
	char buffer[READ_LENGTH+1];
	int fileHandle;
	char *cursor;
	int attempt, goodPass;
	const int MAX_ATTEMPTS = 3;
	
	buffer[READ_LENGTH] = '\0';
	if (list->currentFilePosition == -1) {
		list->currentFilePosition = 0;		
		for (attempt=0,goodPass=0;attempt < MAX_ATTEMPTS;attempt++) {
			fileHandle = openList(list,NULL);
			readBuffer(fileHandle,buffer,READ_LENGTH);
			if (goodString(buffer,1)) {
				goodPass = 1;
				break;
			}
			close(fileHandle);
			logException(30,0,0); // log failed attempt
		}
		if (!goodPass)
			logException(30,0,RESET);
		buffer[READ_LENGTH] = '\0'; //prevents readLine from searching for \n past buffer
		for (cursor = buffer;*cursor != 0x0a && *cursor != 0x0d && *cursor != 0x00;cursor++);
		*cursor = 0x00;
		close(fileHandle);
		strcpy(list->currentString,buffer);
	}
	ret = list->currentString;
	return ret;
}
コード例 #2
0
ファイル: files.c プロジェクト: billev/literacybridge
void clearStaleLog() {
	int handle, ret;
	char buffer[LOG_CARRYOVER_BYTES / 2];
	
	if(vCur_1 < V_MIN_SDWRITE_VOLTAGE) {
		refuse_lowvoltage(0);
		return;
	}
	
	if (LOG_FILE) {
		handle = tbOpen((LPSTR)(LOG_FILE),O_RDONLY);
		if(handle < 0 )
			logException(13,0,0); 
		else {
			lseek(handle,-LOG_CARRYOVER_BYTES,SEEK_END);
			ret = read(handle,(unsigned long)&buffer<<1,LOG_CARRYOVER_BYTES);
			close(handle);
			unlink((LPSTR)(LOG_FILE));
			handle = tbOpen((LPSTR)(LOG_FILE),O_CREAT|O_RDWR|O_TRUNC);
			if (handle != -1) {
				write(handle,(unsigned long)&buffer<<1,LOG_CARRYOVER_BYTES);
				close(handle);
			} else
				logException(13,0,0); 
		}
	}
}
コード例 #3
0
IPropertyTree* RemoteXmlEclRepository::getAttributes(const char *module, const char *attr, int version, unsigned char infoLevel) 
{
    IPropertyTree* repositoryTree = 0;
    StringBuffer xml;
    try
    {
        StringBuffer snapshot;
        getProp("snapshot",snapshot);
        bool sandbox4snapshot = getPropInt("sandbox4snapshot", 0) != 0;

        repository.getAttributes(xml, user, module, attr, version, infoLevel, snapshot.length() ? snapshot.str() : NULL, sandbox4snapshot);
        if (xml.length())
            repositoryTree = createPTreeFromXMLString(xml, ipt_caseInsensitive);
    }
    catch(IException *e) 
    {
        logException(e);
        if (xml.length())
            DBGLOG("Xml: %s", xml.str());
        e->Release();
    }
    catch (...)
    { 
        logException(NULL);
    }

    return repositoryTree;
}
コード例 #4
0
ファイル: main.cpp プロジェクト: morpheby/ntpc-comm
int main(int argc, char **argv) {
	if(argc != 2) {
		std::cout << "Usage:" << std::endl
				<< argv[0] << " {port name}" << std::endl;
		return -1;
	}
	std::string port = argv[1];

	auto logger = std::make_shared<util::Logger>();
	logger->addLog(std::make_shared<util::LogFile>("ntpc-comm", util::LogSeverity::TRACE, "ntpc-comm.log"));
	logger->addLog(std::make_shared<util::LogStream>("ntpc-comm", util::LogSeverity::ERROR, std::cerr.rdbuf()));

	try {
		comm::SerialComm serial(port);

		std::vector<uint16_t> rdbuf(20);

		serial.read(rdbuf.begin(), rdbuf.end());

	} catch(const util::posix_error_exception &e) {
		logger->logPosixError(e.getErrno(), e.getWhile());
	} catch(const std::exception &e) {
		logger->logException(e);
	} catch(const char *str) {
		logger->logException(str);
	} catch(const std::string &s) {
		logger->logException(s);
	}

	return 0;
}
コード例 #5
0
ファイル: lists.c プロジェクト: billev/literacybridge
char *getPreviousList(ListItem *list) {
	char *ret;
	char buffer[READ_LENGTH+1];
	int fileHandle;
	char *line, *tempCursor;
	int attempt,goodPass;
	const int MAX_ATTEMPTS = 3;
	
	if (list->currentFilePosition == -1)
		ret = getCurrentList(list); 
	else {
		for (attempt=0,goodPass=0;attempt < MAX_ATTEMPTS && !goodPass;attempt++) {
			fileHandle = openList(list,NULL);
			lseek(fileHandle,list->currentFilePosition,SEEK_SET);
			buffer[READ_LENGTH] = '\0'; //prevents readLine from searching for \n past buffer
			getLine(-1,0); // resets DONE
			line = getLine(fileHandle,buffer);
			if (!line)
				line[0] = 0; //empty list
			else {
				do {
					line = getLine(fileHandle,buffer);
				} while (line && strspn(line," \x0a\x0d\x00"));
				if (!line) {
					// end of file -- move to start
					line = getLine(fileHandle,0); // to reset DONE and move to BOF
					list->currentFilePosition = 0;
					line = getLine(fileHandle,buffer);
					if (!line)
						logException(9,0,RESET); //todo: format problem with list
				}
				list->currentFilePosition += getFilePosition();
			}
			close(fileHandle);
			for (tempCursor = line;*tempCursor != 0x0a && *tempCursor != 0x0d && *tempCursor != 0x00;tempCursor++);
			*tempCursor = 0x00;
			strcpy(list->currentString,line);
			ret = list->currentString;
			if ((goodPass = goodString(ret,1)))
				break;
			else 
				logException(30,0,0);
		}
		if (!goodPass)
			logException(30,0,RESET);
	}
	return ret;
} 
コード例 #6
0
ファイル: lists.c プロジェクト: billev/literacybridge
static int openList(ListItem *list, char *outFilename) {
	int ret;
	char filename[FILE_LENGTH];
	char filepath[PATH_LENGTH];
	
	stop();
	if (list->filename[0])
		strcpy(filename,list->filename);
	else {
		strcpy(filename,getCurrentList(&context.package->lists[list->idxListWithFilename]));
		list->posListWithFilename = context.package->lists[list->idxListWithFilename].currentFilePosition; 
	}
	strcat(filename,".txt"); //todo: move to config file
	cpyListPath(filepath,filename);
	ret = tbChdir((LPSTR)filepath);
	if (ret == -1) {
		logException(5,filepath,RESET); //todo: package name or path does not exist
	}
	if (outFilename)
		strcpy(outFilename,filename);
	ret = tbOpen((LPSTR)(filename),O_RDONLY);
	if (ret == -1) {
		ret = replaceFromBackup(filename);
		if (ret != -1)
			ret = tbOpen((LPSTR)(filename),O_RDONLY);
		if (ret == -1)
			ret = tbOpen((LPSTR)(filename), O_CREAT|O_RDWR);
		// logException(5,filename,RESET); //todo: package name or path does not exist
	}
	return ret;	
}
コード例 #7
0
ファイル: executeQuery.cpp プロジェクト: yurial/ClickHouse
static void onExceptionBeforeStart(const String & query, Context & context, time_t current_time)
{
    /// Exception before the query execution.
    context.getQuota().addError();

    bool log_queries = context.getSettingsRef().log_queries;

    /// Log the start of query execution into the table if necessary.
    if (log_queries)
    {
        QueryLogElement elem;

        elem.type = QueryLogElement::EXCEPTION_BEFORE_START;

        elem.event_time = current_time;
        elem.query_start_time = current_time;

        elem.query = query.substr(0, context.getSettingsRef().log_queries_cut_to_length);
        elem.exception = getCurrentExceptionMessage(false);

        elem.client_info = context.getClientInfo();

        setExceptionStackTrace(elem);
        logException(context, elem);

        context.getQueryLog().add(elem);
    }
}
DE_BEGIN_EXTERN_C

JNIEXPORT void JNICALL Java_com_drawelements_deqp_execserver_ExecService_onCreateNative (JNIEnv* env, jobject obj)
{
	tcu::Android::ExecService*	service		= DE_NULL;
	JavaVM*						vm			= DE_NULL;

	try
	{
		DE_ASSERT(!getExecService(env, obj));

		env->GetJavaVM(&vm);
		TCU_CHECK_INTERNAL(vm);

		service = new tcu::Android::ExecService(vm, obj);
		service->start();

		setExecService(env, obj, service);
	}
	catch (const std::exception& e)
	{
		logException(e);
		delete service;
		tcu::die("ExecService.onCreateNative() failed");
	}
}
コード例 #9
0
ファイル: parsing.c プロジェクト: billev/literacybridge
static int getIndexFromLine(char *line, char *symbolMapStart) {
	// This fct finds the [label] for a block and gets the block index number stored in symbolMap
	int index;
	char *cursor;
	char overwritten;
	
	cursor = strchr(line,']');
	//set null marker on ']' or at beginning of any whitespace
	if (cursor) {
		while (*(cursor-1) && ((*(cursor-1) == ' ') || (*(cursor - 1) == '\t')))
			cursor--;
		overwritten = *cursor; // to fix it up again
		*cursor= '\0';
		cursor = strchr(line,'[');
		//todo: check that '[' comes before ']'
		do
			cursor++;
		while (isspace(*cursor));
		index = getBlockIndexFromSymbol (symbolMapStart, cursor);
		if (index == -1) {
			logException(6,cursor,(context.package == &pkgSystem)?USB_MODE:RESET);
		}  // todo:invalid internal reference in control track file
		for (;*cursor;cursor++); // get back to \0
		*cursor = overwritten;  // fix it up
	} else
		index = -1;
	return index;
}
コード例 #10
0
JSValueRef EJApp::invokeCallback(JSObjectRef callback, JSObjectRef thisObject, size_t argc, const JSValueRef argv[])
{
    JSValueRef exception = NULL;
    JSValueRef result = JSObjectCallAsFunction( jsGlobalContext, callback, thisObject, argc, argv, &exception );
    logException(exception,jsGlobalContext);
    return result;
}
コード例 #11
0
ファイル: sys_counters.c プロジェクト: billev/literacybridge
void saveSystemCounts() {
	int handle, ret, i;

	if(vCur_1 < V_MIN_SDWRITE_VOLTAGE) {
		refuse_lowvoltage(0);
		return;
	}
		
	i = 0;
	do {
 		ret = unlink((LPSTR)(SYSTEM_VARIABLE_FILE));
 		if (ret)
	 		wait(100);
	}
	while (ret && ++i < 3);
	
	handle = tbOpen((LPSTR)(SYSTEM_VARIABLE_FILE),O_CREAT|O_RDWR);
	if (handle != -1)
		ret = write(handle, (unsigned long)&systemCounts<<1, sizeof(SystemCounts)<<1);
	else {
		if (ret)
			logString((char *)"failed unlink of system var file",BUFFER,LOG_ALWAYS);
		close(handle);
		logException(17,SYSTEM_VARIABLE_FILE,RESET); //can't save SYSTEM_VARIABLE_FILE;
	}
	close(handle);
}
コード例 #12
0
static void onExceptionBeforeStart(const String & query, Context & context, time_t current_time)
{
	/// Эксепшен до начала выполнения запроса.
	context.getQuota().addError(current_time);

	bool log_queries = context.getSettingsRef().log_queries;

	/// Логгируем в таблицу начало выполнения запроса, если нужно.
	if (log_queries)
	{
		QueryLogElement elem;

		elem.type = QueryLogElement::EXCEPTION_BEFORE_START;

		elem.event_time = current_time;
		elem.query_start_time = current_time;

		elem.query = query.substr(0, context.getSettingsRef().log_queries_cut_to_length);
		elem.exception = getCurrentExceptionMessage(false);

		setClientInfo(elem, context);
		setExceptionStackTrace(elem);
		logException(context, elem);

		context.getQueryLog().add(elem);
	}
}
コード例 #13
0
JSValueRef EJApp::loadModuleWithId(NSString * moduleId, JSValueRef module, JSValueRef exports)
{
    NSString * path = NSStringMake(moduleId->getCString() + string(".js"));
    NSString * script = NSString::createWithContentsOfFile(pathForResource(path)->getCString());

    if( !script ) {
        NSLog("Error: Can't Find Module %s", moduleId->getCString() );
        return NULL;
    }

    NSLog("Loading Module: %s", moduleId->getCString() );

    JSStringRef scriptJS = JSStringCreateWithUTF8CString(script->getCString());
    JSStringRef pathJS = JSStringCreateWithUTF8CString(path->getCString());
    JSStringRef parameterNames[] = {
        JSStringCreateWithUTF8CString("module"),
        JSStringCreateWithUTF8CString("exports"),
    };

    JSValueRef exception = NULL;
    JSObjectRef func = JSObjectMakeFunction( jsGlobalContext, NULL, 2,  parameterNames, scriptJS, pathJS, 0, &exception );

    JSStringRelease( scriptJS );
    JSStringRelease( pathJS );
    JSStringRelease(parameterNames[0]);
    JSStringRelease(parameterNames[1]);

    if( exception ) {
        logException(exception, jsGlobalContext);
        return NULL;
    }

    JSValueRef params[] = { module, exports };
    return invokeCallback(func, NULL, 2, params);
}
コード例 #14
0
ファイル: lists.c プロジェクト: billev/literacybridge
char *getCurrentList(ListItem *list) {
	char *ret;
	char buffer[READ_LENGTH+1];
	int fileHandle;
	char *cursor, *cp;
	int attempt, goodPass;
	ListItem *masterlist;
	const int MAX_ATTEMPTS = 3;
	
	buffer[READ_LENGTH] = '\0';
	if (list->currentFilePosition == -1) {
		list->currentFilePosition = 0;		
		for (attempt=0,goodPass=0;attempt < MAX_ATTEMPTS;attempt++) {
			fileHandle = openList(list,NULL);
			readBuffer(fileHandle,buffer,READ_LENGTH);
			if (goodString(buffer,1)) {
				goodPass = 1;
				break;
			}
			close(fileHandle);
			logException(30,0,0); // log failed attempt
		}
		if (!goodPass)
			logException(30,0,RESET);
		buffer[READ_LENGTH] = '\0'; //prevents readLine from searching for \n past buffer
		for (cursor = buffer;*cursor != 0x0a && *cursor != 0x0d && *cursor != 0x00;cursor++);
		*cursor = 0x00;
		close(fileHandle);
		
		//device-58
		masterlist = &pkgSystem.lists[context.package->idxMasterList];
		list->isLocked = 0;
		cp = buffer;
		if(list == masterlist) {
			if(*buffer == '!') { // catagory locked, no writing allowed
				list->isLocked = 1;
				cp++;
			}
		}
		//device-58
		strcpy(list->currentString,cp);		
	}
	ret = list->currentString;
	return ret;
}
コード例 #15
0
ファイル: files.c プロジェクト: billev/literacybridge
INT16 tbChdir(LPSTR path) {
	const int RETRIES = 3;
	int i;
	INT16 ret;
	//todo: move number of attempts into config file, but have fall back number in define (since config has to be open)

	for (i = 0; i < RETRIES; i++) { 
		ret = chdir(path);
		if (ret < 0)
			logException(24,(const char *)path,0);
		else
			break;
	}
	if (ret < 0)
		logException(25,(const char *)path,RESET);
	return ret;
	 	
}
コード例 #16
0
 void exceptionHandler(enum TExcType arg)
 {
    logException(arg);
    class Thread* panicThread = Thread::currentThread();
    if( panicThread ){
       //starts a terminateandjoin process in the main thread.
       ::Panic(panicThread); 
       panicThread->m_alive= false;
    }
    User::Exit(1);
 }
コード例 #17
0
IPropertyTree* RemoteXmlEclRepository::getModules(timestamp_t from)
{ 
    StringBuffer modNames;
    IPropertyTree* repositoryTree = 0;
    try
    {
        repository.getModules(modNames, user, from);
        repositoryTree = createPTreeFromXMLString(modNames.str(), ipt_caseInsensitive);
    }
    catch(IException *e) 
    {
        logException(e);
        e->Release();
    }
    catch (...)
    { 
        logException(NULL);
    }

    return repositoryTree;
}
コード例 #18
0
ファイル: util.c プロジェクト: billev/literacybridge
int goodString(char * str, int forFilename) {
	char *c;
	int ret = 1;

	for (c = str; *c; c++)
		if (!goodChar(*c, forFilename)) {
			ret = 0;
			break;
		}
	if (!ret)
		logException(27,str,0);
	return ret;
}
JNIEXPORT void JNICALL Java_com_drawelements_deqp_execserver_ExecService_onDestroyNative (JNIEnv* env, jobject obj)
{
	try
	{
		tcu::Android::ExecService* service = getExecService(env, obj);
		TCU_CHECK_INTERNAL(service);

		service->stop();
		delete service;

		setExecService(env, obj, DE_NULL);
	}
	catch (const std::exception& e)
	{
		logException(e);
		tcu::die("ExecService.onDestroyNative() failed");
	}
}
コード例 #20
0
ファイル: exception.cpp プロジェクト: fabienchaix/simgrid
void logException(
  e_xbt_log_priority_t prio,
  const char* context, std::exception const& exception)
{
  try {
    auto name = simgrid::xbt::demangle(typeid(exception).name());

    auto with_context =
      dynamic_cast<const simgrid::xbt::WithContextException*>(&exception);
    if (with_context != nullptr)
      XBT_LOG(prio, "%s %s by %s/%d: %s",
        context, name.get(),
        with_context->processName().c_str(), with_context->pid(),
        exception.what());
    else
      XBT_LOG(prio, "%s %s: %s", context, name.get(), exception.what());

    // Do we have a backtrace?
    if (with_context != nullptr) {
      auto backtrace = simgrid::xbt::resolveBacktrace(
        with_context->backtrace().data(), with_context->backtrace().size());
      for (std::string const& s : backtrace)
        XBT_LOG(prio, "  -> %s", s.c_str());
    }

    // Do we have a nested exception?
    auto with_nested = dynamic_cast<const std::nested_exception*>(&exception);
    if (with_nested == nullptr ||  with_nested->nested_ptr() == nullptr)
      return;
    try {
      with_nested->rethrow_nested();
    }
    catch (std::exception& nested_exception) {
      logException(prio, "Caused by", nested_exception);
    }
    // We could catch nested_exception or WithContextException but we don't bother:
    catch (...) {
      XBT_LOG(prio, "Caused by an unknown exception");
    }
  }
  catch (...) {
    // Don't log exceptions we got when trying to log exception
  }
}
コード例 #21
0
ファイル: parsing.c プロジェクト: billev/literacybridge
int addTextToPkgHeap (const char *line, CtnrPackage *pkg) {
	int startingHeap, length;
	char *heapCursor, *lineCursor;

	while (isspace(*line) && *line != 0)
		line++;
	lineCursor = strchr(line,0); 
	while (isspace(*(lineCursor-1)) && lineCursor >= line)
		lineCursor--;
	*lineCursor = 0;
	length = (lineCursor - line + 1);
	startingHeap = pkg->idxStrHeap;
	pkg->idxStrHeap = startingHeap + length;
	if (pkg->idxStrHeap > PKG_HEAP_SIZE)
		logException(11,0,(context.package == &pkgSystem)?USB_MODE:RESET); //todo:heap is full
	heapCursor = &(pkg->strHeapStack[startingHeap]);
	strcpy(heapCursor,line);
	return startingHeap;
}
コード例 #22
0
ファイル: audio.c プロジェクト: billev/literacybridge
static int getFileHandle (CtnrFile *newFile) {
	int ret = 0; 
	char sTemp[PATH_LENGTH];
	BOOL getLastRecording = FALSE;
	CtnrPackage *pkg;
		
	pkg = getPackageFromFile(newFile); // get package that applied to file, rather than context package
	// This is necessary for user packages inserting system sounds.

	// check for list
	if (newFile->idxFirstBlockInFile == -1)
		strcpy(sTemp,LIST_PATH);
	else if (newFile->idxFilename == -1) {  // use last file recorded
		logException(0,0,USB_MODE); // this should never happen -- removed this feature
		// check for last file recorded (parsed from $L)
		//getLastRecording = TRUE;
		//ret = tbChdir((unsigned long)(DRAFT_PATH));
	} 
	else { // not a list or last recording; just a normal file	
		switch (pkg->pkg_type) {
			case PKG_SYS:
				strcpy(sTemp,SYSTEM_PATH);
				break;		
			case PKG_APP:
				strcpy(sTemp, USER_PATH);
				strcat(sTemp,pkg->strHeapStack + pkg->idxName);
				strcat(sTemp,"\\");
				break;
			case PKG_MSG:	
				strcpy(sTemp, USER_PATH);
				break;
		}
	}
	if (getLastRecording)
		strcpy(sTemp,lastFilenameRecorded);
	else {
		strcat(sTemp,pkg->strHeapStack + newFile->idxFilename);
		strcat(sTemp,AUDIO_FILE_EXT);
	}
	ret = tbOpen((LPSTR)sTemp,O_RDWR);			
	return ret;
}
コード例 #23
0
void write_app_flash(int *bufp, int len, int startoffset)
{
	flash  FL = {0}, *newfp; 
	int fl_size = USB_Flash_init((flash *)0, 0), i;
	int flash_execution_buf[fl_size];
	FL.flash_exe_buf = (void *) &flash_execution_buf[0];
	USB_Flash_init(&FL, 1);
	(flash *)newfp = &FL;
	
	if(len < 1 || (startoffset + len) > TB_FLASH_SIZE) {
		#ifndef HIMEM
		logException(99,(const char *)"Attempted to write beyond flash boundary",0);
		#endif
		return;
	}
	
	__asm__("irq off");
	__asm__("fiq off");

	
	newfp->pflash = (unsigned int *)TB_SERIAL_NUMBER_ADDR;
	
	if(startoffset == 0) {
		if(newfp->Flash_type == MX_MID) {	// MX memory, erase 1 4k chunk at 0x37000
			newfp->erasesector(newfp);
		} else { // SST memory, erase 2 2k chunks
			newfp->erasesector(newfp);
			newfp->pflash = (unsigned int *)TB_SERIAL_NUMBER_ADDR + 0x800;
			newfp->erasesector(newfp);
			newfp->pflash = (unsigned int *)TB_SERIAL_NUMBER_ADDR;
		}
	}
	
	for(i=0; i<len; i++) {
		int j = i + startoffset;
		(*newfp->writeword)(newfp, TB_SERIAL_NUMBER_ADDR + j, bufp[i]);
	}

	__asm__("irq on");	
	__asm__("fiq on");
}
コード例 #24
0
ファイル: startup.c プロジェクト: billev/literacybridge
static char * addTextToSystemHeap (char *line) {
	APP_IRAM static char systemHeap [SYSTEM_HEAP_SIZE];
	APP_IRAM static char *cursorSystemHeap = systemHeap;
	int length;
	char *startingHeap, *lineCursor;
	
	while (isspace(*line) && *line != 0)
		line++;
	lineCursor = strchr(line,0); 
	while (isspace(*(lineCursor-1)) && lineCursor >= line)
		lineCursor--;
	*lineCursor = 0;
	length = (lineCursor - line + 1);
	startingHeap = cursorSystemHeap;
	cursorSystemHeap = startingHeap + length;
	if (cursorSystemHeap-systemHeap >= SYSTEM_HEAP_SIZE) {
		logString(line,ASAP);
		logException(15,0,USB_MODE); //todo:system heap is full
	}
	strcpy(startingHeap,line);
	return startingHeap;
}
コード例 #25
0
void EJApp::loadScriptAtPath(NSString * path)
{

    NSString * script = NSString::createWithContentsOfFile(pathForResource(path)->getCString());

    if( !script ) {
        NSLOG("Error: Can't Find Script %s", path->getCString() );
        return;
    }

    NSLOG("Loading Script: %s", path->getCString() );

    JSStringRef scriptJS = JSStringCreateWithUTF8CString(script->getCString());
    JSStringRef pathJS = JSStringCreateWithUTF8CString(path->getCString());

    JSValueRef exception = NULL;
    JSEvaluateScript( jsGlobalContext, scriptJS, NULL, pathJS, 0, &exception );
    logException(exception, jsGlobalContext);

    JSStringRelease( scriptJS );
    JSStringRelease( pathJS );

}
コード例 #26
0
ファイル: exception.cpp プロジェクト: fabienchaix/simgrid
static void handler()
{
  // Avoid doing crazy things if we get an uncaught exception inside
  // an uncaught exception
  static std::atomic_flag lock = ATOMIC_FLAG_INIT;
  if (lock.test_and_set()) {
    XBT_ERROR("Multiple uncaught exceptions");
    std::abort();
  }

  // Get the current backtrace and exception
  auto e = std::current_exception();
  auto bt = backtrace();
  try {
    std::rethrow_exception(e);
  }

  // We manage C++ exception ourselves
  catch (std::exception& e) {
    logException(xbt_log_priority_critical, "Uncaught exception", e);
    showBacktrace(bt);
    std::abort();
  }

  // We don't know how to manage other exceptions
  catch (...) {
    // If there was another handler let's delegate to it
    if (previous_terminate_handler)
      previous_terminate_handler();
    else {
      XBT_ERROR("Unknown uncaught exception");
      showBacktrace(bt);
      std::abort();
    }
  }

}
コード例 #27
0
ファイル: startup.c プロジェクト: billev/literacybridge
void startUp(void) {
	char buffer[200];
	char strCounts[20];
	int key;
	
	SetSystemClockRate(MAX_CLOCK_SPEED); // to speed up initial startup -- set CLOCK_RATE later

	setDefaults();
	setLED(LED_RED,FALSE);  // red light can be left on after reprog restart
	setLED(LED_GREEN,TRUE);  // red light can be left on after reprog restart
	
	//to stop user from wondering if power is on and possibly cycling too quickly,
	playDing();  // it is important to play a sound immediately 
	
	key = keyCheck(1);  // long keycheck 
	
	// voltage checks in SystemIntoUSB.c
	if (key == KEY_STAR || key == KEY_MINUS) {
		// allows USB device mode no matter what is on memory card
		Snd_Stop();
		SystemIntoUDisk(1);	
		loadConfigFile();
		processInbox();
		resetSystem();
	} else if (key == KEY_PLUS) {
		// outbox mode: copy outbox files to connecting device
		loadConfigFile();
		copyOutbox();
		resetSystem();
	}	
	
	// check for new firmware first, but don't flash if voltage is low
	if(V_MIN_SDWRITE_VOLTAGE <= vCur_1) {
		check_new_sd_flash();
	}
	
	if (loadConfigFile() == -1) // config.txt file not found
		testPCB();	
	if (!SNexists())
		logException(32,(const char *)"no serial number",SHUT_DOWN);		

	SysDisableWaitMode(WAITMODE_CHANNEL_A);
	adjustVolume(NORMAL_VOLUME,FALSE,FALSE);
	adjustSpeed(NORMAL_SPEED,FALSE);
	loadDefaultPackage();
	if (MACRO_FILE)	
		loadMacro();
	loadSystemCounts();
	systemCounts.powerUpNumber++;
	if (systemCounts.powerUpNumber - systemCounts.lastLogErase > MAX_PWR_CYCLES_IN_LOG) {
		systemCounts.lastLogErase = systemCounts.powerUpNumber;
		clearStaleLog();	
	}
#ifndef TB_CAN_WAKE
	resetRTC();  //  reset before saving anything to disk and running macros
#endif	
	saveSystemCounts();
	
	strcpy(buffer,"\x0d\x0a" "---------------------------------------------------\x0d\x0a");
	strcat(buffer,getDeviceSN(1));
	strcpy(strCounts,(char *)" counts:S");
	longToDecimalString(systemCounts.powerUpNumber, strCounts+9, 4); 
	strcat(strCounts,(char *)"P");
	longToDecimalString(systemCounts.packageNumber, strCounts+14, 4); 
	strcat(strCounts,(char *)"R");
	longToDecimalString(systemCounts.revdPkgNumber, strCounts+19, 4);
	strcat(buffer,strCounts); 
	strcat(buffer,"\x0d\x0a" "CYCLE "); //cycle number
	longToDecimalString(systemCounts.powerUpNumber,(char *)(buffer+strlen(buffer)),4);
	strcat(buffer,(const char *)" - version " VERSION);
	logString(buffer,BUFFER);
#ifdef TB_CAN_WAKE
	logRTC();  
#endif
	loadPackage(PKG_SYS,BOOT_PACKAGE);	
	SetSystemClockRate(CLOCK_RATE); // either set in config file or the default 48 MHz set at beginning of startUp()
	mainLoop();
}
コード例 #28
0
ファイル: startup.c プロジェクト: billev/literacybridge
int loadConfigFile(void) {
	int ret, handle;
	char *name, *value;
	char buffer[READ_LENGTH+1];
	int attempt, goodPass;
	const int MAX_RETRIES = 3;

	ret = 0;	
	buffer[READ_LENGTH] = '\0'; //prevents readLine from searching for \n past buffer
	
	for (attempt = 0,goodPass = 0;attempt < MAX_RETRIES && !goodPass;attempt++) {
		goodPass = 1;
		LOG_FILE = 0; //default in case no logging location in config file (turns logging off)
		MACRO_FILE = 0; // default case if no MACRO_FILE listed
		handle = tbOpen((unsigned long)(CONFIG_FILE),O_RDONLY);
		if (handle == -1) {
			ret = -1;
			logString((char *)"CONFIG_FILE NOT FOUND",BUFFER); //NOTE:can't be logged if log file comes from config file
		}
		getLine(-1,0);  // reset in case at end from prior use
		while (goodPass && nextNameValuePair(handle, buffer, ':', &name, &value)) {
			if (!value)
				continue;
			// test there is a new line and that it isn't a comment (starting with "//")
			if (*name == '/' && *(name+1) == '/')
				continue; // move to next line
			if (!goodString(name,0) || !goodString(value,0)) { 
				goodPass = 0;
				logException(14,0,0);
				break; //out of while,but continue with for loop
			}
			if (!strcmp(name,(char *)"KEY_PLAY")) KEY_PLAY=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_LEFT")) KEY_LEFT=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_RIGHT")) KEY_RIGHT=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_UP")) KEY_UP=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_DOWN")) KEY_DOWN=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_SELECT")) KEY_SELECT=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_STAR")) KEY_STAR=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_HOME")) KEY_HOME=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_PLUS")) KEY_PLUS=strToInt(value);
				else if (!strcmp(name,(char *)"KEY_MINUS")) KEY_MINUS=strToInt(value);			
				else if (!strcmp(name,(char *)"LED_GREEN")) LED_GREEN=strToInt(value);
				else if (!strcmp(name,(char *)"LED_RED")) LED_RED=strToInt(value);
				else if (!strcmp(name,(char *)"MAX_SPEED")) MAX_SPEED=strToInt(value);
				else if (!strcmp(name,(char *)"NORMAL_SPEED")) NORMAL_SPEED=strToInt(value);
				else if (!strcmp(name,(char *)"MAX_VOLUME")) MAX_VOLUME=strToInt(value);
				else if (!strcmp(name,(char *)"NORMAL_VOLUME")) NORMAL_VOLUME=strToInt(value);
				else if (!strcmp(name,(char *)"SPEED_INCREMENT")) SPEED_INCREMENT=strToInt(value);
				else if (!strcmp(name,(char *)"VOLUME_INCREMENT")) VOLUME_INCREMENT=strToInt(value);
				else if (!strcmp(name,(char *)"BOOT_PACKAGE")) BOOT_PACKAGE=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"SYSTEM_PATH")) SYSTEM_PATH=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"USER_PATH")) USER_PATH=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"LIST_PATH")) LIST_PATH=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"INBOX_PATH")) INBOX_PATH=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"OUTBOX_PATH")) OUTBOX_PATH=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"NEW_PKG_SUBDIR")) NEW_PKG_SUBDIR=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"SYS_UPDATE_SUBDIR")) SYS_UPDATE_SUBDIR=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"LOG_FILE")) LOG_FILE=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"LIST_MASTER")) LIST_MASTER=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"MAX_PWR_CYCLES_IN_LOG")) MAX_PWR_CYCLES_IN_LOG=strToInt(value);
				else if (!strcmp(name,(char *)"SYSTEM_VARIABLE_FILE")) SYSTEM_VARIABLE_FILE=addTextToSystemHeap(value);
				// can we make the following prefixes be single-byte chars? 
				// it would make it easier to check list items starts with CUSTOM_PKG_PREFIX
				else if (!strcmp(name,(char *)"PKG_NUM_PREFIX")) PKG_NUM_PREFIX=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"LIST_NUM_PREFIX")) LIST_NUM_PREFIX=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"CUSTOM_PKG_PREFIX")) CUSTOM_PKG_PREFIX=addTextToSystemHeap(value);				
				else if (!strcmp(name,(char *)"AUDIO_FILE_EXT")) AUDIO_FILE_EXT=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"DEFAULT_TIME_PRECISION")) DEFAULT_TIME_PRECISION=strToInt(value);
				else if (!strcmp(name,(char *)"DEFAULT_REWIND")) DEFAULT_REWIND=strToInt(value);
				else if (!strcmp(name,(char *)"INSERT_SOUND_REWIND_MS")) INSERT_SOUND_REWIND_MS=strToInt(value);
				else if (!strcmp(name,(char *)"SPEAK_SOUND_FILE_IDX")) SPEAK_SOUND_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"REC_PAUSED_FILE_IDX")) REC_PAUSED_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"POST_REC_FILE_IDX")) POST_REC_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"INACTIVITY_SOUND_FILE_IDX")) INACTIVITY_SOUND_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"ERROR_SOUND_FILE_IDX")) ERROR_SOUND_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"EMPTY_LIST_FILE_IDX")) EMPTY_LIST_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"DELETED_FILE_IDX")) DELETED_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"PRE_COPY_FILE_IDX")) PRE_COPY_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"POST_COPY_FILE_IDX")) POST_COPY_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"POST_PLAY_FILE_IDX")) POST_PLAY_FILE_IDX=strToInt(value);				
				else if (!strcmp(name,(char *)"HYPERLINK_SOUND_FILE_IDX")) HYPERLINK_SOUND_FILE_IDX=strToInt(value);
				else if (!strcmp(name,(char *)"BLOCK_START_LEADER")) BLOCK_START_LEADER=strToInt(value);
				else if (!strcmp(name,(char *)"BLOCK_END_LEADER")) BLOCK_END_LEADER=strToInt(value);
				else if (!strcmp(name,(char *)"BIT_RATE")) BIT_RATE=strToLong(value);
				else if (!strcmp(name,(char *)"GREEN_LED_WHEN_PLAYING")) GREEN_LED_WHEN_PLAYING=strToInt(value);
				else if (!strcmp(name,(char *)"INACTIVITY_SECONDS")) INACTIVITY_SECONDS=strToInt(value);
				else if (!strcmp(name,(char *)"MIC_GAIN_NORMAL")) MIC_GAIN_NORMAL=strToInt(value);
				else if (!strcmp(name,(char *)"MIC_GAIN_HEADPHONE")) MIC_GAIN_HEADPHONE=strToInt(value);
				else if (!strcmp(name,(char *)"CONTROL_TEMPLATE")) CONTROL_TEMPLATE=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"MACRO_FILE")) MACRO_FILE=addTextToSystemHeap(value);
				else if (!strcmp(name,(char *)"VOLTAGE_SAMPLE_FREQ_SEC")) VOLTAGE_SAMPLE_FREQ_SEC=strToInt(value);
				else if (!strcmp(name,(char *)"USB_CLIENT_POLL_INTERVAL")) USB_CLIENT_POLL_INTERVAL=strToInt(value);
				else if (!strcmp(name,(char *)"LOG_WARNINGS")) LOG_WARNINGS=strToInt(value);
				else if (!strcmp(name,(char *)"LOG_KEYS")) LOG_KEYS=strToInt(value);
				else if (!strcmp(name,(char *)"CLOCK_RATE")) CLOCK_RATE = strToInt(value);
		}
	}
	if (!goodPass) {
		ret = -1;
		logString((char *)"CONFIG_FILE NOT READ CORRECTLY",BUFFER);	  //logException(14,0,USB_MODE); 		
	}
	close(handle);
	LED_ALL = LED_GREEN | LED_RED;
	if (*(LOG_FILE+1) != ':')
		LOG_FILE = 0; // should be == "a://....." otherwise, logging is turned off
	return ret;
}
コード例 #29
0
ファイル: audio.c プロジェクト: billev/literacybridge
static int recordAudio(char *pkgName, char *cursor, BOOL relatedToLastPlayed) {
	unsigned long getAvailRand();
	int handle, ret = -1;
	char temp[PATH_LENGTH];
	char filepath[PATH_LENGTH];
    char unique_id[PATH_LENGTH], digits[16];
	long start, end, prev;
	CtnrFile *file;
	int key;
	int low_voltage, v;
	unsigned long wrk1;
	char *cp, *cp1, category[9];
	long metadata_start;
	long metadata_numfields;
	unsigned long rand1;
	long previousBitRate;
	
	previousBitRate = BIT_RATE; // set to return BIT_RATE to orig value at end of fct, in case BIT_RATE is changed below
	rand1 = getAvailRand();		// pick random value to identify this recording
    unsignedlongToHexString((long)rand1,digits);
	if (strcmp(cursor,TRANSLATE_TEMP_DIR) == 0) {
		strcpy(filepath,LANGUAGES_PATH);
		strcat(filepath,TRANSLATE_TEMP_DIR);
		strcat(filepath,"/");
		strcat(filepath,pkgName);
		strcat(filepath,AUDIO_FILE_EXT);
		BIT_RATE = MAX_BIT_RATE;
	} else if (*cursor == SYS_MSG_CHAR) {
		strcpy(filepath,LANGUAGES_PATH);
		catLangDir(filepath);	
//		strcat(filepath,pkgName);
		cp1 = filepath + strlen(filepath);	// save this position
		strcat(filepath, (char *)TB_SERIAL_NUMBER_ADDR + CONST_TB_SERIAL_PREFIX_LEN);
		strcat(filepath, "_");
		strcat(filepath, digits);
		strcpy(pkgName, cp1);      // change pkgName to show file name we used
		strcat(filepath,AUDIO_FILE_EXT);
	} else {
		strcpy(filepath,USER_PATH);
//		strcat(filepath,pkgName);
		cp1 = filepath + strlen(filepath);	// save this position
		strcat(filepath, (char *)TB_SERIAL_NUMBER_ADDR + CONST_TB_SERIAL_PREFIX_LEN);
		strcat(filepath, "_");
		strcat(filepath, digits);
		strcpy(pkgName, cp1);      // change pkgName to show file name we used
		strcat(filepath,AUDIO_FILE_EXT);
	}
		
	file = getTempFileFromName(cursor,0);
	if (strcmp(cursor,TRANSLATE_TEMP_DIR) != 0)
		insertSound(file,NULL,FALSE);
	if (context.keystroke == KEY_HOME) {
		//let context.keystroke  propogate through
		ret = 1; // signals no audio recorded but not necessary to throw exception
	} else {
		start = getRTCinSeconds();
		strcpy(temp,"\x0d\x0a");
		longToDecimalString(start,temp+2,8);
		strcat(temp,(const char *)": RECORD ");
		LBstrncat(temp,pkgName,60);
		LBstrncat(temp," -> ",60);
		LBstrncat(temp,cursor,60);	
		logString(temp,BUFFER);
		// play record prompt message unless running translation app or if a button was just pressed 
		if (!context.keystroke && strcmp(cursor,TRANSLATE_TEMP_DIR) != 0) {
			insertSound(&pkgSystem.files[SPEAK_SOUND_FILE_IDX],NULL,FALSE);
			if (context.keystroke == KEY_HOME)
				ret = 1; // signals no audio recorded but not necessary to throw exception
			else
				context.keystroke = 0;
		} else
			context.keystroke = 0; // reset context.keystroke so a second action doesn't take place
		stop();
		start = getRTCinSeconds();
		prev = end = start;
		//asm("INT OFF"); // to prevent recordings with bad blocks
	}
	// only open file to record if HOME was not pressed and only proceed if file opens correctly 
	if (ret != 1 && ((handle = tbOpen((LPSTR)filepath,O_CREAT|O_RDWR)) != -1)) {
		setLED(LED_RED,TRUE);
		playBip();
		turnAmpOff();
		Snd_SACM_RecFAT(handle, C_CODEC_AUDIO1800, BIT_RATE);
		low_voltage = 0;
		do {
			end = getRTCinSeconds();	
			if (0==(end%2) && (prev != end)) { // blink LED every three seconds
				prev = end;
				setLED(LED_RED,FALSE);
				wait (100);
				setLED(LED_RED,TRUE);
				while((v = getCurVoltageSample()) == 0xffff);
				if(vCur_1 < V_MIN_SDWRITE_VOLTAGE) {
					low_voltage = 1;
				}
			}
			key = keyCheck(0);
			if (key == KEY_PLAY) { // pause  TODO: this key press to pause shouldn't be hard coded
				pause();
				setLED(LED_RED,FALSE);
				// insertSound(&pkgSystem.files[REC_PAUSED_FILE_IDX],NULL,FALSE); 	---need to play this from memory				
				do
					key = keyCheck(0);
					// TODO: NEED CODE HERE TO SAFELY SAVE FILE WHEN PAUSED FOR EXTENDED PERIOD OF TIME (maybe 60 min?)
					// checkInactivity(key);   --- this would cause recording to be lost in just 30-300 sec inactivity
				while (!key);
				if (key == KEY_PLAY) {
					setLED(LED_RED,TRUE);
					resume();
				}
			}
		} while ((!key || (key == KEY_PLAY)) && (low_voltage == 0)); // TODO: this key press to stop shouldn't be hard coded
//		while ((end - start) < 3) { // must be at least 2.0 second recording
//			end = getRTCinSeconds();			
//		}
		SACM_Stop();		//Snd_Stop(); // no need to call stop() and flush the log
		setLED(LED_RED,FALSE);
		turnAmpOn();
		playDing();
		//lseek(handle, 6, SEEK_SET );			//Seek to the start of the file input
		//write(handle,(LPSTR)header<<1,6);
 
// write meta data to end of file
               
        close(handle);	// rhm:  I think its already closed, I can't write to it here
        
        systemCounts.recordingNumber++;  // bump global recording number
        saveSystemCounts();
        
       	handle = tbOpen((LPSTR)filepath,O_RDWR);
       	
       	metadata_start = lseek(handle, 0L, SEEK_END);  // offset to start of metadata
        metadata_numfields = 0L; // init num fields
       
		wrk1 = METADATA_VERSION;
        writeLE32(handle, wrk1, CURRENT_POS);  //meta data version = 1
        writeLE32(handle, metadata_numfields, CURRENT_POS); // 4 byte for num fields
        
        strcpy(unique_id, (char *)TB_SERIAL_NUMBER_ADDR + CONST_TB_SERIAL_PREFIX_LEN); // skip serial number prefix
        strcat(unique_id, "_");    
       	strcat(unique_id, digits);
            
        addField(handle, DC_IDENTIFIER, unique_id, 1);       
        metadata_numfields += 1;
        
        addField(handle, DTB_REVISION, (char *)"0", 1);       
        metadata_numfields += 1;
        
        strcpy(unique_id, (char *)TB_SERIAL_NUMBER_ADDR + CONST_TB_SERIAL_PREFIX_LEN); // skip serial number prefix


        strcat(unique_id, "_");    
        longToDecimalString(systemCounts.powerUpNumber,(char *)temp,4);
        strcat(unique_id, temp);
        strcat(unique_id, "_"); 
        longToDecimalString(systemCounts.recordingNumber,(char *)temp,4);
        strcat(unique_id, temp);
        strcat(unique_id, "_"); 
        strncat(unique_id, digits, 8);
        addField(handle, DC_TITLE, unique_id, 1);       
        metadata_numfields += 1;

//        strcpy(unique_id, (char *)TB_SERIAL_NUMBER_ADDR + CONST_TB_SERIAL_PREFIX_LEN); // skip serial number prefix
//        strcat(unique_id, "_");       
//		strcat(unique_id, digits);		
//        addField(handle, DC_AUDIO_ITEM_ID, unique_id, 1);       
//        metadata_numfields += 1;

        if (pkgSystem.idxLanguageCode != -1) {
			strcpy(unique_id,&pkgSystem.strHeapStack[pkgSystem.idxLanguageCode]);
			addField(handle, DC_LANGUAGE, unique_id, 1);
			metadata_numfields += 1;   
        }
         
        cp = cursor;
        if(cp != NULL) {
			if(*cp >= '0' && *cp <= '9') {
	        	strcpy(category, cursor);
			} else if(!strncmp(cp, "AGR", 3))
	        	strcpy(category, CAT_AGRICULTURE);
        	else if(!strncmp(cp, "HEA", 3))
        		strcpy(category, CAT_HEALTH);
        	else if(!strncmp(cp, "EDU", 3))
        		strcpy(category, CAT_EDUCATION);
        	else if(!strncmp(cp, "STO", 3))
        		strcpy(category, CAT_STORIES);
        	else if(!strncmp(cp, "BUS", 3))
        		strcpy(category, CAT_BUSINESS);
        	else if(!strncmp(cp, "GOV", 3))
        		strcpy(category, CAT_GOVERNANCE);
        	else if(!strncmp(cp, "MUS", 3))
        		strcpy(category, CAT_MUSIC);
        	else if(!strncmp(cp, "DIA", 3))
        		strcpy(category, CAT_DIARY);
        	else
        		strcpy(category, CAT_OTHER);
		}
        
       	addField(handle, DC_CATEGORY, category, 1);
    	metadata_numfields += 1;
        	       
        if(relatedToLastPlayed) {
        	strcpy(unique_id, STAT_FN); // DC_IDENTIFIER read at open
        	if(strlen(unique_id)) {
        		addField(handle,DC_RELATION,unique_id,1);
        		metadata_numfields += 1;
        	}
        }

        strcpy(unique_id, (char *)TB_SERIAL_NUMBER_ADDR + CONST_TB_SERIAL_PREFIX_LEN); // skip serial number prefix
 		addField(handle,DC_SOURCE,unique_id,1);       
        metadata_numfields += 1;

		longToDecimalString(systemCounts.powerUpNumber,(char *)temp,4);
		addField(handle,DC_DATE,temp,1);
        metadata_numfields += 1;
        
        // add other fields here
        
        writeLE32(handle, metadata_numfields, metadata_start + 4); // write correct num meta data fields
        
		close(handle);
// done with meta data
		//asm("INT FIQ, IRQ"); -- see INT OFF above used once to prevent corrupted recordings (now possibly handled by SD_Initial() after USB Device mode
        
//		*P_WatchDog_Ctrl &= ~0x8000; // clear bit 15 to disable
	
		if (strcmp(cursor,TRANSLATE_TEMP_DIR) != 0) {
			insertSound(&pkgSystem.files[POST_REC_FILE_IDX],NULL,FALSE);
			if (!context.keystroke)
				insertSound(file,NULL,FALSE);  // replay subject
		}
		// Leaving this out now, because I believe it gets created when it is first played if non-existent.  
		// The delay of having it in recordAudio is too long.
		// createStatsFile(rand1); 
								// Assumes no name collision from using a 32-bit semi-random number
								// Checking all past names was causing a long delay, but maybe (TODO:) we can
								// add in a check if the open() fails and then generate a new number in that unlikely case

		strcpy(temp,"TIME RECORDED (secs): ");
		longToDecimalString((long)end-start,temp+strlen(temp),4);
		strcat(temp,"\x0d\x0a");
		logString(temp,BUFFER);
		//logString(temp,ASAP);

		ret = 0;  // used to set this based on fileExists() check, but too slow
	} else if (ret == -1) {
		logException(16, filepath,RESET);  //can't open file for new recording
	}
	BIT_RATE = previousBitRate;
	return ret;
}	
コード例 #30
0
ファイル: MainWindow.cpp プロジェクト: Vadim-Stupakov/hooq
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, m_editor(0)
, m_hooqPlayInjector(new PlatformInjector(this))
, m_hooqRecordInjector(new PlatformInjector(this))
, m_hooqLogger(0)
, m_hooqPlayer(0)
, m_interpreter(new Interpreter(this))
, m_server(new QTcpServer(this))
, m_testModel(new TestModel(this))
, m_testRunning(false)
, m_testResultsWindow(new TestResultsDialog(this))
, m_xmlDump(0)
{
	if(!m_interpreter->haveRequiredQtScriptExtensions())
	{
		QMessageBox::critical(0, tr("Couldn't load required QtScript extensions"), tr("Please install qtscriptgenerator for the version of Qt you are currently using. While recording in Hooq may work, playback will not be possible."));
	}

	if(!m_server->listen(QHostAddress::LocalHost, Hooq::Communication::serverPort()))
	{
		QMessageBox::critical(0, tr("Couldn't listen for applications"), tr("Hooq couldn't start listening for applications; you're probably running two copies of Hooq. Hooq will not work."));
	}

	m_editor = new ScriptEditor(m_interpreter->engine());
	setupUi(this);
	setStatusBar(0);

	populateTestSets();

	m_testList->setModel(m_testModel);
	PushButtonDelegate* delegate = new PushButtonDelegate(m_testList, this);
	delegate->addButton(1, QApplication::style()->standardIcon(QStyle::SP_MediaPlay));
	delegate->addButton(2, QApplication::style()->standardIcon(QStyle::SP_FileIcon));
	m_testList->setItemDelegate(delegate);

	m_testList->header()->setResizeMode(0, QHeaderView::Stretch);
	m_testList->header()->setResizeMode(1, QHeaderView::Fixed);
	m_testList->header()->setResizeMode(2, QHeaderView::Fixed);
	m_testList->header()->setStretchLastSection(false);

	m_contextMenu = new QMenu(this);
	m_contextMenu->addAction(tr("Run"), this, SLOT(runCurrentTest()));
	m_contextMenu->addAction(tr("Edit"), this, SLOT(editCurrentTest()));
	m_contextMenu->addSeparator();
	m_contextMenu->addAction(tr("Delete"), this, SLOT(deleteCurrentTest()));

	setTestSet(m_testSetEdit->currentText());

	m_testList->setContextMenuPolicy(Qt::CustomContextMenu);

	QObject* deleteObserver = new ModelIndexKeyEventObserver(QKeySequence::Delete, m_testList);

	connect(
		deleteObserver,
		SIGNAL(released(QModelIndex)),
		SLOT(deleteCurrentTest())
	);

	connect(
		m_testList,
		SIGNAL(customContextMenuRequested(QPoint)),
		SLOT(showTestContextMenu(QPoint))
	);

	connect(
		m_testSetEdit,
		SIGNAL(activated(QString)),
		SLOT(setTestSet(QString))
	);

	connect(
		m_runAllButton,
		SIGNAL(clicked()),
		SLOT(runAllTests())
	);

	connect(
		m_addTestButton,
		SIGNAL(clicked()),
		SLOT(startRecording())
	);

	connect(
		m_hooqRecordInjector,
		SIGNAL(finished(int)),
		SLOT(finishRecording())
	);

	connect(
		m_testNameEdit,
		SIGNAL(textChanged(QString)),
		SLOT(updateActionStates())
	);

	connect(
		m_addTestSetButton,
		SIGNAL(clicked()),
		SLOT(addTestSet())
	);

	connect(
		m_newTestSet,
		SIGNAL(triggered()),
		SLOT(addTestSet())
	);
	connect(
		m_editTestSet,
		SIGNAL(triggered()),
		SLOT(editTestSet())
	);
	connect(
		m_removeTestSet,
		SIGNAL(triggered()),
		SLOT(removeTestSet())
	);
	connect(
		m_exportSet,
		SIGNAL(triggered()),
		SLOT(exportCurrentSet())
	);
	connect(
		m_importSet,
		SIGNAL(triggered()),
		SLOT(importTestSet())
	);
	connect(
		m_editor,
		SIGNAL(pickRequested()),
		m_interpreter,
		SLOT(pickObject())
	);
	connect(
		m_editor,
		SIGNAL(startRequested()),
		SLOT(runEditorTest())
	);

	connect(
		m_editor,
		SIGNAL(exceptionThrown(QString, QStringList)),
		SLOT(logException(QString, QStringList))
	);

	connect(
		m_interpreter,
		SIGNAL(objectPicked(ObjectInformation)),
		m_editor,
		SLOT(objectPicked(ObjectInformation))
	);
	connect(
		m_interpreter,
		SIGNAL(objectNotFound(QString)),
		m_editor,
		SLOT(objectNotFound(QString))
	);
	connect(
		m_interpreter,
		SIGNAL(executionFailed(int)),
		m_editor,
		SLOT(handleApplicationExit(int))
	);

	connect(
		m_interpreter,
		SIGNAL(finished()),
		SLOT(testFinished())
	);
	connect(
		m_interpreter,
		SIGNAL(startApplicationAndAttach()),
		SLOT(startApplication())
	);

	connect(
		m_quit,
		SIGNAL(triggered()),
		qApp,
		SLOT(quit())
	);

	connect(
		m_aboutQt,
		SIGNAL(triggered()),
		qApp,
		SLOT(aboutQt())
	);

	connect(
		m_about,
		SIGNAL(triggered()),
		SLOT(about())
	);

	ColumnClickMapper* mapper = new ColumnClickMapper(m_testList);
	mapper->addMapping(1, this, SLOT(runTestScript(QModelIndex)));
	mapper->addMapping(2, this, SLOT(editTestScript(QModelIndex)));

	updateActionStates();
}