コード例 #1
0
ファイル: app.c プロジェクト: JKcompute/395_midi_controller
/////////////////////////////////////////////////////////////////////////////
// This task is called periodically each second
/////////////////////////////////////////////////////////////////////////////
void SEQ_TASK_Period1S(void)
{
  static s8 wait_boot_ctr = 3; // wait 3 seconds before loading from SD Card - this is to increase the time where the boot screen is print!
  u8 load_sd_content = 0;

  // poll for IIC modules as long as HW config hasn't been locked (read from SD card)
  // TODO: use proper mutex handling here
#ifndef MIOS32_FAMILY_EMULATION
  if( !SEQ_FILE_HW_ConfigLocked() ) {
    MIOS32_IIC_MIDI_ScanInterfaces();
  }
#endif  

  // boot phase of 2 seconds finished?
  if( wait_boot_ctr > 0 ) {
    --wait_boot_ctr;
    if( wait_boot_ctr )
      return;
  }

  // BLM timeout counter
  MIOS32_IRQ_Disable();
  if( seq_blm_timeout_ctr )
    --seq_blm_timeout_ctr;
  MIOS32_IRQ_Enable();

  // check if SD Card connected
  MUTEX_SDCARD_TAKE;

  s32 status = FILE_CheckSDCard();

  if( status == 1 ) {
    if( wait_boot_ctr != 0 ) { // don't print message if we just booted
      char str[21];
      sprintf(str, "Label: %s", FILE_VolumeLabel());
#ifndef MBSEQV4L
      SEQ_UI_Msg(SEQ_UI_MSG_SDCARD, 2000, " SD Card connected", "        :-D");
#endif
      DEBUG_MSG("SD Card connected: %s\n", FILE_VolumeLabel());
    }
    SEQ_FILE_LoadSessionName();
    DEBUG_MSG("Loading session %s\n", seq_file_session_name);
    SEQ_FILE_LoadAllFiles(1);
  } else if( status == 2 ) {
#ifndef MBSEQV4L
    SEQ_UI_Msg(SEQ_UI_MSG_SDCARD, 2000, "SD Card disconnected", "        :-/");
#endif
    DEBUG_MSG("SD Card disconnected\n");
    SEQ_FILE_UnloadAllFiles();
    wait_boot_ctr = -1;
  } else if( status == 3 ) {
    if( !FILE_SDCardAvailable() ) {
#ifndef MBSEQV4L
      SEQ_UI_Msg(SEQ_UI_MSG_SDCARD, 2000, "  No SD Card found  ", "        :-(");
#endif
      DEBUG_MSG("SD Card not found\n");
      SEQ_FILE_HW_LockConfig(); // lock configuration
      wait_boot_ctr = -1;
    } else if( !FILE_VolumeAvailable() ) {
#ifndef MBSEQV4L
      SEQ_UI_Msg(SEQ_UI_MSG_SDCARD, 2000, "!! SD Card Error !!!", "!! Invalid FAT !!!!!");
#endif
      DEBUG_MSG("ERROR: SD Card contains invalid FAT!\n");
      SEQ_FILE_HW_LockConfig(); // lock configuration
      wait_boot_ctr = -1;
    } else {
#ifndef MBSEQV4L
      if( wait_boot_ctr != 0 ) { // don't print message if we just booted
	char str1[30];
	sprintf(str1, "Banks: ....");
	u8 bank;
	for(bank=0; bank<4; ++bank)
	  str1[7+bank] = SEQ_FILE_B_NumPatterns(bank) ? ('1'+bank) : '-';
	char str2[30];
	sprintf(str2, 
		"M:%c S:%c G:%c C:%c%c HW:%c", 
		SEQ_FILE_M_NumMaps() ? '*':'-',
		SEQ_FILE_S_NumSongs() ? '*':'-',
		SEQ_FILE_G_Valid() ? '*':'-',
		SEQ_FILE_C_Valid() ? 'S':'-',
		SEQ_FILE_GC_Valid() ? 'G':'-',
		SEQ_FILE_HW_Valid() ? '*':'-');
	SEQ_UI_Msg(SEQ_UI_MSG_SDCARD, 2000, str1, str2);
      }
#endif

#if MBSEQV4L
      // auto-format
      // check if formatting is required
      if( SEQ_FILE_FormattingRequired() ) {
	strcpy(seq_file_new_session_name, "DEF_V4L");
	DEBUG_MSG("Creating initial session '%s'... this can take some seconds!\n", seq_file_new_session_name);

	if( (status=SEQ_FILE_Format()) < 0 ) {
	  DEBUG_MSG("Failed to create session! (status: %d)\n", status);
	} else {
	  SEQ_FILE_StoreSessionName();
	  DEBUG_MSG("Done!\n");
	}
      }
#endif

      // request to load content of SD card
      load_sd_content = 1;

      // notify that boot finished
      wait_boot_ctr = -1;
    }
  } else if( status < 0 ) {
    wait_boot_ctr = -1;
#ifndef MBSEQV4L
    SEQ_UI_SDCardErrMsg(2000, status);
#endif
    DEBUG_MSG("ERROR: SD Card Error %d (FatFs: D%3d)\n", status, file_dfs_errno);
  }

  // check for format request
  // this is running with low priority, so that LCD is updated in parallel!
  if( seq_ui_format_req ) {
    // note: request should be cleared at the end of this process to avoid double-triggers!
    if( (status = SEQ_FILE_Format()) < 0 ) {
#ifndef MBSEQV4L
      SEQ_UI_SDCardErrMsg(2000, status);
#endif
      DEBUG_MSG("ERROR: SD Card Error %d (FatFs: D%3d)\n", status, file_dfs_errno);
    } else {
#ifndef MBSEQV4L
      SEQ_UI_Msg(SEQ_UI_MSG_USER, 1000, "Files created", "successfully!");
#endif
      DEBUG_MSG("Files created successfully!\n");

      // store session name
      status |= SEQ_FILE_StoreSessionName();
    }

    // request to load content of SD card
    load_sd_content = 1;

    // finally clear request
    seq_ui_format_req = 0;
  }

  // check for backup request
  // this is running with low priority, so that LCD is updated in parallel!
  if( seq_ui_backup_req ) {
    // note: request should be cleared at the end of this process to avoid double-triggers!
    status = SEQ_FILE_CreateBackup();
      
    if( status < 0 ) {
      if( status == FILE_ERR_COPY ) {
#ifndef MBSEQV4L
	SEQ_UI_Msg(SEQ_UI_MSG_USER, 2000, "COPY FAILED!", "ERROR :-(");
#endif
	DEBUG_MSG("ERROR: copy failed!\n");
      } else {
#ifndef MBSEQV4L
	SEQ_UI_SDCardErrMsg(2000, status);
#endif
	DEBUG_MSG("ERROR: SD Card Error %d (FatFs: D%3d)\n", status, file_dfs_errno);
      }
    }
    else {
#ifndef MBSEQV4L
      SEQ_UI_Msg(SEQ_UI_MSG_USER, 1000, "Files copied", "successfully!");
#endif
      DEBUG_MSG("Files copied successfully!\n");

      // store session name
      status |= SEQ_FILE_StoreSessionName();
    }

    // finally clear request
    seq_ui_backup_req = 0;
  }

  // check for save all request
  // this is running with low priority, so that LCD is updated in parallel!
  if( seq_ui_saveall_req ) {
    s32 status = 0;

    // store all patterns
    int group;
    for(group=0; group<SEQ_CORE_NUM_GROUPS; ++group)
      status |= SEQ_FILE_B_PatternWrite(seq_file_session_name, seq_pattern[group].bank, seq_pattern[group].pattern, group, 1);

    // store config (e.g. to store current song/mixermap/pattern numbers
    SEQ_FILE_C_Write(seq_file_session_name);

    // store global config
    SEQ_FILE_GC_Write();

    // store mixer map
    SEQ_MIXER_Save(SEQ_MIXER_NumGet());

    // store session name
    if( status >= 0 )
      status |= SEQ_FILE_StoreSessionName();

    if( status < 0 ) {
#ifndef MBSEQV4L
      SEQ_UI_SDCardErrMsg(2000, status);
#endif
      DEBUG_MSG("ERROR: SD Card Error %d (FatFs: D%3d)\n", status, file_dfs_errno);
    }

    // finally clear request
    seq_ui_saveall_req = 0;
  }

  MUTEX_SDCARD_GIVE;

  // load content of SD card if requested ((re-)connection detected)
  if( load_sd_content && !SEQ_FILE_FormattingRequired() ) {
    // send layout request to MBHP_BLM_SCALAR
    MUTEX_MIDIOUT_TAKE;
    SEQ_BLM_SYSEX_SendRequest(0x00);
    MUTEX_MIDIOUT_GIVE;

    // TODO: should we load the patterns when SD Card has been detected?
    // disadvantage: current edit patterns are destroyed - this could be fatal during a live session if there is a bad contact!

    SEQ_MIXER_Load(SEQ_MIXER_NumGet());
    SEQ_SONG_Load(SEQ_SONG_NumGet());
  }

#ifndef MBSEQV4L
  SEQ_LCD_LOGO_ScreenSaver_Period1S();
#endif
}
コード例 #2
0
ファイル: ec_curses_view.c プロジェクト: abdimuna1/ettercap
/*
 * change the WEP key for wifi
 */
