Ejemplo n.º 1
0
void
main(void)
{
	unsigned char  test[] = "123456789";
	printf("Size of short is %i\n", sizeof(short));
	printf("Size of int is %i\n", sizeof(int));
	printf("Size of long is %i\n", sizeof(long));

	/*
	 * Print the check value for the selected CRC algorithm.
	 */
	printf("The check value for the %s standard is 0x%X\n", CRC_NAME, CHECK_VALUE);
	
	/*
	 * Compute the CRC of the test message, slowly.
	 */
	printf("The crcSlow() of \"123456789\" is 0x%X\n", crcSlow(test, strlen(test)));
	
	/*
	 * Compute the CRC of the test message, more efficiently.
	 */
	crcInit();
	printf("The crcFast() of \"123456789\" is 0x%X\n", crcFast(test, strlen(test)));
	int testing = crcFast(test, strlen(test));
	int *helping = &testing;
	printf("Test string with crc %s%c%c%c%c\n", test, helping[0],helping[1], helping[2],helping[3]);
	
	//How to add the characters to the packet
	/*packet[1020] = helping[0];
	packet[1021] = helping[1];
	packet[1022] = helping[2];
	packet[1023] = helping[3];*/

}   /* main() */
Ejemplo n.º 2
0
int main(int argc, char*argv[])
{
  unsigned char retval = 0;
  long i=0;
  struct timeval tf, ti;
  unsigned long timems=0;

  if (argc != 2)
  {
      printf("Usage: hw2 message\n");
      return 1;
  }

  gettimeofday(&ti, NULL);
  for (i = 0; i < TRIALS; i++)
  {
      crcInit();
      retval = crcFast(argv[1], strlen(argv[1]));
  }
  gettimeofday(&tf, NULL);

  timems=(tf.tv_sec*1000+tf.tv_usec/1000) - (ti.tv_sec*1000+tf.tv_usec/1000);
  printf("CRC:%X\n", retval);
printf("Iterations: %lu, TotalTime : %lu ms, IterTime : %lu us\n", i, timems, (1000*timems)/TRIALS);
  return 0;
}
Ejemplo n.º 3
0
///////////////////////////////////////////////////////////////////////////////
// CalcHash
///////////////////////////////////////////////////////////////////////////////
uint32 eError::CalcHash( const char* name )
{
    CRC_INFO crc;
    crcInit( crc );
    crcUpdate( crc, (const uint8*)name, strlen( name ) );
    crcFinit( crc );
    return crc.crc;
}
Ejemplo n.º 4
0
uint32_t NormalUart::Send(uint32_t *Data, uint32_t Length)
{
	SendHeader(&mH);
	for (uint32_t i = 0; i < Length; ++i){
		SendInt(&mH,Data[i]);
	}
	ChangeEndian(Data,Length*sizeof(uint32_t));
	crcInit();
	crc checksum = crcFast((unsigned char*)Data,Length*sizeof(uint32_t));
	//ChangeEndian(&checksum,1);
	SendInt(&mH,checksum);
	return Length;
}
Ejemplo n.º 5
0
/*
=====================
	loadBotResource
=====================
*/
static botEntry_t *loadBotResource( TCHAR *szPath ) {
	BYTE buff[BLOCK_SIZE];
	HANDLE hFile;
	DWORD tmp;
	//TCHAR szName[NAMESIZE];
	botEntry_t *botEntry;
	
	
	hFile = N_FOpenR( szPath );
	if( hFile == INVALID_HANDLE_VALUE ) {
		return NULL;
	}
	
	//increase map count
	//
	k_system.cBots++;

	//increase memory
	//
	if( k_system.pBots ) {
		k_system.pBots = N_Realloc( k_system.pBots, sizeof(botEntry_t)*k_system.cBots );
	}
	else {
		k_system.pBots = N_Malloc( sizeof(botEntry_t)*k_system.cBots );
	}

	//obtain map entry pointer
	//
	botEntry = &( k_system.pBots[ k_system.cBots - 1 ] );
	
	//calculate CRC
	//
	crcInit( &(botEntry->fe.dwCRC) );
	while( ReadFile( hFile, buff, BLOCK_SIZE, &tmp, NULL ) ) {
		if( tmp == 0 ) {
			break;
		}
		crcUpdate( &(botEntry->fe.dwCRC), buff, tmp );
	}
	crcFinish( &(botEntry->fe.dwCRC ) );
	
	N_FClose( hFile );

	//get bot name
	//
	//getBotName( szPath, botEntry->bot.name );
	
	return botEntry;
}
Ejemplo n.º 6
0
/*
=====================
	loadMapResource
=====================
*/
static mapEntry_t * loadMapResource( TCHAR *szPath ) {
	BYTE buff[BLOCK_SIZE];
	HANDLE hFile;
	DWORD tmp;
	mapEntry_t *mapEntry;
	
	
	hFile = N_FOpenR( szPath );
	if( hFile == INVALID_HANDLE_VALUE ) {
		return NULL;
	}
	
	//increase map count
	//
	k_system.cMaps++;

	//increase memory
	//
	if( k_system.pMaps ) {
		k_system.pMaps = N_Realloc( k_system.pMaps, sizeof( mapEntry_t ) * k_system.cMaps );
	}
	else {
		k_system.pMaps = N_Malloc( sizeof( mapEntry_t ) * k_system.cMaps );
	}

	//obtain map entry pointer
	//
	mapEntry = &( k_system.pMaps[ k_system.cMaps - 1 ] );
	
	//calculate CRC
	//
	crcInit( &(mapEntry->fe.dwCRC) );
	while( ReadFile( hFile, buff, BLOCK_SIZE, &tmp, NULL ) ) {
		if( tmp == 0 ) {
			break;
		}
		crcUpdate( &(mapEntry->fe.dwCRC), buff, tmp );
	}
	crcFinish( &(mapEntry->fe.dwCRC ) );
	
	N_FClose( hFile );
	
	//get map name
	//
	//getMapName( szPath, mapEntry->map.name );
	
	return mapEntry;
}
Ejemplo n.º 7
0
bool CryptoTest::Run()
{
	CCrypto Crypto;

	Crypto.Initialize("Key.txt");

	TCHAR szJuhang[] = _T("juhang");

	Crypto.ProcessEncryption(szJuhang, sizeof(szJuhang));
	Crypto.ProcessDecryption(szJuhang, sizeof(szJuhang));

	///////////////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////
	unsigned char  test[] = "123456789";

	/*
	* Print the check value for the selected CRC algorithm.
	*/
	printf("The check value for the %s standard is 0x%X\n", CRC_NAME, CHECK_VALUE);

	/*
	* Compute the CRC of the test message, slowly.
	*/
	printf("The crcSlow() of \"123456789\" is 0x%X\n", crcSlow(test, 9));

	/*
	* Compute the CRC of the test message, more efficiently.
	*/
	crcInit();
	printf("The crcFast() of \"123456789\" is 0x%X\n", crcFast(test, 9));

	///////////////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////
	Cmd5Capi md5Capi;


	std::wstring out, in;
	in = L"JUHANG";

	out = md5Capi.Digest(in);

	return true;

}
Ejemplo n.º 8
0
int main(int argc, char *argv[]) {  
  /* User info */
  user_parameters *parameters;
  parameter_model pmodel;

  /* Generate input data */
  init_data();
  init_verify();
  crcInit();
  init_parameter_model(&pmodel);

  /* Initialize the alarm that will signal every DELTA microsecons */
  /* DELTA is defined in def.h */
  uplink_alarm_init(DELTA);

  #pragma omp parallel num_threads(TASK_THREADS)
  {
     #pragma omp master
     {
       /* Main loop that submits a subframe for execution every DELTA microseconds */
       while (1) {
         /* Generate parameters for next frame */
         parameters = uplink_parameters(&pmodel);

         /* Wait until next subframe should be computed */
         uplink_wait_for_alarm();

         /* Compute users */
         if (parameters) {
           while(parameters->first) {
               userS* task_users = parameters->first;
               #pragma omp task firstprivate(task_users)
                 uplink_user_cilk(task_users);
               parameters->first = parameters->first->next;
           }
           free(parameters);
         }
       }
    }
  }

  return 0;
}
Ejemplo n.º 9
0
void
main(void)
{
	unsigned char  test[] = "123456789";


	/*
	 * Print the check value for the selected CRC algorithm.
	 */
	printf("The check value for the %s standard is 0x%X\n", CRC_NAME, CHECK_VALUE);
	
	/*
	 * Compute the CRC of the test message, slowly.
	 */
	printf("The crcSlow() of \"123456789\" is 0x%X\n", crcSlow(test, strlen(test)));
	
	/*
	 * Compute the CRC of the test message, more efficiently.
	 */
	crcInit();
	printf("The crcFast() of \"123456789\" is 0x%X\n", crcFast(test, strlen(test)));

}   /* main() */
Ejemplo n.º 10
0
MV_Controller::MV_Controller(MainWindow *parent)
{
    ModelBLE::deleteInstance();
    try {
        this->model = ModelBLE::getInstance(this);
    }
    catch(int e) {
        qWarning() << "A bluetooth device needs to be connected." << endl;
        throw e;
    }

    this->view = parent;

    crcInit();

    // Transfer the 'newCapSenseValues' signal to the view
    connect(this->model, SIGNAL(newCapSenseValuesReceived(sensors)), this, SLOT(newValuesReceivedFromModel_slot(sensors)));
    connect(this, SIGNAL(newValuesReceivedFromModel_signal(sensors)), parent, SLOT(newValuesReceived_updateView(sensors)));

    // Transfer the 'statusUpdate' signal to the view
    connect(this->model, SIGNAL(statusUpdate(Status)), this, SLOT(statusUpdateFromModel_slot(Status)));
    connect(this, SIGNAL(statusUpdateFromModel_signal(Status)), parent, SLOT(statusUpdate_updateView(Status)));
}
Ejemplo n.º 11
0
void src_init(cfg_t *source_cfg) {
	char *stream = cfg_getstr(source_cfg, "stream");
	if (!stream) return;
	crcInit();

	if (!strncmp("udp://", stream, 6)) {
		double chunk_duration = cfg_getfloat(source_cfg,"chunk_duration");
		info("Initializing SOURCE mode: tuning to stream %s, sampling rate is "
			"%.2lf Hz", stream, (double)1.0/chunk_duration);
		init_source_ul(stream, chunk_duration);
	} else if (!strncmp("http://", stream, 7)) {
		char addr[128];
		int port,i;

		if (sscanf(stream, "http://%127[^:]:%i", addr, &port) != 2) 
			fatal("Unable to parse source specification %s", stream);

		if (ulChunkReceiverSetup(addr, port)) 
			fatal("Unable to start the HTTP receiver to http://%s:%d", 
					addr, port);
	} else fatal("Unable to parse stream specification %s", stream);
	napaSchedulePeriodic(NULL, 1/60.0, periodicPublishSrcLag, NULL);
}
Ejemplo n.º 12
0
void PreMain() {
	systemDatInit();
	systemInit();
	testabilityDatInit();
	stdlibparseutilsDatInit();
	stdlibstrutilsDatInit();
	stdlibtimesDatInit();
	stdlibposixDatInit();
	stdlibosDatInit();
	listsDatInit();
	stdlibhashesDatInit();
	stdlibstrtabsDatInit();
	stdlibstreamsDatInit();
	stdlibosprocDatInit();
	stdlibmathDatInit();
	stdlibsetsDatInit();
	optionsDatInit();
	stdlibtablesDatInit();
	platformDatInit();
	crcDatInit();
	ropesDatInit();
	stdlibunsignedDatInit();
	stdlibsocketsDatInit();
	msgsDatInit();
	nversionDatInit();
	identsDatInit();
	condsymsDatInit();
	extccompDatInit();
	wordrecgDatInit();
	babelcmdDatInit();
	commandsDatInit();
	llstreamDatInit();
	nimlexbaseDatInit();
	lexerDatInit();
	nimconfDatInit();
	stdlibintsetsDatInit();
	idgenDatInit();
	astDatInit();
	rodutilsDatInit();
	astalgoDatInit();
	parserDatInit();
	pbracesDatInit();
	rendererDatInit();
	filtersDatInit();
	filter_tmplDatInit();
	syntaxesDatInit();
	treesDatInit();
	typesDatInit();
	stdlibmemfilesDatInit();
	rodreadDatInit();
	magicsysDatInit();
	bitsetsDatInit();
	nimsetsDatInit();
	passesDatInit();
	treetabDatInit();
	vmdefDatInit();
	semdataDatInit();
	lookupsDatInit();
	importerDatInit();
	rodwriteDatInit();
	saturateDatInit();
	semfoldDatInit();
	procfindDatInit();
	pragmasDatInit();
	semtypinstDatInit();
	parampatternsDatInit();
	stdliblexbaseDatInit();
	stdlibunicodeDatInit();
	stdlibjsonDatInit();
	docutilsrstastDatInit();
	docutilsrstDatInit();
	docutilshighliteDatInit();
	docutilsrstgenDatInit();
	guardsDatInit();
	sempass2DatInit();
	stdlibmacrosDatInit();
	stdlibxmltreeDatInit();
	stdlibcookiesDatInit();
	stdlibcgiDatInit();
	typesrendererDatInit();
	docgenDatInit();
	stdlibalgorithmDatInit();
	stdlibsequtilsDatInit();
	prettyDatInit();
	sigmatchDatInit();
	cgmethDatInit();
	loweringsDatInit();
	lambdaliftingDatInit();
	transfDatInit();
	vmgenDatInit();
	vmdepsDatInit();
	evaltemplDatInit();
	vmDatInit();
	aliasesDatInit();
	patternsDatInit();
	semmacrosanityDatInit();
	semDatInit();
	ccgutilsDatInit();
	cgendataDatInit();
	ccgmergeDatInit();
	cgenDatInit();
	jsgenDatInit();
	passauxDatInit();
	dependsDatInit();
	docgen2DatInit();
	stdlibparseoptDatInit();
	serviceDatInit();
	modulesDatInit();
	mainDatInit();
	nimrodDatInit();
	initStackBottom();
	testabilityInit();
	stdlibparseutilsInit();
	stdlibstrutilsInit();
	stdlibtimesInit();
	stdlibposixInit();
	stdlibosInit();
	listsInit();
	stdlibhashesInit();
	stdlibstrtabsInit();
	stdlibstreamsInit();
	stdlibosprocInit();
	stdlibmathInit();
	stdlibsetsInit();
	optionsInit();
	stdlibtablesInit();
	platformInit();
	crcInit();
	ropesInit();
	stdlibunsignedInit();
	stdlibsocketsInit();
	msgsInit();
	nversionInit();
	identsInit();
	condsymsInit();
	extccompInit();
	wordrecgInit();
	babelcmdInit();
	commandsInit();
	llstreamInit();
	nimlexbaseInit();
	lexerInit();
	nimconfInit();
	stdlibintsetsInit();
	idgenInit();
	astInit();
	rodutilsInit();
	astalgoInit();
	parserInit();
	pbracesInit();
	rendererInit();
	filtersInit();
	filter_tmplInit();
	syntaxesInit();
	treesInit();
	typesInit();
	stdlibmemfilesInit();
	rodreadInit();
	magicsysInit();
	bitsetsInit();
	nimsetsInit();
	passesInit();
	treetabInit();
	vmdefInit();
	semdataInit();
	lookupsInit();
	importerInit();
	rodwriteInit();
	saturateInit();
	semfoldInit();
	procfindInit();
	pragmasInit();
	semtypinstInit();
	parampatternsInit();
	stdliblexbaseInit();
	stdlibunicodeInit();
	stdlibjsonInit();
	docutilsrstastInit();
	docutilsrstInit();
	docutilshighliteInit();
	docutilsrstgenInit();
	guardsInit();
	sempass2Init();
	stdlibmacrosInit();
	stdlibxmltreeInit();
	stdlibcookiesInit();
	stdlibcgiInit();
	typesrendererInit();
	docgenInit();
	stdlibalgorithmInit();
	stdlibsequtilsInit();
	prettyInit();
	sigmatchInit();
	cgmethInit();
	loweringsInit();
	lambdaliftingInit();
	transfInit();
	vmgenInit();
	vmdepsInit();
	evaltemplInit();
	vmInit();
	aliasesInit();
	patternsInit();
	semmacrosanityInit();
	semInit();
	ccgutilsInit();
	cgendataInit();
	ccgmergeInit();
	cgenInit();
	jsgenInit();
	passauxInit();
	dependsInit();
	docgen2Init();
	stdlibparseoptInit();
	serviceInit();
	modulesInit();
	mainInit();
}
Ejemplo n.º 13
0
int main( int argc, char **argv )
{
    int opt = 0;
    std::string rootFolder;    // Folder where VSCP files & folders will be located
    std::string strcfgfile;    // Points to XML configuration file
    
    openlog( "vscpd", LOG_PERROR | LOG_PID | LOG_CONS, LOG_DAEMON );

    fprintf( stderr, "Prepare to start vscpd...\n" );
    
    // Ignore return value from defunct processes d
    signal( SIGCHLD, SIG_IGN );

    crcInit(); 

    rootFolder = "/srv/vscp/";
    strcfgfile = "/etc/vscp/vscpd.conf";
    gbStopDaemon = false;

    while ( ( opt = getopt(argc, argv, "d:c:f:k:hgs") ) != -1 ) {        

        switch (opt) {
 
        case 's':
            fprintf( stderr, "Stay Hungry. Stay Foolish.\n" );
            fprintf( stderr, "I will ***NOT*** run as daemon! "
                             "(ctrl+c to terminate)\n\n");
            gbDontRunAsDaemon = true;
            break;

        case 'c':
            strcfgfile = optarg;
            break;

        case 'r':
            rootFolder = optarg;
            break;

        case 'k':
            systemKey = optarg;
            break;

        case 'd':
            gnDebugLevel = atoi( optarg );
            break;

        case 'g':
            copyleft();
            exit(0);
            break;

        default:
        case 'h':
            help( argv[0] );
            exit( -1 );
        }

    }

    fprintf( stderr, "[vscpd] Configfile = %s\n",
                (const char *)strcfgfile.c_str() );
    
    if ( !init( strcfgfile, rootFolder ) ) {
        syslog( LOG_CRIT, "[vscpd] Failed to configure. Terminating.\n");
        fprintf( stderr, "VSCPD: Failed to configure. Terminating.\n");
        exit( -1 );
    }

    closelog(); // Close syslog

    fprintf( stderr, "VSCPD: Bye, bye.\n");
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 14
0
/*------------------------------------------------------------------------------
-- FUNCTION:    InitTerminal
--
-- DATE:        Oct 19, 2010
--
-- REVISIONS:   Dec 02, 2010 - Added a crc initialization
--
-- DESIGNER:    Dean Morin
--
-- PROGRAMMER:  Dean Morin
--
-- INTERFACE:   VOID InitTerminal(HWND hWnd)
--                          hWnd- the handle to the window
--
-- RETURNS:     VOID.
--
-- NOTES:
--              Initializes the terminal to its default state.
------------------------------------------------------------------------------*/
VOID InitTerminal(HWND hWnd) {
    PWNDDATA    pwd         = {0};
    HDC         hdc         = {0};
    COMMCONFIG  cc          = {0};
    TEXTMETRIC  tm          = {0};
    PAINTSTRUCT ps          = {0};
    RECT        windowRect  = {0};
    RECT        clientRect  = {0};
    UINT        i           = 0;
    UINT        j           = 0;
    LONG        lxDiff      = 0;
    LONG        lyDiff      = 0;

    // create PWNDATA struct and stor it as the window extra
    if ((pwd = (PWNDDATA) calloc(1, sizeof(WNDDATA))) == 0) {
        DISPLAY_ERROR("Error allocating memory for WNDDATA structure");
    }
    pwd->lpszCommName   = TEXT("COM3");
    SetWindowLongPtr(hWnd, 0, (LONG_PTR) pwd);

    // get text attributes and store values into the window extra struct
    hdc = GetDC(hWnd);
    pwd->displayBuf.hFont = (HFONT) GetStockObject(OEM_FIXED_FONT);
    SelectObject(hdc, pwd->displayBuf.hFont);
    GetTextMetrics(hdc, &tm);
    ReleaseDC(hWnd, hdc);

    // initialize variables in PWDDATA struct to defaults
    DL_STATE				= -1;
    pwd->bConnected         = FALSE;
    CHAR_WIDTH              = tm.tmAveCharWidth;
    CHAR_HEIGHT             = tm.tmHeight;
    CUR_FG_COLOR            = 7;
    WINDOW_BOTTOM           = LINES_PER_SCRN -1;
    pwd->wordWrap			= FALSE;
    pwd->PTFBuffHead        = NULL;
    pwd->PTFBuffTail        = NULL;
    pwd->FTPBuffHead        = NULL;
    pwd->FTPBuffTail        = NULL;
    pwd->FTPQueueSize       = 0;
    pwd->PTFQueueSize       = 0;
    pwd->NumOfFrames        = 0;
    pwd->NumOfReads         = 0;
    pwd->pReadBufHead       = NULL;
    pwd->pReadBufTail       = NULL;
    pwd->bDebug             = FALSE;

    // initialize a "blank" display buffer
    for (i = 0; i < LINES_PER_SCRN; i++) {
        pwd->displayBuf.rows[i] = (PLINE) calloc(1, sizeof(LINE));
        for (j = 0; j < CHARS_PER_LINE; j++) {
            CHARACTER(j, i).character   = ' ';
            CHARACTER(j, i).fgColor     = 7;
        }
    }

    // set the window size based off of the font size
    GetWindowRect(hWnd, &windowRect);
    GetClientRect(hWnd, &clientRect);

    lxDiff  = (windowRect.right  - windowRect.left) 
            - (clientRect.right  - clientRect.left);
    lyDiff  = (windowRect.bottom - windowRect.top)
            - (clientRect.bottom - clientRect.top);

    MoveWindow(hWnd,
               windowRect.left, windowRect.top,
               CHAR_WIDTH  * CHARS_PER_LINE + PADDING * 2 + lxDiff,
               CHAR_HEIGHT * LINES_PER_SCRN + PADDING * 2 + lyDiff,
               TRUE);

    //create tables for crc
    crcInit();

    //print out headers for terminal
    MakeColumns(hWnd);

    
}
Ejemplo n.º 15
0
/*! \brief Main function. Execution starts here.
 */
int main(void)
{
	//uint8_t i = 0;
	uint16_t temp_crc;
	irq_initialize_vectors();
	cpu_irq_enable();

	// Initialize the sleep manager
	sleepmgr_init();

	sysclk_init();
	board_init();

	ui_init();
	ui_powerdown();

	memories_initialization();

	// Initialize LCD
	et024006_Init( FOSC0, FOSC0 );
	gpio_set_gpio_pin(ET024006DHU_BL_PIN);
	
	//et024006_PrintConsole("Welcome Eric", BLACK, -1);
	//clear_lcd
	et024006_DrawFilledRect(1, 1, ET024006_WIDTH, ET024006_HEIGHT, BLACK);
	
	// Initialize AES module
	aes_task();

	// Start TC
	tc_task();

	Init_System_Status();
	// Initialize crc for fast calculations
	crcInit();
		
	// Read the stored values from the flash
	Load_stored_values();
	//i = sizeof(stored_values_t) - sizeof(uint16_t);
	temp_crc = crcFast((const uint8_t *)&Stored_values_ram, 192);
	//temp_crc1 = crcFast("123456789", 9);
	if (temp_crc == Stored_values_ram.block_crc)
	{
		stSystemStatus.stored_value_crc_status = 1;
	}
	//Stored_values_ram.salt[5] = 0x4d68ab23;
	
	//Update_stored_values();
	// Start USB stack to authorize VBus monitoring
	udc_start();

	if (!udc_include_vbus_monitoring()) {
		// VBUS monitoring is not available on this product
		// thereby VBUS has to be considered as present
		main_vbus_action(true);
	}

	// The main loop manages only the power mode
	// because the USB management is done by interrupt
	while (true)
	{
		if (main_b_msc_enable)
		{
			if (!udi_msc_process_trans())
			{
				sleepmgr_enter_sleep();
			}
		}
		else
		{
			sleepmgr_enter_sleep();
		}
		//main_process_mode();
	}
}
Ejemplo n.º 16
0
AppState::AppState(CWinApp *pApp) : _resourceMap(*this)
{
    _pApp = pApp;
    _audioProcessing = std::make_unique<AudioProcessingSettings>();
    // Place all significant initialization in InitInstance
    _pPicTemplate = nullptr;
    _fScaleTracingImages = TRUE;
    _fDontShowTraceScaleWarning = FALSE;
    _fUseAutoSuggest = FALSE;
    _fAllowBraceSyntax = FALSE;
    _fAutoLoadGame = TRUE;
    _fDupeNewCels = TRUE;
    _fUseBoxEgo = FALSE;
    _fShowPolyDotted = FALSE;
    _fBrowseInfo = TRUE;
    _fScriptNav = TRUE;
    _fCodeCompletion = TRUE;
    _fHoverTips = TRUE;
    _fPlayCompileErrorSound = TRUE;
    _fUseOriginalAspectRatioDefault = FALSE;
    _fUseOriginalAspectRatioCached = false;
    _fShowTabs = FALSE;
    _fShowToolTips = TRUE;
    _fSaveScriptsBeforeRun = TRUE;
    _fTrackHeaderFiles = TRUE;
    _fCompileDirtyScriptsBeforeRun = TRUE;

    _pVocabTemplate = nullptr;

    _cxFakeEgo = 30;
    _cyFakeEgo = 48;

    _audioProcessing->TrimLeftMS = 100;
    _audioProcessing->TrimRightMS = 100;
    _audioProcessing->AutoGain = TRUE;
    _audioProcessing->DetectStartEnd = TRUE;
    _audioProcessing->Compression = TRUE;
    _audioProcessing->AudioDither = FALSE;

    _audioProcessing->Noise.AttackTimeMS = 15;
    _audioProcessing->Noise.ReleaseTimeMS = 50;
    _audioProcessing->Noise.HoldTimeMS = 50;
    _audioProcessing->Noise.OpenThresholdDB = -22;
    _audioProcessing->Noise.CloseThresholdDB = -28;

    _ptFakeEgo = CPoint(160, 120);
    _fObserveControlLines = false;
    _fObservePolygons = false;
    _fDontCheckPic = FALSE;
    _pidlFolder = nullptr;
    _fNoGdiPlus = FALSE;

    _pResourceDoc = nullptr;
    _shownType = ResourceType::View;

    _pACThread = nullptr;
    _pACThread = new AutoCompleteThread2();
    _pHoverTipScheduler = std::make_unique<BackgroundScheduler<HoverTipPayload, HoverTipResponse>>();

    crcInit();

    // Prepare g_egaColorsExtended
    for (int i = 0; i < 256; i += 16)
    {
        CopyMemory(g_egaColorsExtended + i, g_egaColors, sizeof(g_egaColors));
    }
    // Fake EGA palette for when it's needed.
    memcpy(g_egaDummyPalette.Colors, g_egaColors, sizeof(g_egaColors));

	// Gamma-corrected mixed ega colors
	for (int i = 0; i < 256; i++)
	{
		int iA = i / 16;
		int iB = i % 16;
		g_egaColorsMixed[i] = _CombineGamma(g_egaColors[iA], g_egaColors[iB]);
	}

    // Prepare g_vgaPaletteMapping
    for (int i = 0; i < 256; i++)
    {
        g_vgaPaletteMapping[i] = (uint8_t)i;
    }

    // A greenish palette for continuous priority
    for (int i = 0; i < 256; i++)
    {
        g_continuousPriorityColors[i] = RGBQUADFromCOLORREF(RGB(0, i, 0));
    }

    CelDataClipboardFormat = RegisterClipboardFormat("SCICompanionVGACelData");
    ViewAttributesClipboardFormat = RegisterClipboardFormat("SCICompanionViewAttributes");
    PaletteColorsClipboardFormat = RegisterClipboardFormat("SCICompanionPaletteColors");
    EGAPaletteColorsClipboardFormat = RegisterClipboardFormat("SCICompanionEGAPaletteColors");
    LoadSyntaxHighlightingColors();

    InitializeSyntaxParsers();
}
Ejemplo n.º 17
0
/**
 * @brief	Inizializzazione del livello Datalink.
 * @param	none.

 * @retval	Esito inizializzazione, che pu� assumere uno dei seguenti valori:
 * 			@arg	DL_OK:	inizializzazione avvenuta con successo;
 * 			@arg	DL_ERROR:	errore qualsiasi durante l'inizializzazione, nessuna risorsa allocata.
 */
DL_Status dlInit()
{

	calLogInt(CAL_LOG_INFORMATIONAL,"dlInit","FUN-CALLED",0);
	memset(&dlInterfaceReady, DL_READY, GET_MAX_INTERFACES());
	memset(&seqNumberMap, AVAILABLE, DL_SEQ_NUMBER_MAP_SIZE);
	memset(&numRetryMap, 0, DL_SEQ_NUMBER_MAP_SIZE);
	memset(&tickMap, 0, DL_SEQ_NUMBER_MAP_SIZE);
	memset(&dlTempInterfaceStatus, CAL_NO, GET_MAX_INTERFACES());
	memset(&dlInterfaceAttachStatus, CAL_NO, GET_MAX_INTERFACES());


	//receivedPacketCounter = 0;
	seqNumberCounter = 0;
	lastUsedSeqNumber = 0;
	DL_Status status = DL_OK;

	//Initialize all dlQueues
	dlRxQueue = initFrameQueue();
	if (dlRxQueue == NULL)
		status = DL_ERROR;

	//If the status isn't OK doesn't initialize the Notification Queue
	if (status == DL_OK)
	{
		dlNotificationQueue = initFrameQueue();
		if (dlNotificationQueue == NULL)
		{
			deInitFrameQueue(dlRxQueue);
			status = DL_ERROR;
		}
	}

	int i = 0;
	while (i < GET_MAX_INTERFACES() && status == DL_OK)
	{
		dlTxQueue[i] = initFrameQueue();
		if (dlTxQueue[i] != NULL)
			++i;
		else
			status = DL_ERROR;
	}

	//If something is gone wrong perform a rollback
	if (status == DL_ERROR)
	{

		calLogInt(CAL_LOG_ERROR,"dlInit","INIT-ERROR",0);
		//In case of problems perform a deInit "rollback" operation
		int j = 0;
		while (j < i)
			deInitFrameQueue(dlTxQueue[j++]);

		deInitFrameQueue(dlRxQueue);
		deInitFrameQueue(dlNotificationQueue);
	}

#if (CAL_USE_OS == 0)
	timerScanCounter=0;
	CAL_TIM_Init(DL_TIMEOUT_PERIOD_MS);
	CAL_TIM_Start();
#endif
	//Enable CRC
	crcInit();
	return status;
}
Ejemplo n.º 18
0
int main(int argc, char **argv) 
{
    int i;
    struct stat statInfo;
    struct sigaction act;
    extern void *Usb0IpWatchTask(void *);

    UNUSED_PARAM(argc);
    UNUSED_PARAM(argv);
    memset(&gEqptDescriptors, 0, sizeof(ReconnEqptDescriptors));

#ifndef __SIMULATION__
    initReconnCrashHandlers();
#endif
    memset(&act, 0, sizeof(act));
    act.sa_flags = SA_SIGINFO;
    act.sa_sigaction = reconnCleanUp;
    signal(SIGPIPE, SIG_IGN);
    sigaction(SIGTERM, &act, NULL);

    i = sizeof(reconnThreadIds);
    for(i = 0; i < RECONN_MAX_NUM_CLIENTS + RECONN_NUM_SYS_TASKS; i++)
    {
        reconnThreadIds[i] = -1;
    }
    for(i = 0; i < (RECONN_MAX_NUM_CLIENTS); i++)
    { 
        activeClientsList[i] = 0;
    }


    // If there is an upgrade in progress then start a task that will sleep for 10 minutes then run.
    // If the task wakes up, then the upgraded application has not crashed and so the new image 
    // is probably OK.
    if(stat(UPGRADE_INPROGRESS_FILE_NAME, &statInfo) == 0)
    {
        if( pthread_create(&(reconnThreadIds[RECONN_UPGRADE_CHECK_TASK]), NULL, upgradeCheckTask, (void *)0) < 0)
        {
            reconnDebugPrint("%s: Could not start upgradeCheckTask, %d %s\n", __FUNCTION__, errno, strerror(errno));
        }
        unlink(UPGRADE_INPROGRESS_FILE_NAME);
    }

    /*
     * Initialize the AVCOM crc routine. The crc is used for spectrum analyzer upgrade and firmware 
     * version intefaces.
     */
    crcInit();

    PeripheralInit();
//#ifdef DEBUG_CONNECT
    reconnDebugPrint("      gEqptDescriptors->powerMeterFd = %d\n", gEqptDescriptors.powerMeterFd);
    reconnDebugPrint("      gEqptDescriptors->dmmFd = %d\n", gEqptDescriptors.dmmFd);
    reconnDebugPrint("      gEqptDescriptors->analyzerFd = %d\n", gEqptDescriptors.analyzerFd);
//#endif
#ifndef __SIMULATION__
    //dmmDiags();
    dmmLoadSavedConfig();
#endif
    //
    // Startup debug menus
    //
    registerClientDebugMenu();
    registerFuelGaugeDebugMenu();
    registerSystemDebugMenu();
    registerDmmDebugMenu();
    registerSocketDebugMenu();
    registerRemoteMonDebugMenu();
    registerReconnMsgsMenu();

    if(pthread_create(&(reconnThreadIds[RECONN_MASTER_SOCKET_TASK]), NULL, insertedMasterTransmitTask, (void *)0) < 0)
    {
        reconnDebugPrint("%s: Could not start openInsertedMasterSocket %d %s\n", __FUNCTION__, errno, strerror(errno));
    }


    /*  Start up the command processing */
    if( pthread_create(&(reconnThreadIds[RECONN_EQPT_TASK]), NULL, reconnEqptTask, (void *)0) < 0)
    {
        reconnDebugPrint("%s: Could not start reconnEqptTask %d %s\n", __FUNCTION__, errno, strerror(errno));
    }
    else
    {
        if(pthread_create(&(reconnThreadIds[RECONN_PWR_MGMT_TASK]), NULL, reconnPwrMgmtTask, (void  *)&gEqptDescriptors) < 0)
        {
            reconnDebugPrint("%s: Could not start reconnPwrMgmtTask, %d %s\n", __FUNCTION__, errno, strerror(errno));
        }
        else if(pthread_create(&(reconnThreadIds[RECONN_EQPT_RSP_TASK]), NULL, reconnGetEqptResponseTask,(void *)&gEqptDescriptors) < 0)
        {
            reconnDebugPrint("%s: Could not start reconnGetEqptResponseTask, %d %s\n", __FUNCTION__, errno, strerror(errno));
        }
        else if(pthread_create(&(reconnThreadIds[RECONN_BATTERY_MONITOR_TASK]), NULL, reconnBatteryMonTask, (void *) 0 ) < 0)
        {
            reconnDebugPrint("%s: Could not start reconnBatteryMonTask, %d %s\n", __FUNCTION__, errno, strerror(errno));
        }
        else if(pthread_create(&(reconnThreadIds[RECONN_DEBUG_MENU_TASK]), NULL, debugMenuTask, (void *) 0 ) < 0)
        {
            reconnDebugPrint("%s: Could not start debugMenuTask, %d %s\n", __FUNCTION__, errno, strerror(errno));
        }
        else if(pthread_create(&(reconnThreadIds[RECONN_POWER_METER_TASK]), NULL, powerMeterPresenceTask, (void *) &gEqptDescriptors) < 0)
        {
            reconnDebugPrint("%s: Could not start powerMeterPresenceTask, %d %s\n", __FUNCTION__, errno, strerror(errno));
        }
//#ifndef __SIMULATION__
        else if(pthread_create(&(reconnThreadIds[RECONN_DMM_SAVE_CONFIG_TASK]), NULL, dmmSaveConfigTask, (void *) 0 ) < 0)
        {
            reconnDebugPrint("%s: Could not start dmmSaveConfigTask, %d %s\n", __FUNCTION__, errno, strerror(errno));
        }
//#endif
        else
        {
#ifndef __SIMULATION__
            //
            // Need to register with libiphoned. This callback will signal when
            // the iphone has been inserted into the reconn toolkit.
            //
            libiphoned_register_presence_change_callback(reconnMasterIphone);
            libiphoned_register_rx_callback(insertedMasterRead, RECONN_RSP_PAYLOAD_SIZE);

            //
            // Now start libiphoned. This is a daemon which does all of the "heavy lifting" for the 
            // front panel iPhone. The daemon does the reading, writing, insertion, and iPhone extraction.
            //
            reconnDebugPrint("%s: Calling libiphoned_start()\n", __FUNCTION__);
            if(libiphoned_start() == -1)
            {
                reconnDebugPrint("%s: libiphoned_start() failed\n", __FUNCTION__);
                exit(0);
            }

            /*
             * Now that the embedded software is up and running, stop the power LED from flashing.
             */
            if(reconnGpioAction(POWER_LED_GPIO, ENABLE, NULL) != RECONN_SUCCESS)
            {
                reconnDebugPrint("%s: reconnGpioAction(POWER_LED_GPIO, ENABLE, NULL) failed.\n", __FUNCTION__);
            }
#endif
            wifiStartConnectionTask();
#ifndef __SIMULATION__
            if(pthread_create(&(reconnThreadIds[RECONN_IP_WATCH_TASK]), NULL, Usb0IpWatchTask, (void *)0) < 0)
            
            {
                reconnDebugPrint("%s: Could not start Usb0IpWatchTask, %d %s\n", __FUNCTION__, errno, strerror(errno));
            }
#endif
        }
    }

    /*
     * See if we should start the task that accepts Wifi connections.
     */ 
    pthread_join(reconnThreadIds[RECONN_POWER_METER_TASK], NULL);
    reconnDebugPrint("%s: Exiting *******************\n",__FUNCTION__);
    exit (0);
}
Ejemplo n.º 19
0
/*
=====================
	endReplaySystem
=====================
*/
BOOL endReplaySystem() {
	repHeader_t repHeader = {0};
	HANDLE hFile;
	HANDLE hTmpFile;
	BYTE buff[BLOCK_SIZE];
	TCHAR szRepTmpPath[MAX_PATH];
	TCHAR szRepPath[MAX_PATH];
	TCHAR szTmpPath[MAX_PATH];
	TCHAR szArchPath[MAX_PATH];
	DWORD crc;
	DWORD tmp, tmp2;
	int i;

	//this will make replay hold till
	//the end.
	//
	addReplayFrame( NOMOVE, LEFTGAME );

	N_FClose( ghRepFile );


	//create paths
	//
	N_Sprintf( szTmpPath, MAX_PATH, TEXT( "%s\\demos\\~demo.rep" ),
		kcfTable[VAR_BASE].v.s );
	N_Sprintf( szRepPath, MAX_PATH, TEXT( "%s\\demos\\demo_%i.rep" ),
		kcfTable[VAR_BASE].v.s, gSuffix );
	N_Sprintf( szRepTmpPath, MAX_PATH, TEXT( "%s.tmp" ), szRepPath );
	N_Sprintf( szArchPath, MAX_PATH, TEXT( "%s.z" ), szRepTmpPath);

	//create temporary replay file
	//
	hFile = N_FOpenC( szRepTmpPath );
	if( hFile == INVALID_HANDLE_VALUE ) {
		return FALSE;
	}
	
	//write figure data
	//
	N_FWrite( hFile, &k_replayFigSize, sizeof(k_replayFigSize) );
	for( i=0; i<k_replayFigSize; i++ ) {
		N_FWrite( hFile, &(k_replayFig[i].type), sizeof(k_replayFig[i].type) );
		N_FWrite( hFile, &(k_replayFig[i].state), sizeof(k_replayFig[i].state) );
	}
	
	//copy replay data from temporary file
	//
	hTmpFile = N_FOpenR( szTmpPath );
	while( ReadFile( hTmpFile, buff, BLOCK_SIZE, &tmp, NULL ) ) {
		if( tmp == 0 ) {
			break;
		}
		WriteFile( hFile, buff, tmp, &tmp2, NULL );
	}
	
	N_FClose( hTmpFile );
	N_FClose( hFile );

	
	//create replay file
	//
	hFile = N_FOpenC( szRepPath );
	
	//write header
	//
	repHeader.header = REPLAYHEADER;
	repHeader.gametype = gGameType;
	if( gMapID >= 0 ) {
		repHeader.mapCRC = k_system.pMaps[gMapID].fe.dwCRC;
	}
	else {
		repHeader.mapCRC = 0;
	}
	N_FWrite( hFile, &repHeader, sizeof(repHeader) );
		
	crcInit( &crc );
	
	//compress
	//
	if( beginCompress( szRepTmpPath ) ) {
		hTmpFile = N_FOpenR( szArchPath );
		
		while( ReadFile( hTmpFile, buff, BLOCK_SIZE, &tmp, NULL ) ) {
			if( tmp == 0 ) {
				break;
			}
			WriteFile( hFile, buff, tmp, &tmp2, NULL );
			crcUpdate( &crc, buff, tmp );
		}
		
		N_FClose( hTmpFile );
		endCompress( szRepTmpPath );
	}
	
	crcFinish( &crc );
	
	//write CRC
	//
	repHeader.crc = crc;
	N_FSeek( hFile, 0, FILE_BEGIN );
	N_FWrite( hFile, &repHeader, sizeof(repHeader) );


	//clean-up
	//

	N_FClose( hFile );
	
	//delete ~demo.rep and demo_%i.rep.tmp
	//
	DeleteFile( szTmpPath );
	DeleteFile( szRepTmpPath );
	
	N_Free( k_replayFig );
	k_replayFig = NULL;
	k_replayFigSize = 0;
	k_replayFigID = 0;

	gFrameTime = 0;
	gGameType = GNO;
	gMapID = -1;
	
	k_system.flags &= ~SF_RECORDING;
	
	return TRUE;
}
Ejemplo n.º 20
0
/*
=====================
	playDemo
=====================
*/
BOOL playDemo() {
	repHeader_t repHeader = {0};
	HANDLE hFile = INVALID_HANDLE_VALUE;
	TCHAR szRepPath[MAX_PATH];
	DWORD crc;
	DWORD tmp;
	BYTE buff[BLOCK_SIZE];
	BOOL bRes;
	int mapID;
	int i;
	
	__try {
		bRes = FALSE;
		
		//get replay file path
		//
		if( !GetLoadPath( k_system.hwnd, TEXT( "(*.rep)\0*.rep" ), TEXT( "*.rep" ), szRepPath ) ) {
			__leave;
		}

		//open replay file
		//
		hFile = N_FOpenR( szRepPath );
		if( hFile == INVALID_HANDLE_VALUE ) {
			__leave;
		}
		
		//read header
		//
		N_FRead( hFile, &repHeader, sizeof(repHeader) );
		
		//check header
		//
		if( repHeader.header != REPLAYHEADER ) {
			__leave;
		}
		
		//check map availability
		//
		if( (repHeader.mapCRC != 0) && !seeMapID( repHeader.mapCRC, NULL ) ) {
			__leave;
		}
		
		//check CRC
		//
		crcInit( &crc );
		while( ReadFile( hFile, buff, BLOCK_SIZE, &tmp, NULL ) ) {
			if( tmp == 0 ) {
				break;
			}
			crcUpdate( &crc, buff, tmp );
		}
		crcFinish( &crc );
		if( repHeader.crc != crc ) {
			__leave;
		}

		//restore file position
		//
		N_FSeek( hFile, sizeof(repHeader), FILE_BEGIN );
		
		//end all running games
		//
		endAllGames();

		//decompress replay data
		//		
		if( beginDecompress( szRepPath, sizeof(repHeader), gszTmpPath, NULL ) ) {
		
			ghRepFile = N_FOpenR( gszTmpPath );
			if( ghRepFile == INVALID_HANDLE_VALUE ) {
				__leave;
			}
		
			//read figure data
			//
			N_FRead( ghRepFile, &k_replayFigSize, sizeof(k_replayFigSize) );
			k_replayFig = N_Malloc( k_replayFigSize*sizeof(figure_t) );
			for( i=0; i<k_replayFigSize; i++ ) {
				N_FRead( ghRepFile, &(k_replayFig[i].type), sizeof(k_replayFig[i].type) );
				N_FRead( ghRepFile, &(k_replayFig[i].state), sizeof(k_replayFig[i].state) );
			}
			k_replayFigID = 0;
			
			bRes = TRUE;
		}
	}
	
	__finally {
		
		if( hFile != INVALID_HANDLE_VALUE ) {
			N_FClose( hFile );
		}
	
		//check if failed
		//
		if( bRes == FALSE ) {
			if( k_replayFig ) {
				N_Free( k_replayFig );
				k_replayFig = NULL;
				k_replayFigSize = 0;
			}
		}
	}
	
	//play demo
	//
	if( bRes ) {

		k_system.flags |= SF_DEMOPLAY;
		
		//find map
		//
		if( repHeader.mapCRC == 0 ) {
			k_system.idMap = -1;
		}
		else {
			if( seeMapID( repHeader.mapCRC, &mapID ) ) {
				k_system.idMap = mapID;
			}
			else {
				return FALSE;
			}
		}

		//start the game
		//
		switch( repHeader.gametype ) {
			case GSINGLE:
				singleGameStart();
				break;

			case GVS:
				vsGameStart();
				break;

			default:
				return FALSE;
		}
		
		//schedule frame
		//
		N_FRead( ghRepFile, &gFrame, sizeof(gFrame) );
		pushTimeSlice( TIME_REPLAY_FRAME, gFrame.time, gFrame.time, NULL, REPLAY, FALSE );
		
		N_Message( TEXT( "Replaying: %s" ), szRepPath );
	}
	
	
	return bRes;
}
Ejemplo n.º 21
0
int main(int argc, char **argv)
{
	int arg = 0;
	wxString strcfgfile;

	wxSocketBase::Initialize();
	crcInit();
	/*	
	  unsigned char ttt[ 50 ];
	  for ( int m=0; m<50; m++ ) {
	  ttt[ m ] = m+8;
	  }	
    
	 *((unsigned short *)(ttt + 48 )) = crcFast( ttt, 48 );
	  ttt[ 48 ] = 0x9f; 
	  ttt[ 49 ] = 0x87;
	  printf( "CRC for data = %X\n", crcFast( ttt, 48 ) );
	  printf( "CRC for all = %X\n", crcFast( ttt, 50 ) );
	 */

	wxInitializer initializer;
	if (!::wxInitialize()) {
		fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");

		return -1;
	}
	
	gpobj = new CControlObject();

	//wxStandardPaths *strpath = wxStandardPaths::Get();
	//strcfgFile =  _("/etc/vscp/vscpd.conf" );     // default config path
	strcfgfile = wxStandardPaths::Get().GetConfigDir() + _("/vscp/vscpd.conf");
	gbStopDaemon = false;


	VSCPApp theApp;
	//IMPLEMENT_APP(theApp)

	while ((arg = getopt(argc, argv, "d:c:hgs")) != EOF) {

		switch (arg) {

		case 's':
			wxPrintf(_("Be hungry, stay foolish my friend!\n"));
			wxPrintf(_("I will ***NOT*** run as daemon! (ctrl+c to terminate)\n"));
			gbDontRunAsDaemon = true;
			break;

		case 'c':
			strcfgfile = wxString(optarg, wxConvUTF8);
			//wxMBConvUTF8 cnv;
			//cnv.MB2WC( strcfgfile, optarg, 10 );
			break;

		case 'd':
			gnDebugLevel = atoi(optarg);
			break;

		case 'g':
			copyleft();
			exit(0);
			break;

		default:
		case 'h':
			help(argv[0]);
			exit(-1);
		}
	}

	wxLogDebug(_("ControlObject: Configfile =") + strcfgfile);
	if ( !theApp.init( strcfgfile ) ) {
		printf("ControlObject: Failed to configure. Terminating.");
		wxLogDebug(_("ControlObject: Failed to configure. Terminating."));
	}
	
	delete gpobj;

}
Ejemplo n.º 22
0
void main(void)
{
    char* input_data = malloc(DATA_SIZE);

    FILE* input_file; 
    input_file = fopen(INPUT_FILE, "r");

    if(input_file == NULL){
        fprintf(stderr, "Failed to open %s\n", INPUT_FILE);
        exit(1);
    }

    int i = 0;

    char buffer[BLOCK_SIZE];
    while(fgets(buffer, BLOCK_SIZE, input_file)){
        strcpy(input_data+i,buffer);
        i = i + BLOCK_SIZE - 1;
    }
    fclose(input_file);

    /*Replace the line field ascii with \0*/
    input_data[strlen(input_data) - 1] = '\0';

    struct stopwatch_t* sw = stopwatch_create();

/*--------------------------------------------------------------------------------------*/
    stopwatch_init();
    stopwatch_start(sw);

    printf("crcSlow() 0x%X  ", crcSlow(input_data, strlen(input_data)));

    stopwatch_stop(sw);   

    printf("  Time: %Lg\n", stopwatch_elapsed(sw));
/*--------------------------------------------------------------------------------------*/

    stopwatch_start(sw);

    size_t input_data_len = strlen(input_data);
    
    int input_blocks = input_data_len / BLOCK_SIZE;
    int extra_blocks = 0;
    if(input_data_len % BLOCK_SIZE != 0)
        extra_blocks = 1;

    int total_blocks = input_blocks + extra_blocks;
    int *result = malloc(total_blocks * sizeof(int));
    
    omp_set_num_threads(16);

    unsigned int ans = 0;

    char* block_data = malloc(input_blocks * (BLOCK_SIZE + 1));
    char* block_addr;

    i = 0;

    #pragma omp parallel  for default(none) shared(input_blocks, input_data, result, block_data) private (i, block_addr)  
    for(i = 0; i < input_blocks; ++i){
        block_addr = block_data + (BLOCK_SIZE + 1) * i;
        strncpy(block_addr, input_data + BLOCK_SIZE * i, BLOCK_SIZE);
        *(block_addr + BLOCK_SIZE) = '\0';
        result[i] = CrcHash(block_addr, BLOCK_SIZE);
    }
    
    int rem = input_data_len % BLOCK_SIZE;

    char* last_block_data = malloc(rem + 1);
    
    if(extra_blocks == 1){
        strncpy(last_block_data, input_data + BLOCK_SIZE * input_blocks, rem);
        *(last_block_data + rem) = '\0';
        result[input_blocks] = CrcHash(last_block_data, rem);
    }

    i=0;
    for(i = 0; i < input_blocks; ++i){
        ans = crc32_combine(ans, result[i], BLOCK_SIZE);
    }
    
    if(extra_blocks == 1)
        ans = crc32_combine(ans, result[i], rem);

    stopwatch_stop(sw);

    printf("Parallel() 0x%X   Time:  %Lg \n",ans, stopwatch_elapsed(sw)); 
/*--------------------------------------------------------------------------------------*/

    crcInit();
    stopwatch_start(sw);
    printf("crcFast() 0x%X  ", crcFast(input_data, strlen(input_data)));
    stopwatch_stop(sw);
    printf("  Time: %Lg\n", stopwatch_elapsed(sw));

    stopwatch_destroy(sw);
/*--------------------------------------------------------------------------------------*/
    stopwatch_start(sw);
    printf("crc_intel() 0x%X  ", CrcHash((const void*)input_data, strlen(input_data)));
    stopwatch_stop(sw);
    printf("  Time: %Lg\n", stopwatch_elapsed(sw));

/*--------------------------------------------------------------------------------------*/
    
    /*Cleanup*/  
    free(last_block_data);
    free(block_data);
    free(input_data);
} 
Ejemplo n.º 23
0
void ctrlUpdate::eventThreadMessage( wxCommandEvent &event )
{
	int write_pointer,checksum16;
	unsigned long intflash_blocksize,max_intflash_blocknumber,extflash_blocksize,max_extflash_blocknumber;
	int block_number;
	int i = event.GetInt();
	int id = i & 0xFFFF;
	int type = (i >> 16) & 0xFFFF;
	CDeviceNode* pNode = m_plistNode->GetNodeByNickName(id);
	wxString strData = event.GetString();
	vscpEvent* pVscp = new vscpEvent;
	getVscpDataFromString( pVscp, strData );

	if(pNode != NULL)
	{
		if(event.GetExtraLong()==0)
		{
			switch(type)
			{
				case VSCP_TYPE_PROTOCOL_ACK_BOOT_LOADER:
					// pVscp->pdata[ 0 ] = 2;	MSB internal flash block size
					// pVscp->pdata[ 1 ] = 2;	MSB spi flash block size
					// pVscp->pdata[ 2 ] = 0;	LSB spi flash block size
					// pVscp->pdata[ 3 ] = 0;	LSB internal flash block size
					// pVscp->pdata[ 4 ] = 1;	MSB internal flash number of block avalaible
					// pVscp->pdata[ 5 ] = 4;	MSB spi flash number of block avalaible
					// pVscp->pdata[ 6 ] = 0;	LSB spi flash number of block avalaible
					// pVscp->pdata[ 7 ] = 0;	LSB internal flash number of block avalaible
					intflash_blocksize = (pVscp->pdata[0] << 8) | pVscp->pdata[3];
					extflash_blocksize = (pVscp->pdata[1] << 8) | pVscp->pdata[2];
					max_intflash_blocknumber = (pVscp->pdata[4] << 8) | pVscp->pdata[7];
					max_extflash_blocknumber = (pVscp->pdata[5] << 8) | pVscp->pdata[6];

					if((intflash_blocksize == BLOCKDATA_SIZE)	&&
				       (extflash_blocksize == BLOCKDATA_SIZE)	&&
					   (max_intflash_blocknumber >= (m_IntFlashBinaryLength/BLOCKDATA_SIZE))&&
					   (max_extflash_blocknumber >= (m_ExtFlashBinaryLength/BLOCKDATA_SIZE))
					  )
					{
						crcInit();
						m_nTotalChecksum = 0;
						m_nCurrentBlockNumber = 0;
						m_nCurrentFlashType = INT_FLASH;	// internal flash
						// attenzione: questo messaggio (VSCP_TYPE_PROTOCOL_ACK_BOOT_LOADER) è l'ultimo arrivato dal 
						// programma user, ora ha preso il controllo il bootloader; è probabile che sia necessario
						// un delay prima di trasmettere il messaggio di "start block transfer"
						wxMilliSleep( 2000 );//wxMilliSleep( 500 );//wxMilliSleep( 200 );
						StartBlockTransferMsg( pNode->GetNickName(), m_nCurrentBlockNumber, m_nCurrentFlashType );
					}
					else
					{
						UpdateError(pNode);
					}

					//::wxGetApp().logMsg ( _("event ack bootloader"), DAEMON_LOGMSG_CRITICAL );
					break;
				case VSCP_TYPE_PROTOCOL_START_BLOCK_ACK:
					// pVscp->pdata[0] MSB block number
					// pVscp->pdata[1] INTERNAL_FLASH/SPI_FLASH
					// pVscp->pdata[2]
					// pVscp->pdata[3] LSB block number
					if(m_nCurrentFlashType == pVscp->pdata[1])
					{
						switch(m_nCurrentFlashType)
						{
							case INT_FLASH:
								DataBlockTransferMsg();
								m_nChecksum = crcFast( &m_pIntFlashBinaryContent[USER_PROGRAM_ADDRESS + m_nCurrentBlockNumber*BLOCKDATA_SIZE], BLOCKDATA_SIZE );//crcFast( &m_pIntFlashBinaryContent[30208], BLOCKDATA_SIZE );//crcFast( &m_pIntFlashBinaryContent[USER_PROGRAM_ADDRESS + m_nCurrentBlockNumber*BLOCKDATA_SIZE], BLOCKDATA_SIZE );
								//m_nTotalChecksum += m_nChecksum;
								break;
							case EXT_FLASH:

								DataBlockTransferMsg();
								m_nChecksum = crcFast( &m_pExtFlashBinaryContent[m_nCurrentBlockNumber*BLOCKDATA_SIZE], BLOCKDATA_SIZE );
								break;
						}
					}
					else
					{
						UpdateError(pNode);
					}
					//::wxGetApp().logMsg ( _("event ack data block"), DAEMON_LOGMSG_CRITICAL );
					break;
				case VSCP_TYPE_PROTOCOL_BLOCK_DATA_ACK:
					// pVscp->pdata[0] = (checksum16 >> 8) & 0xFF;		MSB 16 bit CRC for block
					// pVscp->pdata[1] = checksum16 & 0xFF;				LSB 16 bit CRC for block
					// pVscp->pdata[2] = (write_pointer >> 8) & 0xFF;	MSB of block number 
					// pVscp->pdata[3] = 0;
					// pVscp->pdata[4] = 0;
					// pVscp->pdata[5] = write_pointer & 0xFF;			LSB of block number
					checksum16 = (pVscp->pdata[0] << 8) | pVscp->pdata[1];
					write_pointer = (pVscp->pdata[2] << 8) | pVscp->pdata[5];
					if((checksum16 == m_nChecksum) && (write_pointer == m_nCurrentBlockNumber))
						BlockProgramMsg( m_nCurrentBlockNumber, m_nCurrentFlashType );
					else
					{
						// in questo caso di errore si ritrasmette il blocco
						StartBlockTransferMsg( pNode->GetNickName(), m_nCurrentBlockNumber, m_nCurrentFlashType );
						//UpdateError(pNode);
					}

					//::wxGetApp().logMsg ( _("event ack data block"), DAEMON_LOGMSG_CRITICAL );
					break;
				case VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_ACK:
					// pVscp->pdata[0] MSB block number
					// pVscp->pdata[1] INTERNAL_FLASH/SPI_FLASH
					// pVscp->pdata[2]
					// pVscp->pdata[3] LSB block number
					block_number = (pVscp->pdata[0] << 8) | pVscp->pdata[3];
					if((block_number == m_nCurrentBlockNumber) && (pVscp->pdata[1] == m_nCurrentFlashType))
					{
						switch(m_nCurrentFlashType)
						{
							case INT_FLASH:
								m_nCurrentBlockNumber++;
								//::wxGetApp().logMsg ( _("event PROGRAM ACK"), DAEMON_LOGMSG_CRITICAL );
								m_nTotalChecksum += m_nChecksum;
								if(m_nCurrentBlockNumber == (int)((m_IntFlashBinaryLength - USER_PROGRAM_ADDRESS)/BLOCKDATA_SIZE))
								{
									m_nCurrentBlockNumber = 0;
									m_nCurrentFlashType = EXT_FLASH;
									
							//ActivateNewImageMsg();	// DEBUG!!
								}
							//else // DEBUG!!
							//{// DEBUG!!
								// avanzamento progress control della dialog
								pNode->FirmwareProgressStep();
								wxGetApp().Yield();
								StartBlockTransferMsg( pNode->GetNickName(), m_nCurrentBlockNumber, m_nCurrentFlashType );
							//}// DEBUG!!
								break;
							case EXT_FLASH:
								m_nCurrentBlockNumber++;
								if(m_nCurrentBlockNumber == (int)(m_ExtFlashBinaryLength/BLOCKDATA_SIZE))
								{
									ActivateNewImageMsg();
								}
								else
								{
									// avanzamento progress control della dialog
									pNode->FirmwareProgressStep();
									wxGetApp().Yield();
									StartBlockTransferMsg( pNode->GetNickName(), m_nCurrentBlockNumber, m_nCurrentFlashType );
								}
								break;
						}
					}
					else
					{
						UpdateError(pNode);
					}

					//::wxGetApp().logMsg ( _("event ack program block"), DAEMON_LOGMSG_CRITICAL );
					break;
				case VSCP_TYPE_PROTOCOL_ACTIVATENEWIMAGE_ACK:
					// delay per attendere che il nodo remoto abbia finito la fase di 
					// inizializzazione altrimenti quando l'utente chiude la dialog di update
					// c'e' il rischio che il gestore dell' heartbeat non rilevi il nuovo stato (stato user)
					// del nodo
					wxMilliSleep( 8000 );

					m_tDoneUpgrade = wxDateTime::Now();
					::wxGetApp().logMsg ( wxT("Upgrade Finished... taking: ") + (m_tDoneUpgrade - m_tStartUpgrade).Format(), DAEMON_LOGMSG_CRITICAL );

					// avvisa la dialog che è finito il processo di update
					pNode->EndFirmwareProgress(FIRMWAREUPDATEOK);
					break;

				case VSCP_TYPE_PROTOCOL_NACK_BOOT_LOADER:
					UpdateError(pNode);
					::wxGetApp().logMsg ( _("event NACK bootloader"), DAEMON_LOGMSG_CRITICAL );
					break;
				case VSCP_TYPE_PROTOCOL_START_BLOCK_NACK:
					UpdateError(pNode);
					::wxGetApp().logMsg ( _("event NACK start block"), DAEMON_LOGMSG_CRITICAL );
					break;
				case VSCP_TYPE_PROTOCOL_BLOCK_DATA_NACK:
					UpdateError(pNode);
					::wxGetApp().logMsg ( _("event NACK data block"), DAEMON_LOGMSG_CRITICAL );
					break;
				case VSCP_TYPE_PROTOCOL_PROGRAM_BLOCK_DATA_NACK:
					UpdateError(pNode);
					::wxGetApp().logMsg ( _("event NACK program block"), DAEMON_LOGMSG_CRITICAL );
					break;
				case VSCP_TYPE_PROTOCOL_ACTIVATENEWIMAGE_NACK:
					UpdateError(pNode);
					::wxGetApp().logMsg ( _("event NACK activate new image"), DAEMON_LOGMSG_CRITICAL );
					break;
			}
		}
		else
		{
			UpdateError(pNode);
		}
	}

	deleteVSCPevent( pVscp );
}
Ejemplo n.º 24
0
Archivo: mod_rsi.c Proyecto: ksthar/RSI
/** 
 * @brief Open an RSI session
 * 
 * @return File descriptor for session
 */
uInt16_t rsi_open(void)
{
	crcInit();
	return rs485_open();
}
Ejemplo n.º 25
0
N_CDECL(void, NimMain)(void) {
  nim__datInit();
  systemInit();
parseutilsInit();
strutilsInit();
timesInit();
posixInit();
osInit();
listsInit();
nhashesInit();
nstrtabsInit();
optionsInit();
msgsInit();
nversionInit();
crcInit();
platformInit();
ropesInit();
identsInit();
astInit();
rodutilsInit();
astalgoInit();
condsymsInit();
hashesInit();
strtabsInit();
streamsInit();
osprocInit();
extccompInit();
wordrecgInit();
commandsInit();
llstreamInit();
lexbaseInit();
scannerInit();
nimconfInit();
pnimsynInit();
pbracesInit();
rnimsynInit();
filtersInit();
ptmplsynInit();
syntaxesInit();
rodreadInit();
treesInit();
typesInit();
mathInit();
magicsysInit();
bitsetsInit();
nimsetsInit();
passesInit();
treetabInit();
semdataInit();
lookupsInit();
importerInit();
rodwriteInit();
semfoldInit();
evalsInit();
procfindInit();
pragmasInit();
suggestInit();
semInit();
rstInit();
highliteInit();
docgenInit();
ccgutilsInit();
cgmethInit();
cgenInit();
ecmasgenInit();
interactInit();
passauxInit();
dependsInit();
transfInit();
mainInit();
parseoptInit();
nimrodInit();
}
Ejemplo n.º 26
0
/* TCPD_M1 Program called with No Arguments */
main()
{
  int ftps_M1_sock, troll_M1_sock, M1_troll_sock;
  int namelen, buflen;
  char TCPD_M1_buf[MAX_MES_LEN];
  struct sockaddr_in ftps_M1_name;
  struct sockaddr_in troll_M1_name;
  struct sockaddr_in M1_listen_name;
  struct sockaddr_in M1_comm_name;
  struct sockaddr_in M1_troll_name;
  struct hostent *hp, *gethostbyname();
  
  /******** DATA AND ACKNOWLEDGEMENT PACKET ******/
  data_packet *packet, *ack_packet, *FYN_packet;
  packet = calloc(1,sizeof(data_packet));
  ack_packet = calloc(1,sizeof(data_packet));
  FYN_packet = calloc(1,sizeof(data_packet));

  /********** RECEIVER BUFFER *********/
  data_packet recv_buffer[1000] ; 
  int recv_buffer_head = 0;

  int loopj=0;
  /*
    int loopi = 0 ; 

  for (loopi = 0 ; loopi < 1000; loopi++){
    recv_buffer->sequence_number = -3;
  }
  */

  /********** create socket for connecting to FTPS ************/
  ftps_M1_sock = socket(AF_INET, SOCK_DGRAM,0);
  if(ftps_M1_sock < 0) {
    perror("opening datagram socket");
    exit(2);
  }

  /********* construct name for connecting to FTPS **********/
  ftps_M1_name.sin_family = AF_INET;
  ftps_M1_name.sin_port = htons(FTPS_M1_PORT);
  ftps_M1_name.sin_addr.s_addr = INADDR_ANY;

  if(bind(ftps_M1_sock, (struct sockaddr *)&ftps_M1_name, sizeof(ftps_M1_name)) < 0) {
    perror("getting socket name");
    exit(2);
  }
	
  /*create a sock for M1 to Troll */
  M1_troll_sock = socket(AF_INET, SOCK_DGRAM,0);
  if(M1_troll_sock < 0) {
    perror("opening datagram socket: for reverse communication from M2 to Troll");
    exit(2);
  }
    
  /* construct name for connecting M1 to TROLL */
  bzero((char*)&M1_comm_name, sizeof M1_comm_name);
  M1_comm_name.sin_family = AF_INET;
  M1_comm_name.sin_port = htons(M1_TROLL_PORT);
  M1_comm_name.sin_addr.s_addr = INADDR_ANY;
  
  /* Copy Source Address and Source Port Number into Socket(M1_troll_sock) */
  if(bind(M1_troll_sock, (struct sockaddr *)&M1_comm_name, sizeof(M1_comm_name)) < 0) {
    perror("getting socket name");
    exit(2);
  }
  /* construct name for connecting to TROLL */
  bzero ((char*)&M1_troll_name, sizeof M1_troll_name);
  M1_troll_name.sin_family = AF_INET;
  M1_troll_name.sin_port = htons(atoi(M1_TROLL_PORT_BUF));
  
  /* convert hostname to IP address and enter into name */
  hp = gethostbyname(TROLL_ADDR);
  if(hp == 0) {
    fprintf(stderr, "%s:unknown host\n",TROLL_ADDR);
    exit(3);
  }
  bcopy((char *)hp->h_addr, (char *)&M1_troll_name.sin_addr, hp->h_length);
    
  /* Variable Size Initialization */
  namelen=sizeof(struct sockaddr_in);
  buflen = MAX_MES_LEN;
  crcInit();

  /* waiting for connection from client on name and print what client sends */

  if(recvfrom(ftps_M1_sock, packet, sizeof(data_packet), 0, (struct sockaddr *)&ftps_M1_name, &namelen) < 0) {
    perror("error receiving"); 
    exit(4);
  }
  printf("TCPD_M1 receives Packet from FTPS (ListenPort):\t%s\n", packet->payload);

  /************* REMOTE COMMUNICATION INITIALIZATION **********/
  /* create socket for connecting to troll */
  troll_M1_sock = socket(AF_INET, SOCK_DGRAM,0);
  if(troll_M1_sock < 0) {
    perror("opening datagram socket");
    exit(2);
  }

  /* construct name for local port and address */
  M1_listen_name.sin_family = AF_INET;
  M1_listen_name.sin_port = htons(atoi(packet->payload));
  M1_listen_name.sin_addr.s_addr = INADDR_ANY;

  if(bind(troll_M1_sock, (struct sockaddr *)&M1_listen_name, sizeof(M1_listen_name)) < 0) {
    perror("Unable to bind (TROLL_to_M1 Sock)");
    exit(2);
  }

  fprintf(stdout,"Waiting for connection from client via troll at %d ...\n",ntohs(M1_listen_name.sin_port));
    
  /************** INFORMATION RECIEPT ************/
 
  /********* FILE SIZE **************/
  recv_bufferInit(recv_buffer, sizeof(recv_buffer)/sizeof(data_packet));
    
  while(1){
		
    if(recvfrom(troll_M1_sock, packet, sizeof(data_packet), 0, (struct sockaddr *)&troll_M1_name, &namelen) < 0) {
      perror("error receiving"); 
      exit(4);
    }
    printf("TCPD_M2 --> TCPD_M1 :: RECVD PACKET-> Sequence Number: %d\t", packet->sequence_number);

    /************** DATA PACKET MANIPULATION ************/

    if(packet->sequence_number <= 2000 && packet->FYN != '1'){
    /******* CRC COMPUTATION **********/
      if(crcFast(packet->payload,1000) == packet->checksum) {

	printf("Packet Health: GOOD\n");

	/***** ACK COMMUNICATION *********/
	ack_packet->sequence_number = packet->sequence_number ;

	/******** ADDING INTO RECEIVER BUFFER ********/
	if(recv_buffer[packet->sequence_number].sequence_number == -3){
	  recv_buffer[packet->sequence_number] = *packet ; 
	}

	/************ SENDING ACK FOR VALID DATA PACKET***********/
	  printf("TCPD_M1 --> TCPD_M2 :: SEND ACK_PACKET-> sequence_number: %d \n",ack_packet->sequence_number);
	  if(sendto(M1_troll_sock, ack_packet, sizeof(data_packet), 0, (struct sockaddr *)&M1_troll_name, sizeof(M1_troll_name)) < 0) {
	    perror("error Sending ack");
	    exit(4);
	  }

	/*********** ORDERED BYTES TRANSFER TO FTPC FROM TCPD_M1 ***********/
	  if(recv_buffer[recv_buffer_head].sequence_number != -3){
	  /*************** INITIATING COMMUNICATION BETWEEN TCPD_M1 AND FTPS **********/
	  printf("TCPD_M1 --> FTPS :: SEND DATA_PACKET-> sequence number: %d\n\n", recv_buffer[recv_buffer_head].sequence_number); 
	  if(sendto(ftps_M1_sock, &recv_buffer[recv_buffer_head], sizeof(data_packet), 0, (struct sockaddr *)&ftps_M1_name, sizeof(ftps_M1_name)) < 0) {
	    perror("error Sending");
	    exit(4);
	  }
	  recv_buffer[recv_buffer_head].sequence_number = -3;
	  recv_buffer_head++; // MOVING HEAD TO NEXT AVAILABLE PACKET IN RECEIVER BUFFER
	}
      }
      else {
	printf("Packet Health: CORRUPTED\n");
	printf("TCPD_M2 --> TCPD_M1 :: DROP DATA_PACKET-> sequence_number: %d\n",packet->sequence_number);
      }
    }

    /********** EXPLICIT CHECKS FOR FYN, FYN+ACK PACKETS *************/
    else if(packet->FYN == '1'){ 

      FYN_packet->FYN = '1';

      /******* CRC COMPUTATION **********/
      if(crcFast(packet->payload,1000) == packet->checksum){
  
	printf("Packet Health: GOOD\n");

	/***** ACK COMMUNICATION *********/
	ack_packet->sequence_number = packet->sequence_number ;

	/*****CONNECTION SHUTDOWN CHECK AND CORRESPONDING ACKS***/
	if(packet->FYN == '1' && ack_packet->sequence_number == 1){
	  printf("TCPD_M1 --> TCPD_M2 :: RECVD ACK_PACKET-> sequence_number: %d\n",ack_packet->sequence_number);
	  if(Isrecv_bufferEmpty(recv_buffer,sizeof(recv_buffer)/sizeof(data_packet))){
	    if(sendto(ftps_M1_sock, FYN_packet, sizeof(data_packet), 0, (struct sockaddr *)&ftps_M1_name, sizeof(ftps_M1_name)) < 0) {
	      perror("error Sending");
	      exit(4);
	    }
	  }  
	  break;
	}
	else if(packet->FYN == '1'){
	  ack_packet->FYN = '1';
	  printf("TCPD_M1 --> TCPD_M2 :: SEND FYN+ACK PACKET-> sequence_number: %d \n",ack_packet->sequence_number);
	  if(sendto(M1_troll_sock, ack_packet, sizeof(data_packet), 0, (struct sockaddr *)&M1_troll_name, sizeof(M1_troll_name)) < 0) {
	    perror("error Sending ack");
	    exit(4);
	  }
	}
      }
      else {
	printf("Packet Health: CORRUPTED\n");
	printf("TCPD_M2 --> TCPD_M1 :: DROP FYN||FYN+ACK PACKET-> sequence_number: %d\n",ack_packet->sequence_number);
      }
    }
    else{
      printf("Packet Health: CORRUPTED\n");
      printf("TCPD_M2 --> TCPD_M1 :: DROP PACKET SEQUENCT NUMBER CORRUPUTED.\n");
    }
  }
  
    for(loopj=recv_buffer_head;loopj<1000;loopj++){
		if(recv_buffer[loopj].sequence_number != -3){
			if(sendto(ftps_M1_sock, &recv_buffer[loopj], sizeof(data_packet), 0, (struct sockaddr *)&ftps_M1_name, sizeof(ftps_M1_name)) < 0) {
				perror("error Sending");
				exit(4);
			}
		}		
	}
	fprintf(stdout, "\n\n....CONNECTION SHUTDOWN...\n");
	
  /* close connection */
  close(troll_M1_sock);
  close(ftps_M1_sock);
  exit(0);
}
Ejemplo n.º 27
0
void *UDPReceiveThread::Entry()
{
	unsigned long errorCode = 0;
#ifdef WIN32
	int nLen;
#else
	socklen_t nLen;
#endif
	unsigned char buf[ 1024 ];
	unsigned char *p;

	CLIENTEVENTLIST::compatibility_iterator nodeVSCP;
	vscpEvent *pvscpEvent = NULL;

	// Must be a valid control object pointer
	if (NULL == m_pCtrlObject) return NULL;


	// We need to create a clientobject and add this object to the list
	CClientItem *pClientItem = new CClientItem;
	if (NULL == pClientItem) return NULL;

	// This is an active client
	pClientItem->m_bOpen = true;
	pClientItem->m_type = CLIENT_ITEM_INTERFACE_TYPE_CLIENT_INTERNAL;
	pClientItem->m_strDeviceName = _("Internal UDP Receive Client. Started at ");
	wxDateTime now = wxDateTime::Now();
	pClientItem->m_strDeviceName += now.FormatISODate();
	pClientItem->m_strDeviceName += _(" ");
	pClientItem->m_strDeviceName += now.FormatISOTime();

	// Mark as UDP receive channel
	pClientItem->m_bUDPReceiveChannel = true;

	// Add the client to the Client List
	m_pCtrlObject->m_wxClientMutex.Lock();
	m_pCtrlObject->addClient(pClientItem/*, CLIENT_ITEM_SPECIAL_ID_UDP*/);
	m_pCtrlObject->m_wxClientMutex.Unlock();


	crcInit();

	char szName[ 128 ];
	struct hostent * lpLocalHostEntry;

	if (-1 == gethostname(szName, sizeof( szName))) {
		wxLogError(_("UDP Receive Thread: Failed to get hostname\n"));
		return NULL;
	}

	wxLogDebug(_("udpReceiceThread: Hostname: %s"), szName);

	lpLocalHostEntry = gethostbyname(szName);
	if (NULL == lpLocalHostEntry) {
		wxLogError(_("UDP Receive Thread: Failed to get hostaddress\n"));
		return NULL;
	}

	// Get the address
	//localaddr = (in_addr_t *)lpLocalHostEntry->h_addr_list[ 0 ];

#ifndef WIN32

	/*
	  char ac[ 80 ];
	  if ( gethostname( ac, sizeof( ac ) ) == -1 ) {
	    ;
	  }
 
	  struct hostent *phe = gethostbyname( ac );

	  for ( int i = 0; phe->h_addr_list[i] != 0; ++i ) {
	    struct in_addr addr;
	    memcpy( &addr, phe->h_addr_list[i], sizeof (struct in_addr ) );
	    //cout << "Address " << i << ": " << inet_ntoa(addr) << endl;
	    wxLogDebug( _("Interface address:  %X\n"), addr );
	  }
	 */

#endif

	// Get all local addresses of the local machine
	int idx = -1;
	void *pAddr;
#ifdef WIN32
	unsigned long localaddr[ 16 ]; // max 16 local addresses
#else
	in_addr_t localaddr[ 16 ]; // max 16 local addresses
#endif
	do {
		idx++;
		localaddr[ idx ] = 0;
#ifdef WIN32
		pAddr = lpLocalHostEntry->h_addr_list[ idx ];
		if (NULL != pAddr) localaddr[ idx ] = *((unsigned long *) pAddr);
#else
		pAddr = (in_addr_t *) lpLocalHostEntry->h_addr_list[ idx ];
		if (NULL != pAddr) localaddr[ idx ] = *((in_addr_t *) pAddr);
		if (NULL != pAddr) wxLogTrace(_("wxTRACE_vscpd_receiveQueue"),
			_("udpReceiceThread: Local address: %X"),
			* (in_addr_t *) pAddr);

#endif


	} while ((NULL != pAddr) && (idx < 16));

	//
	// Create a UDP/IP datagram socket
	//
	int theSocket;

	theSocket = socket(AF_INET, SOCK_DGRAM, 0);
	if (-1 == theSocket) {
		return NULL;
	}

	int on = 1; // As suggested by Charles Tewiah
	setsockopt(theSocket,
		SOL_SOCKET,
		SO_REUSEADDR,
		(const char *) &on,
		sizeof( on));

	//
	// Fill in the address structure
	//
	struct sockaddr_in saServer;

	saServer.sin_family = AF_INET;
	saServer.sin_addr.s_addr = INADDR_ANY;
	saServer.sin_port = htons(m_pCtrlObject->m_UDPPort);

	// For multi interface machines.
	// If no bind address is given the default interface is used to receive
	// UDP datagrams which means datagrams will be received from all interfaces. Set
	// to ip of interface to select a specific interface.
	if (0 != m_pCtrlObject->m_strUdpBindInterfaceAddress.Length()) {
#if ( WIN32 && (_WIN32_WINNT<0x0600) ) 
		saServer.sin_addr.s_addr =
			inet_addr(m_pCtrlObject->m_strUdpBindInterfaceAddress.ToAscii());
#else
		inet_pton(AF_INET,
			m_pCtrlObject->m_strUdpBindInterfaceAddress.ToAscii(),
			(void *) &saServer.sin_addr.s_addr);
#endif
	}

	//
	// bind the name to the socket
	//

	int nRet;

	nRet = bind(theSocket,
		(struct sockaddr *) &saServer,
		sizeof( struct sockaddr));

	if (-1 == nRet) {
		return NULL;
	}

	struct sockaddr_in saClient;
	nLen = sizeof( struct sockaddr_in);

	wxLogDebug(_("udpReceiceThread: Ready to Work!"));

	while (!TestDestroy() && !m_bQuit) {

#ifdef WIN32
		memset(buf, 0, sizeof( buf));

		// Wait for data from the client
		nRet = recvfrom(theSocket,
			(char *) buf,
			sizeof(buf),
			0,
			(LPSOCKADDR) & saClient,
			&nLen);

		if (!nRet || (nRet == SOCKET_ERROR) || (nRet < 25)) {
			continue;
		}
#else
		bzero((uint8_t *) & saClient, sizeof( saClient));
		nLen = sizeof( struct sockaddr_in);
		bzero((uint8_t *) buf, sizeof( buf));

		// Wait for data from the client

		nRet = recvfrom(theSocket,
			buf,
			sizeof( buf),
			0,
			(struct sockaddr *) &saClient,
			&nLen);

		if ((0 == nRet) || (-1 == nRet) || (nRet < 25)) {
			continue;
		}

		wxLogDebug(_("udpReceiveThread: Incoming event. Addr=%X"),
			(in_addr_t) saClient.sin_addr.s_addr);
#endif
		// Handle received package

#ifdef WIN32

		// If this is a packet sent from this machine
		// we just disregards it		
		bool bLocalAddress = false;
		idx = 0;
		while ((0 != localaddr[ idx ]) && (idx < 16)) {
			if (localaddr[ idx ] == (unsigned long) saClient.sin_addr.S_un.S_addr) {
				bLocalAddress = true;
				break;
			}

			idx++;
		}

#else

		// If this is a packet sent from this machine
		// we just disregards it
		//if ( *localaddr == saClient.sin_addr.s_addr ) continue;
		bool bLocalAddress = false;
		idx = 0;
		while ((0 != localaddr[ idx ]) && (idx < 16)) {
			wxLogTrace(_("wxTRACE_vscpd_receiveQueue"),
				_(" Received address = %x"), (in_addr_t)
				saClient.sin_addr.s_addr);
			if (localaddr[ idx ] == (in_addr_t) saClient.sin_addr.s_addr) {
				bLocalAddress = true;
				wxLogTrace(_("wxTRACE_vscpd_receiveQueue"),
					_("Skipped because event has local origin "));
				break;
			}
			idx++;
		}

#endif

		if (bLocalAddress) continue; // From ourself get next event

		wxLogTrace(_("wxTRACE_vscpd_receiveQueue"),
			_("udpReceiveThread: It's from another machine. Grab it."));

		// Check size
		// The size member must be low enough for the data to fit
		// in the package
		unsigned short size;
		p = (unsigned char *) &size;
		* (p + 0) = buf[ VSCP_UDP_POS_SIZE + 1 ];
		* (p + 1) = buf[ VSCP_UDP_POS_SIZE + 0 ];

		if ((size + 25) > nRet) {
			// Wrong size -> Package faulty
			continue;
		}

		// Calculate CRC if requested
		if (!(buf[ VSCP_UDP_POS_HEAD + 0 ] & VSCP_NO_CRC_CALC)) {
			if (!crcFast(buf, size)) continue; // Faulty CRC
		}

		vscpEvent *pEvent = new vscpEvent;

		if (NULL != pEvent) {

			pEvent->obid = pClientItem->m_clientID;

			// Head
			p = (unsigned char *) &pEvent->head;
			* (p + 0) = buf[ VSCP_UDP_POS_HEAD + 0 ];

			// VSCP class
			p = (unsigned char *) &pEvent->vscp_class;
			* (p + 0) = buf[ VSCP_UDP_POS_CLASS + 1 ];
			* (p + 1) = buf[ VSCP_UDP_POS_CLASS + 0 ];

			// VSCP type
			p = (unsigned char *) &pEvent->vscp_type;
			* (p + 0) = buf[ VSCP_UDP_POS_TYPE + 1 ];
			* (p + 1) = buf[ VSCP_UDP_POS_TYPE + 0 ];

			// Node address
			p = (unsigned char *) &pEvent->GUID;
			memcpy(p, &buf[ VSCP_UDP_POS_GUID + 0 ], 16);

			// Number of valid data bytes
			pEvent->sizeData = size;

			if (pEvent->sizeData > 487) {
				// Can't be a VSCP package
				delete pEvent;
				continue;
			}

			// CRC
			p = (unsigned char *) &pEvent->crc;
			* (p + 0) = buf[ VSCP_UDP_POS_CRC + 1 ];
			* (p + 1) = buf[ VSCP_UDP_POS_CRC + 0 ];

			pEvent->pdata = NULL;

			if (0 != pEvent->sizeData) {

				// Allocate storage for data
				unsigned char *pDataArea = new unsigned char[ pEvent->sizeData ];

				if (NULL != pDataArea) {

					// Data Max 487 (512- 25) bytes
					pEvent->pdata = pDataArea;

					// size = sz - command_byte - control_bytes
					memcpy(pEvent->pdata, &buf[ VSCP_UDP_POS_DATA ], pEvent->sizeData);

				}
			}

			// RX Statistics
			pClientItem->m_statistics.cntReceiveData += pEvent->sizeData;
			pClientItem->m_statistics.cntReceiveFrames++;


			// There must be room in the send queue
			if (m_pCtrlObject->m_maxItemsInClientReceiveQueue >
				m_pCtrlObject->m_clientOutputQueue.GetCount()) {
				m_pCtrlObject->m_mutexClientOutputQueue.Lock();
				m_pCtrlObject->m_clientOutputQueue.Append(pEvent);
				m_pCtrlObject->m_semClientOutputQueue.Post();
				m_pCtrlObject->m_mutexClientOutputQueue.Unlock();
			} else {
				pClientItem->m_statistics.cntOverruns++;
				deleteVSCPevent(pEvent);
			}

		}

	} // while

#ifdef WIN32
	_close(theSocket);
#else
	close(theSocket);
#endif

	// Remove the client
	m_pCtrlObject->m_wxClientMutex.Lock();
	m_pCtrlObject->removeClient(pClientItem);
	m_pCtrlObject->m_wxClientMutex.Unlock();

	return NULL;

}