void COpenProgDlg::Read12F5xx(int dim, int dim2)
// read 12 bit PIC
// dim=program size 	dim2=config size
// vdd before vpp
// CONFIG @ 0x7FF (upon entering in program mode)
// OSCCAL in last memory location
// 4 ID + reserved area beyond code memory
{
	CString str,aux;
	int size;
	int k=0,z=0,i,j;
	char s[256],t[256];
	if(dim2<4) dim2=4;
	size=0x1000;
	dati_hex.RemoveAll();
	dati_hex.SetSize(size);
	if(saveLog){
		OpenLogFile();	//"Log.txt"
		fprintf(logfile,"Read12F5xx(%d,%d)\n",dim,dim2);
	}
	unsigned int start=GetTickCount();
	bufferU[0]=0;
	j=1;
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T1T2;
	bufferU[j++]=1;						//T1=1u
	bufferU[j++]=100;					//T2=100u
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T3;
	bufferU[j++]=2000>>8;
	bufferU[j++]=2000&0xff;
	bufferU[j++]=EN_VPP_VCC;		//enter program mode
	bufferU[j++]=0x0;
	bufferU[j++]=SET_CK_D;
	bufferU[j++]=0x0;
	bufferU[j++]=EN_VPP_VCC;		//VDD
	bufferU[j++]=0x1;
	bufferU[j++]=EN_VPP_VCC;		//VDD+VPP
	bufferU[j++]=0x5;
	bufferU[j++]=NOP;
	bufferU[j++]=READ_DATA_PROG;	//configuration word
	bufferU[j++]=INC_ADDR;			// 7FF->000
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(2);
	read();
	if(saveLog)WriteLogIO();
	for(z=0;z<DIMBUF-2&&bufferI[z]!=READ_DATA_PROG;z++);
	if(z<DIMBUF-2){
		dati_hex[0xfff]=(bufferI[z+1]<<8)+bufferI[z+2];
		PrintMessage("\r\n");
		PrintMessage1(strings[S_ConfigWord],dati_hex[0xfff]);	//"\r\nConfiguration word: 0x%03X\r\n"
		switch(dati_hex[0xfff]&0x03){
			case 0:
				PrintMessage(strings[S_LPOsc]);	//"LP oscillator\r\n"
				break;
			case 1:
				PrintMessage(strings[S_XTOsc]);	//"XT oscillator\r\n"
				break;
			case 2:
				PrintMessage(strings[S_IntOsc]);	//"Internal osc.\r\n"
				break;
			case 3:
				PrintMessage(strings[S_RCOsc]);	//"RC oscillator\r\n"
				break;
		}
		if(dati_hex[0xfff]&0x04) PrintMessage(strings[S_WDTON]);	//"WDT ON\r\n"
		else PrintMessage(strings[S_WDTOFF]);	//"WDT OFF\r\n"
		if(dati_hex[0xfff]&0x08) PrintMessage(strings[S_CPOFF]);	//"Code protection OFF\r\n"
		else PrintMessage(strings[S_CPON]);	//"Code protection ON\r\n"
		if(dati_hex[0xfff]&0x10) PrintMessage(strings[S_MCLRON]);	//"Master clear ON\r\n"
		else PrintMessage(strings[S_MCLROFF]);	//"Master clear OFF\r\n"
	}
	else PrintMessage(strings[S_NoConfigW]);	//"Impossibile leggere la config word\r\n"
//****************** read code ********************
	PrintMessage(strings[S_CodeReading1]);		//lettura codice ...
	for(i=0,j=1;i<dim+dim2;i++){
		bufferU[j++]=READ_DATA_PROG;
		bufferU[j++]=INC_ADDR;
		if(j>DIMBUF*2/4-2||i==dim+dim2-1){		//2 istruzioni -> 4 risposte
			bufferU[j++]=FLUSH;
			for(;j<DIMBUF;j++) bufferU[j]=0x0;
			write();
			msDelay(5);
			read();
			for(z=1;z<DIMBUF-2;z++){
				if(bufferI[z]==READ_DATA_PROG){
					dati_hex[k++]=(bufferI[z+1]<<8)+bufferI[z+2];
					z+=2;
				}
			}
			PrintStatus(strings[S_CodeReading],i*100/(dim+dim2),i);	//"Read: %d%%, addr. %03X"
			j=1;
			if(saveLog){
				fprintf(logfile,strings[S_Log7],i,i,k,k);	//"i=%d(0x%X), k=%d(0x%X)\n"
				WriteLogIO();
			}
		}
	}
	bufferU[j++]=NOP;				//uscita program mode
	bufferU[j++]=EN_VPP_VCC;
	bufferU[j++]=0x1;
	bufferU[j++]=EN_VPP_VCC;
	bufferU[j++]=0x0;
	bufferU[j++]=SET_CK_D;
	bufferU[j++]=0x0;
	bufferU[j++]=WAIT_T3;
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(1);
	read();
	unsigned int stop=GetTickCount();
	if(saveLog)CloseLogFile();
	for(i=k;i<0xfff;i++) dati_hex[i]=0xfff;
	if(k!=dim+dim2){
		PrintMessage2(strings[S_ReadErr],dim+dim2,k);	//"Errore in lettura: word richieste=%d, lette=%d\r\n"
	}
	else PrintMessage1(strings[S_Compl],k);	//"completed\n"
//****************** visualize ********************
	for(i=0;i<4;i+=2){
		PrintMessage4(strings[S_ChipID],i,dati_hex[dim+i],i+1,dati_hex[dim+i+1]);	//"ID%d: 0x%03X   ID%d: 0x%03X\r\n"
	}
	if(dim2>4){
		PrintMessage1(strings[S_BKOsccal],dati_hex[dim+4]);	//"Backup OSCCAL: 0x%03X\r\n"
	}
	PrintMessage("\r\n");
	PrintMessage(strings[S_CodeMem]);	//"\r\nMemoria programma:\r\n"
	s[0]=0;
	int valid=0,empty=1;
	for(i=0;i<dim;i+=COL){
		valid=0;
		for(j=i;j<i+COL&&j<dim;j++){
			sprintf(t,"%03X ",dati_hex[j]);
			strcat(s,t);
			if(dati_hex[j]<0xfff) valid=1;
		}
		if(valid){
			sprintf(t,"%04X: %s\r\n",i,s);
			empty=0;
			aux+=t;
		}
		s[0]=0;
	}
	if(empty) PrintMessage(strings[S_Empty]);	//empty
	else PrintMessage(aux);
	aux.Empty();
	if(dim2>5){
		PrintMessage(strings[S_ConfigResMem]);	//"\r\nMemoria configurazione e riservata:\r\n"
		empty=1;
		for(i=dim;i<dim+dim2;i+=COL){
			valid=0;
			for(j=i;j<i+COL&&j<dim+64;j++){
				sprintf(t,"%03X ",dati_hex[j]);
				strcat(s,t);
				if(dati_hex[j]<0xfff) valid=1;
			}
			if(valid){
				sprintf(t,"%04X: %s\r\n",i,s);
				empty=0;
				aux+=t;
			}
			s[0]=0;
		}
		if(empty) PrintMessage(strings[S_Empty]);	//empty
		else PrintMessage(aux);
	}
	StatusBar.SetWindowText("");
	PrintMessage("\r\n");
	PrintMessage1(strings[S_End],(stop-start)/1000.0);	//"\r\nEnd (%.2f s)\r\n"

}
Beispiel #2
0
void QueueScriptController::AddMessage(Message::EKind kind, const char* text)
{
	const char* msgText = text + m_prefixLen;

	if (!strncmp(msgText, "[NZB] ", 6))
	{
		debug("Command %s detected", msgText + 6);
		if (!strncmp(msgText + 6, "NZBPR_", 6))
		{
			CString param = msgText + 6 + 6;
			char* value = strchr(param, '=');
			if (value)
			{
				*value = '\0';
				GuardedDownloadQueue downloadQueue = DownloadQueue::Guard();
				NzbInfo* nzbInfo = QueueScriptCoordinator::FindNzbInfo(downloadQueue, m_id);
				if (nzbInfo)
				{
					nzbInfo->GetParameters()->SetParameter(param, value + 1);
				}
			}
			else
			{
				error("Invalid command \"%s\" received from %s", msgText, GetInfoName());
			}
		}
		else if (!strncmp(msgText + 6, "DIRECTORY=", 10) &&
			m_event == QueueScriptCoordinator::qeNzbDownloaded)
		{
			GuardedDownloadQueue downloadQueue = DownloadQueue::Guard();
			NzbInfo* nzbInfo = QueueScriptCoordinator::FindNzbInfo(downloadQueue, m_id);
			if (nzbInfo)
			{
				nzbInfo->SetFinalDir(msgText + 6 + 10);
			}
		}
		else if (!strncmp(msgText + 6, "MARK=BAD", 8))
		{
			m_markBad = true;
			GuardedDownloadQueue downloadQueue = DownloadQueue::Guard();
			NzbInfo* nzbInfo = QueueScriptCoordinator::FindNzbInfo(downloadQueue, m_id);
			if (nzbInfo)
			{
				SetLogPrefix(nullptr);
				PrintMessage(Message::mkWarning, "Marking %s as bad", *m_nzbName);
				SetLogPrefix(m_script->GetDisplayName());
				nzbInfo->SetMarkStatus(NzbInfo::ksBad);
			}
		}
		else
		{
			error("Invalid command \"%s\" received from %s", msgText, GetInfoName());
		}
	}
	else
	{
		NzbInfo* nzbInfo = nullptr;
		{
			GuardedDownloadQueue downloadQueue = DownloadQueue::Guard();
			nzbInfo = QueueScriptCoordinator::FindNzbInfo(downloadQueue, m_id);
			if (nzbInfo)
			{
				nzbInfo->AddMessage(kind, text);
			}
		}

		if (!nzbInfo)
		{
			ScriptController::AddMessage(kind, text);
		}
	}
}
Beispiel #3
0
/***************************End of Declaration**************************************************************/
int main(int argc, char *argv[])
{
  int originalsize;
  FILE *pFile;
  
	if(argc >=5 && argv[4] != NULL)
	{
		deltaFile = fopen(argv[4],"wb");
	}
  // size of sym_t is 4 bytes
  pFile = fopen (argv[1],"rb");

  FILE *txtfile1 = fopen("rela1.txt","w+");
  FILE *txtfile2 = fopen("rela2.txt","w+");
  FILE *addrFreq = fopen(argv[5],"w+");
  if (pFile!=NULL)
  {
    fseek (pFile, 0, SEEK_END);
    originalsize = ftell (pFile); 
    
    originalsize /= sizeof(sym_t); // in terms of # of symbols
    rewind (pFile);
  }

  beta = atoi(argv[3]);

  originalfile=(sym_t*)malloc((originalsize + 1)*sizeof(sym_t));

  int c , i;
  i=0;

  fread(originalfile, sizeof(sym_t), originalsize, pFile);
  // need to do so??	
  originalfile[originalsize].offset=originalfile[originalsize].address=0;

  rewind(pFile);
  sort(originalfile,0,originalsize-1);
  for (i=0; i<originalsize; i++) {
    //sym_t mysym;
    //fread(&mysym, sizeof(sym_t), 1, pFile);

    fprintf(txtfile1, "%04X %04X\n", originalfile[i].offset, originalfile[i].address);
  }
  fclose(txtfile1);
  /* open  the new file and read it into an array   */
  
  FILE * qFile;
  int newsize;

  qFile = fopen (argv[2],"rb");

  if (qFile!=NULL){
    fseek (qFile, 0, SEEK_END);
    newsize=ftell (qFile); newsize /= sizeof(sym_t);
    rewind (qFile);
  }

  // read new file into an array
  newfile=(sym_t *)malloc((newsize + 1)*sizeof(sym_t));

  int j = 0;

  fread(newfile, sizeof(sym_t), newsize, qFile);
  // need to do so??	
  newfile[newsize].offset=newfile[newsize].address=0;

  rewind(qFile);
  sort(newfile,0,newsize-1);
  target_addr * head =  (target_addr*)malloc(sizeof(target_addr));
  head->next = NULL;
  for (i=0; i<newsize; i++) {
	  addAddr(newfile[i].address,head);
    fprintf(txtfile2, "%04X %04X\n", newfile[i].offset, newfile[i].address);
  }
  target_addr* tail = head->next;
  while(tail !=NULL)
  {
	  fprintf(addrFreq,"%04X\t%d\n",tail->address,tail->count);
	  tail = tail->next;
  }
  fclose(addrFreq);
  fclose(txtfile2);

  // Segment size 

  // printf("Segment size is  %d  \n" , sizeof(Segment));
  // printf("Char size is  %d  \n" , sizeof(char));
  // printf("Int size is  %d  \n" , sizeof(int));

  // initialize file_size_global
  file_size_global = newsize ; // in terms of # of symbols
  new_size_global = newsize ;  // in terms of # of symbols

  int maxsize = (originalsize>newsize)?originalsize:newsize; // in terms of # of symbols

  // printf("maxsize is : %d  \n", maxsize);
  
  //Initialize Table C
  Table_C = (sym_t**)malloc((originalsize) * sizeof(sym_t *));

  if(Table_C == NULL)
  {
    fprintf(stderr, "out of memory\n");
    exit(1);
  }
	
  for(i = 0; i < originalsize; i++)
  {
    Table_C[i] = (sym_t*)malloc(newsize * sizeof(sym_t));
    if(Table_C[i] == NULL)
    {
      fprintf(stderr, "out of memory\n");
      exit(1);
    }
  }

  // StoreCommon Segments
  printf("originalsize %d\n", originalsize*sizeof(sym_t));
  printf("newsize %d\n", newsize*sizeof(sym_t));


  StoreCommonSeg(Table_C, originalfile, newfile, originalsize, newsize);

  
  printf("SegCounter %d \n",Seg_counter );

  //
  //Segment * tmp = (&Seghead) -> next ;
  //for( i = 0; i < Seg_counter ; i++ ) {
	 // printf("The %d Seg's length=%d StartingX is %d , Ending X is %d , StartingY is %d, EndingY is %d (%d,%d) \n", tmp->num,tmp->Ending_Y-tmp->Starting_Y, tmp->Starting_X , tmp->Ending_X, tmp->Starting_Y, tmp->Ending_Y,
  //      tmp->offset, tmp->address);
  //  tmp = tmp -> next ;
  //}
  

  // run MDCD
  N = newsize;
  Local_Optimum = (int *) malloc( (N+1) * sizeof(int));
  S = (int *) malloc( (N+1) * sizeof(int));

  Message = (char **) malloc((N+1) * sizeof(char *)) ;
  cmd = (cmd_t*)malloc((N+1)*sizeof(cmd_t));
  for( i = 0 ; i < N+1 ; i++) {
    Message[i] = (char *) malloc(300 * sizeof(char));
  }
  //char   Message[N+1][300]; 
  //int beta;
  //int Transfer_length;
  Local_Optimum[0] = 0;
  Message[0] = "Here is the beginning of the new code image" ;
  cmd[0].type = -1;
  cmd[0].length =-1;
  cmd[0].inew=-1;
  cmd[0].iold = -1;
  //printf("%s", Message[0]);
  S[0] = 0;
  //printf("\n %d \n", beta);
  runMDCD(newfile);
  //for(i=1;i<N+1;i++)
  //{
	 // printf("%s\n",Message[i]);
  //}
  //PrintMessage1(N);
  PrintMessage(N);
  printf("delta %d\n",Transfer_length);
  // system("PAUSE");
  
  for(i = 0; i < originalsize; i++)
    free(Table_C[i]);
  free(Table_C);

  return 0;
}
Beispiel #4
0
void scale2x(SDL_Surface *src, SDL_Surface *dst)
{
     if(SDL_LockSurface(src) < 0)
        PrintMessage("scale2x:Was not able to lock work surface");
    
    if(SDL_LockSurface(dst) < 0)
        PrintMessage("scale2x:Was not able to lock screen surface");

	int looph, loopw;
	
	Uint8* srcpix = (Uint8*)src->pixels;
	Uint8* dstpix = (Uint8*)dst->pixels;

	const int srcpitch = src->pitch;
	const int dstpitch = dst->pitch;
	const int width = src->w;
	const int height = src->h;

	switch(src->format->BytesPerPixel)
	{
	case 1: { 
	    	Uint8 E0, E1, E2, E3, B, D, E, F, H;
		for(looph = 0; looph < height; ++looph)
		{
			for(loopw = 0; loopw < width; ++ loopw)
			{
			    	B = *(Uint8*)(srcpix + (MAX(0,looph-1)*srcpitch) + (1*loopw));
			    	D = *(Uint8*)(srcpix + (looph*srcpitch) + (1*MAX(0,loopw-1)));
			    	E = *(Uint8*)(srcpix + (looph*srcpitch) + (1*loopw));
			    	F = *(Uint8*)(srcpix + (looph*srcpitch) + (1*MIN(width-1,loopw+1)));
			    	H = *(Uint8*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (1*loopw));
				
				E0 = D == B && B != F && D != H ? D : E;
    	    	    	    	E1 = B == F && B != D && F != H ? F : E;
				E2 = D == H && D != B && H != F ? D : E;
				E3 = H == F && D != H && B != F ? F : E;

				*(Uint8*)(dstpix + looph*2*dstpitch + loopw*2*1) = E0;
				*(Uint8*)(dstpix + looph*2*dstpitch + (loopw*2+1)*1) = E1;
				*(Uint8*)(dstpix + (looph*2+1)*dstpitch + loopw*2*1) = E2;
				*(Uint8*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*1) = E3;
			}
		}break;}
	case 2: { 
	    	Uint16 E0, E1, E2, E3, B, D, E, F, H;
		for(looph = 0; looph < height; ++looph)
		{
			for(loopw = 0; loopw < width; ++ loopw)
			{
			    	B = *(Uint16*)(srcpix + (MAX(0,looph-1)*srcpitch) + (2*loopw));
			    	D = *(Uint16*)(srcpix + (looph*srcpitch) + (2*MAX(0,loopw-1)));
			    	E = *(Uint16*)(srcpix + (looph*srcpitch) + (2*loopw));
			    	F = *(Uint16*)(srcpix + (looph*srcpitch) + (2*MIN(width-1,loopw+1)));
			    	H = *(Uint16*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (2*loopw));
				
				E0 = D == B && B != F && D != H ? D : E;
    	    	    	    	E1 = B == F && B != D && F != H ? F : E;
				E2 = D == H && D != B && H != F ? D : E;
				E3 = H == F && D != H && B != F ? F : E;

				*(Uint16*)(dstpix + looph*2*dstpitch + loopw*2*2) = E0;
				*(Uint16*)(dstpix + looph*2*dstpitch + (loopw*2+1)*2) = E1;
				*(Uint16*)(dstpix + (looph*2+1)*dstpitch + loopw*2*2) = E2;
				*(Uint16*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*2) = E3;
			}
		}break;}
	case 3: { 
	    	int E0, E1, E2, E3, B, D, E, F, H;
		for(looph = 0; looph < height; ++looph)
		{
			for(loopw = 0; loopw < width; ++ loopw)
			{
			    	B = READINT24(srcpix + (MAX(0,looph-1)*srcpitch) + (3*loopw));
			    	D = READINT24(srcpix + (looph*srcpitch) + (3*MAX(0,loopw-1)));
			    	E = READINT24(srcpix + (looph*srcpitch) + (3*loopw));
			    	F = READINT24(srcpix + (looph*srcpitch) + (3*MIN(width-1,loopw+1)));
			    	H = READINT24(srcpix + (MIN(height-1,looph+1)*srcpitch) + (3*loopw));
				
				E0 = D == B && B != F && D != H ? D : E;
    	    	    	    	E1 = B == F && B != D && F != H ? F : E;
				E2 = D == H && D != B && H != F ? D : E;
				E3 = H == F && D != H && B != F ? F : E;

				WRITEINT24((dstpix + looph*2*dstpitch + loopw*2*3), E0);
				WRITEINT24((dstpix + looph*2*dstpitch + (loopw*2+1)*3), E1);
				WRITEINT24((dstpix + (looph*2+1)*dstpitch + loopw*2*3), E2);
				WRITEINT24((dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*3), E3);
			}
		}break;}
	default: { /*case 4:*/
	    	Uint32 E0, E1, E2, E3, B, D, E, F, H;
		for(looph = 0; looph < height; ++looph)
		{
			for(loopw = 0; loopw < width; ++ loopw)
			{
			    	B = *(Uint32*)(srcpix + (MAX(0,looph-1)*srcpitch) + (4*loopw));
			    	D = *(Uint32*)(srcpix + (looph*srcpitch) + (4*MAX(0,loopw-1)));
			    	E = *(Uint32*)(srcpix + (looph*srcpitch) + (4*loopw));
			    	F = *(Uint32*)(srcpix + (looph*srcpitch) + (4*MIN(width-1,loopw+1)));
			    	H = *(Uint32*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (4*loopw));
				
				E0 = D == B && B != F && D != H ? D : E;
    	    	    	    	E1 = B == F && B != D && F != H ? F : E;
				E2 = D == H && D != B && H != F ? D : E;
				E3 = H == F && D != H && B != F ? F : E;

				*(Uint32*)(dstpix + looph*2*dstpitch + loopw*2*4) = E0;
				*(Uint32*)(dstpix + looph*2*dstpitch + (loopw*2+1)*4) = E1;
				*(Uint32*)(dstpix + (looph*2+1)*dstpitch + loopw*2*4) = E2;
				*(Uint32*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*4) = E3;
			}
		}break;}
	}
   SDL_UnlockSurface(src);
   SDL_UnlockSurface(dst);
}
Beispiel #5
0
ssize_t read_data(int fd,char *buffer,size_t n)
{
    io_context *context;
    int err=0,nr=0;
    io_buffer iobuffer;

    if(fd==-1)
        PrintMessage(Fatal,"IO: Function read_data(%d) was called with an invalid argument.",fd);

    if(nio<=fd || !io_contexts[fd])
        PrintMessage(Fatal,"IO: Function read_data(%d) was called without calling init_io(%d) first.",fd,fd);

    context=io_contexts[fd];

    /* Create the output buffer */

    iobuffer.data=buffer;
    iobuffer.size=n;
    iobuffer.length=0;

    /* Read in new data */

    if(!context->r_zlib_context)
    {
        if(!context->r_chunk_context)
        {
            if(context->r_file_data && context->r_file_data->length)
            {
                if(iobuffer.size>context->r_file_data->length)
                {
                    memcpy(iobuffer.data,context->r_file_data->data,context->r_file_data->length);
                    iobuffer.length=context->r_file_data->length;
                    context->r_file_data->length=0;
                }
                else
                {
                    memcpy(iobuffer.data,context->r_file_data->data,iobuffer.size);
                    iobuffer.length+=iobuffer.size;
                    memmove(context->r_file_data->data,context->r_file_data->data+iobuffer.size,context->r_file_data->length-iobuffer.size);
                    context->r_file_data->length-=iobuffer.size;
                }

                nr=iobuffer.length;
            }
            else
            {
                if(context->gnutls_context)
                    nr=io_gnutls_read_with_timeout(context->gnutls_context,&iobuffer,context->r_timeout);
                else
                    nr=io_read_with_timeout(fd,&iobuffer,context->r_timeout);
                if(nr>0) context->r_raw_bytes+=nr;
            }
        }
        else /* if(context->r_chunk_context) */
        {
            do
            {
                if(context->gnutls_context)
                    err=io_gnutls_read_with_timeout(context->gnutls_context,context->r_file_data,context->r_timeout);
                else
                    err=io_read_with_timeout(fd,context->r_file_data,context->r_timeout);
                if(err>0) context->r_raw_bytes+=err;
                if(err<0) break;
                err=io_chunk_decode(context->r_file_data,context->r_chunk_context,&iobuffer);
                if(err<0 || err==1) break;
            }
            while(iobuffer.length==0);
            nr=iobuffer.length;
        }
    }
    else /* if(context->r_zlib_context) */
    {
        if(!context->r_chunk_context)
        {
            /* Pre-emptively try uncompressing the data that already exists */
            if(context->r_file_data->length>0)
            {
                err=io_zlib_uncompress(context->r_file_data,context->r_zlib_context,&iobuffer);
                nr=iobuffer.length;
            }

            /* Read more data and uncompress it only if there was no error and no data already */
            if(err==0 && nr==0)
            {
                do
                {
                    if(context->gnutls_context)
                        err=io_gnutls_read_with_timeout(context->gnutls_context,context->r_file_data,context->r_timeout);
                    else
                        err=io_read_with_timeout(fd,context->r_file_data,context->r_timeout);
                    if(err>0) context->r_raw_bytes+=err;
                    if(err<0) break;
                    err=io_zlib_uncompress(context->r_file_data,context->r_zlib_context,&iobuffer);
                    if(err<0 || err==1) break;
                }
                while(iobuffer.length==0);
                nr=iobuffer.length;
            }
        }
        else /* if(context->r_chunk_context) */
        {
            /* Pre-emptively try uncompressing the data that already exists */
            if(context->r_zlch_data->length>0)
            {
                err=io_zlib_uncompress(context->r_zlch_data,context->r_zlib_context,&iobuffer);
                nr=iobuffer.length;
            }

            /* Read more data and uncompress it only if there was no error and no data already */
            if(err==0 && nr==0)
            {
                do
                {
                    if(context->gnutls_context)
                        err=io_gnutls_read_with_timeout(context->gnutls_context,context->r_file_data,context->r_timeout);
                    else
                        err=io_read_with_timeout(fd,context->r_file_data,context->r_timeout);
                    if(err>0) context->r_raw_bytes+=err;
                    if(err<0) break;
                    err=io_chunk_decode(context->r_file_data,context->r_chunk_context,context->r_zlch_data);
                    if(err<0) break;

                    /* Try uncompressing only if chunking is finished or there is data or zlib is initialised. */
                    if(err==1 || context->r_zlch_data->length>0 || context->r_zlib_context->stream.state)
                        err=io_zlib_uncompress(context->r_zlch_data,context->r_zlib_context,&iobuffer);

                    if(err<0 || err==1) break;
                }
                while(iobuffer.length==0);
                nr=iobuffer.length;
            }
        }
    }

    if(err<0)
        return(err);
    else
        return(nr);
}
int KITECH_SDM8::SetParameter(Property parameter)
{
	if(uart == NULL) {
		PrintMessage("ERROR : KITECH_SDM8::SetParameter() -> A handle of UART is NULL.\n");
		return API_ERROR;
	}

	if(parameter.FindName("Size") == false)				return API_ERROR;
	int size = atoi(parameter.GetValue("Size").c_str());

	if(size <= 0) 	return API_ERROR;
	
	joints.clear();
	joints.resize(size);

	char temp[64];
	
	for(int i = 0; i < size; i++) {
		sprintf(temp, "ID%d", i);
		if(parameter.FindName(string(temp)) == false)			goto ERROR_KITECH_SDM8_SET_PARAMETER;
		joints[i].id = atoi(parameter.GetValue(temp).c_str());

		sprintf(temp, "MaximumPower%d", i);
		if(parameter.FindName(string(temp)) == false)			goto ERROR_KITECH_SDM8_SET_PARAMETER;
		joints[i].maximumPower = atof(parameter.GetValue(temp).c_str());

		sprintf(temp, "LinePerRevolution%d", i);
		if(parameter.FindName(string(temp)) == false)			goto ERROR_KITECH_SDM8_SET_PARAMETER;
		joints[i].linePerRevolution = atof(parameter.GetValue(temp).c_str());

		sprintf(temp, "ReductionRatio%d", i);
		if(parameter.FindName(string(temp)) == false)			goto ERROR_KITECH_SDM8_SET_PARAMETER;
		joints[i].reductionRatio = atof(parameter.GetValue(temp).c_str());

		sprintf(temp, "MaximumVelocity%d", i);
		if(parameter.FindName(string(temp)) == false)			goto ERROR_KITECH_SDM8_SET_PARAMETER;
		joints[i].maximumVelocity = atof(parameter.GetValue(temp).c_str());

		sprintf(temp, "Acceleration%d", i);
		if(parameter.FindName(string(temp)) == false)			goto ERROR_KITECH_SDM8_SET_PARAMETER;
		joints[i].acceleration = atof(parameter.GetValue(temp).c_str());

		sprintf(temp, "MinimumPositionLimit%d", i);
		if(parameter.FindName(string(temp)) == false)			goto ERROR_KITECH_SDM8_SET_PARAMETER;
		joints[i].minimumPositionLimit = atof(parameter.GetValue(temp).c_str());

		sprintf(temp, "MaximumPositionLimit%d", i);
		if(parameter.FindName(string(temp)) == false)			goto ERROR_KITECH_SDM8_SET_PARAMETER;
		joints[i].maximumPositionLimit = atof(parameter.GetValue(temp).c_str());		

		joints[i].deg2pulse = ENCODER_RESOLUTION / 360.0 / joints[i].reductionRatio;
		joints[i].deg2rpm = 60.0 / 360.0 / joints[i].reductionRatio;

		joints[i].dynamixel = new RobotisDynamixelUART(joints[i].id, uart);
	}
	
	for(size_t i = 0; i < joints.size(); i++) {
		joints[i].dynamixel->SetMovingspeed(100);
	}

	this->parameter = parameter;

	return API_SUCCESS;

ERROR_KITECH_SDM8_SET_PARAMETER :
	PrintMessage("ERROR : KITECH_SDM8::SetParameter() -> Can't find parameters\n");
	joints.clear();
	joints.resize(size);
	return API_ERROR;
}
Beispiel #7
0
 void Debug::PrintMessage(std::string& message) {
     PrintMessage((const Char *)message.c_str());
 }