static void curses_wep_key(void)
{
   DEBUG_MSG("curses_wep_key");

   curses_input("WEP key :", wkey, WLEN, curses_set_wepkey);
}
コード例 #3
0
void
MapArea::updateCache(const GRect & pm_rect, const GP<GPixmap> & pm,
		     GRectMapper * sdoc_mapper)
      // Takes the passed pixmap and updated the internal cache.
      // The pixmap should already contain the hyperlink draw in the
      // INACTIVE state. We will copy it and apply ACTIVE part here.
      // pm_rect is a rectangle in pane's coordinates where pm is supposed
      // to go to. sdoc_mapper maps screen coordinates to the coordinates
      // of the scaled document (see qd_base_paint.cpp)
{
   DEBUG_MSG("MapArea::updateCache(): updating caches\n");
   DEBUG_MAKE_INDENT(3);

   if (!isCacheUsed() || !pm || !pane) return;
   
   GRect brect=gmap_area->get_bound_rect();
   mapper->map(brect);
   brect.inflate(3, 3);		// To take into account edit controls
      
   GRect urect;
   if (urect.intersect(pm_rect, brect))
   {
      for(GPosition pos=pieces;pos;++pos)
      {
	 GP<MapPiece> piece=pieces[pos];
	 GRect prect=*piece;
	 mapper->map(prect);
	 GRect irect;
	 if (irect.intersect(prect, urect))
	 {
	    if (piece->getOnPixmap().isNull() || piece->getOffPixmap().isNull())
	       piece->createPixmaps();

	    QPixmap & on_pix=piece->getOnPixmap();
	    QPixmap & off_pix=piece->getOffPixmap();

	       // Now I need to make a copy of the area to be cached.
	       // The problem is that I'll need to draw into the GPixmap
	       // and I don't want to spoil the original.
	    GP<GPixmap> ipix_off;
	    GRect pix_rect=irect;
	    pix_rect.translate(-pm_rect.xmin, -pm_rect.ymin);
	    ipix_off=GPixmap::create(*pm, GRect(pix_rect.xmin, pm->rows()-pix_rect.ymax,
					    pix_rect.width(), pix_rect.height()));
	    GP<GPixmap> ipix_on=GPixmap::create(*ipix_off);

	       // Now ipix_off and ipix_on contains the data, which can be modified.
	       // Draw the map area into them
	    draw(irect, ipix_on, APPLY_ACTIVE);

	       // Dither pix_off and pix_on
	    GRect drect=irect;
	    sdoc_mapper->map(drect);
	    if (qxImager)
              qxImager->dither(*ipix_on, drect.xmin, drect.ymin);
	    if (qxImager)
              qxImager->dither(*ipix_off, drect.xmin, drect.ymin);

	       // Now copy the GPixmaps into QPixmaps to be used for caching
	    QDPainter p_off(&off_pix);
	    p_off.drawPixmap(GRect(irect.xmin-prect.xmin,
				   irect.ymin-prect.ymin,
				   irect.width(), irect.height()), ipix_off);
	    p_off.end();
	    
	    QDPainter p_on(&on_pix);
	    p_on.drawPixmap(GRect(irect.xmin-prect.xmin,
				  irect.ymin-prect.ymin,
				  irect.width(), irect.height()), ipix_on);
	    p_on.end();
	 }
      }
   }
}
コード例 #4
0
ファイル: seq_ui_info.c プロジェクト: glocklueng/MIOS32
/////////////////////////////////////////////////////////////////////////////
// Local button callback function
// Should return:
//   1 if value has been changed
//   0 if value hasn't been changed
//  -1 if invalid or unsupported button
/////////////////////////////////////////////////////////////////////////////
static s32 Button_Handler(seq_ui_button_t button, s32 depressed)
{
  if( depressed ) return 0; // ignore when button depressed

  if( button <= SEQ_UI_BUTTON_GP8 || button == SEQ_UI_BUTTON_Select ) {
    if( button != SEQ_UI_BUTTON_Select )
      ui_selected_item = button / 2;

    SEQ_UI_Msg(SEQ_UI_MSG_USER_R, 10000, "Sending Informations", "to MIOS Terminal!");

    switch( ui_selected_item + list_view_offset ) {

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_SYSTEM:
	SEQ_TERMINAL_PrintSystem(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_GLOBALS:
	SEQ_TERMINAL_PrintGlobalConfig(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_CONFIG:
	SEQ_TERMINAL_PrintSessionConfig(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_TRACKS:
	SEQ_TERMINAL_PrintTracks(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_TRACK_INFO:
	SEQ_TERMINAL_PrintTrack(DEBUG_MSG, SEQ_UI_VisibleTrackGet());
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_MIXER_MAP:
	SEQ_TERMINAL_PrintCurrentMixerMap(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_SONG:
	SEQ_TERMINAL_PrintCurrentSong(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_GROOVES:
	SEQ_TERMINAL_PrintGrooveTemplates(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_BOOKMARKS:
	SEQ_TERMINAL_PrintBookmarks(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_SD_CARD:
	SEQ_TERMINAL_PrintSdCardInfo(DEBUG_MSG);
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      case LIST_ITEM_NETWORK:
#if !defined(MIOS32_FAMILY_EMULATION)
	UIP_TERMINAL_PrintNetwork(DEBUG_MSG);
#endif
	break;

      //////////////////////////////////////////////////////////////////////////////////////////////
      default:
	DEBUG_MSG("No informations available.");
    }

    SEQ_UI_Msg(SEQ_UI_MSG_USER_R, 1000, "Sent Informations", "to MIOS Terminal!");

    return 1;
  }

  if( button >= SEQ_UI_BUTTON_GP9 && button <= SEQ_UI_BUTTON_GP16 ) {
    // re-using encoder handler
    return Encoder_Handler(button, 0);
  }

  switch( button ) {
    case SEQ_UI_BUTTON_Right:
    case SEQ_UI_BUTTON_Up:
      return Encoder_Handler(SEQ_UI_ENCODER_Datawheel, 1);

    case SEQ_UI_BUTTON_Left:
    case SEQ_UI_BUTTON_Down:
      return Encoder_Handler(SEQ_UI_ENCODER_Datawheel, -1);
  }

  return -1; // invalid or unsupported button
}
コード例 #5
0
ファイル: ec_curses_view.c プロジェクト: abdimuna1/ettercap
/*
 * change the visualization method 
 */
static void curses_vis_method(void)
{
   DEBUG_MSG("curses_vis_method");

   curses_input("Visualization method :", vmethod, VLEN, curses_set_method);
}
コード例 #6
0
ファイル: server_select.c プロジェクト: Cnlouds/citypw-SCFE
int main(int argc, char *argv[])
{
  int sockfd, clientfd, sockaddr_size, ret;
  fd_set fds_tmp, fds_rd;
  int fd_max, i, j, max_client = -1, addrlen, conn_num = 0;;
  struct sockaddr_in serv_addr, client_addr;
  struct timeval tv;
  char buf[256], answer[32];
  int client_arr[FD_SETSIZE];

  /* create a socket */
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd == -1) {
	perror("socket()");
	exit(1);
  }
  DEBUG_MSG("Server socket() is OK...\n");

  memset(&serv_addr, 0x00, sizeof(struct sockaddr_in));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(SERV_PORT);
  serv_addr.sin_addr.s_addr = INADDR_ANY;

  if (bind(sockfd, (SA *) & serv_addr, sizeof(SA)) == -1) {
	perror("Unable to bind");
	exit(1);
  }
  DEBUG_MSG("Server bind() is OK...\n");

  if(listen(sockfd, BACKLOG) == -1){
    perror("listen()");
    exit(1);
  }
  DEBUG_MSG("Server listen() is OK...\n");

  /* initialize the fd set and add one to it */
  FD_ZERO(&fds_rd);
  FD_SET(sockfd, &fds_rd);
  for(i = 0; i < FD_SETSIZE; i++)
    client_arr[i] = -1;

  /* Keep track of the biggest fd */
  fd_max = sockfd;

  printf("TCP server waiting for client on port 5566!\n");
  sockaddr_size = sizeof(SA);

  while (1) {
    memset(buf, '\0', sizeof(buf));

    /* focus on fds_rd, fds_tmp is only a tmp variable */
    fds_tmp = fds_rd;

    /* wait for 5 secs */
    tv.tv_sec =5;
    tv.tv_usec =0;

    ret = select(fd_max + 1, &fds_tmp, NULL, NULL, &tv);
    //    printf("ret is %d\n", ret);
    if(ret == 0){
      DEBUG_MSG("No data within %d seconds.!\n", tv.tv_sec);
      continue;
    }
    else if( ret == -1){
      perror("select()");
      exit(1);
    }

    /* handle new connection */
    if(FD_ISSET(sockfd, &fds_tmp)){

      DEBUG_MSG("Client is trying to connect...\n");
      addrlen = sizeof(client_addr);

      clientfd = accept(sockfd, (SA *) & client_addr, &sockaddr_size);
      if(clientfd == -1){
            perror("accept()");
      }
      DEBUG_MSG("Server accept() is OK...\n");
      DEBUG_MSG("Got a new connection from %s:%d\n",
                inet_ntoa(client_addr.sin_addr),
                ntohs(client_addr.sin_port));

      /* find a place where to save the fd */
      for(i = 0; i < FD_SETSIZE; i++){
        if(client_arr[i] < 0)
        {
          client_arr[i] = clientfd;
          break;
        }
      }

      FD_SET(clientfd, &fds_rd);
      if(clientfd > fd_max){
        fd_max = clientfd;
      }
      if(i > max_client){
        max_client = i;
      }

      /* check all clients */
      for(j = 0; j <= i; j++)
      {
        if(client_arr[j] > 0)
        {
          if(FD_ISSET(client_arr[j], &fds_rd)){
            int n;
            n = recv(client_arr[j], buf, sizeof(buf), 0);
            if(n > 0){
              buf[n] = '\0';
              printf("Received Client %d: %s\n", client_arr[j], buf);
              send(client_arr[j], GREETING, strlen(GREETING), 0);
              printf("Server sent to Client %d:%s\n", client_arr[j], GREETING);
            }

            /* close and clear the fd from fd set, if no data received */
            if(n == 0){
              close(client_arr[j]);
              FD_CLR(client_arr[j], &fds_rd);
              client_arr[j] = -1;
            }
          }
        }
      }
    }
  }

  close(sockfd);
  return 0;
}
コード例 #7
0
ファイル: sys_info.cpp プロジェクト: flyawayii/kbengine
//-------------------------------------------------------------------------------------
float SystemInfo::getCPUPerByPID(uint32 pid)
{
	if(pid == 0)
	{
		pid = (uint32)getProcessPID();
	}

    float percent = 0.f;
	bool tryed = false;

_TRYGET:
	if(!hasPID(pid, &_g_proclist))
	{
		DEBUG_MSG(fmt::format("SystemInfo::getCPUPerByPID: error: not found pid({})\n", pid));

		if(!tryed)
		{
			clear();
			tryed = true;

			if(_autocreate())
				goto _TRYGET;
		}

		return 0.f;
	}

	/*
	int status = SIGAR_OK;
	// for (size_t i = 0; i < proclist.number; i++)
    {
        sigar_proc_cpu_t cpu;
        status = sigar_proc_cpu_get(_g_sigarproclist, pid, &cpu);

		if (status != SIGAR_OK) 
		{
			DEBUG_MSG(fmt::format("error: {} ({}) proc_cpu_get({})\n",
				   status, sigar_strerror(_g_sigarproclist, status), pid));

			return 0.f;
		}
    }
	*/
  // sleep(1000);

	// for (size_t i = 0; i < proclist.number; i++)
    {
        sigar_proc_cpu_t cpu;
        int status = sigar_proc_cpu_get(_g_sigarproclist, pid, &cpu);
        if (status == SIGAR_OK)
        {
			/*
            sigar_proc_state_t procstate;
            status = sigar_proc_state_get(sigarproclist, pid, &procstate);

			if (status != SIGAR_OK) 
			{
				DEBUG_MSG(fmt::format("error: {} ({}) proc_state({})\n",
					   status, sigar_strerror(sigarproclist, status), pid));

				return 0.f;
			}
			*/
            percent = float(cpu.percent) * 100.f;

#if KBE_PLATFORM == PLATFORM_WIN32
			percent /= float(countCPU());
#endif

        }
		else
		{
			DEBUG_MSG(fmt::format("error: {} ({}) proc_cpu_get({})\n",
				   status, sigar_strerror(_g_sigarproclist, status), pid));

			return 0.f;
		}
    }

	return percent;
}
コード例 #8
0
ファイル: test-instanced.c プロジェクト: freedreno/freedreno
void test_quad_instanced(int instances, int div0, int div1)
{
	GLint width, height;
	GLuint texturename = 0, texture_handle;
	GLfloat vVertices[] = {
			// front
			-0.45, -0.75, 0.0,
			 0.45, -0.75, 0.0,
			-0.45,  0.75, 0.0,
			 0.45,  0.75, 0.0
	};

	GLfloat vTexCoords[] = {
			1.0f, 1.0f,
			0.0f, 1.0f,
			1.0f, 0.0f,
			0.0f, 0.0f,
	};

	EGLSurface surface;

	RD_START("instanced", "instances=%d, div0=%d, div1=%d", instances, div0, div1);

	display = get_display();

	/* get an appropriate EGL frame buffer configuration */
	ECHK(eglChooseConfig(display, config_attribute_list, &config, 1, &num_config));
	DEBUG_MSG("num_config: %d", num_config);

	/* create an EGL rendering context */
	ECHK(context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribute_list));

	surface = make_window(display, config, 255, 255);

	ECHK(eglQuerySurface(display, surface, EGL_WIDTH, &width));
	ECHK(eglQuerySurface(display, surface, EGL_HEIGHT, &height));

	DEBUG_MSG("Buffer: %dx%d", width, height);

	/* connect the context to the surface */
	ECHK(eglMakeCurrent(display, surface, surface, context));

	printf("EGL Version %s\n", eglQueryString(display, EGL_VERSION));
	printf("EGL Vendor %s\n", eglQueryString(display, EGL_VENDOR));
	printf("EGL Extensions %s\n", eglQueryString(display, EGL_EXTENSIONS));
	printf("GL Version %s\n", glGetString(GL_VERSION));
	printf("GL extensions: %s\n", glGetString(GL_EXTENSIONS));

	program = get_program(vertex_shader_source, fragment_shader_source);

	GCHK(glBindAttribLocation(program, 0, "in_position"));
	GCHK(glBindAttribLocation(program, 1, "in_TexCoord"));

	link_program(program);

	GCHK(glViewport(0, 0, width, height));

	/* clear the color buffer */
	GCHK(glClearColor(0.5, 0.5, 0.5, 1.0));
	GCHK(glClear(GL_COLOR_BUFFER_BIT));

	GCHK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices));
	GCHK(glEnableVertexAttribArray(0));

	GCHK(glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, vTexCoords));
	GCHK(glEnableVertexAttribArray(1));

	GCHK(glActiveTexture(GL_TEXTURE0));
	GCHK(glGenTextures(1, &texturename));
	GCHK(glBindTexture(GL_TEXTURE_2D, texturename));

	GCHK(glTexImage2D(
			GL_TEXTURE_2D, 0, GL_RGB,
			cube_texture.width, cube_texture.height, 0,
			GL_RGB, GL_UNSIGNED_BYTE, cube_texture.pixel_data));

	/* Note: cube turned black until these were defined. */
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
	GCHK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE));


	GCHK(texture_handle = glGetUniformLocation(program, "uTexture"));

	GCHK(glUniform1i(texture_handle, 0)); /* '0' refers to texture unit 0. */

	GCHK(glEnable(GL_CULL_FACE));

	if (instances > 0) {
		GCHK(glVertexAttribDivisor(0, div0));
		GCHK(glVertexAttribDivisor(1, div1));
		GCHK(glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, instances));
	} else {
		GCHK(glDrawArrays(GL_TRIANGLE_STRIP, 0, 4));
	}

	ECHK(eglSwapBuffers(display, surface));
	GCHK(glFlush());

	sleep(1);

	ECHK(eglDestroySurface(display, surface));

	ECHK(eglTerminate(display));

	RD_END();
}
コード例 #9
0
static
rc_t XML_ValidateNode(FSNode* parent, const KXMLNode* n, SRAConfigFlags flags, char* errmsg)
{
    rc_t rc = 0;
    const char* name = NULL;
    FSNode* fsn = NULL;
    bool children_allowed = false, should_have_children = false, ignore_children = false;

    if( (rc = KXMLNodeElementName(n, &name)) != 0 ) {
        return rc;
    }
    DEBUG_MSG(8, ("Node: %s\n", name));
    if( name == NULL ) {
        return RC(rcExe, rcDoc, rcValidating, rcDirEntry, rcNull);
    }

    if( strcmp(name, "Directory") == 0 ) {
        rc = DirectoryNode_Make(n, &fsn, errmsg, g_start_dir, g_xml_mtime, g_xml_validate);
        children_allowed = true;
    } else if( strcmp(name, "File") == 0 ) {
        rc = FileNode_Make(n, &fsn, errmsg, g_start_dir, g_xml_validate);
    } else if( strcmp(name, "SRA") == 0 ) {
        if( (rc = SRAListNode_Make(n, parent, flags, errmsg, g_start_dir, g_xml_validate)) == 0 ) {
            fsn = parent;
        }
    } else if( strcmp(name, "TAR") == 0 ) {
        /* tar nodes do not validate on creation */
        rc = TarNode_MakeXML(n, &fsn, errmsg, g_start_dir);
        children_allowed = true;
        ignore_children = true;
    } else if( strcmp(name, "SRAConfig") == 0 ) {
        if( (rc = SRAConfigParse(n, &flags, errmsg)) == 0 ) {
            fsn = parent;
            children_allowed = true;
            should_have_children = true;
        }
    } else {
        strcpy(errmsg, name);
        rc = RC(rcExe, rcDoc, rcValidating, rcTag, rcUnknown);
    }
    if( rc == 0 ) {
        strcpy(errmsg, name);
        if( fsn == parent || (rc = FSNode_AddChild(parent, fsn)) == 0 ) {
            uint32_t count = 0;
            if( (rc = KXMLNodeCountChildNodes(n, &count)) == 0 && count > 0 ) {
                if( !children_allowed ) {
                    if( fsn != NULL ) {
                        FSNode_GetName(fsn, &name);
                    }
                    rc = RC(rcExe, rcDoc, rcValidating, rcDirEntry, rcInvalid);
                    strcpy(errmsg, name);
                } else if( !ignore_children ) {
                    uint32_t i = 0;
                    const KXMLNode* ch = NULL;
                    while( rc == 0 && i < count ) {
                        if( (rc = KXMLNodeGetNodeRead(n, &ch, i++)) == 0 ) {
                            rc = XML_ValidateNode(fsn, ch, flags, errmsg);
                            ReleaseComplain(KXMLNodeRelease, ch);
                        }
                    }
                }
            } else if( count == 0 && should_have_children ) {
                PLOGMSG(klogWarn, (klogWarn, "$(n) may have children", PLOG_S(n), name));
            }
        }
    }
    return rc;
}
コード例 #10
0
static int default_exited_cb(struct state_t*state,void* input)
{
	DEBUG_MSG("default exited\n");
	return 0;
}
コード例 #11
0
//-------------------------------------------------------------------------------------
PyObject* ClientEntityMethod::callmethod(PyObject* args, PyObject* kwds)
{
	Entity* srcEntity = Cellapp::getSingleton().findEntity(srcEntityID_);

	if(srcEntity == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "Entity::clientEntity(%s): srcEntityID(%d) not found!\n",		
			methodDescription_->getName(), srcEntityID_);		
		PyErr_PrintEx(0);
		return 0;
	}

	if(srcEntity->isDestroyed())
	{
		PyErr_Format(PyExc_AssertionError, "Entity::clientEntity(%s): srcEntityID(%d) is destroyed!\n",		
			methodDescription_->getName(), srcEntityID_);		
		PyErr_PrintEx(0);
		return 0;
	}

	if(srcEntity->pWitness() == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): no client, srcEntityID(%d).\n",		
			srcEntity->scriptName(), methodDescription_->getName(), srcEntity->id());		
		PyErr_PrintEx(0);
		return 0;
	}

	EntityRef::AOI_ENTITIES::iterator iter = srcEntity->pWitness()->aoiEntities().begin();
	Entity* e = NULL;

	for(; iter != srcEntity->pWitness()->aoiEntities().end(); ++iter)
	{
		if((*iter)->id() == clientEntityID_ && ((*iter)->flags() & 
			(ENTITYREF_FLAG_ENTER_CLIENT_PENDING | ENTITYREF_FLAG_LEAVE_CLIENT_PENDING)) <= 0)
		{
			e = (*iter)->pEntity();
			break;
		}
	}

	if(e == NULL)
	{
		PyErr_Format(PyExc_AssertionError, "%s::clientEntity(%s): not found entity(%d), srcEntityID(%d).\n",		
			srcEntity->scriptName(), methodDescription_->getName(), clientEntityID_, srcEntity->id());	

		PyErr_PrintEx(0);

		return 0;
	}

	MethodDescription* methodDescription = getDescription();
	if(methodDescription->checkArgs(args))
	{
		MemoryStream* mstream = MemoryStream::ObjPool().createObject();
		methodDescription->addToStream(mstream, args);

		Network::Bundle* pForwardBundle = Network::Bundle::ObjPool().createObject();
		Network::Bundle* pSendBundle = Network::Bundle::ObjPool().createObject();

		srcEntity->pWitness()->addSmartAOIEntityMessageToBundle(pForwardBundle, ClientInterface::onRemoteMethodCall, 
				ClientInterface::onRemoteMethodCallOptimized, clientEntityID_);

		if(mstream->wpos() > 0)
			(*pForwardBundle).append(mstream->data(), (int)mstream->wpos());

		if(Network::g_trace_packet > 0)
		{
			if(Network::g_trace_packet_use_logfile)
				DebugHelper::getSingleton().changeLogger("packetlogs");

			DEBUG_MSG(fmt::format("ClientEntityMethod::callmethod: pushUpdateData: ClientInterface::onRemoteOtherEntityMethodCall({}::{})\n",
				srcEntity->scriptName(), methodDescription->getName()));
																								
			switch(Network::g_trace_packet)							
			{																								
			case 1:																							
				mstream->hexlike();																			
				break;																						
			case 2:																							
				mstream->textlike();																			
				break;																						
			default:																						
				mstream->print_storage();																	
				break;																						
			};																								

			if(Network::g_trace_packet_use_logfile)	
				DebugHelper::getSingleton().changeLogger(COMPONENT_NAME_EX(g_componentType));																				
		}

		NETWORK_ENTITY_MESSAGE_FORWARD_CLIENT(srcEntity->id(), (*pSendBundle), (*pForwardBundle));

		srcEntity->pWitness()->sendToClient(ClientInterface::onRemoteMethodCallOptimized, pSendBundle);

		// 记录这个事件产生的数据量大小
		g_publicClientEventHistoryStats.trackEvent(srcEntity->scriptName(), 
			(std::string(e->scriptName()) + "." + methodDescription->getName()), 
			pForwardBundle->currMsgLength(), 
			"::");

		MemoryStream::ObjPool().reclaimObject(mstream);
		Network::Bundle::ObjPool().reclaimObject(pForwardBundle);
	}

	S_Return;
}
コード例 #12
0
ファイル: ec_gtk_help.c プロジェクト: mfer/ettercap
void gtkui_help(void)
{
   GtkWidget *dialog, *scrolled, *treeview, *hbox, *textview;
   GtkCellRenderer   *renderer;
   GtkTreeViewColumn *column;
   GtkTreeIter iter;
   help_pair *section;

   DEBUG_MSG("gtkui_help");

   dialog = gtk_dialog_new_with_buttons(EC_PROGRAM" Help", GTK_WINDOW (window),
                                        GTK_DIALOG_MODAL, GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, NULL);
   gtk_window_set_default_size(GTK_WINDOW (dialog), 780, 580);
   gtk_dialog_set_has_separator(GTK_DIALOG (dialog), TRUE);
   gtk_container_set_border_width(GTK_CONTAINER (dialog), 5);

   hbox = gtk_hbox_new (FALSE, 6);
   gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), hbox, TRUE, TRUE, 0);

   scrolled = gtk_scrolled_window_new(NULL, NULL);
   gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (scrolled), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
   gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW (scrolled), GTK_SHADOW_IN);
   gtk_box_pack_start(GTK_BOX(hbox), scrolled, FALSE, FALSE, 0);
   gtk_widget_show(scrolled);
   
   treeview = gtk_tree_view_new();
   gtk_tree_view_set_headers_visible(GTK_TREE_VIEW (treeview), FALSE);
   gtk_container_add(GTK_CONTAINER (scrolled), treeview);
   gtk_widget_show(treeview);

   selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
   gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);
   g_signal_connect(selection, "changed", G_CALLBACK (gtkui_help_selected), liststore);

   renderer = gtk_cell_renderer_text_new ();
   column = gtk_tree_view_column_new_with_attributes ("Contents", renderer, "text", 0, NULL);
   gtk_tree_view_column_set_sort_column_id (column, 0);
   gtk_tree_view_append_column (GTK_TREE_VIEW(treeview), column);

   liststore = gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_POINTER);

   for(section = help_list; section->title; section++) {
      gtk_list_store_append (liststore, &iter);
      gtk_list_store_set (liststore, &iter,
                          0, section->title,
                          1, section->file, -1);
   }
   
   gtk_tree_view_set_model(GTK_TREE_VIEW (treeview), GTK_TREE_MODEL (liststore));

   /* text area */
   scrolled = gtk_scrolled_window_new(NULL, NULL);
   gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
   gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW (scrolled), GTK_SHADOW_IN);
   gtk_box_pack_start(GTK_BOX(hbox), scrolled, TRUE, TRUE, 0);
   gtk_widget_show(scrolled);

   textview = gtk_text_view_new();
   gtk_text_view_set_editable(GTK_TEXT_VIEW (textview), FALSE);
   gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW (textview), FALSE);
   gtk_container_add(GTK_CONTAINER (scrolled), textview);
   gtk_widget_show(textview);

   textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW (textview));

   gtk_widget_show_all(hbox);

   gtk_dialog_run(GTK_DIALOG (dialog));

   gtk_widget_destroy (dialog);
}
コード例 #13
0
ファイル: billing_tasks.cpp プロジェクト: gameogre/kbengine
//-------------------------------------------------------------------------------------
bool CreateAccountTask::process()
{
	if(!enable)
	{
		return false;
	}

	// 如果没有设置第三方服务地址则我们默认为成功
	if(strlen(serviceAddr()) == 0)
	{
		success = true;
		getDatas = postDatas;
		return false;
	}

	Mercury::EndPoint endpoint;
	endpoint.socket(SOCK_STREAM);

	if (!endpoint.good())
	{
		ERROR_MSG("BillingTask::process: couldn't create a socket\n");
		return false;
	}

	if(postDatas.size() == 0)
	{
		ERROR_MSG(boost::format("BillingTask::process: %1% postData is NULL.\n") % commitName);
		return false;
	}

	u_int32_t addr;
	KBEngine::Mercury::EndPoint::convertAddress(serviceAddr(), addr);

	if(endpoint.connect(htons(servicePort()), addr) == -1)
	{
		ERROR_MSG(boost::format("BillingTask::process: connect billingserver(%1%:%2%) is error(%3%)!\n") % 
			serviceAddr() % servicePort() % kbe_strerror());

		endpoint.close();
		return false;
	}

	endpoint.setnonblocking(true);
	endpoint.setnodelay(true);

	Mercury::Bundle::SmartPoolObjectPtr bundle = Mercury::Bundle::createSmartPoolObj();
	(*(*bundle)).append(postDatas.data(), postDatas.size());
	(*(*bundle)).send(endpoint);

	Mercury::TCPPacket packet;
	packet.resize(1024);

	fd_set	frds;
	struct timeval tv = { 0, 5000000 }; // 5000ms

	FD_ZERO( &frds );
	FD_SET((int)endpoint, &frds);
	int selgot = select(endpoint+1, &frds, NULL, NULL, &tv);
	if(selgot <= 0)
	{
		ERROR_MSG(boost::format("BillingTask::process: %1% send(%2%).\n") % commitName % postDatas);
		ERROR_MSG(boost::format("BillingTask::process: %1% recv is error(%2%).\n") % commitName % KBEngine::kbe_strerror());
		endpoint.close();
		return false;
	}
	
	int len = endpoint.recv(packet.data(), 1024);

	if(len <= 0)
	{
		ERROR_MSG(boost::format("BillingTask::process: %1% recv is size<= 0.\n===>postdatas=%2%\n") % commitName % postDatas);
		endpoint.close();
		return false;
	}

	packet.wpos(len);

	getDatas.assign((const char *)(packet.data() + packet.rpos()), packet.opsize());

	try
	{
		std::string::size_type fi = getDatas.find("\r\n\r\n");
		if(fi != std::string::npos)
		{
			fi += 4;
			MemoryStream s;
			s.append(getDatas.data() + fi, getDatas.size() - fi);

			while(s.opsize() > 0)
			{
				int32 type, len;
				s >> type >> len;
				EndianConvertReverse<int32>(type);
				EndianConvertReverse<int32>(len);
				
				int32 error = 0;

				switch(type)
				{
				case 1:
					s >> error;
					EndianConvertReverse<int32>(error);

					if(error != 0)
					{
						success = false;
						endpoint.close();
						
						std::string err;
						if(s.opsize() >= (sizeof(int32) * 2))
						{
							s >> type >> len;
							
							if(len > 0 && len < 1024)
							{
								char* buf = new char[len + 1];
								memcpy(buf, s.data() + s.rpos(), len);
								buf[len] = 0;
								err = buf;
								delete[] buf;
							}

						}

						DEBUG_MSG(boost::format("BillingTask::process: (%1%)op is failed! err=%2%\n<==send(%3%)\n==>recv(%4%).\n") % commitName % err % postDatas % getDatas);
						return false;
					}
					else
					{
						success = true;
					}

					break;
				case 2:
					{
						s.read_skip(len);
					}
					break;
				case 3:
					{
						char* buf = new char[len + 1];
						memcpy(buf, s.data() + s.rpos(), len);
						buf[len] = 0;
						accountName = buf;
						delete[] buf;

						s.read_skip(len);
					}
					break;
				default:
					break;
				};
コード例 #14
0
ファイル: VoltageDet.c プロジェクト: magic-gjh/NT96620_GMD223
/**
  Get battery voltage level

  Get battery voltage level.
  If battery voltage level is VOLDET_BATTERY_LVL_EMPTY, it means
  that you have to power off the system.

  @param void
  @return UINT32 Battery Level, refer to VoltageDet.h -> VOLDET_BATTERY_LVL_XXXX
*/
UINT32 VolDet_GetBatteryLevel(void)
{
    static UINT32   uiPreBatteryLvl = VOLDET_BATTERY_LVL_UNKNOWN;
    static UINT32   uiPreBatteryADC = 0;
    static UINT32   uiRetBatteryLvl;
    UINT32          uiCurBatteryADC, uiCurBatteryLvl;
    UINT32          uiBattAdcLvl3, uiBattAdcLvl2, uiBattAdcLvl1, uiBattAdcLvl0;

    uiBattAdcLvl3 = VOLDET_BATTERY_ADC_LVL3;
    uiBattAdcLvl2 = VOLDET_BATTERY_ADC_LVL2;
    uiBattAdcLvl1 = VOLDET_BATTERY_ADC_LVL1;
    uiBattAdcLvl0 = VOLDET_BATTERY_ADC_LVL0;
    uiCurBatteryADC = VolDet_GetBatteryADC();

    DEBUG_MSG(("VOLDET: battery ADC = %d\r\n", uiCurBatteryADC));

    // Rising
    if (uiCurBatteryADC > uiPreBatteryADC)
    {
        if (uiCurBatteryADC > (uiBattAdcLvl3 + VOLDET_BATTERY_ADC_TH))
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_3;
        }
        else if (uiCurBatteryADC > (uiBattAdcLvl2 + VOLDET_BATTERY_ADC_TH))
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_2;
        }
        else if (uiCurBatteryADC > (uiBattAdcLvl1 + VOLDET_BATTERY_ADC_TH))
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_1;
        }
        else if (uiCurBatteryADC > (uiBattAdcLvl0 + VOLDET_BATTERY_ADC_TH))
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_0;
        }
        else
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_EMPTY;
        }
    }
    // Falling
    else
    {
        if (uiCurBatteryADC > (uiBattAdcLvl3 - VOLDET_BATTERY_ADC_TH))
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_3;
        }
        else if (uiCurBatteryADC > (uiBattAdcLvl2 - VOLDET_BATTERY_ADC_TH))
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_2;
        }
        else if (uiCurBatteryADC > (uiBattAdcLvl1 - VOLDET_BATTERY_ADC_TH))
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_1;
        }
        else if (uiCurBatteryADC > (uiBattAdcLvl0 - VOLDET_BATTERY_ADC_TH))
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_0;
        }
        else
        {
            uiCurBatteryLvl = VOLDET_BATTERY_LVL_EMPTY;
        }
    }

    // Debounce
    if ((uiCurBatteryLvl == uiPreBatteryLvl) ||
        (uiPreBatteryLvl == VOLDET_BATTERY_LVL_UNKNOWN))
    {
        uiRetBatteryLvl = uiCurBatteryLvl;
    }
    uiPreBatteryLvl = uiCurBatteryLvl;
    uiPreBatteryADC = uiCurBatteryADC;

    return uiRetBatteryLvl;
}
コード例 #15
0
ファイル: bottle.cpp プロジェクト: Art67bB/barwin-arduino
/**
 * Turn servo towards 'pos' in 1 microsecond steps, waiting delay_ms
 * milliseconds between steps (speed = 1/delay). If check_weight weight
 * is true, might abort with WHERE_THE_FUCK_IS_THE_CUP error. If a valid pointer
 * stable_weight is passed, turns bottle until a stable weight is measured
 * (returns WEIGHT_NOT_STABLE if pos is reached before weight stable).
 *
 * Returns 0 when the position is reached or SERVO_OUT_OF_RANGE on error.
 *
 * For details about the built-in Servo class see:
 *     /usr/share/arduino/libraries/Servo/Servo.cpp
 *
 */