Beispiel #8
0
void PrintHeader( const char *title ) {
   PrintMessage( "----- %s -----\n", title );
}
Beispiel #9
0
void main() 
{
	PrintMessage("Hello, World\n");
}
Beispiel #10
0
/*----------------------------------------------------------------------------------------------------------------------
|	Called when the LOG command needs to be parsed from within the GarliReader block.
*/
void GarliReader::HandleLog(
  NxsToken &token)	/* the token used to read from `in' */
	{
	bool starting = false;
	bool stopping = false;
	bool appending = false;
	bool replacing = false;
	bool name_provided = false;
	NxsString logfname;

	// Retrieve all tokens for this command, stopping only in the event
	// of a semicolon or an unrecognized keyword
	//
	for (;;)
		{
		token.GetNextToken();

		if (token.Equals(";"))
			{
			break;
			}
		else if (token.Abbreviation("STOp"))
			{
			stopping = true;
			}
		else if (token.Abbreviation("STArt"))
			{
			starting = true;
			}
		else if (token.Abbreviation("Replace"))
			{
			replacing = true;
			}
		else if (token.Abbreviation("Append"))
			{
			appending = true;
			}
		else if (token.Abbreviation("File"))
			{
			logfname = GetFileName(token);
			name_provided = true;
			}
		else
			{
			errormsg = "Unexpected keyword (";
			errormsg += token.GetToken();
			errormsg += ") encountered reading LOG command";
			throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
			}
		}

	// Check for incompatible combinations of keywords
	//
	if (stopping && (starting || appending || replacing || name_provided))
		{
		errormsg = "Cannot specify STOP with any of the following START, APPEND, REPLACE, FILE";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	if (appending && replacing)
		{
		errormsg = "Cannot specify APPEND and REPLACE at the same time";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	if (logf_open && (starting || name_provided || appending || replacing))
		{
		errormsg = "Cannot start log file since log file is already open";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}

	// Is user closing an open log file?
	//
	if (stopping)
		{
		logf.close();
		logf_open = false;

		message = "\nLog file closed";
		PrintMessage();

		return;
		}

	// If this far, must be attempting to open a log file
	//
	if (!name_provided)
		{
		errormsg = "Must provide a file name when opening a log file\n";
		errormsg += "e.g., log file=doofus.txt start replace;";
		throw NxsException(errormsg, token.GetFilePosition(), token.GetFileLine(), token.GetFileColumn());
		}   

	if (appending)
		{
		logf_open = true;
		logf.open(logfname.c_str(), ios::out | ios::app);

		message = "\nAppending to log file ";
		message += logfname;
		PrintMessage();
		}

	else if (replacing)
		{
		logf_open = true;
		logf.open(logfname.c_str());

		message = "\nReplacing log file ";
		message += logfname;
		PrintMessage();
		}

	else 
		{
		bool exists = FileExists(logfname.c_str());
		bool userok = true;
		if (exists && !UserQuery("Ok to replace?", "Log file specified already exists", GarliReader::UserQueryEnum(GarliReader::uq_yes | GarliReader::uq_no)))
			userok = false;

		if (userok)
			{
			logf_open = true;
			logf.open(logfname.c_str());
			}

		if (exists && userok)
			{
			message = "\nReplacing log file ";
			message += logfname;
			}

		else if (userok)
			{
			message = "\nLog file ";
			message += logfname;
			message += " opened";
			}

		else
			{
			message = "\nLog command aborted";
			}

		PrintMessage();
		}
	}
Beispiel #11
0
// Call back Declaration
ReturnType JoystickComp::onInitialize()
{
	//	XML에 저장된 프라퍼티를 parameter에 저장
	Property parameter;
	std::map<std::string, std::string> temp = getPropertyMap();
	parameter.SetProperty(temp);
	
	//	dll 파일이름을 확인하여 없으면 에러 리턴
	if(parameter.FindName("APIName") == false) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't find the APIName in property\n");
		return OPROS_FIND_PROPERTY_ERROR;
	}

#if defined(WIN32)
	//	DLL 로드
	hOprosAPI = LoadLibrary((LPCSTR)parameter.GetValue("APIName").c_str());
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("APIName").c_str());
		return OPROS_FIND_DLL_ERROR;
	}
	
	//	API 로드
	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)GetProcAddress(hOprosAPI, "GetAPI");
	if(getOprosAPI == NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		FreeLibrary(hOprosAPI);
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}
#else
	hOprosAPI = dlopen(parameter.GetValue("APIName").c_str(), RTLD_LAZY);
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("APIName").c_str());
		return OPROS_FIND_DLL_ERROR;
	}

	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)dlsym(hOprosAPI, "GetAPI");
	char *lastError = dlerror();
	if(lastError != NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		dlclose(hOprosAPI);
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}
#endif
	
	joystick = static_cast<Joystick *>(getOprosAPI());
	if(joystick == NULL) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't get a handle of Joystick API\n");