errv_t Bottle::turn_to(int pos, int delay_ms, bool check_weight, int* stable_weight, bool enable_abortcheck) {
    int weight_previous1 = -9999;  // just any impossible value
    int weight_previous2 = -9999;  // ..before we have real values

    if (pos < SERVO_MIN || pos > SERVO_MAX) {
        DEBUG_MSG_LN("Invalid pos");
        return SERVO_OUT_OF_RANGE;
    }

    int current_pos = servo.readMicroseconds();
    if (pos == current_pos)
        return 0;
    int step = (current_pos < pos) ? 1 : -1;

    DEBUG_START();
    DEBUG_MSG("turn ");
    DEBUG_MSG(number);
    DEBUG_MSG(", params ");
    DEBUG_VAL(current_pos);
    DEBUG_VAL(step);
    DEBUG_VAL(pos);
    DEBUG_VAL(delay_ms);
    DEBUG_END();
    unsigned long last_called = millis();
    for (int i = current_pos + step; i * step <= pos * step; i += step) {
        //                             ˆˆˆˆˆˆ        ˆˆˆˆˆˆ
        //                             this inverts the relation if turning down

        // Warning: printing to serial delays turning!
        // Might help to to debug servo movement. Not necessary now, commenting
        // out to save bytes.
        //if (print_steps && i % 10 == 0) {
        //    DEBUG_VAL_LN(i);
        //}

        // check abort only if not already aborted...
        if (enable_abortcheck) {
            // turn up and return if we should abort...
            errv_t ret = check_aborted();
            if (ret) {
                // turn_up might not be necessary here, called another time
                // later (does not matter if called twice)
                turn_up(FAST_TURN_UP_DELAY, false);
                return ret;
            }
        }

        if (check_weight || stable_weight) {
            int weight;
            int ret = ads1231_get_noblock(weight);
            if (ret == 0) {
                // we got a valid weight from scale
                if (check_weight && weight < WEIGHT_EPSILON) {
                    return WHERE_THE_FUCK_IS_THE_CUP;
                }

                // get next weight sample and return if weight is stable
                if (stable_weight) {
                    if (weight_previous2 == weight_previous1
                            && weight_previous1 == weight) {
                        *stable_weight = weight;
                        return 0;
                    }
                    weight_previous2 = weight_previous1;
                    weight_previous1 = weight;
                }
            }
            else if (ret != ADS1231_WOULD_BLOCK) {
                // ignoring if it would take too long to get weight, but
                // return in case of other error != 0
                return ret;
            }
        }

        // turn servo one step
        delay(delay_ms);
        servo.writeMicroseconds(i);
    }

    // pos reached before weight stable
    if (stable_weight) {
        return WEIGHT_NOT_STABLE;
    }

    return 0;
}
コード例 #16
0
static
rc_t XMLLock(bool exclusive)
{
    DEBUG_MSG(10, ("Lock XML tree %s\n", exclusive ? "write" : "read"));
    return exclusive ? KRWLockAcquireExcl(g_lock) : KRWLockAcquireShared(g_lock);
}
コード例 #17
0
void gtkui_sniff_live(void)
{
   DEBUG_MSG("gtk_sniff_live");

   gtkui_create_menu(1); /* online menus */
}
コード例 #18
0
static
void XMLUnlock(void)
{
    DEBUG_MSG(10, ("Unlocked XML tree\n"));
    ReleaseComplain(KRWLockUnlock, g_lock);
}
コード例 #19
0
ファイル: clientobject.cpp プロジェクト: warmwine/kbengine
//-------------------------------------------------------------------------------------
void ClientObject::gameTick()
{
	if(pServerChannel()->pEndPoint())
	{
		pServerChannel()->processPackets(NULL);
	}
	else
	{
		if(connectedGateway_)
		{
			EventData_ServerCloased eventdata;
			eventHandler_.fire(&eventdata);
			connectedGateway_ = false;
			canReset_ = true;
			state_ = C_STATE_INIT;
			
			DEBUG_MSG(fmt::format("ClientObject({})::tickSend: serverCloased! name({})!\n", 
			this->appID(), this->name()));
		}
	}

	if(locktime() > 0 && timestamp() < locktime())
	{
		return;
	}

	switch(state_)
	{
		case C_STATE_INIT:

			state_ = C_STATE_PLAY;

			if(!initCreate())
				return;

			break;
		case C_STATE_CREATE:

			state_ = C_STATE_PLAY;

			if(!createAccount())
				return;

			break;
		case C_STATE_LOGIN:

			state_ = C_STATE_PLAY;

			if(!login())
				return;

			break;
		case C_STATE_LOGIN_GATEWAY_CREATE:

			state_ = C_STATE_PLAY;

			if(!initLoginGateWay())
				return;

			break;
		case C_STATE_LOGIN_GATEWAY:

			state_ = C_STATE_PLAY;

			if(!loginGateWay())
				return;

			break;
		case C_STATE_PLAY:
			break;
		default:
			KBE_ASSERT(false);
			break;
	};

	tickSend();
}
コード例 #20
0
rc_t XML_FindLock(const char* path, bool recur, const FSNode** node, const char** subpath)
{
    rc_t rc = 0;
    size_t sz = 0;
    const char* p0 = NULL, *p = NULL;
    const FSNode* pn = NULL, *n = NULL;
    bool hidden = false;

    if( path == NULL || node == NULL || subpath == NULL ) {
        return RC(rcExe, rcPath, rcResolving, rcParam, rcNull);
    }
    sz = strlen(path);
    if( sz == 0 ) {
        return RC(rcExe, rcPath, rcResolving, rcParam, rcEmpty);
    }
    p0 = path;
    if( (rc = XMLLock(false)) != 0 ) {
        return rc;
    }
    pn = g_root;
    do {
        DEBUG_MSG(8, ("Path: '%s'\n", p0));
        while( *p0 == '/' && *p0 != '\0' ) {
            p0++;
        }
        if( *p0 == '\0' ) {
            break;
        }
        p = strchr(p0, '/');
        if( p == NULL ) {
            p = p0 + strlen(p0);
        }
        DEBUG_MSG(8, ("Push: '%.*s'\n", p - p0, p0));
        if( (rc = FSNode_FindChild(pn, p0, p - p0, &n, &hidden)) == 0 ) {
            if( hidden ) {
                pn = n;
                DEBUG_MSG(8, ("Match! hidden '%s' left '%s'\n", pn->name, p0));
                break;
            } else {
                DEBUG_MSG(8, ("Match! '%.*s' left '%s'\n", p - p0, p0, p));
            }
        } else if( GetRCState(rc) == rcNotFound ) {
            rc = 0;
            break;
        }
        pn = n;
        p0 = p;
    } while( rc == 0 && p0 < path + sz );

    if( rc == 0 ) {
        if( pn == NULL ) {
            rc = RC(rcExe, rcPath, rcResolving, rcDirEntry, rcNotFound);
            DEBUG_MSG(10, ("Not found: '%s', in '%s'\n", p0, path));
        } else {
            if( (rc = FSNode_Touch(pn)) != 0 ) {
                PLOGERR(klogWarn, (klogWarn, rc, "touch failed for $(n)", PLOG_S(n), pn->name));
                rc = 0;
            }
            *node = pn;
            *subpath = (p0 && p0[0] != '\0') ? p0 : NULL;
#if _DEBUGGING
            {
                const char* nm = NULL;
                FSNode_GetName(pn, &nm);
                DEBUG_MSG(10, ("Found: '%s', sub '%s'\n", nm, *subpath));
            }
#endif
        }
    }
    if( rc != 0 ) {
        XMLUnlock();
    }
    return rc;
}
コード例 #21
0
ファイル: sys_info.cpp プロジェクト: flyawayii/kbengine
//-------------------------------------------------------------------------------------
uint64 SystemInfo::getMemUsedByPID(uint32 pid)
{
	if(pid == 0)
	{
		pid = (uint32)getProcessPID();
	}

	int status;
	sigar_uint64_t total = 0;
	bool tryed = false;

_TRYGET:
	if(!hasPID(pid, &_g_proclist))
	{
		DEBUG_MSG(fmt::format("SystemInfo::getMemUsedByPID: error: not found pid({})\n", pid));

		if(!tryed)
		{
			clear();
			tryed = true;

			if(_autocreate())
				goto _TRYGET;
		}

		return 0;
	}

    //for (i=0; i<(int)proclist.number; i++) 
	{
        sigar_proc_state_t pstate;
        sigar_proc_time_t ptime;

        status = sigar_proc_state_get(_g_sigarproclist, pid, &pstate);
        if (status != SIGAR_OK) 
		{
			DEBUG_MSG(fmt::format("error: {} ({}) proc_state({})\n",
                   status, sigar_strerror(_g_sigarproclist, status), pid));
			
			goto _END;
        }

        status = sigar_proc_time_get(_g_sigarproclist, pid, &ptime);
        if (status != SIGAR_OK) 
		{
			DEBUG_MSG(fmt::format("error: {} ({}) proc_time({})\n",
                   status, sigar_strerror(_g_sigarproclist, status), pid));

           goto _END;
        }

		sigar_proc_mem_t proc_mem;
		status = sigar_proc_mem_get(_g_sigarproclist, pid, &proc_mem);

        if (status != SIGAR_OK) 
		{
			DEBUG_MSG(fmt::format("error: {} ({}) sigar_proc_mem_get({})\n",
                   status, sigar_strerror(_g_sigarproclist, status), pid));
            
			goto _END;
        }

		total = proc_mem.resident;
    }

_END:
	return total;
}
コード例 #22
0
ファイル: seq_file_bm.c プロジェクト: gillspice/mios32
/////////////////////////////////////////////////////////////////////////////
// reads the config file content (again)
// returns < 0 on errors (error codes are documented in seq_file.h)
/////////////////////////////////////////////////////////////////////////////
s32 SEQ_FILE_BM_Read(char *session, u8 global)
{
  s32 status = 0;
  seq_file_bm_info_t *info = &seq_file_bm_info[global];
  seq_file_t file;

  info->valid = 0; // will be set to valid if file content has been read successfully

  char filepath[MAX_PATH];
  if( global )
    sprintf(filepath, "%sMBSEQ_BM.V4", SEQ_FILES_PATH);
  else
    sprintf(filepath, "%s/%s/MBSEQ_BM.V4", SEQ_FILE_SESSION_PATH, session);

#if DEBUG_VERBOSE_LEVEL >= 2
  DEBUG_MSG("[SEQ_FILE_BM] Open config file '%s'\n", filepath);
#endif

  if( (status=SEQ_FILE_ReadOpen(&file, filepath)) < 0 ) {
#if DEBUG_VERBOSE_LEVEL >= 2
    DEBUG_MSG("[SEQ_FILE_BM] failed to open file, status: %d\n", status);
#endif
    return status;
  }

  // read config values
  u8 current_bookmark = 0;
  char line_buffer[128];
  do {
    status=SEQ_FILE_ReadLine((u8 *)line_buffer, 128);

    if( status > 1 ) {
#if DEBUG_VERBOSE_LEVEL >= 3
      DEBUG_MSG("[SEQ_FILE_BM] read: %s", line_buffer);
#endif

      // sscanf consumes too much memory, therefore we parse directly
      char *separators = " \t";
      char *brkt;
      char *parameter;

      if( (parameter = strtok_r(line_buffer, separators, &brkt)) ) {

	u8 parameter_enabled = 1;
	if( *parameter == '-' ) {
	  parameter_enabled = 0;
	  ++parameter;
	} else if( *parameter == '+' ) {
	  ++parameter;
	}

	if( *parameter == '#' ) {
	  // ignore comments
	} else if( strcmp(parameter, "Slot") == 0 ) {
	  char *word = strtok_r(NULL, separators, &brkt);
	  s32 value = get_dec(word);
	  if( value < 1 || value > SEQ_UI_BOOKMARKS_NUM ) {
#if DEBUG_VERBOSE_LEVEL >= 1
	    DEBUG_MSG("[SEQ_FILE_BM] ERROR invalid Slot number %d\n", value);
#endif
	  } else {
	    current_bookmark = value - 1;
	  }
	} else if( strcmp(parameter, "Name") == 0 ) {
	  //char *word = strtok_r(NULL, separators, &brkt);
	  seq_ui_bookmark_t *bm = &seq_ui_bookmarks[current_bookmark];
	  //strncpy(bm->name, word, 6);
	  //strncpy(bm->name, (char *)&line_buffer+5, 6); // allow spaces...
	  strncpy(bm->name, brkt, 6); // allow spaces...
	} else if( strcmp(parameter, "ParLayer") == 0 ) {
	  char *word = strtok_r(NULL, separators, &brkt);
	  int layer = word[0] - 'A';
	  if( layer < 0 || layer > 16 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
	    DEBUG_MSG("[SEQ_FILE_BM] ERROR invalid ParLayer '%s' in Slot %d\n", word, current_bookmark+1);
#endif
	  } else {
	    seq_ui_bookmark_t *bm = &seq_ui_bookmarks[current_bookmark];
	    bm->par_layer = layer;
	    bm->enable.PAR_LAYER = parameter_enabled;
	  }
	} else if( strcmp(parameter, "TrgLayer") == 0 ) {
	  char *word = strtok_r(NULL, separators, &brkt);
	  int layer = word[0] - 'A';
	  if( layer < 0 || layer > 16 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
	    DEBUG_MSG("[SEQ_FILE_BM] ERROR invalid TrgLayer '%s' in Slot %d\n", word, current_bookmark+1);
#endif
	  } else {
	    seq_ui_bookmark_t *bm = &seq_ui_bookmarks[current_bookmark];
	    bm->trg_layer = layer;
	    bm->enable.TRG_LAYER = parameter_enabled;
	  }
	} else if( strcmp(parameter, "Tracks") == 0 ) {
	  char *word = strtok_r(NULL, separators, &brkt);
	  if( strlen(word) < 16 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
	    DEBUG_MSG("[SEQ_FILE_BM] ERROR invalid Tracks Parameter '%s' in Slot %d\n", word, current_bookmark+1);
#endif
	  } else {
	    seq_ui_bookmark_t *bm = &seq_ui_bookmarks[current_bookmark];
	    bm->tracks = 0;
	    int i;
	    for(i=0; i<16; ++i)
	      if( word[i] == '1' )
		bm->tracks |= (1 << i);
	    bm->enable.TRACKS = parameter_enabled;
	  }
	} else if( strcmp(parameter, "Mutes") == 0 ) {
	  char *word = strtok_r(NULL, separators, &brkt);
	  if( strlen(word) < 16 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
	    DEBUG_MSG("[SEQ_FILE_BM] ERROR invalid Mutes Parameter '%s' in Slot %d\n", word, current_bookmark+1);
#endif
	  } else {
	    seq_ui_bookmark_t *bm = &seq_ui_bookmarks[current_bookmark];
	    bm->mutes = 0;
	    int i;
	    for(i=0; i<16; ++i)
	      if( word[i] == '1' )
		bm->mutes |= (1 << i);
	    bm->enable.MUTES = parameter_enabled;
	  }
	} else {
	  char *word = strtok_r(NULL, separators, &brkt);
	  s32 value = get_dec(word);
	  seq_ui_bookmark_t *bm = &seq_ui_bookmarks[current_bookmark];

	  if( value < 0 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
	    DEBUG_MSG("[SEQ_FILE_BM] ERROR invalid value for parameter '%s' in Slot %d\n", parameter, current_bookmark);
#endif
	  } else if( strcmp(parameter, "Page") == 0 ) {
	    bm->page = value;
	    bm->enable.PAGE = parameter_enabled;
	  } else if( strcmp(parameter, "Group") == 0 ) {
	    bm->group = value - 1;
	    bm->enable.GROUP = parameter_enabled;
	  } else if( strcmp(parameter, "Instrument") == 0 ) {
	    bm->instrument = value - 1;
	    bm->enable.INSTRUMENT = parameter_enabled;
	  } else if( strcmp(parameter, "StepView") == 0 ) {
	    bm->step_view = value - 1;
	    bm->enable.STEP_VIEW = parameter_enabled;
	  } else if( strcmp(parameter, "Step") == 0 ) {
	    bm->step = value - 1;
	    bm->enable.STEP = parameter_enabled;
	  } else if( strcmp(parameter, "EditView") == 0 ) {
	    bm->edit_view = value;
	    bm->enable.EDIT_VIEW = parameter_enabled;
	  } else if( strcmp(parameter, "Solo") == 0 ) {
	    bm->flags.SOLO = value ? 1 : 0;
	    bm->enable.SOLO = parameter_enabled;
	  } else if( strcmp(parameter, "All") == 0 ) {
	    bm->flags.CHANGE_ALL_STEPS = value ? 1 : 0;
	    bm->enable.CHANGE_ALL_STEPS = parameter_enabled;
	  } else if( strcmp(parameter, "Fast") == 0 ) {
	    bm->flags.FAST = value ? 1 : 0;
	    bm->enable.FAST = parameter_enabled;
	  } else if( strcmp(parameter, "Metronome") == 0 ) {
	    bm->flags.METRONOME = value ? 1 : 0;
	    bm->enable.METRONOME = parameter_enabled;
	  } else if( strcmp(parameter, "LoopMode") == 0 ) {
	    bm->flags.LOOP = value ? 1 : 0;
	    bm->enable.LOOP = parameter_enabled;
	  } else if( strcmp(parameter, "FollowMode") == 0 ) {
	    bm->flags.FOLLOW = value ? 1 : 0;
	    bm->enable.FOLLOW = parameter_enabled;
	  } else {
#if DEBUG_VERBOSE_LEVEL >= 1
	    DEBUG_MSG("[SEQ_FILE_HW] ERROR: unknown parameter: %s in Slot %d", line_buffer, current_bookmark);
#endif
	  }
	}
      } else {
#if DEBUG_VERBOSE_LEVEL >= 1
	DEBUG_MSG("[SEQ_FILE_BM] ERROR no space separator in following line: %s", line_buffer);
#endif
      }
    }

  } while( status >= 1 );

  // close file
  status |= SEQ_FILE_ReadClose(&file);

  if( status < 0 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
    DEBUG_MSG("[SEQ_FILE_BM] ERROR while reading file, status: %d\n", status);
#endif
    return SEQ_FILE_BM_ERR_READ;
  }

  // file is valid! :)
  info->valid = 1;

  return 0; // no error
}
コード例 #23
0
//-------------------------------------------------------------------------------------
bool DBInterfaceMysql::attach(const char* databaseName)
{
	if(!_g_installedWatcher)
	{
		initializeWatcher();
	}

	if(db_port_ == 0)
		db_port_ = 3306;
	
	if(databaseName != NULL)
		kbe_snprintf(db_name_, MAX_BUF, "%s", databaseName);

	hasLostConnection_ = false;

	try
	{
		pMysql_ = mysql_init(0);
		if(pMysql_ == NULL)
		{
			ERROR_MSG("DBInterfaceMysql::attach: mysql_init is error!\n");
			return false;
		}
		
		DEBUG_MSG(fmt::format("DBInterfaceMysql::attach: connect: {}:{} starting...\n", db_ip_, db_port_));

		int ntry = 0;

__RECONNECT:
		if(mysql_real_connect(mysql(), db_ip_, db_username_, 
    		db_password_, db_name_, db_port_, NULL, 0)) // CLIENT_MULTI_STATEMENTS  
		{
			if(mysql_select_db(mysql(), db_name_) != 0)
			{
				ERROR_MSG(fmt::format("DBInterfaceMysql::attach: Could not set active db[{}]\n",
					db_name_));

				detach();
				return false;
			}
		}
		else
		{
			if (mysql_errno(pMysql_) == 1049 && ntry++ == 0)
			{
				if (mysql())
				{
					::mysql_close(mysql());
					pMysql_ = NULL;
				}

				pMysql_ = mysql_init(0);
				if (pMysql_ == NULL)
				{
					ERROR_MSG("DBInterfaceMysql::attach: mysql_init is error!\n");
					return false;
				}

				if (mysql_real_connect(mysql(), db_ip_, db_username_,
					db_password_, NULL, db_port_, NULL, 0)) // CLIENT_MULTI_STATEMENTS  
				{
					this->createDatabaseIfNotExist();
					if (mysql_select_db(mysql(), db_name_) != 0)
					{
						goto __RECONNECT;
					}
				}
				else
				{
					goto __RECONNECT;
				}
			}
			else
			{
				ERROR_MSG(fmt::format("DBInterfaceMysql::attach: mysql_errno={}, mysql_error={}\n",
					mysql_errno(pMysql_), mysql_error(pMysql_)));

				detach();
				return false;
			}
		}

		if (mysql_set_character_set(mysql(), "utf8") != 0)
		{
			ERROR_MSG("DBInterfaceMysql::attach: Could not set client connection character set to UTF-8\n" );
			return false;
		}

		// 不需要关闭自动提交,底层会START TRANSACTION之后再COMMIT
		// mysql_autocommit(mysql(), 0);

		char characterset_sql[MAX_BUF];
		kbe_snprintf(characterset_sql, MAX_BUF, "ALTER DATABASE CHARACTER SET %s COLLATE %s", 
			characterSet_.c_str(), collation_.c_str());

		query(&characterset_sql[0], strlen(characterset_sql), false);
	}
	catch (std::exception& e)
	{
		ERROR_MSG(fmt::format("DBInterfaceMysql::attach: {}\n", e.what()));
		hasLostConnection_ = true;
		detach();
		return false;
	}

	bool ret = mysql() != NULL && ping();

	if(ret)
	{
		DEBUG_MSG(fmt::format("DBInterfaceMysql::attach: successfully! addr: {}:{}\n", db_ip_, db_port_));
	}

    return ret;
}
コード例 #24
0
ファイル: pyprofile_handler.cpp プロジェクト: aabbox/kbengine
//-------------------------------------------------------------------------------------
PyTickProfileHandler::~PyTickProfileHandler()
{
	DEBUG_MSG(fmt::format("PyTickProfileHandler::~PyTickProfileHandler(), name = {}\n", name_));
	networkInterface_.dispatcher().cancelTask(this);
	script::PyProfile::remove(name_);
}
コード例 #25
0
ファイル: ec_curses_view.c プロジェクト: abdimuna1/ettercap
/*
 * change the visualization regex 
 */