#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return OPROS_LOAD_DLL_ERROR;
	}

	//	API 초기화
	if(joystick->Initialize(parameter) != API_SUCCESS) {
		PrintMessage("ERROR : JoystickComp::onInitialize() -> Can't intilaize a Joystick API\n");
		
		delete joystick;
		joystick = NULL;

#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return OPROS_INITIALIZE_API_ERROR;
	}

	lastError = OPROS_SUCCESS;

	PrintMessage("SUCCESS : JoystickComp::onInitialize()\n");
	return OPROS_SUCCESS;
}
BOOL  CMemStat::GetStatus(PBALLOON_STAT pStat)
{
    MEMORYSTATUS stat = {sizeof(stat)};
    CComPtr< IEnumWbemClassObject > enumerator;
    CComPtr< IWbemClassObject > memory;
    ULONG retcnt;
    _variant_t var_val;
    HRESULT status  = S_OK;
    UINT idx = 0;
    if(!pStat) {
        PrintMessage("Invalid pointer");
        return FALSE;
    }

    status = service->ExecQuery(
                             L"WQL",
                             L"SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory",
                             WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
                             NULL,
                             &enumerator
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot execute query");
        return FALSE;
    }

    while(enumerator)
    {
        status = enumerator->Next(
                             WBEM_INFINITE,
                             1L,
                             &memory,
                             &retcnt
                             );
        if (retcnt == 0) {
            break;
        }

        status = memory->Get( 
                             L"PagesInputPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PagesInputPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_SWAP_IN;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get( 
                             L"PagesOutputPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PagesOutputPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_SWAP_OUT;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get( 
                             L"PageReadsPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PageReadsPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_MAJFLT;
        pStat[idx].val = (long)var_val;
        idx++;

        status = memory->Get( 
                             L"PageFaultsPerSec",
                             0,
                             &var_val,
                             NULL,
                             NULL
                             );

        if (FAILED(status) || (var_val.vt == VT_NULL)) {
            PrintMessage("Cannot get PageFaultsPerSec");
            var_val.vt =  -1;
        }
        pStat[idx].tag = VIRTIO_BALLOON_S_MINFLT;
        pStat[idx].val = (long)var_val;
        idx++;

        GlobalMemoryStatus(&stat);

        pStat[idx].tag = VIRTIO_BALLOON_S_MEMFREE;
        pStat[idx].val = stat.dwAvailPhys;
        idx++;

        pStat[idx].tag = VIRTIO_BALLOON_S_MEMTOT;
        pStat[idx].val = stat.dwTotalPhys;
    }
    return TRUE;
}
BOOL CMemStat::Init()
{
    HRESULT status  = S_OK;
    status = CoInitializeEx(NULL,
                            COINIT_MULTITHREADED);
    if (FAILED(status)) {
        PrintMessage("Cannot initialize COM");
        return status;
    }
    initialized = TRUE;

    status = CoInitializeSecurity(
                             NULL,
                             -1,
                             NULL,
                             NULL,
                             RPC_C_AUTHN_LEVEL_PKT,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE,
                             0
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot initialize security");
        return FALSE;
    }

    status = CoCreateInstance(
                             CLSID_WbemLocator,
                             NULL,
                             CLSCTX_INPROC_SERVER,
                             IID_IWbemLocator,
                             reinterpret_cast< void** >( &locator )
                             );

    if (FAILED(status)) {
        PrintMessage("Cannot create instance");
        return FALSE;
    }

    status = locator->ConnectServer(
                             L"root\\cimv2",
                             NULL,
                             NULL,
                             0L,
                             0L,
                             NULL,
                             NULL,
                             &service
                             );
    if (FAILED(status)) {
        PrintMessage("Cannot connect to wmi server");
        return FALSE;
    }

    status = CoSetProxyBlanket(service,
                             RPC_C_AUTHN_WINNT,
                             RPC_C_AUTHZ_NONE,
                             NULL,
                             RPC_C_AUTHN_LEVEL_CALL,
                             RPC_C_IMP_LEVEL_IMPERSONATE,
                             NULL,
                             EOAC_NONE
                             );
    if (FAILED(status)) {
        PrintMessage("Cannot set proxy blanket");
        return FALSE;
    }
    return TRUE;
}
Beispiel #14
0
bool CompactingHashTable::Build(const unsigned  n,
                                const unsigned *d_keys,
                                const unsigned *d_values)
{
    CUDA_CHECK_ERROR("Failed before attempting to build.");

    unsigned num_failures = 1;
    unsigned num_attempts = 0;
    unsigned max_iterations = ComputeMaxIterations(n, table_size_,
                                                   num_hash_functions_);
    unsigned total_table_size = table_size_ + kStashSize;

    while (num_failures && ++num_attempts < kMaxRestartAttempts) {
        if (num_hash_functions_ == 2)
            constants_2_.Generate(n, d_keys, table_size_);
        else if (num_hash_functions_ == 3)
            constants_3_.Generate(n, d_keys, table_size_);
        else if (num_hash_functions_ == 4)
            constants_4_.Generate(n, d_keys, table_size_);
        else
            constants_5_.Generate(n, d_keys, table_size_);

        // Initialize the cuckoo hash table.
        CUDAWrapper::ClearTable(total_table_size,
                                kKeyEmpty,
                                d_scratch_cuckoo_keys_);

        num_failures = 0;
        cudaMemcpy(d_failures_,
                   &num_failures,
                   sizeof(unsigned),
                   cudaMemcpyHostToDevice);

        unsigned *d_stash_count = NULL;
        cudaMalloc((void**)&d_stash_count, sizeof(unsigned));
        cudaMemset(d_stash_count, 0, sizeof(unsigned));

        CUDAWrapper::CallHashBuildCompacting(n, 
                                             num_hash_functions_,
                                             d_keys,
                                             table_size_,
                                             constants_2_,
                                             constants_3_,
                                             constants_4_,
                                             constants_5_,
                                             stash_constants_,
                                             max_iterations,
                                             d_scratch_cuckoo_keys_,
                                             d_stash_count,
                                             d_failures_);

        CUDA_SAFE_CALL(cudaMemcpy(&stash_count_, d_stash_count, 
                                  sizeof(unsigned), cudaMemcpyDeviceToHost));
        if (stash_count_) {
            char buffer[256];
            sprintf(buffer, "Stash count: %u", stash_count_);
            PrintMessage(buffer, true);
        }
        CUDA_SAFE_CALL(cudaFree(d_stash_count));

        CUDA_CHECK_ERROR("!!! Failed to cuckoo hash.\n");

        CUDA_SAFE_CALL(cudaMemcpy(&num_failures,
                                  d_failures_,
                                  sizeof(unsigned),
                                  cudaMemcpyDeviceToHost));

#ifdef COUNT_UNINSERTED
        if (num_failures > 0) {
            char buffer[256];
            sprintf(buffer, "Num failures: %u", num_failures);
            PrintMessage(buffer, true);
        }
#endif
    }

    if (num_attempts >= kMaxRestartAttempts) {
        PrintMessage("Completely failed to build.", true);
        return false;
    } else if (num_attempts > 1) {
        char buffer[256];
        sprintf(buffer, "Needed %u attempts", num_attempts);
        PrintMessage(buffer);
    }

    if (num_failures == 0) {
        CUDAWrapper::CallHashRemoveDuplicates(num_hash_functions_,
                                              table_size_,
                                              total_table_size,
                                              constants_2_,
                                              constants_3_,
                                              constants_4_,
                                              constants_5_,
                                              stash_constants_,
                                              d_scratch_cuckoo_keys_,
                                              d_scratch_counts_);

        // Do a prefix-sum over the values to assign each key a unique index.
        CUDPPConfiguration config;
        config.op        = CUDPP_ADD;
        config.datatype  = CUDPP_UINT;
        config.algorithm = CUDPP_SCAN;
        config.options   = CUDPP_OPTION_FORWARD | CUDPP_OPTION_INCLUSIVE;

        CUDPPResult result = cudppPlan(theCudpp, &scanplan_, config, 
                                       total_table_size, 1, 0);
        if (CUDPP_SUCCESS == result) {
            cudppScan(scanplan_, d_scratch_unique_ids_, d_scratch_counts_,
                      total_table_size);
        } else {
            PrintMessage("!!! Failed to create plan.", true);
        }
        CUDA_CHECK_ERROR("!!! Scan failed.\n");

        // Determine how many unique values there are.
        CUDA_SAFE_CALL(cudaMemcpy(&unique_keys_size_,
                                  d_scratch_unique_ids_ + total_table_size - 1,
                                  sizeof(unsigned),
                                  cudaMemcpyDeviceToHost));

        // Copy the unique indices back and compact down the neighbors.
        CUDA_SAFE_CALL(cudaMalloc((void**)&d_unique_keys_,
                                  sizeof(unsigned) * unique_keys_size_));
        CUDA_SAFE_CALL(cudaMemset(d_unique_keys_,
                                  0xff,
                                  sizeof(unsigned) * unique_keys_size_));
        CUDAWrapper::CallHashCompactDown(total_table_size, 
                                         d_contents_, 
                                         d_unique_keys_, 
                                         d_scratch_cuckoo_keys_, 
                                         d_scratch_unique_ids_);
    }

    CUDA_CHECK_ERROR("Error occurred during hash table build.\n");

    return true;
}
DWORD CService::ServiceHandlePowerEvent(DWORD evtype, DWORD flags)
{
    PrintMessage("ServiceHandlePowerEvent");
    return NO_ERROR;
}
Beispiel #16
0
/*********************************************************************//**
 * @brief		c_entry: Main CAN program body
 * @param[in]	none
 * @return 		int
 **********************************************************************/
int c_entry(void) { /* Main Program */
	uint32_t i;
	uint32_t cnt;
	CAN_ERROR error;
	PINSEL_CFG_Type PinCfg;

	/* Initialize debug via UART0
	 * – 115200bps
	 * – 8 data bit
	 * – No parity
	 * – 1 stop bit
	 * – No flow control
	 */
	debug_frmwrk_init();
	print_menu();

	/* Pin configuration
	 * CAN1: select P0.0 as RD1. P0.1 as TD1
	 * CAN2: select P2.7 as RD2, P2.8 as RD2
	 */
	PinCfg.Funcnum = 1;
	PinCfg.OpenDrain = 0;
	PinCfg.Pinmode = 0;
	PinCfg.Pinnum = 0;
	PinCfg.Portnum = 0;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 1;
	PINSEL_ConfigPin(&PinCfg);

	PinCfg.Pinnum = 7;
	PinCfg.Portnum = 2;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 8;
	PINSEL_ConfigPin(&PinCfg);

	//Initialize CAN1 & CAN2
	CAN_Init(LPC_CAN1, 125000);
	CAN_Init(LPC_CAN2, 125000);

	//Enable Receive Interrupt
	CAN_IRQCmd(LPC_CAN2, CANINT_FCE, ENABLE);
	CAN_IRQCmd(LPC_CAN2, CANINT_RIE, ENABLE);

	//Enable CAN Interrupt
	NVIC_EnableIRQ(CAN_IRQn);

	/* First, we send 10 messages:
	 * - message 0,2,4,6,8 have id in AFLUT >>> will be received
	 * - message 1,3,5,7,9 don't have id in AFLUT >>> will be ignored
	 * Then, we change AFLUT by load/remove entries in AFLUT and re-send messages
	 * - message 1,3,5,7,9 have id in AFLUT >>> will be received
	 * - message 0,2,4,6,8 don't have id in AFLUT >>> will be ignored
	 * Note that: FullCAN Object must be read from FullCAN Object Section next to AFLUT
	 */
	/*-------------------------Init Message & AF Look-up Table------------------------*/

	_DBG_("Test Acceptance Filter function...");
	_DBG_("Press '1' to initialize message and AF Loop-up Table...");_DBG_("");
	while(_DG !='1');
	CAN_InitAFMessage(); /* initialize Transmit Message */
	_DBG_("Init message finished!!!");
	CAN_SetupAFTable(); /* initialize AF Look-up Table sections*/
	error = CAN_SetupAFLUT(LPC_CANAF,&AFTable); /* install AF Look-up Table */
	if (error != CAN_OK) {
		_DBG_("Setup AF: ERROR...");
		while (1); // AF Table has error
	}
	else _DBG_("Setup AF: SUCCESSFUL!!!");_DBG_("");


	/*-------------------------Send messages------------------------*/
	_DBG_("Press '2' to start CAN transferring operation...");_DBG_("");
	while(_DG !='2');
	for (i = 0; i < CAN_TX_MSG_CNT; i++) {
		CAN_SendMsg(LPC_CAN1, &AFTxMsg[i]);
		PrintMessage(&AFTxMsg[i]);_DBG_("");
		for(cnt=0;cnt<10000;cnt++); //transmit delay
		CANTxCount++;
	}
	_DBG_("Sending finished !!!");

	/*-------------------------Display Received messages------------------------*/
	_DBG_("Press '3' to display received messages...");_DBG_("");
	while(_DG !='3');
	for (i = 0; i < CAN_RX_MSG_CNT; i++) {
		PrintMessage(&AFRxMsg[i]);_DBG_("");
	}

	/*-------------------------Change AFLUT Table --------------------*/
	_DBG_("Press '4' to change AF look-up table...");_DBG_("");
	while(_DG !='4');
	CAN_ChangeAFTable();
	_DBG_("Change AFLUT: FINISHED!!!");
	CAN_SetAFMode(LPC_CANAF, CAN_eFCAN);
	CAN_InitAFMessage();
	CANRxCount = CANTxCount = 0;

	/*-------------------------Re-Send messages------------------------*/
	_DBG_("Press '5' to re-send messages...");_DBG_("");
	while(_DG !='5');
	for (i = 0; i < CAN_TX_MSG_CNT; i++) {
		CAN_SendMsg(LPC_CAN1, &AFTxMsg[i]);
		PrintMessage(&AFTxMsg[i]);_DBG_("");
		for(cnt=0;cnt<10000;cnt++); //transmit delay
		CANTxCount++;
	}

	/*-------------------------Display received messages------------------------*/
	_DBG_("Re-Sending finished !!!");

	_DBG_("Press '6' to display received messages...");_DBG_("");
	while(_DG !='6');
	for (i = 0; i < CAN_RX_MSG_CNT; i++) {
		PrintMessage(&AFRxMsg[i]);_DBG_("");
	}
	_DBG_("Demo terminal !!!");

	CAN_DeInit(LPC_CAN1);
	CAN_DeInit(LPC_CAN2);
	while (1);
	return 0;
}
  void Meshing2 :: BlockFillLocalH (Mesh & mesh, const MeshingParameters & mp)
  {
    double filldist = mp.filldist;

    cout << "blockfill local h" << endl;
    cout << "rel filldist = " << filldist << endl;
    PrintMessage (3, "blockfill local h");

    Array<Point<3> > npoints;

    // adfront -> CreateTrees();

    Box<3> bbox ( Box<3>::EMPTY_BOX );
    double maxh = 0;

    for (int i = 0; i < adfront->GetNFL(); i++)
      {
	const FrontLine & line = adfront->GetLine (i);

	const Point<3> & p1 = adfront->GetPoint(line.L().I1());
	const Point<3> & p2 = adfront->GetPoint(line.L().I2());

	double hi = Dist (p1, p2);
	if (hi > maxh) maxh = hi;

	bbox.Add (p1);
	bbox.Add (p2);
      }


    cout << "bbox = " << bbox << endl;


    // Point<3> mpc = bbox.Center();
    bbox.Increase (bbox.Diam()/2);
    Box<3> meshbox = bbox;

    LocalH loch2 (bbox, 1);

    if (mp.maxh < maxh) maxh = mp.maxh;

    bool changed;
    do
      {
	mesh.LocalHFunction().ClearFlags();

	for (int i = 0; i < adfront->GetNFL(); i++)
	  {
	    const FrontLine & line = adfront->GetLine(i);

	    Box<3> bbox (adfront->GetPoint (line.L().I1()));
	    bbox.Add (adfront->GetPoint (line.L().I2()));


	    double filld = filldist * bbox.Diam();
	    bbox.Increase (filld);

	    mesh.LocalHFunction().CutBoundary (bbox);
	  }


	mesh.LocalHFunction().FindInnerBoxes (adfront, NULL);

	npoints.SetSize(0);
	mesh.LocalHFunction().GetInnerPoints (npoints);

	changed = false;
	for (int i = 0; i < npoints.Size(); i++)
	  {
	    if (mesh.LocalHFunction().GetH(npoints[i]) > 1.5 * maxh)
	      {
		mesh.LocalHFunction().SetH (npoints[i], maxh);
		changed = true;
	      }
	  }
      }
    while (changed);

    if (debugparam.slowchecks)
      (*testout) << "Blockfill with points: " << endl;
    *testout << "loch = " << mesh.LocalHFunction() << endl;

    *testout << "npoints = " << endl << npoints << endl;

    for (int i = 1; i <= npoints.Size(); i++)
      {
	if (meshbox.IsIn (npoints.Get(i)))
	  {
	    PointIndex gpnum = mesh.AddPoint (npoints.Get(i));
	    adfront->AddPoint (npoints.Get(i), gpnum);

	    if (debugparam.slowchecks)
	      {
		(*testout) << npoints.Get(i) << endl;

		Point<2> p2d (npoints.Get(i)(0), npoints.Get(i)(1));
		if (!adfront->Inside(p2d))
		  {
		    cout << "add outside point" << endl;
		    (*testout) << "outside" << endl;
		  }
	      }

	  }
      }



  // find outer points

    loch2.ClearFlags();

    for (int i = 0; i < adfront->GetNFL(); i++)
      {
	const FrontLine & line = adfront->GetLine(i);

	Box<3> bbox (adfront->GetPoint (line.L().I1()));
	bbox.Add (adfront->GetPoint (line.L().I2()));

	loch2.SetH (bbox.Center(), bbox.Diam());
      }


    for (int i = 0; i < adfront->GetNFL(); i++)
      {
	const FrontLine & line = adfront->GetLine(i);

	Box<3> bbox (adfront->GetPoint (line.L().I1()));
	bbox.Add (adfront->GetPoint (line.L().I2()));

	bbox.Increase (filldist * bbox.Diam());
	loch2.CutBoundary (bbox);
      }

    loch2.FindInnerBoxes (adfront, NULL);

    npoints.SetSize(0);
    loch2.GetOuterPoints (npoints);

    for (int i = 1; i <= npoints.Size(); i++)
      {
	if (meshbox.IsIn (npoints.Get(i)))
	  {
	    PointIndex gpnum = mesh.AddPoint (npoints.Get(i));
	    adfront->AddPoint (npoints.Get(i), gpnum);
	  }
      }

  }
LfcCommand * StartTransState2::NextState(
        std::vector<Item *>::const_iterator & iterator,
        vector<Item*> items,
        Item* item
        ) {

    bool secondStatg = false;
    bool mkdir = false;
    bool creat = false;
    bool setfsizeg = false;
    bool addreplica = false;

    vector<Item *> itemsToAssigne;

    for (; iterator != items.end() and
            *iterator != NULL
            ; ++iterator) {
        Item * item2 = *iterator;
        if (!item2->IsAssigned()) {
            if (item->compareUserSiteTid(item2)) {
                FunctionType function = item2->GetCommand()->getName();

                if (function == STATG) {
                    int retCommand = item2->GetCommand()->getReturnCode();
                    if (retCommand == 0 and !secondStatg) {
                        secondStatg = true;
                        PrintMessage("START TRANS 2 STATG 0", item2);
                        itemsToAssigne.push_back(item2);
                    }
                } else if (function == MKDIR and !mkdir) {
                    mkdir = true;
                    PrintMessage("START TRANS 2 MKDIR", item2);
                    itemsToAssigne.push_back(item2);
                } else if (function == CREAT and !creat) {
                    creat = true;
                    itemsToAssigne.push_back(item2);

                    string::size_type pos;
                    pos = item2->GetFilePath().find(' ', 0);
                    string second = item2->GetFilePath().substr(pos + 1);
                    string first = item2->GetFilePath().substr(0, pos);
                    item->SetFilePath(first);
                    PrintMessage("START TRANS 2 CREAT", item2);
                } else if (function == SETFSIZEG and !setfsizeg) {
                    setfsizeg = true;
                    itemsToAssigne.push_back(item2);
                    PrintMessage("START TRANS 2 SETFSIZEG", item2);
                } else if (function == ADDREPLICA and !addreplica) {
                    addreplica = true;
                    itemsToAssigne.push_back(item2);
                    PrintMessage("START TRANS 2 ADDREPLICA", item2);
                } else if (function == ENDTRANS) {
                    PrintMessage("START TRANS 2 END TRANS", item2);
                    itemsToAssigne.push_back(item2);
                    item->SetEndTime(item2->GetEndTime());
                    this->AssignAllItems(itemsToAssigne);
                    return new LfcCrCommand(item->GetStartTime(),
                            item->GetEndTime(),
                            item->GetFilePath(),
                            item->GetUser(),
                            item->GetSite(),
                            false,
                            NULL);
                }
            }
        }

        if (*iterator == items.back()) {
            break;
        }
    }

    PrintMessage("START TRANS 2 NULL", item);
    return NULL;
}
int KITECH_SDM8::InitializeUART(Property parameter)
{
	Property uartParameter;

	if(parameter.FindName("UARTAPIName") == false)	return API_ERROR;
	if(parameter.FindName("PortName") == false)	return API_ERROR;	uartParameter.SetValue("PortName", parameter.GetValue("PortName"));
	if(parameter.FindName("TimeOut") == false)		return API_ERROR;	uartParameter.SetValue("TimeOut", parameter.GetValue("TimeOut"));
	if(parameter.FindName("BaudRate") == false)	return API_ERROR;	uartParameter.SetValue("BaudRate", parameter.GetValue("BaudRate"));
	if(parameter.FindName("DataBits") == false)	return API_ERROR;	uartParameter.SetValue("DataBits", parameter.GetValue("DataBits"));
	if(parameter.FindName("StopBits") == false)	return API_ERROR;	uartParameter.SetValue("StopBits", parameter.GetValue("StopBits"));
	if(parameter.FindName("Parity") == false)		return API_ERROR;	uartParameter.SetValue("Parity", parameter.GetValue("Parity"));
	if(parameter.FindName("FlowControl") == false)	return API_ERROR;	uartParameter.SetValue("FlowControl", parameter.GetValue("FlowControl"));

	if(uart != NULL) {
		delete uart;
	}
#if defined(WIN32)
	//	DLL 로드
	hOprosAPI = LoadLibrary((LPCSTR)parameter.GetValue("UARTAPIName").c_str());
	if(hOprosAPI == NULL) {
		return API_ERROR;
	}

	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)GetProcAddress(hOprosAPI, "GetAPI");
	if(getOprosAPI == NULL) {
		FreeLibrary(hOprosAPI);
		hOprosAPI = NULL;
		return API_ERROR;
	}
#else
	hOprosAPI = dlopen(parameter.GetValue("UARTAPIName").c_str(), RTLD_LAZY);
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : InitializeUART() -> dlopen (%s)\n",parameter.GetValue("UARTDllName").c_str());
		return API_ERROR;
	}

	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)dlsym(hOprosAPI, "GetAPI");
	char *error = dlerror();
	if(error != NULL) {
		PrintMessage ("ERROR -> %s\n", error);
		dlclose(hOprosAPI);
		hOprosAPI = NULL;
		return API_ERROR;
	}
#endif

	uart = (UART *)getOprosAPI();
	if(uart == NULL) {
#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return API_ERROR;
	}

	//	API 초기화
	if(uart->Initialize(uartParameter) < 0) {
		FinalizeUART();
		return API_ERROR;
	}

	if(uart->Enable() < 0) {
		FinalizeUART();
		return API_ERROR;
	}

	return API_SUCCESS;
}
Beispiel #20
0
//evaluates and * and / expression
void CStateParser::Term(CTokenizer &tok,CStateManager &StateManager)
{
         
     Primary(tok,StateManager);
     
     //search for operators 
     while( tok.CheckToken("*",false) || tok.CheckToken("/",false)  || 
            tok.CheckToken("=",false) || tok.CheckToken("!=",false) ||
            tok.CheckToken("<",false) || tok.CheckToken("<=",false) ||
            tok.CheckToken(">",false) || tok.CheckToken(">=",false) ||
            tok.CheckToken(":",false) || /*tok.CheckToken("&&",false) || 
            tok.CheckToken("||",false)||*/ tok.CheckToken("^^",false) ||
            tok.CheckToken("&",false) || tok.CheckToken("~",false)  ||
            tok.CheckToken("|",false) || tok.CheckToken("^",false)  || 
            tok.CheckToken("%",false) || tok.CheckToken("(", false) 	
			&& !tok.AtEndOfLine() )  
     {  
      
            if( tok.CheckToken("*") )
            {
                //Have we a ** operator?
                if( tok.CheckToken("*") )
                {
                    Primary(tok,StateManager);
                    StateManager.AddInstruction(OP_SQUARE,0,"#");
                    
                }else
                {
                    Primary(tok,StateManager);
                    StateManager.AddInstruction(OP_MUL,0,"#");
                }
            }
         
           if( tok.CheckToken("/") )
           {
               Primary(tok,StateManager);
               StateManager.AddInstruction(OP_DIV,0,"#");
           }
           
           if( tok.CheckToken("=") )
           {    
                //check for intervall operator
                if( tok.CheckToken("(") )
                {
                    //evaluate first expression                   
                    EvaluateExpression(tok,StateManager);
                    if( !tok.CheckToken(",") )
                        Error("Expectetd a , in intervall operator",tok);

                    //evaluate second expression 
                    EvaluateExpression(tok,StateManager);
                    
                    //intervall op =(,)
                    if( tok.CheckToken(")") )
                    {
                        StateManager.AddInstruction(OP_INTERVALOP4,0,"#");
                    }else if( tok.CheckToken("]") )
                    {
                         StateManager.AddInstruction(OP_INTERVALOP3,0,"#");
                    }
                    
                }else if (tok.CheckToken("[") )
                {
                    //evaluate first expression                   
                    EvaluateExpression(tok,StateManager);
                    if( !tok.CheckToken(",") )
                        Error("Expectetd a , in intervall operator",tok);

                    //evaluate second expression 
                    EvaluateExpression(tok,StateManager);
                    
                    //intervall op =[,)
                    if( tok.CheckToken(")") )
                    {
                       StateManager.AddInstruction(OP_INTERVALOP2,0,"#");
                    }else if( tok.CheckToken("]") )
                    {
                         StateManager.AddInstruction(OP_INTERVALOP1,0,"#");
                    }
                      
                }
                else // is the = op
                {                
					//evalute the right side of the operator
					Primary(tok,StateManager);
					StateManager.AddInstruction(OP_EQUAL,0,"#");
                }
           }
           
           if( tok.CheckToken(":") )
           {    //evalute the right side of the operator
                if(tok.CheckToken("="))
                {
                 EvaluateExpression(tok,StateManager);
                 PrintMessage("TODO:Handel assign operator :=");
                }
           }
           
           if( tok.CheckToken("!=") )
           {    //evalute the right side of the operator
                //check for intervall operator
                if( tok.CheckToken("(") )
                {
                    //evaluate first expression                   
                    EvaluateExpression(tok,StateManager);
                    if( !tok.CheckToken(",") )
                        Error("Expectetd a , in intervall operator",tok);

                    //evaluate second expression 
                    EvaluateExpression(tok,StateManager);
                    
                    //intervall op !=(,)
                    if( tok.CheckToken(")") )
                    {
                        StateManager.AddInstruction(OP_INTERVALOP8,0,"#");
                    }else if( tok.CheckToken("]") )
                    {
                         StateManager.AddInstruction(OP_INTERVALOP7,0,"#");
                    }
                    
                }else if (tok.CheckToken("[") )
                {
                    //evaluate first expression                   
                    EvaluateExpression(tok,StateManager);
                    if( !tok.CheckToken(",") )
                        Error("Expectetd a , in intervall operator",tok);

                    //evaluate second expression 
                    EvaluateExpression(tok,StateManager);
                    
                    //intervall op !=[,)
                    if( tok.CheckToken(")") )
                    {
                       StateManager.AddInstruction(OP_INTERVALOP6,0,"#");
                    }else if( tok.CheckToken("]") )
                    {
                         StateManager.AddInstruction(OP_INTERVALOP5,0,"#");
                    }
                      
                }
                else // is the != op
                {                
					//evalute the right side of the operator
					//EvaluateExpression(tok,StateManager);
					Primary(tok,StateManager);
					StateManager.AddInstruction(OP_NOTEQUAL,0,"#");
					continue;
                }
                //EvaluateExpression(tok,StateManager);
                //StateManager.AddInstruction(OP_NOTEQUAL,0,"#");
           }
           
           if( tok.CheckToken("<") )
           {    //evalute the right side of the operator
                EvaluateExpression(tok,StateManager);
                StateManager.AddInstruction(OP_LESS,0,"#");
           }
           
           if( tok.CheckToken("<=") )
           {    //evalute the right side of the operator
                EvaluateExpression(tok,StateManager);
                StateManager.AddInstruction(OP_LESSEQUAL,0,"#");
           }
           
           if( tok.CheckToken(">") )
           {    //evalute the right side of the operator
                EvaluateExpression(tok,StateManager);
                StateManager.AddInstruction(OP_GREATER,0,"#");
           }
           
           if( tok.CheckToken(">=") )
           {    //evalute the right side of the operator
                EvaluateExpression(tok,StateManager);
                StateManager.AddInstruction(OP_GRAETEREQUAL,0,"#");
           }
           
//            if( tok.CheckToken("&&") )
//            {    //evalute the right side of the operator
//                 EvaluateExpression(tok,StateManager);
//                 StateManager.AddInstruction(OP_LOGAND,0,"#");
//            }
           
//            if( tok.CheckToken("||") )
//            {    //evalute the right side of the operator
//                 EvaluateExpression(tok,StateManager);
//                 StateManager.AddInstruction(OP_LOGOR,0,"#");
//            }
           
           if( tok.CheckToken("^^") ) // is this realy needed?
                                      //FIXME:Cant read ^^
           {    //evalute the right side of the operator
                EvaluateExpression(tok,StateManager);
                StateManager.AddInstruction(OP_LOGXOR,0,"#");
           }
           
           if( tok.CheckToken("&") ) 
           {    //evalute the right side of the operator
                Primary(tok,StateManager);
                StateManager.AddInstruction(OP_AND,0,"#");
           }
           
           if( tok.CheckToken("~") ) 
           {    //evalute the right side of the operator
                Primary(tok,StateManager);
                StateManager.AddInstruction(OP_NOT,0,"#");
           }
           
           if( tok.CheckToken("|") ) 
           {    //evalute the right side of the operator
                Primary(tok,StateManager);
                StateManager.AddInstruction(OP_OR,0,"#");
           }
           
           if( tok.CheckToken("^") ) 
           {    //evalute the right side of the operator
                Primary(tok,StateManager);
                StateManager.AddInstruction(OP_XOR,0,"#");
           }
           
           if( tok.CheckToken("%") ) 
           {    //evalute the right side of the operator
                Primary(tok,StateManager);
                StateManager.AddInstruction(OP_MOD,0,"#");
           }

		   if (tok.CheckToken("("))
		   {
			   EvaluateExpression(tok,StateManager);

			   if( !tok.CheckToken(")") )
				   Error("Missing )",tok);
		   }
           
      }
     
}
Beispiel #21
0
// ************ The ship handling screen ************ //
void Base::ShipScreen()
{
	char tempstring[200], temp2string[200];

	meter[0].value = dummy.maxpower;			//Ship power usage
	meter[0].maxvalue = MAXPOWERMETERVALUE;
	meter[0].type = MPOWER;
	meter[1].value = dummy.maxenergy;			//Ship energy
	meter[1].maxvalue = MAXENERGYMETERVALUE;
	meter[1].type = MENERGY;
	meter[2].value = dummy.forwardsspeed;			//Ship speed
	meter[2].maxvalue = MAXSPEEDMETERVALUE;
	meter[2].type = MSPEED;

	sprintf_s(descstring,2048,"%s",dummy.description);
	if(playmode==SINGLEPLAYER)
	{
		UINT m[6];
		m[0] = messageindex;
		for(int i=1;i<6;++i)
			m[i] = (m[0]+i)%6;
		if(newmessagetime<=thistick)
		{
			newmessagetime = thistick + rand()%800;
			PrintMessage(message[messageindex].txt);
			messageindex = (messageindex + 1)%6;
		}
		sprintf_s(descstring2,2048,"%s\n%s\n%s\n%s\n%s\n%s\n",message[m[0]].txt,message[m[1]].txt,message[m[2]].txt,message[m[3]].txt,message[m[4]].txt,message[m[5]].txt);
	}
	else sprintf_s(descstring2,2048," \0");

	sprintf_s(datastring,2048,"Ship: %s\nManufacturer: %s\nPower: %.1f\nEnergy: %.1f\nEngines: %d\nWeapon mounts: %d\nMissile capacity: %d \0",dummy.name,dummy.manufacturer,dummy.maxpower,dummy.maxenergy,dummy.engines,dummy.weaponmounts,dummy.maxmissiles);

	if(ship[player].keys.OPERATE)
	{
		ship[player].keys.OPERATE = false;
		soundeffect[MENUSELECT].SetSoundEffect(0);
		switch(button[buttonselector])
		{
		case EXIT:
			ChangeScreen(HOME);
			return;
		case SELECT:		//Select
			if(strcmp(data->ships[listselector].name,ship[player].name)==0)
			{
				soundeffect[MENUREJECT].SetSoundEffect(0);
				sprintf_s(messagestring,1024,"This is the same as your current ship!");
				break;
			}
			if(ship[player].credits>=dummy.cost)
			{
				ship[player].credits -= dummy.cost;

				if(ship[player].equipment[LASER_DRONE])
				{
					SET(ship[player].drone->state,FORDESTRUCTION);
					ship[player].drone = NULL;
				}
				if(ship[player].equipment[LIGHTNING_DRONE])
				{
					SET(ship[player].lightningdrone->state,FORDESTRUCTION);
					ship[player].lightningdrone = NULL;
				}
				if(ship[player].equipment[SHIELD_DRONE])
				{
					for(int i=0;i<3;i++)
					{
						SET(ship[player].shielddrone[i]->state,FORDESTRUCTION);
						ship[player].shielddrone[i] = NULL;
					}
				}
				for(int i=0;i<NUMEQUIPTYPES;i++)
					if(ship[player].equipment[i])
					{
						data->equipment[i] = true;
						ship[player].equipment[i] = false;
					}

				if(ship[player].missiles)
				{
					if(dummy.missilemount)
					{
						if(dummy.maxmissiles>=ship[player].missiles) dummy.missiles = ship[player].missiles;
						else dummy.missiles = dummy.maxmissiles;
					}
					else dummy.missiles = 0;
				}
				ship[player].power = 0;
				dummy.credits = ship[player].credits;
				strcpy_s(tempstring,50,ship[player].filename);	//Save file name of our ship
				strcpy_s(temp2string,50,ship[player].name);		//Save name of our ship
				DuplicatePlayer(&dummy,&ship[player]);
				ship[player].equipment[RADAR] = true;
				ship[player].equipment[SCANNER] = true;
				sprintf_s(messagestring,1024,"Changed to %s, charge %d",ship[player].name,ship[player].cost);
				//dbout<<"Current ship now "<<ship[player].name<<", ship in base "<<data->ships[listselector].name<<endl;
			}
			else
			{
				soundeffect[MENUREJECT].SetSoundEffect(0);
				sprintf_s(messagestring,1024,"Not enough credits - cost %d",dummy.cost);
			}
			break;
		case EQUIP:		//Equip screen
			ChangeScreen(EQUIP);
			return;
		case WEAPON:		//Weapon screen
			ChangeScreen(WEAPON);
			return;
		case SHIP:
			ChangeScreen(SHIP);
			return;
		}
	}
	if(ship[player].keys.UP)
	{
		ship[player].keys.UP = false;
		if(--listselector<0) listselector = data->numships-1;
		LoadDummy(data->ships[listselector].filename);
		//glyph.CreateGraphicalObject(dummy.blueprintfile,1);
		sprintf_s(messagestring,1024,"Cost: %d    Credits: %d",dummy.cost,ship[player].credits);
		soundeffect[MENUMOVE].SetSoundEffect(0);
	}
	else if(ship[player].keys.DOWN)
	{
		ship[player].keys.DOWN = false;
		if(++listselector==data->numships) listselector = 0;
		LoadDummy(data->ships[listselector].filename);
		//glyph.CreateGraphicalObject(dummy.blueprintfile,1);
		sprintf_s(messagestring,1024,"Cost: %d    Credits: %d",dummy.cost,ship[player].credits);
		soundeffect[MENUMOVE].SetSoundEffect(0);
	}

	return;
}
void COpenProgDlg::PIC18_ID(int id)
{
	char s[64];
	switch(id>>5){
		case 0x040>>1:
			sprintf(s,"18F252/2539 rev%d\r\n",id&0x1F);
			break;
		case 0x042>>1:
			sprintf(s,"18F452/4539 rev%d\r\n",id&0x1F);
			break;
		case 0x048>>1:
			sprintf(s,"18F242/2439 rev%d\r\n",id&0x1F);
			break;
		case 0x04A>>1:
			sprintf(s,"18F442/4439 rev%d\r\n",id&0x1F);
			break;
		case 0x050>>1:
			sprintf(s,"18F2320 rev%d\r\n",id&0x1F);
			break;
		case 0x052>>1:
			sprintf(s,"18F4320 rev%d\r\n",id&0x1F);
			break;
		case 0x058>>1:
			sprintf(s,"18F2220 rev%d\r\n",id&0x1F);
			break;
		case 0x05A>>1:
			sprintf(s,"18F4220 rev%d\r\n",id&0x1F);
			break;
		case 0x07C>>1:
			sprintf(s,"18F1320 rev%d\r\n",id&0x1F);
			break;
		case 0x07E>>1:
			sprintf(s,"18F1220 rev%d\r\n",id&0x1F);
			break;
		case 0x080>>1:
			sprintf(s,"18F248 rev%d\r\n",id&0x1F);
			break;
		case 0x082>>1:
			sprintf(s,"18F448 rev%d\r\n",id&0x1F);
			break;
		case 0x084>>1:
			sprintf(s,"18F258 rev%d\r\n",id&0x1F);
			break;
		case 0x086>>1:
			sprintf(s,"18F458 rev%d\r\n",id&0x1F);
			break;
		case 0x088>>1:
			sprintf(s,"18F4431 rev%d\r\n",id&0x1F);
			break;
		case 0x08A>>1:
			sprintf(s,"18F4331 rev%d\r\n",id&0x1F);
			break;
		case 0x08C>>1:
			sprintf(s,"18F2431 rev%d\r\n",id&0x1F);
			break;
		case 0x08E>>1:
			sprintf(s,"18F2331 rev%d\r\n",id&0x1F);
			break;
		case 0x0C0>>1:
			sprintf(s,"18F4620 rev%d\r\n",id&0x1F);
			break;
		case 0x0C2>>1:
			sprintf(s,"18F4610 rev%d\r\n",id&0x1F);
			break;
		case 0x0C4>>1:
			sprintf(s,"18F4525 rev%d\r\n",id&0x1F);
			break;
		case 0x0C6>>1:
			sprintf(s,"18F4515 rev%d\r\n",id&0x1F);
			break;
		case 0x0C8>>1:
			sprintf(s,"18F2620 rev%d\r\n",id&0x1F);
			break;
		case 0x0CA>>1:
			sprintf(s,"18F2610 rev%d\r\n",id&0x1F);
			break;
		case 0x0CC>>1:
			sprintf(s,"18F2525 rev%d\r\n",id&0x1F);
			break;
		case 0x0CE>>1:
			sprintf(s,"18F2515 rev%d\r\n",id&0x1F);
			break;
		case 0x0E8>>1:
			sprintf(s,"18F4680 rev%d\r\n",id&0x1F);
			break;
		case 0x0EA>>1:
			sprintf(s,"18F4585 rev%d\r\n",id&0x1F);
			break;
		case 0x0EC>>1:
			sprintf(s,"18F2680 rev%d\r\n",id&0x1F);
			break;
		case 0x0EE>>1:
			sprintf(s,"18F2585 rev%d\r\n",id&0x1F);
			break;
		case 0x108>>1:
			if(id&0x10) sprintf(s,"18F4523 rev%d\r\n",id&0x1F);
			else sprintf(s,"18F4520 rev%d\r\n",id&0x1F);
			break;
		case 0x10A>>1:
			sprintf(s,"18F4510 rev%d\r\n",id&0x1F);
			break;
		case 0x10C>>1:
			if(id&0x10) sprintf(s,"18F4423 rev%d\r\n",id&0x1F);
			else sprintf(s,"18F4420 rev%d\r\n",id&0x1F);
			break;
		case 0x10E>>1:
			sprintf(s,"18F4410 rev%d\r\n",id&0x1F);
			break;
		case 0x110>>1:
			if(id&0x10) sprintf(s,"18F2523 rev%d\r\n",id&0x1F);
			else sprintf(s,"18F2520 rev%d\r\n",id&0x1F);
			break;
		case 0x112>>1:
			sprintf(s,"18F2510 rev%d\r\n",id&0x1F);
			break;
		case 0x114>>1:
			if(id&0x10) sprintf(s,"18F2423 rev%d\r\n",id&0x1F);
			else sprintf(s,"18F2420 rev%d\r\n",id&0x1F);
			break;
		case 0x116>>1:
			sprintf(s,"18F2410 rev%d\r\n",id&0x1F);
			break;
		case 0x120>>1:
			sprintf(s,"18F4550 rev%d\r\n",id&0x1F);
			break;
		case 0x122>>1:
			sprintf(s,"18F4455 rev%d\r\n",id&0x1F);
			break;
		case 0x124>>1:
			sprintf(s,"18F2550 rev%d\r\n",id&0x1F);
			break;
		case 0x126>>1:
			sprintf(s,"18F2455 rev%d\r\n",id&0x1F);
			break;
		case 0x134>>1:
			sprintf(s,"18F6527 rev%d\r\n",id&0x1F);
			break;
		case 0x136>>1:
			sprintf(s,"18F8527 rev%d\r\n",id&0x1F);
			break;
		case 0x138>>1:
			sprintf(s,"18F6622 rev%d\r\n",id&0x1F);
			break;
		case 0x13A>>1:
			sprintf(s,"18F8622 rev%d\r\n",id&0x1F);
			break;
		case 0x13C>>1:
			sprintf(s,"18F6627 rev%d\r\n",id&0x1F);
			break;
		case 0x13E>>1:
			sprintf(s,"18F8627 rev%d\r\n",id&0x1F);
			break;
		case 0x140>>1:
			sprintf(s,"18F6722 rev%d\r\n",id&0x1F);
			break;
		case 0x142>>1:
			sprintf(s,"18F8722 rev%d\r\n",id&0x1F);
			break;
		case 0x1A8>>1:
			sprintf(s,"18F4580 rev%d\r\n",id&0x1F);
			break;
		case 0x1AA>>1:
			sprintf(s,"18F4480 rev%d\r\n",id&0x1F);
			break;
		case 0x1AC>>1:
			sprintf(s,"18F2580 rev%d\r\n",id&0x1F);
			break;
		case 0x1AE>>1:
			sprintf(s,"18F2480 rev%d\r\n",id&0x1F);
			break;
		case 0x1C0>>1:
			sprintf(s,"18F25J10 rev%d\r\n",id&0x1F);
			break;
		case 0x1C2>>1:
			sprintf(s,"18F45J10 rev%d\r\n",id&0x1F);
			break;
		case 0x1C4>>1:
			sprintf(s,"18LF25J10 rev%d\r\n",id&0x1F);
			break;
		case 0x1C6>>1:
			sprintf(s,"18LF45J10 rev%d\r\n",id&0x1F);
			break;
		case 0x1D0>>1:
			sprintf(s,"18F24J10 rev%d\r\n",id&0x1F);
			break;
		case 0x1D2>>1:
			sprintf(s,"18F44J10 rev%d\r\n",id&0x1F);
			break;
		case 0x1D4>>1:
			sprintf(s,"18LF24J10 rev%d\r\n",id&0x1F);
			break;
		case 0x1D6>>1:
			sprintf(s,"18LF44J10 rev%d\r\n",id&0x1F);
			break;
		case 0x1E0>>1:
			sprintf(s,"18F1230 rev%d\r\n",id&0x1F);
			break;
		case 0x1E2>>1:
			sprintf(s,"18F1330 rev%d\r\n",id&0x1F);
			break;
		case 0x1FE>>1:
			sprintf(s,"18F1330-ICD rev%d\r\n",id&0x1F);
			break;
		case 0x200>>1:
			sprintf(s,"18F46K20 rev%d\r\n",id&0x1F);
			break;
		case 0x202>>1:
			sprintf(s,"18F26K20 rev%d\r\n",id&0x1F);
			break;
		case 0x204>>1:
			sprintf(s,"18F45K20 rev%d\r\n",id&0x1F);
			break;
		case 0x206>>1:
			sprintf(s,"18F25K20 rev%d\r\n",id&0x1F);
			break;
		case 0x208>>1:
			sprintf(s,"18F44K20 rev%d\r\n",id&0x1F);
			break;
		case 0x20A>>1:
			sprintf(s,"18F24K20 rev%d\r\n",id&0x1F);
			break;
		case 0x20C>>1:
			sprintf(s,"18F43K20 rev%d\r\n",id&0x1F);
			break;
		case 0x20E>>1:
			sprintf(s,"18F23K20 rev%d\r\n",id&0x1F);
			break;
		case 0x210>>1:
			sprintf(s,"18F4321 rev%d\r\n",id&0x1F);
			break;
		case 0x212>>1:
			sprintf(s,"18F2321 rev%d\r\n",id&0x1F);
			break;
		case 0x214>>1:
			sprintf(s,"18F4221 rev%d\r\n",id&0x1F);
			break;
		case 0x216>>1:
			sprintf(s,"18F2221 rev%d\r\n",id&0x1F);
			break;
		case 0x240>>1:
			sprintf(s,"18F4450 rev%d\r\n",id&0x1F);
			break;
		case 0x242>>1:
			sprintf(s,"18F2450 rev%d\r\n",id&0x1F);
			break;
		case 0x270>>1:
			sprintf(s,"18F2682 rev%d\r\n",id&0x1F);
			break;
		case 0x272>>1:
			sprintf(s,"18F2685 rev%d\r\n",id&0x1F);
			break;
		case 0x274>>1:
			sprintf(s,"18F4682 rev%d\r\n",id&0x1F);
			break;
		case 0x276>>1:
			sprintf(s,"18F4685 rev%d\r\n",id&0x1F);
			break;
		case 0x2A0>>1:
			sprintf(s,"18F4553 rev%d\r\n",id&0x1F);
			break;
		case 0x2A2>>1:
			sprintf(s,"18F4458 rev%d\r\n",id&0x1F);
			break;
		case 0x2A4>>1:
			sprintf(s,"18F2553 rev%d\r\n",id&0x1F);
			break;
		case 0x2A6>>1:
			sprintf(s,"18F2458 rev%d\r\n",id&0x1F);
			break;
		case 0x470>>1:
			sprintf(s,"18LF13K50 rev%d\r\n",id&0x1F);
			break;
		case 0x472>>1:
			sprintf(s,"18LF14K50 rev%d\r\n",id&0x1F);
			break;
		case 0x474>>1:
			sprintf(s,"18F13K50 rev%d\r\n",id&0x1F);
			break;
		case 0x476>>1:
			sprintf(s,"18F14K50 rev%d\r\n",id&0x1F);
			break;
		case 0x49C>>1:
			sprintf(s,"18F6628 rev%d\r\n",id&0x1F);
			break;
		case 0x49E>>1:
			sprintf(s,"18F8628 rev%d\r\n",id&0x1F);
			break;
		case 0x4A0>>1:
			sprintf(s,"18F6723 rev%d\r\n",id&0x1F);
			break;
		case 0x4A2>>1:
			sprintf(s,"18F8723 rev%d\r\n",id&0x1F);
			break;
		case 0x4C0>>1:
			sprintf(s,"18F24J50 rev%d\r\n",id&0x1F);
			break;
		case 0x4C2>>1:
			sprintf(s,"18F25J50 rev%d\r\n",id&0x1F);
			break;
		case 0x4C4>>1:
			sprintf(s,"18F26J50 rev%d\r\n",id&0x1F);
			break;
		case 0x4C6>>1:
			sprintf(s,"18F44J50 rev%d\r\n",id&0x1F);
			break;
		case 0x4C8>>1:
			sprintf(s,"18F45J50 rev%d\r\n",id&0x1F);
			break;
		case 0x4D8>>1:
			sprintf(s,"18F24J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4DA>>1:
			sprintf(s,"18F25J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4DC>>1:
			sprintf(s,"18F26J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4DE>>1:
			sprintf(s,"18F44J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4E0>>1:
			sprintf(s,"18F45J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4E2>>1:
			sprintf(s,"18F46J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4E6>>1:
			sprintf(s,"18LF25J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4E8>>1:
			sprintf(s,"18LF26J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4EA>>1:
			sprintf(s,"18LF44J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4EC>>1:
			sprintf(s,"18LF45J11 rev%d\r\n",id&0x1F);
			break;
		case 0x4EE>>1:
			sprintf(s,"18LF46J11 rev%d\r\n",id&0x1F);
			break;
		case 0x582>>1:
			sprintf(s,"18F26J53 rev%d\r\n",id&0x1F);
			break;
		case 0x586>>1:
			sprintf(s,"18F27J53 rev%d\r\n",id&0x1F);
			break;
		case 0x58A>>1:
			sprintf(s,"18F46J53 rev%d\r\n",id&0x1F);
			break;
		case 0x58E>>1:
			sprintf(s,"18F47J53 rev%d\r\n",id&0x1F);
			break;
		case 0x592>>1:
			sprintf(s,"18F26J13 rev%d\r\n",id&0x1F);
			break;
		case 0x596>>1:
			sprintf(s,"18F27J13 rev%d\r\n",id&0x1F);
			break;
		case 0x59A>>1:
			sprintf(s,"18F46J13 rev%d\r\n",id&0x1F);
			break;
		case 0x59E>>1:
			sprintf(s,"18F47J13 rev%d\r\n",id&0x1F);
			break;
		case 0x5A2>>1:
			sprintf(s,"18LF26J53 rev%d\r\n",id&0x1F);
			break;
		case 0x5A6>>1:
			sprintf(s,"18LF27J53 rev%d\r\n",id&0x1F);
			break;
		case 0x5AA>>1:
			sprintf(s,"18LF46J53 rev%d\r\n",id&0x1F);
			break;
		case 0x5AE>>1:
			sprintf(s,"18LF47J53 rev%d\r\n",id&0x1F);
			break;
		case 0x5B2>>1:
			sprintf(s,"18LF26J13 rev%d\r\n",id&0x1F);
			break;
		case 0x5B6>>1:
			sprintf(s,"18LF27J13 rev%d\r\n",id&0x1F);
			break;
		case 0x5BA>>1:
			sprintf(s,"18LF46J13 rev%d\r\n",id&0x1F);
			break;
		case 0x5BE>>1:
			sprintf(s,"18LF47J13 rev%d\r\n",id&0x1F);
			break;
		default:
			sprintf(s,"%s",strings[S_nodev]); //"Unknown device\r\n");
	}
	PrintMessage(s);
}
Beispiel #23
0
void configure_io_chunked(int fd,int chunked_r,int chunked_w)
{
    io_context *context;

    if(fd==-1)
        PrintMessage(Fatal,"IO: Function configure_io_chunked(%d) was called with an invalid argument.",fd);

    if(nio<=fd || !io_contexts[fd])
        PrintMessage(Fatal,"IO: Function configure_io_chunked(%d) was called without calling init_io(%d) first.",fd,fd);

    context=io_contexts[fd];

    /* Create the chunked decoding context for reading */

    if(chunked_r>=0)
    {
        if(chunked_r && !context->r_chunk_context)
        {
            context->r_chunk_context=io_init_chunk_decode();
            if(!context->r_chunk_context)
                PrintMessage(Fatal,"IO: Could not initialise chunked decoding; [%!s].");

            if(context->r_zlib_context && !context->r_zlch_data)
                context->r_zlch_data=create_io_buffer(IO_BUFFER_SIZE);

            if(!context->r_file_data)
                context->r_file_data=create_io_buffer(IO_BUFFER_SIZE);
            else
                resize_io_buffer(context->r_file_data,IO_BUFFER_SIZE);
        }
        else if(!chunked_r && context->r_chunk_context)
        {
            context->r_chunk_context=NULL;

            if(context->r_zlch_data)
                destroy_io_buffer(context->r_zlch_data);
            context->r_zlch_data=NULL;
        }
    }

    /* Create the chunked encoding context for writing */

    if(chunked_w>=0)
    {
        if(chunked_w && !context->w_chunk_context)
        {
            context->w_chunk_context=io_init_chunk_encode();
            if(!context->w_chunk_context)
                PrintMessage(Fatal,"IO: Could not initialise chunked encoding; [%!s].");

            if(context->w_zlib_context && !context->w_zlch_data)
                context->w_zlch_data=create_io_buffer(IO_BUFFER_SIZE);

            if(!context->w_file_data)
                context->w_file_data=create_io_buffer(IO_BUFFER_SIZE+16);
            else
                resize_io_buffer(context->w_file_data,IO_BUFFER_SIZE+16);
        }
        else if(!chunked_w && context->w_chunk_context)
        {
            context->w_chunk_context=NULL;

            if(context->w_zlch_data)
                destroy_io_buffer(context->w_zlch_data);
            context->r_zlch_data=NULL;
        }
    }
}
void COpenProgDlg::Read18Fx(int dim,int dim2,int options){
// read 16 bit PIC 18Fxxxx
// dim=program size 	dim2=eeprom size
// options:
//   0 = vdd before vpp (12V)
//   1 = vdd before vpp (9V)
//   2 = low voltage entry with 32 bit key
	CString str,aux;
	int k=0,k2=0,z=0,i,j;
	int entry=options&0xF;
	if(dim>0x1FFFFF||dim<0){
		PrintMessage(strings[S_CodeLim]);	//"Code size out of limits\r\n"
		return;
	}
	if(dim2>0x800||dim2<0){
		PrintMessage(strings[S_EELim]);	//"EEPROM size out of limits\r\n"
		return;
	}
	if(entry>0&&!CheckV33Regulator()){
		PrintMessage(strings[S_noV33reg]);	//Can't find 3.3V expansion board
		return;
	}
	double vpp=entry<2?(entry==0?12:8.5):-1;
	if(!StartHVReg(vpp)){
		PrintMessage(strings[S_HVregErr]); //"HV regulator error\r\n"
		return;
	}
	if(saveLog){
		OpenLogFile();	//"log.txt"
		fprintf(logfile,"Read18F(%d,%d,%d)    (0x%X,0x%X,0x%X)\n",dim,dim2,options,dim,dim2,options);
	}
	memCODE.RemoveAll();
	memCODE.SetSize(dim);		//CODE
	memEE.RemoveAll();
	memEE.SetSize(dim2);		//EEPROM
	memID.RemoveAll();
	memID.SetSize(8);			//ID+CONFIG
	memCONFIG.RemoveAll();
	memCONFIG.SetSize(14);		//CONFIG
	unsigned int start=GetTickCount();
	bufferU[0]=0;
	j=1;
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T1T2;
	bufferU[j++]=1;						//T1=1u
	bufferU[j++]=100;					//T2=100u
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T3;
	bufferU[j++]=2000>>8;
	bufferU[j++]=2000&0xff;
	bufferU[j++]=EN_VPP_VCC;		//enter program mode
	bufferU[j++]=0x0;
	bufferU[j++]=SET_CK_D;
	bufferU[j++]=0x0;
	bufferU[j++]=EN_VPP_VCC;		//VDD
	bufferU[j++]=0x1;
	bufferU[j++]=NOP;
	bufferU[j++]=EN_VPP_VCC;		//VDD+VPP
	bufferU[j++]=0x5;
	if(entry==2){					//LV entry with key
		bufferU[j++]=EN_VPP_VCC;		//VDD
		bufferU[j++]=0x1;
		bufferU[j++]=WAIT_T3;
		bufferU[j++]=WAIT_T3;
		bufferU[j++]=TX16;
		bufferU[j++]=2;
		bufferU[j++]=0x4D;
		bufferU[j++]=0x43;
		bufferU[j++]=0x48;
		bufferU[j++]=0x50;
		bufferU[j++]=EN_VPP_VCC;		//VDD+VPP
		bufferU[j++]=0x5;
		bufferU[j++]=WAIT_T3;
	}
	bufferU[j++]=WAIT_T3;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//3F
	bufferU[j++]=0x3F;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRU
	bufferU[j++]=0xF8;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//FF
	bufferU[j++]=0xFF;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRH
	bufferU[j++]=0xF7;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//FE
	bufferU[j++]=0xFE;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRL
	bufferU[j++]=0xF6;
	bufferU[j++]=TBLR_INC_N;		//DevID1-2	0x3FFFFE-F
	bufferU[j++]=2;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRU
	bufferU[j++]=0xF8;			//TBLPTRU
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRH
	bufferU[j++]=0xF7;			//TBLPTRH
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRL
	bufferU[j++]=0xF6;			//TBLPTRL
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(3);
	if(entry==2) msDelay(7);
	read();
	if(saveLog)WriteLogIO();
	for(z=1;bufferI[z]!=TBLR_INC_N&&z<DIMBUF;z++);
	if(z<DIMBUF-3){
		PrintMessage2(strings[S_DevID2],bufferI[z+3],bufferI[z+2]);	//"DevID: 0x%02X%02X\r\n"
		PIC18_ID(bufferI[z+2]+(bufferI[z+3]<<8));
	}
//****************** read code ********************
	PrintMessage(strings[S_CodeReading1]);		//code read ...
	for(i=0,j=1;i<dim;i+=DIMBUF-4){
		bufferU[j++]=TBLR_INC_N;
		bufferU[j++]=i<dim-(DIMBUF-4)?DIMBUF-4:dim-i;
		bufferU[j++]=FLUSH;
		for(;j<DIMBUF;j++) bufferU[j]=0x0;
		write();
		msDelay(2);
		read();
		if(bufferI[1]==TBLR_INC_N){
			for(z=3;z<bufferI[2]+3&&z<DIMBUF;z++) memCODE[k++]=bufferI[z];
		}
		PrintStatus(strings[S_CodeReading2],i*100/(dim+dim2),i);	//"Read: %d%%, addr. %05X"
		j=1;
		if(saveLog){
			fprintf(logfile,strings[S_Log7],i,i,k,k);	//"i=%d(0x%X), k=%d(0x%X)\n"
			WriteLogIO();
		}
	}
	if(k!=dim){
		PrintMessage("\r\n");
		PrintMessage2(strings[S_ReadCodeErr2],dim,k);	//"Error reading code area, requested %d bytes, read %d\r\n"
	}
	else PrintMessage(strings[S_Compl]);
//****************** read config area ********************
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//TBLPTRU	ID 0x200000
	bufferU[j++]=0x20;			//TBLPTRU	ID 0x200000
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//TBLPTRU
	bufferU[j++]=0xF8;			//TBLPTRU
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRH
	bufferU[j++]=0xF7;			//TBLPTRH
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRL
	bufferU[j++]=0xF6;			//TBLPTRL
	bufferU[j++]=TBLR_INC_N;
	bufferU[j++]=8;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//TBLPTRU	CONFIG 0x300000
	bufferU[j++]=0x30;			//TBLPTRU	CONFIG 0x300000
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//TBLPTRU
	bufferU[j++]=0xF8;			//TBLPTRU
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRH
	bufferU[j++]=0xF7;			//TBLPTRH
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRL
	bufferU[j++]=0xF6;			//TBLPTRL
	bufferU[j++]=TBLR_INC_N;
	bufferU[j++]=14;
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(8);
	read();
	for(z=1;bufferI[z]!=TBLR_INC_N&&z<DIMBUF-28;z++);
	if(z<DIMBUF-28){
		for(i=0;i<8;i++) memID[k2++]=bufferI[z+i+2];
		for(;i<14+8;i++) memCONFIG[-8+k2++]=bufferI[z+i+8];
	}
	j=1;
	if(saveLog){
		fprintf(logfile,strings[S_Log7],i,i,k2,k2);	//"i=%d(0x%X), k=%d(0x%X)\n"
		WriteLogIO();
	}
	if(k2!=22){
		PrintMessage2(strings[S_ReadConfigErr],22,k2);	//"Error reading config area, requested %d bytes, read %d\r\n"
	}
//****************** read eeprom ********************
	if(dim2){
		PrintMessage(strings[S_ReadEE]);		//read eeprom ...
		bufferU[j++]=CORE_INS;
		bufferU[j++]=0x9E;				//EEPGD=0
		bufferU[j++]=0xA6;
		bufferU[j++]=CORE_INS;
		bufferU[j++]=0x9C;				//CFGS=0
		bufferU[j++]=0xA6;
		for(k2=0,i=0;i<dim2;i++){
			bufferU[j++]=CORE_INS;
			bufferU[j++]=0x0E;
			bufferU[j++]=i&0xFF;
			bufferU[j++]=CORE_INS;
			bufferU[j++]=0x6E;			//ADDR
			bufferU[j++]=0xA9;			//ADDR
			bufferU[j++]=CORE_INS;
			bufferU[j++]=0x0E;
			bufferU[j++]=(i>>8)&0xFF;
			bufferU[j++]=CORE_INS;
			bufferU[j++]=0x6E;			//ADDRH
			bufferU[j++]=0xAA;			//ADDRH
			bufferU[j++]=CORE_INS;
			bufferU[j++]=0x80;			//RD=1 :Read
			bufferU[j++]=0xA6;
			bufferU[j++]=CORE_INS;
			bufferU[j++]=0x50;			//MOVF EEDATA,W
			bufferU[j++]=0xA8;
			bufferU[j++]=CORE_INS;
			bufferU[j++]=0x6E;			//MOVWF TABLAT
			bufferU[j++]=0xF5;
			bufferU[j++]=CORE_INS;
			bufferU[j++]=0x00;			//NOP
			bufferU[j++]=0x00;
			bufferU[j++]=SHIFT_TABLAT;
			if(j>DIMBUF-26||i==dim2-1){
				bufferU[j++]=FLUSH;
				for(;j<DIMBUF;j++) bufferU[j]=0x0;
				write();
				msDelay(10);
				read();
				for(z=1;z<DIMBUF-1;z++){
					if(bufferI[z]==SHIFT_TABLAT){
						memEE[k2++]=bufferI[z+1];
						z+=8;
					}
				}
				PrintStatus(strings[S_CodeReading],(i+dim)*100/(dim+dim2),i);	//"Read: %d%%, addr. %03X"
				j=1;
				if(saveLog){
					fprintf(logfile,strings[S_Log7],i,i,k2,k2);	//"i=%d(0x%X), k=%d(0x%X)\n"
					WriteLogIO();
				}
			}
		}
		if(k2!=dim2){
			PrintMessage("\r\n");
			PrintMessage2(strings[S_ReadEEErr],dim2,k2);	//"Error reading EEPROM area, requested %d bytes, read %d\r\n"
		}
		else PrintMessage(strings[S_Compl]);
	}
	PrintMessage("\r\n");
//****************** exit ********************
	bufferU[j++]=EN_VPP_VCC;		//VDD
	bufferU[j++]=1;
	bufferU[j++]=EN_VPP_VCC;		//0
	bufferU[j++]=0x0;
	bufferU[j++]=SET_CK_D;
	bufferU[j++]=0x0;
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(1);
	read();
	unsigned int stop=GetTickCount();
	StatusBar.SetWindowText("");
//****************** visualize ********************
	for(i=0;i<8;i+=2){
		PrintMessage4(strings[S_ChipID2],i,memID[i],i+1,memID[i+1]);	//"ID%d: 0x%02X   ID%d: 0x%02X\r\n"
	}
	for(i=0;i<7;i++){
		PrintMessage2(strings[S_ConfigWordH],i+1,memCONFIG[i*2+1]);	//"CONFIG%dH: 0x%02X\t"
		PrintMessage2(strings[S_ConfigWordL],i+1,memCONFIG[i*2]);	//"CONFIG%dL: 0x%02X\r\n"
	}
	PrintMessage(strings[S_CodeMem]);	//"\r\nCode memory:\r\n"
	char s[256],t[256];
	s[0]=0;
	int valid=0,empty=1;
	for(i=0;i<dim;i+=COL*2){
		valid=0;
		for(j=i;j<i+COL*2&&j<dim;j++){
			sprintf(t,"%02X ",memCODE[j]);
			strcat(s,t);
			if(memCODE[j]<0xff) valid=1;
		}
		if(valid){
			sprintf(t,"%04X: %s\r\n",i,s);
			aux+=t;
			empty=0;
		}
		s[0]=0;
	}
	if(empty) PrintMessage(strings[S_Empty]);	//empty
	else PrintMessage(aux);
	if(dim2){
		DisplayEE();	//visualize
	}
	PrintMessage1(strings[S_End],(stop-start)/1000.0);	//"\r\nEnd (%.2f s)\r\n"
	if(saveLog) CloseLogFile();
}
Beispiel #25
0
char *read_line(int fd,char *line)
{
    io_context *context;
    int found=0,eof=0;
    size_t n=0;

    if(fd==-1)
        PrintMessage(Fatal,"IO: Function read_line(%d) was called with an invalid argument.",fd);

    if(nio<=fd || !io_contexts[fd])
        PrintMessage(Fatal,"IO: Function read_line(%d) was called without calling init_io(%d) first.",fd,fd);

    context=io_contexts[fd];

    /* Create the temporary line buffer if there is not one */

    if(!context->r_file_data)
        context->r_file_data=create_io_buffer(LINE_BUFFER_SIZE+1);

    /* Use the existing data or read in some more */

    do
    {
        line=(char*)realloc((void*)line,n+(LINE_BUFFER_SIZE+1));

        if(context->r_file_data->length>0)
        {
            for(n=0; n<context->r_file_data->length && n<LINE_BUFFER_SIZE; n++)
                if(context->r_file_data->data[n]=='\n')
                {
                    found=1;
                    n++;
                    break;
                }

            memcpy(line,context->r_file_data->data,n);

            if(n==context->r_file_data->length)
                context->r_file_data->length=0;
            else
            {
                context->r_file_data->length-=n;
                memmove(context->r_file_data->data,context->r_file_data->data+n,context->r_file_data->length);
            }
        }
        else
        {
            ssize_t nn;
            io_buffer iobuffer;

            /* FIXME
               Cannot call read_line() on compressed files.
               Probably not important, wasn't possible with old io.c either.
               FIXME */

            iobuffer.data=line+n;
            iobuffer.size=LINE_BUFFER_SIZE;
            iobuffer.length=0;

            if(context->gnutls_context)
                nn=io_gnutls_read_with_timeout(context->gnutls_context,&iobuffer,context->r_timeout);
            else
                nn=io_read_with_timeout(fd,&iobuffer,context->r_timeout);
            if(nn>0) context->r_raw_bytes+=nn;

            if(nn<=0)
            {
                eof=1;
                break;
            }
            else
                nn+=n;

            for(; n<nn; n++)
                if(line[n]=='\n')
                {
                    found=1;
                    n++;
                    break;
                }

            if(found)
            {
                context->r_file_data->length=nn-n;
                memcpy(context->r_file_data->data,line+n,context->r_file_data->length);
            }
        }
    }
    while(!found && !eof);

    if(found)
        line[n]=0;

    if(eof)
    {
        free(line);
        line=NULL;
    }

    return(line);
}
void COpenProgDlg::Write18Fx(int dim,int dim2,int wbuf=8,int eraseW1=0x10000,int eraseW2=0x10000,int options=0)
// write 16 bit PIC 18Fxxxx
// dim=program size 	dim2=eeprom size	wbuf=write buffer size {<=64}
// eraseW1=erase word @3C0005	(not used if > 0x10000)
// eraseW2=erase word @3C0004	(not used if > 0x10000)
// options:
//	bit [3:0]
//     0 = vdd before vpp (12V)
//     1 = vdd before vpp (9V)
//     2 = low voltage entry with 32 bit key
//	bit [7:4]
//     0 = normal eeprom write algoritm
//     1 = with unlock sequence 55 AA
//	bit [11:8]
//     0 = 5ms erase delay, 1ms code write time, 5ms EE write delay, 5ms config write time
//     1 = 550ms erase delay, 1.2ms code write time, no config or EEPROM
//     2 = 550ms erase delay, 3.4ms code write time, no config or EEPROM
{
	CString str;
	int size=memCODE.GetSize(),sizeEE=memEE.GetSize();
	int k=0,k2,z=0,i,j;
	int err=0,devID=0;
	int EEalgo=(options>>4)&0xF,entry=options&0xF,optWrite=(options>>8)&0xF;
	if(dim>0x1FFFFF||dim<0){
		PrintMessage(strings[S_CodeLim]);	//"Code size out of limits\r\n"
		return;
	}
	if(dim2>0x800||dim2<0){
		PrintMessage(strings[S_EELim]);	//"EEPROM size out of limits\r\n"
		return;
	}
	if(wbuf>64){
		PrintMessage(strings[S_WbufLim]);	//"Write buffer size out of limits\r\n"
		return;
	}
	if(entry==2&&!CheckV33Regulator()){
		PrintMessage(strings[S_noV33reg]);	//Can't find 3.3V expansion board
		return;
	}
	double vpp=entry<2?(entry==0?12:8.5):-1;
	if(!StartHVReg(vpp)){
		PrintMessage(strings[S_HVregErr]); //"HV regulator error\r\n"
		return;
	}
	if(saveLog){
		OpenLogFile();	//"log.txt"
		fprintf(logfile,"Write18F(%d,%d,%d,%d)    (0x%X,0x%X,0x%X,0x%X)\n",dim,dim2,wbuf,options,dim,dim2,wbuf,options);
	}
	if(dim>size) dim=size;
	if(dim%wbuf){			//grow to an integer number of rows
		dim+=wbuf-dim%wbuf;
		j=size;
		if(j<dim)memCODE.SetSize(dim);
		for(;j<dim;j++) memCODE[j]=0xFF;
	}
	if(dim2>sizeEE) dim2=sizeEE;
	if(dim<1){
		PrintMessage(strings[S_NoCode]);	//"Empty data area\r\n"
		return;
	}
	unsigned int start=GetTickCount();
	bufferU[0]=0;
	j=1;
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T1T2;
	bufferU[j++]=1;						//T1=1u
	bufferU[j++]=100;					//T2=100u
	bufferU[j++]=EN_VPP_VCC;		//enter program mode
	bufferU[j++]=0x0;
	bufferU[j++]=SET_CK_D;
	bufferU[j++]=0x0;
	bufferU[j++]=EN_VPP_VCC;		//VDD
	bufferU[j++]=0x1;
	bufferU[j++]=EN_VPP_VCC;		//VDD+VPP
	bufferU[j++]=0x5;
	if(entry==2){					//LV entry with key
		bufferU[j++]=EN_VPP_VCC;		//VDD
		bufferU[j++]=0x1;
		bufferU[j++]=WAIT_T3;
		bufferU[j++]=WAIT_T3;
		bufferU[j++]=TX16;
		bufferU[j++]=2;
		bufferU[j++]=0x4D;
		bufferU[j++]=0x43;
		bufferU[j++]=0x48;
		bufferU[j++]=0x50;
		bufferU[j++]=EN_VPP_VCC;		//VDD+VPP
		bufferU[j++]=0x5;
		bufferU[j++]=WAIT_T3;
	}
	bufferU[j++]=WAIT_T3;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//3F
	bufferU[j++]=0x3F;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRU
	bufferU[j++]=0xF8;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//FF
	bufferU[j++]=0xFF;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRH
	bufferU[j++]=0xF7;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//FE
	bufferU[j++]=0xFE;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRL
	bufferU[j++]=0xF6;
	bufferU[j++]=TBLR_INC_N;		//DevID1-2	0x3FFFFE-F
	bufferU[j++]=2;
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T3;
	bufferU[j++]=5100>>8;
	bufferU[j++]=5100&0xff;
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(3);
	if(entry==2) msDelay(7);
	read();
	if(saveLog)WriteLogIO();
	for(z=1;bufferI[z]!=TBLR_INC_N&&z<DIMBUF;z++);
	if(z<DIMBUF-3){
		PrintMessage2(strings[S_DevID2],bufferI[z+3],bufferI[z+2]);	//"DevID: 0x%02X%02X\r\n"
		PIC18_ID(bufferI[z+2]+(bufferI[z+3]<<8));
	}
	j=1;
//****************** erase memory ********************
	PrintMessage(strings[S_StartErase]);	//"Erase ... "
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//3C
	bufferU[j++]=0x3C;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRU
	bufferU[j++]=0xF8;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRH=0
	bufferU[j++]=0xF7;
	if(eraseW1<0x10000){
		bufferU[j++]=CORE_INS;
		bufferU[j++]=0x0E;			//05
		bufferU[j++]=0x05;
		bufferU[j++]=CORE_INS;
		bufferU[j++]=0x6E;			//-> TBLPTRL
		bufferU[j++]=0xF6;
		bufferU[j++]=TABLE_WRITE;		// eraseW1@3C0005
		bufferU[j++]=(eraseW1>>8)&0xFF; 	//0x3F;
		bufferU[j++]=eraseW1&0xFF; 		//0x3F;
	}
Beispiel #27
0
// Call back Declaration
ReturnType EncoderComp::onInitialize()
{
	Property parameter;
	std::map<std::string, std::string> temp = getPropertyMap();
	parameter.SetProperty(temp);
	
	if(parameter.FindName("ApiName") == false) {
		PrintMessage("ERROR : EncoderComp::onInitialize() -> Can't find the APIName in property\n");
		return lastError = OPROS_FIND_PROPERTY_ERROR;
	}
	
#if defined(WIN32)
	//	DLL 로드
	hOprosAPI = LoadLibrary((LPCSTR)parameter.GetValue("ApiName").c_str());
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : EncoderComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("ApiName").c_str());
		return lastError = OPROS_FIND_DLL_ERROR;
	}
	
	//	API 로드
	GET_OPROS_API getOprosAPI;
	getOprosAPI = (GET_OPROS_API)GetProcAddress(hOprosAPI, "GetAPI");
	if(getOprosAPI == NULL) {
		PrintMessage("ERROR : EncoderComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		FreeLibrary(hOprosAPI);
		hOprosAPI = NULL;
		return lastError = OPROS_LOAD_DLL_ERROR;
	}

	//	API Casting
	encoder = dynamic_cast<Encoder *>(getOprosAPI());
	if(encoder == NULL) {
		PrintMessage("ERROR : EncoderComp::onInitialize() -> Can't get a handle of AccelerationSensor API\n");
		FreeLibrary(hOprosAPI);
		hOprosAPI = NULL;
		return lastError = OPROS_LOAD_DLL_ERROR;
	}
#else
	//	Shared Library 로드
	hOprosAPI = dlopen(parameter.GetValue("ApiName").c_str(), RTLD_NOW);
	if(hOprosAPI == NULL) {
		PrintMessage("ERROR : EncoderComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("ApiName").c_str());
		return lastError = OPROS_FIND_DLL_ERROR;
	}

	//	API 로드
	GET_OPROS_API getOprosAPI = (GET_OPROS_API)dlsym(hOprosAPI, "GetAPI");
	char *error = dlerror();
	if(error != NULL) {
		PrintMessage("ERROR : EncoderComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n");
		dlclose(hOprosAPI);
		hOprosAPI = NULL;
		return lastError = OPROS_LOAD_DLL_ERROR;
	}
	
	//	API Casting
	encoder = static_cast<Encoder *>(getOprosAPI());
	if(encoder == NULL) {
		PrintMessage("ERROR : EncoderComp::onInitialize() -> Can't get a handle of AccelerationSensor API\n");
		dlclose(hOprosAPI);
		hOprosAPI = NULL;
		return lastError = OPROS_LOAD_DLL_ERROR;
	}
#endif

	if(encoder->Initialize(parameter) != API_SUCCESS) {
		delete encoder;
		encoder = NULL;

#if defined(WIN32)
		FreeLibrary(hOprosAPI);
#else
		dlclose(hOprosAPI);
#endif
		hOprosAPI = NULL;
		return lastError = OPROS_INITIALIZE_API_ERROR;
	}

	return lastError = OPROS_SUCCESS;
}
DWORD CService::ServiceHandleDeviceChange(DWORD evtype, _DEV_BROADCAST_HEADER* dbhdr)
{
    PrintMessage("ServiceHandleDeviceChange");
    return NO_ERROR;
}
Beispiel #29
0
int main(int argc,char **argv)
{
 URL *Url;
 URL **list,*refresh;
 int j;

 if(argc==1)
   {fprintf(stderr,"usage: test-doc URL < contents-of-url\n");return(1);}

 StderrLevel=ExtraDebug;

 InitErrorHandler("test-doc",0,1);

 InitConfigurationFile("./wwwoffle.conf");

 init_io(STDERR_FILENO);

 if(ReadConfigurationFile(STDERR_FILENO))
    PrintMessage(Fatal,"Error in configuration file 'wwwoffle.conf'.");

 finish_io(STDERR_FILENO);

 Url=SplitURL(argv[1]);

 init_io(0);

 ParseDocument(0,Url,1);

 if((refresh=GetReference(RefMetaRefresh)))
    printf("Refresh = %s\n",refresh->file);

 if((list=GetReferences(RefStyleSheet)))
    for(j=0;list[j];j++)
       printf("StyleSheet = %s\n",list[j]->file);

 if((list=GetReferences(RefImage)))
    for(j=0;list[j];j++)
       printf("Image = %s\n",list[j]->file);

 if((list=GetReferences(RefFrame)))
    for(j=0;list[j];j++)
       printf("Frame = %s\n",list[j]->file);

 if((list=GetReferences(RefScript)))
    for(j=0;list[j];j++)
       printf("Script = %s\n",list[j]->file);

 if((list=GetReferences(RefObject)))
    for(j=0;list[j];j++)
       printf("Object = %s\n",list[j]->file);

 if((list=GetReferences(RefInlineObject)))
    for(j=0;list[j];j++)
       printf("InlineObject = %s\n",list[j]->file);

 if((list=GetReferences(RefLink)))
    for(j=0;list[j];j++)
       printf("Link = %s\n",list[j]->file);

 FreeURL(Url);

 finish_io(0);

 return(0);
}
void COpenProgDlg::Write12F5xx(int dim,int OscAddr)
{
// write 12 bit PIC
// dim=program size     max~4300=10CC
// OscAddr=OSCCAL address (saved at the beginning), -1 not to use it
// vdd before vpp
// CONFIG @ 0x7FF upon entering program mode
// BACKUP OSCCAL @ dim+5 (saved at the beginning)
// erase: BULK_ERASE_PROG (1001) +10ms
// write: BEGIN_PROG (1000) + Tprogram 2ms + END_PROG2 (1110);
	CString str;
	int usa_BKosccal,usa_osccal,size;
	int k=0,z=0,i,j,w;
	int err=0;
	WORD osccal=-1,BKosccal=-1;
	if(OscAddr>dim) OscAddr=dim-1;
	CButton* b=(CButton*)m_DispoPage.GetDlgItem(IDC_OSC_OSCCAL);
	usa_osccal=b->GetCheck();
	b=(CButton*)m_DispoPage.GetDlgItem(IDC_OSC_BK);
	usa_BKosccal=b->GetCheck();
	size=dati_hex.GetSize();
	if(OscAddr==-1) usa_BKosccal=usa_osccal=0;
	if(size<0x1000){
		PrintMessage(strings[S_NoConfigW2]);	//"Impossibile trovare la locazione CONFIG (0xFFF)\r\n"
		return;
	}
	if(saveLog){
		OpenLogFile();	//"Log.txt"
		fprintf(logfile,"Write12F5xx(%d,%d)\n",dim,OscAddr);
	}
	for(i=0;i<size;i++) dati_hex[i]&=0xFFF;
	unsigned int start=GetTickCount();
	bufferU[0]=0;
	j=1;
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T1T2;
	bufferU[j++]=1;						//T1=1u
	bufferU[j++]=100;					//T2=100u
	bufferU[j++]=EN_VPP_VCC;		//enter program mode
	bufferU[j++]=0x0;
	bufferU[j++]=SET_CK_D;
	bufferU[j++]=0x0;
	bufferU[j++]=EN_VPP_VCC;		//VDD
	bufferU[j++]=0x1;
	bufferU[j++]=NOP;
	bufferU[j++]=EN_VPP_VCC;		//VDD+VPP
	bufferU[j++]=0x5;
	bufferU[j++]=NOP;
	if(OscAddr!=-1){
		for(i=-1;i<OscAddr-0xff;i+=0xff){
			bufferU[j++]=INC_ADDR_N;
			bufferU[j++]=0xff;
		}
		bufferU[j++]=INC_ADDR_N;
		bufferU[j++]=OscAddr-i;
		bufferU[j++]=READ_DATA_PROG;	// OSCCAL
		if(OscAddr<dim){
			bufferU[j++]=INC_ADDR_N;
			bufferU[j++]=dim-OscAddr;
		}
		bufferU[j++]=INC_ADDR_N;
		bufferU[j++]=0x4;				// 400->404
		bufferU[j++]=READ_DATA_PROG;	// backup OSCCAL
	}
	bufferU[j++]=NOP;				//uscita program mode
	bufferU[j++]=EN_VPP_VCC;
	bufferU[j++]=0x1;
	bufferU[j++]=EN_VPP_VCC;
	bufferU[j++]=0x0;
	bufferU[j++]=SET_CK_D;
	bufferU[j++]=0x0;
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T3;
	bufferU[j++]=10000>>8;
	bufferU[j++]=10000&0xff;
	bufferU[j++]=WAIT_T3;
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(15);
	read();
	if(saveLog)WriteLogIO();
	if(OscAddr!=-1){
		for(z=4;z<DIMBUF-2&&bufferI[z]!=READ_DATA_PROG;z++);
		if(z<DIMBUF-2) osccal=(bufferI[z+1]<<8)+bufferI[z+2];
		for(z+=3;z<DIMBUF-2&&bufferI[z]!=READ_DATA_PROG;z++);
		if(z<DIMBUF-2) BKosccal=(bufferI[z+1]<<8)+bufferI[z+2];
		if(osccal==-1||BKosccal==-1){
			PrintMessage(strings[S_ErrOsccal]);	//"Errore in lettura OSCCAL e BKOSCCAL"
			PrintMessage("\r\n");
			return;
		}
		PrintMessage1(strings[S_Osccal],osccal);	//"OSCCAL: 0x%03X\r\n"
		PrintMessage1(strings[S_BKOsccal],BKosccal);	//"Backup OSCCAL: 0x%03X\r\n"
	}
//****************** erase memory ********************
	PrintMessage(strings[S_StartErase]);	//"Cancellazione ... "
	j=1;
	bufferU[j++]=EN_VPP_VCC;			// enter program mode
	bufferU[j++]=0x1;
	bufferU[j++]=NOP;
	bufferU[j++]=EN_VPP_VCC;
	bufferU[j++]=0x5;
	if(dim>OscAddr+1){				//12F519 (Flash+EEPROM)
		bufferU[j++]=BULK_ERASE_PROG;	// Bulk erase
		bufferU[j++]=WAIT_T3;			// delay T3=10ms
		for(i=-1;i<dim-0xff;i+=0xff){	// 0x43F
			bufferU[j++]=INC_ADDR_N;
			bufferU[j++]=0xff;
		}
		bufferU[j++]=INC_ADDR_N;
		bufferU[j++]=dim-i-1;
		bufferU[j++]=BULK_ERASE_PROG;	// Bulk erase EEPROM
		bufferU[j++]=WAIT_T3;			// delay T3=10ms
		if(programID){
			bufferU[j++]=INC_ADDR;
			bufferU[j++]=BULK_ERASE_PROG;	// Bulk erase
			bufferU[j++]=WAIT_T3;			// delay T3=10ms
		}
	}
	else{							//12Fxxx
		if(programID){
			for(i=-1;i<dim-0xff;i+=0xff){
				bufferU[j++]=INC_ADDR_N;
				bufferU[j++]=0xff;
			}
			bufferU[j++]=INC_ADDR_N;
			bufferU[j++]=dim-i;
			bufferU[j++]=BULK_ERASE_PROG;	// Bulk erase
			bufferU[j++]=WAIT_T3;			// delay T3=10ms
		}
		else{
			bufferU[j++]=BULK_ERASE_PROG;	// Bulk erase
			bufferU[j++]=WAIT_T3;			// delay T3=10ms
		}
	}
	bufferU[j++]=EN_VPP_VCC;		// uscita program mode
	bufferU[j++]=0x1;
	bufferU[j++]=EN_VPP_VCC;
	bufferU[j++]=0x0;
	bufferU[j++]=WAIT_T3;			// delay T3=10ms before entering program mode
	bufferU[j++]=EN_VPP_VCC;		// enter program mode
	bufferU[j++]=0x1;
	bufferU[j++]=NOP;
	bufferU[j++]=EN_VPP_VCC;
	bufferU[j++]=0x5;
	bufferU[j++]=INC_ADDR;				// 7FF->000
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T3;
	bufferU[j++]=2000>>8;				//T3=2ms
	bufferU[j++]=2000&0xff;
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(30);
	if(dim>OscAddr+1) msDelay(20);
	read();
	PrintMessage(strings[S_Compl]);	//"completed\r\n"
	if(saveLog)WriteLogIO();
//****************** write code ********************
	PrintMessage(strings[S_StartCodeProg]);	//"Scrittura codice ... "
	int dim1=dim;
	if(programID) dim1=dim+5;
	if(dati_hex[dim+4]>=0xFFF) dati_hex[dim+4]=BKosccal;  //reload BKosccal if not present
	if(usa_BKosccal) dati_hex[OscAddr]=BKosccal;
	else if(usa_osccal) dati_hex[OscAddr]=osccal;
	for(i=k=w=0,j=1;i<dim1;i++){
		if(dati_hex[i]<0xfff){
			bufferU[j++]=LOAD_DATA_PROG;
			bufferU[j++]=dati_hex[i]>>8;		//MSB
			bufferU[j++]=dati_hex[i]&0xff;		//LSB
			bufferU[j++]=BEGIN_PROG;
			bufferU[j++]=WAIT_T3;				//Tprogram 2ms
			bufferU[j++]=END_PROG2;
			bufferU[j++]=WAIT_T2;				//Tdischarge
			bufferU[j++]=READ_DATA_PROG;
			w++;
		}
		bufferU[j++]=INC_ADDR;
		if(j>DIMBUF-10||i==dim1-1){
			PrintStatus(strings[S_CodeWriting],i*100/dim,i);	//"Write: %d%%, ind. %03X"
			bufferU[j++]=FLUSH;
			for(;j<DIMBUF;j++) bufferU[j]=0x0;
			write();
			msDelay(w*3+3);
			w=0;
			read();
			for(z=1;z<DIMBUF-7;z++){
				if(bufferI[z]==INC_ADDR&&dati_hex[k]>=0xfff) k++;
				else if(bufferI[z]==LOAD_DATA_PROG&&bufferI[z+5]==READ_DATA_PROG){
					if (dati_hex[k]!=(bufferI[z+6]<<8)+bufferI[z+7]){
						PrintMessage("\r\n");
						PrintMessage3(strings[S_CodeWError],k,dati_hex[k],(bufferI[z+6]<<8)+bufferI[z+7]);	//"Errore in scrittura all'indirizzo %3X: scritto %03X, letto %03X\r\n"
						err++;
						if(max_err&&err>max_err){
							PrintMessage1(strings[S_MaxErr],err);	//"Exceeded maximum number of errors (%d), write interrupted\r\n"
							PrintMessage(strings[S_IntW]);	//"write interrupted"
							i=dim1;
							z=DIMBUF;
						}
					}
					k++;
					z+=8;
				}
			}
			j=1;
			if(saveLog){
				fprintf(logfile,strings[S_Log8],i,i,k,k,err);	//"i=%d, k=%d, errori=%d\n"
				WriteLogIO();
			}
		}
	}