static void curses_vis_regex(void)
{
   DEBUG_MSG("curses_vis_regex");

   curses_input("Visualization regex :", vregex, RLEN, curses_set_regex);
}
コード例 #26
0
ファイル: seq.c プロジェクト: JKcompute/395_midi_controller
/////////////////////////////////////////////////////////////////////////////
// called when a Meta event should be played/processed at a given tick
/////////////////////////////////////////////////////////////////////////////
static s32 SEQ_PlayMeta(u8 track, u8 meta, u32 len, u8 *buffer, u32 tick)
{
  switch( meta ) {
    case 0x00: // Sequence Number
      if( len == 2 ) {
	u32 seq_number = (buffer[0] << 8) | buffer[1];
#if DEBUG_VERBOSE_LEVEL >= 2
	DEBUG_MSG("[SEQ:%d:%u] Meta - Sequence Number %u\n", track, tick, seq_number);
#endif
      } else {
#if DEBUG_VERBOSE_LEVEL >= 2
	DEBUG_MSG("[SEQ:%d:%u] Meta - Sequence Number with %d bytes -- ERROR: expecting 2 bytes!\n", track, tick, len);
#endif
      }
      break;

    case 0x01: // Text Event
#if DEBUG_VERBOSE_LEVEL >= 2
      DEBUG_MSG("[SEQ:%d:%u] Meta - Text: %s\n", track, tick, buffer);
#endif
      break;

    case 0x02: // Copyright Notice
#if DEBUG_VERBOSE_LEVEL >= 2
      DEBUG_MSG("[SEQ:%d:%u] Meta - Copyright: %s\n", track, tick, buffer);
#endif
      break;

    case 0x03: // Sequence/Track Name
#if DEBUG_VERBOSE_LEVEL >= 2
      DEBUG_MSG("[SEQ:%d:%u] Meta - Track Name: %s\n", track, tick, buffer);
#endif
      break;

    case 0x04: // Instrument Name
#if DEBUG_VERBOSE_LEVEL >= 2
      DEBUG_MSG("[SEQ:%d:%u] Meta - Instr. Name: %s\n", track, tick, buffer);
#endif
      break;

    case 0x05: // Lyric
#if DEBUG_VERBOSE_LEVEL >= 2
      DEBUG_MSG("[SEQ:%d:%u] Meta - Lyric: %s\n", track, tick, buffer);
#endif
      break;

    case 0x06: // Marker
#if DEBUG_VERBOSE_LEVEL >= 2
      DEBUG_MSG("[SEQ:%d:%u] Meta - Marker: %s\n", track, tick, buffer);
#endif
      break;

    case 0x07: // Cue Point
#if DEBUG_VERBOSE_LEVEL >= 2
      DEBUG_MSG("[SEQ:%d:%u] Meta - Cue Point: %s\n", track, tick, buffer);
#endif
      break;

    case 0x20: // Channel Prefix
      if( len == 1 ) {
	u32 prefix = *buffer;
#if DEBUG_VERBOSE_LEVEL >= 2
	DEBUG_MSG("[SEQ:%d:%u] Meta - Channel Prefix %u\n", track, tick, prefix);
#endif
      } else {
#if DEBUG_VERBOSE_LEVEL >= 2
	DEBUG_MSG("[SEQ:%d:%u] Meta - Channel Prefix with %d bytes -- ERROR: expecting 1 byte!\n", track, tick, len);
#endif
      }
      break;

    case 0x2f: // End of Track
#if DEBUG_VERBOSE_LEVEL >= 2
      DEBUG_MSG("[SEQ:%d:%u] Meta - End of Track\n", track, tick, meta);
#endif
      break;

    case 0x51: // Set Tempo
      if( len == 3 ) {
	u32 tempo_us = (buffer[0] << 16) | (buffer[1] << 8) | buffer[2];
	float bpm = 60.0 * (1E6 / (float)tempo_us);
	SEQ_BPM_PPQN_Set(MIDI_PARSER_PPQN_Get());

	// set tempo immediately on first tick
	if( tick == 0 ) {
	  SEQ_BPM_Set(bpm);
	} else {
	  // put tempo change request into the queue
	  mios32_midi_package_t tempo_package; // or Softis?
	  tempo_package.ALL = (u32)bpm;
	  SEQ_MIDI_OUT_Send(DEFAULT, tempo_package, SEQ_MIDI_OUT_TempoEvent, tick, 0);
	}

#if DEBUG_VERBOSE_LEVEL >= 2
	DEBUG_MSG("[SEQ:%d:%u] Meta - Tempo to %u uS -> %u BPM\n", track, tick, tempo_us, (u32)bpm);
#endif
      } else {
#if DEBUG_VERBOSE_LEVEL >= 2
	DEBUG_MSG("[SEQ:%d:%u] Meta - Tempo with %u bytes -- ERROR: expecting 3 bytes!\n", track, tick, len);
#endif
      }
      break;

    // other known events which are not handled here:
    // 0x54: SMPTE offset
    // 0x58: Time Signature
    // 0x59: Key Signature
    // 0x7f: Sequencer Specific Meta Event

#if DEBUG_VERBOSE_LEVEL >= 2
    default:
      DEBUG_MSG("[SEQ:%d:%u] Meta Event 0x%02x with length %u not processed\n", track, tick, meta, len);
#endif
  }

  return 0;
}
コード例 #27
0
ファイル: misc.c プロジェクト: heyunlong565/LCUI
/* 根据传入的字符串,获取字符串实际表达的数值,确定数值的单位是PX还是百分比 */
LCUI_API int
GetIntOrFloat( char *str, IntOrFloat_t *combo_num )
{
	char buff[256];
	int bits, j, i, len;
	
	DEBUG_MSG( "enter\n" );
	if( !str ) {
		DEBUG_MSG( "!str, quit\n" );
		return -1;
	}
	DEBUG_MSG( "string: %s\n", str );
	len = strlen(str);
	if(len == 0) {
		DEBUG_MSG( "len == 0, quit\n" );
		return -1;
	}
	for(bits=0,j=0,i=0; i<len; ++i, ++j) {
		if(str[i] == ' ') {
			--j;
			continue;
		}
		/* 判断正负符号 */
		if( str[i] == '-' || str[i] == '+' ) {
			/* 正负符号必须在首位 */
			if( j == 0 ) {
				buff[j] = str[i];
				continue;
			} else {
				return -1;
			}
		}
		if((str[i] >= '0' && str[i] <= '9') || str[i] == '.' ) {
			buff[j] = str[i];
			++bits;
			continue;
		}
		else if(str[i] == '%') {/* 如果有%,取浮点数 */ 
			buff[j] = 0; 
			DEBUG_MSG( "buff: %s\n", buff );
			sscanf( buff, "%lf", &combo_num->scale );
			combo_num->scale/=100.0; 
			combo_num->which_one = 1;
			DEBUG_MSG( "scale: %.2f, quit\n", combo_num->scale );
			return 0;
		}
		else if (str[i] == 'p' || str[i] == 'P') { 
			if(i<len-1) { 
				if (str[i+1] == 'x' || str[i+1] == 'X') {
					buff[j+1] = 0;
					sscanf( str, "%d", &combo_num->px ); 
					combo_num->which_one = 0;
					DEBUG_MSG( "px: %d, quit\n", combo_num->px );
					return 0;
				}
			}
			DEBUG_MSG( "1, quit\n" );
			return -1;
		} else {
			DEBUG_MSG( "2, quit\n" );
			break;
		}
	}
	/* 如果数字位数不大于0,也就是没有数字,则退出 */
	if( bits <= 0 ) {
		return -1;
	}
	/* 不包含px和%,那单位就默认为px,取整数 */
	sscanf( buff, "%d", &combo_num->px ); 
	combo_num->which_one = 0;
	DEBUG_MSG( "quit\n" );
	return 0;
}
コード例 #28
0
ファイル: bottle.cpp プロジェクト: Art67bB/barwin-arduino
/**
 * Pour requested_amount grams from bottle..
 * Return 0 on success, other values are return values of
 * delay_until (including scale error codes).
 */
errv_t Bottle::pour(int requested_amount, int& measured_amount) {
    // orig_weight is weight including ingredients poured until now
    int orig_weight, ret;
    while (1) {
        // get weight while turning bottle, because ads1231_stable_millis()
        // blocks bottle in pause position too long
        int below_pause = (pos_down + get_pause_pos()) / 2;
        ret = turn_to(below_pause, TURN_DOWN_DELAY, true, &orig_weight);

        // Note that checking weight here is a critical issue, allows hacking
        // the robot. If a heavy weight is placed while measuring and then
        // removed while pouring (results in more alcohol). Stable weight
        // should resolve most problems.
        if (ret == WEIGHT_NOT_STABLE) {
            ret = ads1231_get_stable_grams(orig_weight);
        }
        if (ret != 0 && ret != WHERE_THE_FUCK_IS_THE_CUP) {
            return ret;
        }
        if (ret == WHERE_THE_FUCK_IS_THE_CUP || orig_weight < WEIGHT_EPSILON) {
            // no cup...
            RETURN_IFN_0(wait_for_cup());
        }
        else {
            // everything fine
            break;
        }
    }

    // loop until successfully poured or aborted or other fatal error
    while(1) {
        // petres wants POURING message also after resume...
        // https://github.com/rfjakob/barwin-arduino/issues/10
        MSG(String("POURING ") + String(number) + String(" ") + String(orig_weight));

        DEBUG_MSG_LN("Turn down");
        ret = turn_down(TURN_DOWN_DELAY, true); // enable check_weight

        // wait for requested weight
        // FIXME here we do not want WEIGHT_EPSILON and sharp >
        if (ret == 0) {
            DEBUG_MSG_LN("Waiting");
            ret = delay_until(POURING_TIMEOUT,
                    orig_weight + requested_amount - UPGRIGHT_OFFSET, true);
        }
        if (ret == 0)
            break; // All good

        DEBUG_MSG_LN(String("pour: got err ") + String(ret));

        // Bottle empty
        // Note that this does not work if requested_amount is less than
        // UPGRIGHT_OFFSET!
        if(ret == BOTTLE_EMPTY) {
            ERROR(strerror(BOTTLE_EMPTY) + String(" ") + String(number) );
            // TODO other speed here? it is empty already!
            RETURN_IFN_0(turn_to(pos_up + BOTTLE_EMPTY_POS_OFFSET, TURN_UP_DELAY));
            RETURN_IFN_0(wait_for_resume()); // might return ABORTED
        }
        // Cup was removed early
        else if(ret == WHERE_THE_FUCK_IS_THE_CUP) {
            ERROR(strerror(WHERE_THE_FUCK_IS_THE_CUP));
            RETURN_IFN_0(turn_to_pause_pos(FAST_TURN_UP_DELAY));
            RETURN_IFN_0(wait_for_cup());
        }
        // other error - turn bottle up and return error code
        // includes: scale error, user abort, ...
        else {
            return ret;
        }
    }

    // We turn to pause pos and not completely up so we can crossfade
    RETURN_IFN_0(turn_to_pause_pos(TURN_UP_DELAY));

    RETURN_IFN_0(ads1231_get_grams(measured_amount));
    measured_amount -= orig_weight;

    DEBUG_START();
    DEBUG_MSG("Stats: ");
    DEBUG_VAL(requested_amount);
    DEBUG_VAL(measured_amount);
    DEBUG_END();
    return 0;
}
コード例 #29
0
//-------------------------------------------------------------------------------------
InitProgressHandler::~InitProgressHandler()
{
	// networkInterface_.mainDispatcher().cancelFrequentTask(this);
	DEBUG_MSG("InitProgressHandler::~InitProgressHandler()\n");
}
コード例 #30
0
ファイル: ir.c プロジェクト: gregory38/mesa-sso
void ir_shader_destroy(struct ir_shader *shader)
{
	DEBUG_MSG("");
	free(shader);
}