Exemple #1
0
/* user main function, called by AppFramework.
 */
OSStatus user_main( app_context_t * const app_context )
{
  user_log_trace();
  OSStatus err = kUnknownErr;
  
  user_log("User main task start...");
  
  
  
  err = user_uartInit();
  require_noerr_action( err, exit, user_log("ERROR: user_uartInit err = %d.", err) );
 
  
  
  user_log("start photo...");
  unsigned char* image="hello world";
  user_uartSend( image,strlen(image));
  char aa[200];
  
  memset(aa, '\0', 200);
  
  mico_thread_sleep(5);
  
  int len=user_uartRecv((unsigned char *)aa, 200);
  user_log("uart_data_recv: [%d][%.*s]", len,  len,(unsigned char*)aa);
  user_log("end...");
  
  
 
#if (MICO_CLOUD_TYPE != CLOUD_DISABLED)
  /* start fogcloud msg handle task */
  err = start_fog_msg_handler(app_context);
  require_noerr_action( err, exit, user_log("ERROR: start_fog_msg_handler err = %d.", err) );

  /* start properties notify task(upload data) */
  err = mico_start_properties_notify(app_context, service_table, 
                                     MICO_PROPERTIES_NOTIFY_INTERVAL_MS, 
                                     STACK_SIZE_NOTIFY_THREAD);
  require_noerr_action( err, exit, user_log("ERROR: mico_start_properties_notify err = %d.", err) );
#endif
  
  /* main loop for user display */
  while(1){
    // check every 1 seconds
    mico_thread_sleep(1);
    
    // system work state show on OLED
    system_state_display(app_context, &g_user_context);
  }
  
exit:
  user_log("ERROR: user_main exit with err=%d", err);
  return err;
}
Exemple #2
0
void mutex_thread(void *inContext)
{
  int delay;
  char *thread_name = (char *)inContext;
  srand( 1000 );
  while(1)
  {
    delay = rand()%9 + 1;
    mico_rtos_lock_mutex(&os_mutex);
    os_mutex_log("%s thread is using resources, delay %ds", thread_name, delay);
    mico_thread_sleep(delay);
    os_mutex_log("%s thread will release resource", thread_name);
    mico_rtos_unlock_mutex(&os_mutex);  
    mico_thread_sleep(5);
  }
}
/* user main function, called by AppFramework.
 */
OSStatus user_main( app_context_t * const app_context )
{
  user_log_trace();
  OSStatus err = kUnknownErr;
  
  user_log("User main thread start...");
  
  // start prop get/set thread
  err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "prop_recv", property_recv, 
                                STACK_SIZE_PROP_RECV_THREAD, (void*)app_context);
  require_noerr_action( err, exit, user_log("ERROR: Unable to start the prop_recv thread.") );
  
  err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "prop_update", property_update, 
                                STACK_SIZE_PROP_UPDATE_THREAD, (void*)app_context);
  require_noerr_action( err, exit, user_log("ERROR: Unable to start the prop_update thread.") );

  /* main loop for user display */
  while(1){
    // system work state show on OLED
    system_state_display(app_context);
    mico_thread_sleep(1);
  }
  
exit:
  user_log("ERROR: user_main exit with err=%d", err);
  return err;
}
void property_update(void *inContext)
{
  int num = 0;
  app_context_t * app_context = (app_context_t*)inContext;
  
  while(1)
  {
    mico_thread_sleep(1);
    if(!app_context->appStatus.arrayentStatus.isCloudConnected){
      continue;
    }
    
    switch(num)
    {
    case 0:
      update_dht11_sensor();
      break;
    case 1:
      update_light_sensor();
      break;
    case 2:
      update_infrared_sensor();
      break;
    }
    num++;
    if(num == 3)num = 0;
  }
}
Exemple #5
0
int application_start( void )
{
#if MCU_POWERSAVE_ENABLED
  MicoMcuPowerSaveConfig(true);
#endif
    
  power_log( "Power measure program: RTOS initialized and wait 5 seconds to standy" );

  mico_thread_sleep( 5 ); //Wait a period to avoid enter standby mode when boot
  
  power_log( "Enter standby mode..., and exit in 5 seconds" );
  
#ifdef EMW1088
  //MicoInit( );
  //micoWlanPowerOff( );
  //wlan_deepsleepps_on( );
#endif
  
#if IEEE_POWERSAVE_ENABLED
   micoWlanEnablePowerSave();
#endif
    
  MicoSystemStandBy( 5 );
  
  power_log( "Enter standby mode error!" );
  
  mico_rtos_delete_thread( NULL );
  return 0;
}
void mico_mfg_test(void)
{
    char str[64];
    char mac[6];
    char *ssid;
  
    sprintf(str, "Library Version: %s\r\n", system_lib_version());
	mf_printf(str);
    mf_printf("APP Version: ");
    memset(str, 0, sizeof(str));
    system_version(str, sizeof(str));
    mf_printf(str);
    mf_printf("\r\n");
    memset(str, 0, sizeof(str));
    wlan_driver_version(str, sizeof(str));
    mf_printf("Driver: ");
    mf_printf(str);
    mf_printf("\r\n");
	wlan_get_mac_address(mac);
	sprintf(str, "MAC: %02X-%02X-%02X-%02X-%02X-%02X\r\n",
			mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
	mf_printf(str);

    mfg_scan();

    ssid = ssid_get();
    mfg_connect(ssid);
    
    mico_thread_sleep(MICO_NEVER_TIMEOUT);
}
Exemple #7
0
void thread_1(void *arg)
{
  UNUSED_PARAMETER(arg);
  while(1){
    os_thread_log( "This is thread 1" );
    mico_thread_sleep( 2 );
  }
}
Exemple #8
0
void thread_2(void *arg)
{
  UNUSED_PARAMETER(arg);
  os_thread_log( "This is thread 2" );
  mico_thread_sleep( 4 );
  /* Make with terminiate state and IDLE thread will clean resources */
  mico_rtos_delete_thread(NULL);
}
Exemple #9
0
void run2(void *arg)
{
  int j=0;
  while(1)
  {
       j++;
       os_thread_log("thread2 running,j=%d",j);
       mico_thread_sleep (1);
  }
}
Exemple #10
0
void run1(void *arg)
{
  int i=0;
  while(1)
  {
       i++;
       os_thread_log("thread1 running,i=%d",i);
       mico_thread_sleep (1);
  }
}
/* MICO APP entrance */
OSStatus MICOStartApplication( mico_Context_t * const mico_context )
{
  app_log_trace();
  OSStatus err = kNoErr;
  LinkStatusTypeDef wifi_link_status;
    
  require_action(mico_context, exit, err = kParamErr);
    
  app_log("Application version: %s", mico_context->flashContentInRam.appConfig.fogcloudConfig.romVersion);
  
  // LED on when Wi-Fi connected.
  MicoSysLed(false);
  
  // init application wifi link status
  do{
    err = micoWlanGetLinkStatus(&wifi_link_status);
    if(kNoErr != err){
      mico_thread_sleep(3);
    }
  }while(kNoErr != err);
  
  if(1 ==  wifi_link_status.is_connected){
    mico_context->appStatus.isWifiConnected = true;
  }
  else{
    mico_context->appStatus.isWifiConnected = false;
  }
    
  /* Bonjour for service searching */
  if(mico_context->flashContentInRam.micoSystemConfig.bonjourEnable == true) {
    MICOStartBonjourService( Station, mico_context );
  }
  
  /* start cloud service */
#if (MICO_CLOUD_TYPE == CLOUD_FOGCLOUD)
  app_log("MICO CloudService: FogCloud.");
  err = MicoStartFogCloudService( mico_context );
  require_noerr_action( err, exit, app_log("ERROR: Unable to start FogCloud service.") );
#elif (MICO_CLOUD_TYPE == CLOUD_ALINK)
  app_log("MICO CloudService: Alink.");
#elif (MICO_CLOUD_TYPE == CLOUD_DISABLED)
  app_log("MICO CloudService: disabled.");
#else
  #error "MICO cloud service type is not defined"?
#endif
  
  /* start user thread */
  err = startUserMainThread( mico_context );
  require_noerr_action( err, exit, app_log("ERROR: start user_main thread failed!") );

exit:
  return err;
}
/* mxchip library manufacture test. */
void mxchip_mfg_test(void)
{
  char str[64];
  char mac[6];
  char *ssid;
  mico_uart_config_t uart_config;
  volatile ring_buffer_t  rx_buffer;
  volatile uint8_t *      rx_data;
  
  rx_data = malloc(50);
  require(rx_data, exit);
  
  /* Initialize UART interface */
  uart_config.baud_rate    = 115200;
  uart_config.data_width   = DATA_WIDTH_8BIT;
  uart_config.parity       = NO_PARITY;
  uart_config.stop_bits    = STOP_BITS_1;
  uart_config.flow_control = FLOW_CONTROL_DISABLED;
  uart_config.flags = UART_WAKEUP_DISABLE;
  
  ring_buffer_init  ( (ring_buffer_t *)&rx_buffer, (uint8_t *)rx_data, 50 );
  MicoUartInitialize( MFG_TEST, &uart_config, (ring_buffer_t *)&rx_buffer );  

  mf_printf("==== MXCHIP Manufacture Test ====\r\n");
  mf_printf("Bootloader Version: ");
  mf_printf(mico_get_bootloader_ver());
  mf_printf("\r\n");
  sprintf(str, "Library Version: %s\r\n", system_lib_version());
  mf_printf(str);
  mf_printf("APP Version: ");
  memset(str, 0, sizeof(str));
  system_version(str, sizeof(str));
  mf_printf(str);
  mf_printf("\r\n");
  memset(str, 0, sizeof(str));
  MicoGetRfVer(str, sizeof(str));
  mf_printf("Driver: ");
  mf_printf(str);
  mf_printf("\r\n");
  wlan_get_mac_address(mac);
  sprintf(str, "MAC: %02X-%02X-%02X-%02X-%02X-%02X\r\n",
          mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  mf_printf(str);
  
  mfg_scan();
  
  ssid = ssid_get();
  mfg_connect(ssid);
  
exit:
  mico_thread_sleep(MICO_NEVER_TIMEOUT);
}
Exemple #13
0
void fogcloud_ota_thread(void *arg)
{
  OSStatus err = kUnknownErr;
  MVDOTARequestData_t devOTARequestData;
  mico_Context_t *inContext = (mico_Context_t *)arg;
  
  fogcloud_log("OTA: check new firmware ...");
  memset((void*)&devOTARequestData, 0, sizeof(devOTARequestData));
  strncpy(devOTARequestData.loginId,
          inContext->flashContentInRam.appConfig.fogcloudConfig.loginId,
          MAX_SIZE_LOGIN_ID);
  strncpy(devOTARequestData.devPasswd,
          inContext->flashContentInRam.appConfig.fogcloudConfig.devPasswd,
          MAX_SIZE_DEV_PASSWD);
  strncpy(devOTARequestData.user_token,
          inContext->flashContentInRam.appConfig.fogcloudConfig.userToken,
          MAX_SIZE_USER_TOKEN);
  err = fogCloudDevFirmwareUpdate(inContext, devOTARequestData);
  if(kNoErr == err){
    if(inContext->appStatus.fogcloudStatus.RecvRomFileSize > 0){
      fogcloud_log("OTA: firmware download success, system will reboot && update...");
      // set bootloader to reboot && update app firmware
      mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex);
      memset(&inContext->flashContentInRam.bootTable, 0, sizeof(boot_table_t));
      inContext->flashContentInRam.bootTable.length = inContext->appStatus.fogcloudStatus.RecvRomFileSize;
      inContext->flashContentInRam.bootTable.start_address = UPDATE_START_ADDRESS;
      inContext->flashContentInRam.bootTable.type = 'A';
      inContext->flashContentInRam.bootTable.upgrade_type = 'U';
      if(inContext->flashContentInRam.micoSystemConfig.configured != allConfigured)
        inContext->flashContentInRam.micoSystemConfig.easyLinkByPass = EASYLINK_SOFT_AP_BYPASS;
      MICOUpdateConfiguration(inContext);
      mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex);
      inContext->micoStatus.sys_state = eState_Software_Reset;
      if(inContext->micoStatus.sys_state_change_sem != NULL ){
        mico_rtos_set_semaphore(&inContext->micoStatus.sys_state_change_sem);
      }
      mico_thread_sleep(MICO_WAIT_FOREVER);
    }
    else{
      fogcloud_log("OTA: firmware is up-to-date!");
    }
  }
  else{
    fogcloud_log("OTA: firmware download failed, err=%d", err);
  }
  
  fogcloud_log("fogcloud_ota_thread exit err=%d.", err);
  mico_rtos_delete_thread(NULL);
  return;
}
void stab_test_cycle(void)
{
	int i=0;
	ramtest_init(1,1);
	stab_titlePrint();
	printf("%s\n",TEST_URL);
	//while(1)
	for(;i < 1; i++)
	{
		stab_oneCrcuRequest();
		stab_resultPrint();
        mico_thread_sleep(1);
		}
	stab_endPrint();
}
/* user main function, called by AppFramework after system init done && wifi
 * station on in user_main thread.
 */
OSStatus user_main( app_context_t * const app_context )
{
    OSStatus err = kNoErr;
    int time_sencond = 50*1000;  /* 60s */


    require(app_context, exit);
    net_init(app_context);

    /* Create a new thread */

    err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "RGB_LED", LED_handleThread, 1024, NULL );
    require_noerr_string( err, exit, "ERROR: Unable to start the RGB LED thread ." );

    err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "MP3_PLAY", MP3_handleThread, 1024, NULL );
    require_noerr_string( err, exit, "ERROR: Unable to start the MP3 PLAY thread" );

    err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "BAT_DETECT", BAT_handleThread, 500, NULL );
    require_noerr_string( err, exit, "ERROR: Unable to start the BAT DETECT thread ." );

    KEY_Init(KEY_irq_handler); //按键初始化

    mico_rtos_init_semaphore(&cupTimeObj.playMp3_sem, 1);  //信号量初始化
    mico_rtos_init_semaphore(&cupTimeObj.playLed_sem, 1);
    mico_rtos_init_semaphore(&cupTimeObj.stopLed_sem, 1);

    err = mico_init_timer(&cupTimeObj.cup_timer, time_sencond, cup_timer_timeout_handler, (void *)&cupTimeObj);
    cupTimeObj.drinkTime = 1;
    cupTimeObj.playMode = PLAY_MP3_LED;
    if (KEY_getValue() == KEY_DOWN)
    {
        TIMER_start(); //启动定时喝水
    }

    while(1)
    {
        // printf("this is main thread.\r\n");
        //net_test(app_context);
        mico_thread_sleep(10);
    }

exit:
    if(kNoErr != err) {
        printf("ERROR: user_main thread exit with err=%d", err);
    }
    mico_rtos_delete_thread(NULL);
    return kNoErr;
}
Exemple #16
0
static void mico_mfg_test(void)
{
  int ret;
  extern int mfg_test(char *);
  
  ret = mfg_test("MXCHIP_CAGE");
  if (ret == 0)
    printf("MFG test success\r\n");
  else {
    if (ret & 1) 
      printf("SCAN FAIL\r\n");
    if (ret & 2)
      printf("Connect AP FAIL\r\n");
  }
  
  mico_thread_sleep(MICO_NEVER_TIMEOUT);
}
int application_start( void )
{
  OSStatus err = kNoErr;
  uint16_t light_sensor_data = 0;
  
  /*init Light sensor*/ 
  err = light_sensor_init();
  require_noerr_action( err, exit, ext_light_sensor_log("ERROR: Unable to Init light sensor") );
  
  while(1)
  {
    err = light_sensor_read(&light_sensor_data);
    require_noerr_action( err, exit, ext_light_sensor_log("ERROR: Can't light sensor read data") );
    ext_light_sensor_log("light date: %d", light_sensor_data);
    mico_thread_sleep(1);
  }
exit:
  return err; 
}
/* user main function, called by AppFramework after system init done && wifi
 * station on in user_main thread.
 */
OSStatus user_main( app_context_t * const app_context )
{
  user_log_trace();
  OSStatus err = kUnknownErr;
  require(app_context, exit);
  
  hsb2rgb_led_init();  // rgb led init
  
  while(1){
    mico_thread_sleep(1);
    
    // system work state show on OLED
    system_state_display(app_context);
  }

exit:
  user_log("ERROR: user_main exit with err=%d", err);
  return err;
}
int application_start( void )
{
  OSStatus err = kNoErr;
  os_timer_log("timer demo");
  int arg = 0;

  err = mico_init_timer(&timer_handle, 1000, alarm, &arg);
  require_noerr(err, exit);

  err = mico_start_timer(&timer_handle);
  require_noerr(err, exit);

  mico_thread_sleep( MICO_NEVER_TIMEOUT );

exit:
  if( err != kNoErr )
    os_timer_log( "Thread exit with err: %d", err );

  mico_rtos_delete_thread( NULL );
  return err;
}
int application_start( void )
{
  OSStatus err = kNoErr;
  uint16_t apds9930_Prox = 0;
  uint16_t apds9930_Lux = 0;
  
  err = apds9930_sensor_init();
  require_noerr_action( err, exit, ext_ambient_light_sensor_log("ERROR: Unable to Init APDS9930") );
  
  while(1)
  {
     mico_thread_sleep(1); 
     err = apds9930_data_readout(&apds9930_Prox, &apds9930_Lux);
     require_noerr_action( err, exit, ext_ambient_light_sensor_log("ERROR: Can't Read Data") );
     ext_ambient_light_sensor_log("APDS9930  Prox: %.1fmm  Lux: %d", 
                                  (float)(10239-apds9930_Prox)/100, apds9930_Lux);  
  }
  
exit:
  return err;
}
int application_start( void )
{
  char time[16]={0};
  ext_oled_log("OLED control demo!");
  /*Init Organic Light-Emitting Diode*/
  OLED_Init();
  /*Starting position display string at the first row*/
  OLED_ShowString(0, 0, "MXCHIP Inc.");
  /*Starting position display string at the second row*/
  OLED_ShowString(0, 2, "MiCO run time:");
  while(1)
  {
    memset(time, 0, sizeof(time));
    /*Gets time in miiliseconds since MiCO RTOS start*/
    sprintf(time, "%d ms", mico_get_time());
    /*Starting position display time at the third row*/
    OLED_ShowString(0, 4, (uint8_t *)time);
    mico_thread_sleep(1);
  }
  //OLED_Clear();
  return 1;
}
Exemple #22
0
/* user main function, called by AppFramework.
 */
OSStatus user_main( mico_Context_t * const mico_context )
{
  user_log_trace();
  OSStatus err = kUnknownErr;
  
  user_log("User main task start...");
  
  err = user_uartInit();
  require_noerr_action( err, exit, user_log("ERROR: user_uartInit err = %d.", err) );
  
  user_log("user_uartInit ok");
 
#if (MICO_CLOUD_TYPE != CLOUD_DISABLED)
  /* start fogcloud msg handle task */
  err = start_fog_msg_handler(mico_context);
  require_noerr_action( err, exit, user_log("ERROR: start_fog_msg_handler err = %d.", err) );

  /* start properties notify task(upload data) */
  err = mico_start_properties_notify(mico_context, service_table, 
                                     MICO_PROPERTIES_NOTIFY_INTERVAL_MS, 
                                     STACK_SIZE_NOTIFY_THREAD);
  require_noerr_action( err, exit, user_log("ERROR: mico_start_properties_notify err = %d.", err) );
#endif
  
  
  /* main loop for user display */
  while(1){
    // check every 1 seconds
    mico_thread_sleep(1);
    
    // system work state show on OLED
    system_state_display(mico_context, &g_user_context);
  }
  
exit:
  user_log("ERROR: user_main exit with err=%d", err);
  return err;
}
void property_recv(void *inContext)
{
  uint16_t len = 0;
  char property[150];
  
  app_context_t * app_context = (app_context_t*)inContext;
  
  while(1)
  {  
    if(!app_context->appStatus.arrayentStatus.isCloudConnected){
      mico_thread_sleep(1);
      continue;
    }

    len = sizeof(property);
    memset(property, 0, len);
    if(ARRAYENT_SUCCESS == ArrayentRecvProperty(property,&len,10000)){//receive property data from server
      user_log("recv property=%s\n\r",property);
      if(0 != checkCmd(property, inContext)){//parse cmd success
        user_log("checkCmd error: property=%s", property);
      }
    }
  }
}
Exemple #24
0
void NTPClient_thread(void *inContext)
{
  ntp_log_trace();
  OSStatus err = kUnknownErr;
  mico_Context_t *Context = inContext;
  
  int  Ntp_fd = -1;
  fd_set readfds;
  struct timeval_t t ;
  struct sockaddr_t addr;
  socklen_t addrLen;	
  char ipstr[16];
  unsigned int trans_sec, current;
  struct NtpPacket outpacket ,inpacket;
  socklen_t sockLen;
  char timeString[40];
  
  /* Regisist notifications */
  err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)ntpNotify_WifiStatusHandler );
  require_noerr( err, exit ); 
 
  memset(&outpacket,0x0,sizeof(outpacket));
  memset(&inpacket,0x0,sizeof(inpacket));

  outpacket.flags = NTP_Flags;
  outpacket.stratum = NTP_Stratum;
  outpacket.poll = NTP_Poll;
  outpacket.precision = NTP_Precision;
  outpacket.root_delay = NTP_Root_Delay;
  outpacket.root_dispersion = NTP_Root_Dispersion;
  
  if(_wifiConnected == false){
    mico_rtos_get_semaphore(&_wifiConnected_sem, MICO_WAIT_FOREVER);
    mico_thread_msleep(50);
  }
  
  Ntp_fd = socket(AF_INET, SOCK_DGRM, IPPROTO_UDP);
  require_action(IsValidSocket( Ntp_fd ), exit, err = kNoResourcesErr );
  addr.s_ip = INADDR_ANY; 
  addr.s_port = 45000;
  err = bind(Ntp_fd, &addr, sizeof(addr));
  err = kNoErr;
  require_noerr(err, exit);

  while(1) {
    err = gethostbyname(NTP_Server, (uint8_t *)ipstr, 16);
    require_noerr(err, ReConnWithDelay);
    ntp_log("NTP server address: %s",ipstr);
    break;

  ReConnWithDelay:
    mico_thread_sleep(5);
  }

  addr.s_ip = inet_addr(ipstr);
  addr.s_port = NTP_Port;
  
  t.tv_sec = 5;
  t.tv_usec = 0;
  
  while(1) {
    require_action(sendto(Ntp_fd, &outpacket,sizeof(outpacket), 0, &addr, sizeof(addr)), exit, err = kNotWritableErr);

    FD_ZERO(&readfds);
    FD_SET(Ntp_fd, &readfds);
    
    select(1, &readfds, NULL, NULL, &t);
    
    if(FD_ISSET(Ntp_fd, &readfds))
    {
      require_action(recvfrom(Ntp_fd, &inpacket, sizeof(struct NtpPacket), 0, &addr, &addrLen)>=0, exit, err = kNotReadableErr);

      trans_sec = inpacket.trans_ts_sec;
      trans_sec = ntohl(trans_sec);
      current = trans_sec - UNIX_OFFSET;
      ntp_log("Time Synchronoused, %s",asctime(localtime(&current)));
      PlatformRTCWrite( localtime(&current) );
      goto exit;
    }
  }
exit:
    if( err!=kNoErr )ntp_log("Exit: NTP client exit with err = %d", err);
    MICORemoveNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)ntpNotify_WifiStatusHandler );
    if(_wifiConnected_sem) mico_rtos_deinit_semaphore(&_wifiConnected_sem);
    SocketClose(&Ntp_fd);
    mico_rtos_delete_thread(NULL);
    return;
}
int application_start(void)
{
  OSStatus err = kNoErr;
  IPStatusTypedef para;
  struct tm currentTime;
  mico_rtc_time_t time;
  char wifi_ver[64] = {0};
  mico_log_trace(); 


  /*Read current configurations*/
  context = ( mico_Context_t *)malloc(sizeof(mico_Context_t) );
  require_action( context, exit, err = kNoMemoryErr );
  memset(context, 0x0, sizeof(mico_Context_t));
  mico_rtos_init_mutex(&context->flashContentInRam_mutex);//ram互斥初始化
  mico_rtos_init_semaphore(&context->micoStatus.sys_state_change_sem, 1);//系统状态信号量 
  mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY, "sys", _sys_state_thread, 800, NULL );

  MICOReadConfiguration( context );//读flash数据

  err = MICOInitNotificationCenter  ( context );

  err = MICOAddNotification( mico_notify_READ_APP_INFO, (void *)micoNotify_ReadAppInfoHandler );
  require_noerr( err, exit );  

  err = MICOAddNotification( mico_notify_WIFI_CONNECT_FAILED, (void *)micoNotify_ConnectFailedHandler );
  require_noerr( err, exit ); 

  err = MICOAddNotification( mico_notify_WIFI_Fatal_ERROR, (void *)micoNotify_WlanFatalErrHandler );
  require_noerr( err, exit ); 

  err = MICOAddNotification( mico_notify_Stack_Overflow_ERROR, (void *)micoNotify_StackOverflowErrHandler );
  require_noerr( err, exit ); 

  /*wlan driver and tcpip init*/
  mico_log( "MiCO starting..." );
  MicoInit();
#ifdef MICO_CLI_ENABLE
  MicoCliInit();
#endif
  MicoSysLed(true);
  mico_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory); 
  micoWlanGetIPStatus(&para, Station);
  formatMACAddr(context->micoStatus.mac, (char *)para.mac);
  MicoGetRfVer(wifi_ver, sizeof(wifi_ver));
  mico_log("ip = %s,mac=%s",para.ip,para.mac);
  mico_log("%s mxchipWNet library version: %s", APP_INFO, MicoGetVer());
  mico_log("Wi-Fi driver version %s, mac %s", wifi_ver, context->micoStatus.mac);
 
  /*Start system monotor thread*/
  //err = MICOStartSystemMonitor(context);
  require_noerr_action( err, exit, mico_log("ERROR: Unable to start the system monitor.") );

  err = MICORegisterSystemMonitor(&mico_monitor, APPLICATION_WATCHDOG_TIMEOUT_SECONDS*1000);
  require_noerr( err, exit );
  mico_init_timer(&_watchdog_reload_timer,APPLICATION_WATCHDOG_TIMEOUT_SECONDS*1000/2, _watchdog_reload_timer_handler, NULL);
  mico_start_timer(&_watchdog_reload_timer);

  /* Enter test mode, call a build-in test function amd output on MFG UART */
  if(MicoShouldEnterMFGMode()==true){
    mico_log( "Enter MFG mode by MFG button" );
    mico_mfg_test(context);
  }
  
  /*Read current time from RTC.*/
  if( MicoRtcGetTime(&time) == kNoErr ){
    currentTime.tm_sec = time.sec;
    currentTime.tm_min = time.min;
    currentTime.tm_hour = time.hr;
    currentTime.tm_mday = time.date;
    currentTime.tm_wday = time.weekday;
    currentTime.tm_mon = time.month - 1;
    currentTime.tm_year = time.year + 100;
    mico_log("Current Time: %s",asctime(&currentTime));
  }else
    mico_log("RTC function unsupported");
  
  /* Regisist notifications */
  err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler );
  require_noerr( err, exit ); 

  if( context->flashContentInRam.micoSystemConfig.configured == wLanUnConfigured ||
      context->flashContentInRam.micoSystemConfig.configured == unConfigured){
    mico_log("Empty configuration. Starting configuration mode...");
//HERE TO config network
#if (MICO_CONFIG_MODE == CONFIG_MODE_EASYLINK) || (MICO_CONFIG_MODE == CONFIG_MODE_EASYLINK_WITH_SOFTAP)
    err = startEasyLink( context );
    require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_SOFT_AP)
    err = startEasyLinkSoftAP( context );
    require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_AIRKISS)
    err = startAirkiss( context );
    require_noerr( err, exit );
#elif (MICO_CONFIG_MODE == CONFIG_MODE_WPS) || MICO_CONFIG_MODE == defined (CONFIG_MODE_WPS_WITH_SOFTAP)
    err = startWPS( context );
    require_noerr( err, exit );
#elif ( MICO_CONFIG_MODE == CONFIG_MODE_WAC)
    WACPlatformParameters_t* WAC_Params = NULL;
    WAC_Params = calloc(1, sizeof(WACPlatformParameters_t));
    require(WAC_Params, exit);

    str2hex((unsigned char *)para.mac, WAC_Params->macAddress, 6);
    WAC_Params->isUnconfigured          = 1;
    WAC_Params->supportsAirPlay         = 0;
    WAC_Params->supportsAirPrint        = 0;
    WAC_Params->supports2_4GHzWiFi      = 1;
    WAC_Params->supports5GHzWiFi        = 0;
    WAC_Params->supportsWakeOnWireless  = 0;

    WAC_Params->firmwareRevision =  FIRMWARE_REVISION;
    WAC_Params->hardwareRevision =  HARDWARE_REVISION;
    WAC_Params->serialNumber =      SERIAL_NUMBER;
    WAC_Params->name =              context->flashContentInRam.micoSystemConfig.name;
    WAC_Params->model =             MODEL;
    WAC_Params->manufacturer =      MANUFACTURER;

    WAC_Params->numEAProtocols =    1;
    WAC_Params->eaBundleSeedID =    BUNDLE_SEED_ID;
    WAC_Params->eaProtocols =       (char **)eaProtocols;

    err = startMFiWAC( context, WAC_Params, MICO_I2C_CP, 1200 );
    free(WAC_Params);
    require_noerr( err, exit );
#else
    #error "Wi-Fi configuration mode is not defined"
#endif
  }
  else{
    mico_log("Available configuration. Starting Wi-Fi connection...");
    _ConnectToAP( context );
  }


#ifdef MFG_MODE_AUTO
  if( context->flashContentInRam.micoSystemConfig.configured == mfgConfigured ){
    mico_log( "Enter MFG mode automatically" );
    mico_mfg_test(context);
    mico_thread_sleep(MICO_NEVER_TIMEOUT);
  }
#endif
  
  err = MICOAddNotification( mico_notify_WiFI_PARA_CHANGED, (void *)micoNotify_WiFIParaChangedHandler );
  require_noerr( err, exit ); 

  err = MICOAddNotification( mico_notify_DHCP_COMPLETED, (void *)micoNotify_DHCPCompleteHandler );
  require_noerr( err, exit );  
 
  if(context->flashContentInRam.micoSystemConfig.rfPowerSaveEnable == true){
    micoWlanEnablePowerSave();
  }

  if(context->flashContentInRam.micoSystemConfig.mcuPowerSaveEnable == true){
    MicoMcuPowerSaveConfig(true);
  }
 
  /*Local configuration server*/
  if(context->flashContentInRam.micoSystemConfig.configServerEnable == true){
    err =  MICOStartConfigServer(context);
    require_noerr_action( err, exit, mico_log("ERROR: Unable to start the local server thread.") );
  }

  err =  MICOStartNTPClient(context);
  require_noerr_action( err, exit, mico_log("ERROR: Unable to start the NTP client thread.") );

  /*Start mico application*/
  err = MICOStartApplication( context );
  require_noerr( err, exit );
  
  mico_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory) ; 
  
  require_noerr_action( err, exit, mico_log("Closing main thread with err num: %d.", err) );

exit:
  mico_rtos_delete_thread(NULL);
  return kNoErr;
}
Exemple #26
0
void fogcloud_main_thread(void *arg)
{
  OSStatus err = kUnknownErr;
  mico_Context_t *inContext = (mico_Context_t *)arg;
  
  MVDResetRequestData_t devResetRequestData;
  
#ifdef ENABLE_FOGCLOUD_AUTO_ACTIVATE
  MVDActivateRequestData_t devDefaultActivateData;
#endif
  
  /* wait for station on */
  while(!inContext->appStatus.isWifiConnected){
    mico_thread_msleep(500);
  }
  
  //--- create msg recv queue, NOTE: just push msg pionter into queue, so msg memory must be freed after used.
  if(NULL == msg_recv_queue_mutex){
    err = mico_rtos_init_mutex(&msg_recv_queue_mutex);
    require_noerr_action(err, exit,
                         fogcloud_log("ERROR: mico_rtos_init_mutex (msg_recv_queue_mutex) failed, err=%d.", err));
  }
  err = mico_rtos_init_queue(&msg_recv_queue, "fog_recv_queue", sizeof(int), FOGCLOUD_MAX_RECV_QUEUE_LENGTH);
  require_noerr_action(err, exit,
                       fogcloud_log("ERROR: mico_rtos_init_queue (msg_recv_queue) failed, err=%d", err));
  
  /* start FogCloud service */
  err = fogCloudStart(inContext);
  require_noerr_action(err, exit, 
                       fogcloud_log("ERROR: MicoFogCloudCloudInterfaceStart failed!") );
  
  /* start configServer for fogcloud (server for activate/authorize/reset/ota cmd from user APP) */
  if(false == inContext->flashContentInRam.appConfig.fogcloudConfig.owner_binding){
    err = MicoStartFogCloudConfigServer( inContext);
    require_noerr_action(err, exit, 
                         fogcloud_log("ERROR: start FogCloud configServer failed!") );
  }
  
 #ifdef ENABLE_FOGCLOUD_AUTO_ACTIVATE
  /* activate when wifi on */
  while(false == inContext->flashContentInRam.appConfig.fogcloudConfig.isActivated){
    // auto activate, using default login_id/dev_pass/user_token
    fogcloud_log("device activate start...");
    memset((void*)&devDefaultActivateData, 0, sizeof(devDefaultActivateData));
    strncpy(devDefaultActivateData.loginId,
            inContext->flashContentInRam.appConfig.fogcloudConfig.loginId,
            MAX_SIZE_LOGIN_ID);
    strncpy(devDefaultActivateData.devPasswd,
            inContext->flashContentInRam.appConfig.fogcloudConfig.devPasswd,
            MAX_SIZE_DEV_PASSWD);
    strncpy(devDefaultActivateData.user_token,
            inContext->micoStatus.mac,   // use MAC as default user_token
            MAX_SIZE_USER_TOKEN);
    err = fogCloudDevActivate(inContext, devDefaultActivateData);
    if(kNoErr == err){
      fogcloud_log("device activate success!");
      break;
    }
    else{
      fogcloud_log("device auto activate failed, err = %d, will retry in 3s ...", err);
    }
    mico_thread_sleep(3);
  }

#endif  // ENABLE_FOGCLOUD_AUTO_ACTIVATE
  
#ifndef DISABLE_FOGCLOUD_OTA_CHECK
  /* OTA check just device activated */
  if( (!inContext->appStatus.noOTACheckOnSystemStart) && 
     (inContext->flashContentInRam.appConfig.fogcloudConfig.isActivated) ){
    // start ota thread
    err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "fogcloud_ota", 
                                  fogcloud_ota_thread, STACK_SIZE_FOGCLOUD_OTA_THREAD, 
                                  inContext);
    if(kNoErr != err){
      fogcloud_log("ERROR: start FogCloud OTA thread failed, err=%d.", err);
    }
  }
  inContext->appStatus.noOTACheckOnSystemStart = false;
#endif  // DISABLE_FOGCLOUD_OTA_CHECK
  
  while(1){
    // device info reset
    if(device_need_delete){
      fogcloud_log("delete device from cloud ...");
      memset((void*)&devResetRequestData, 0, sizeof(devResetRequestData));
      strncpy(devResetRequestData.loginId,
              inContext->flashContentInRam.appConfig.fogcloudConfig.loginId,
              MAX_SIZE_LOGIN_ID);
      strncpy(devResetRequestData.devPasswd,
              inContext->flashContentInRam.appConfig.fogcloudConfig.devPasswd,
              MAX_SIZE_DEV_PASSWD);
      strncpy(devResetRequestData.user_token,
              inContext->flashContentInRam.appConfig.fogcloudConfig.userToken,
                MAX_SIZE_USER_TOKEN);
      err = fogCloudResetCloudDevInfo(inContext, devResetRequestData);
      if(kNoErr == err){
        device_need_delete = false;
        fogcloud_log("delete device success, system need reboot...");
        mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex);
        MicoFogCloudRestoreDefault(inContext);
        MICOUpdateConfiguration(inContext);
        mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex);
        // system restart
        inContext->micoStatus.sys_state = eState_Software_Reset;
        if(inContext->micoStatus.sys_state_change_sem){
          mico_rtos_set_semaphore(&inContext->micoStatus.sys_state_change_sem);
        }
      }
      else{
        fogcloud_log("delete device failed, err = %d.", err);
      }
    }
    
    mico_thread_sleep(1);
    if(inContext->appStatus.fogcloudStatus.isOTAInProgress){
      continue;  // ota is in progress, the oled && system led will be holding
    }
    
    if(inContext->appStatus.fogcloudStatus.isCloudConnected){
      set_RF_LED_cloud_connected(inContext);  // toggle LED
    }
    else{
      set_RF_LED_cloud_disconnected(inContext);  // stop LED blink
    }
  }
  
exit:
  fogcloud_log("fogcloud_main_thread exit err=%d.", err);
  if(NULL != msg_recv_queue_mutex){
    mico_rtos_deinit_mutex(&msg_recv_queue_mutex);
  }
  if(NULL != msg_recv_queue){
    mico_rtos_deinit_queue(&msg_recv_queue);
  }
  mico_rtos_delete_thread(NULL);
  return;
}
Exemple #27
0
/* mxchip library manufacture test. */
void mxchip_mfg_test(void)
{
  char str[128];
  char mac[6];
  char *ssid;
  mico_uart_config_t uart_config;
  volatile ring_buffer_t  rx_buffer;
  volatile uint8_t *      rx_data;
  mico_debug_enabled = 0;
  
  rx_data = malloc(50);
  require(rx_data, exit);
  
  /* Initialize UART interface */
  uart_config.baud_rate    = 115200;
  uart_config.data_width   = DATA_WIDTH_8BIT;
  uart_config.parity       = NO_PARITY;
  uart_config.stop_bits    = STOP_BITS_1;
  uart_config.flow_control = FLOW_CONTROL_DISABLED;
  uart_config.flags = UART_WAKEUP_DISABLE;

  ring_buffer_init ((ring_buffer_t *)&rx_buffer, (uint8_t *)rx_data, 50);
  MicoUartInitialize (MFG_TEST, &uart_config, (ring_buffer_t *)&rx_buffer);

  mf_printf ("==== MXCHIP Manufacture Test ====\r\n");
  mf_printf ("Serial Number: ");
  mf_printf (SERIAL_NUMBER);
  mf_printf ("\r\n");

  mf_printf ("App CRC: ");
  memset (str, 0, sizeof (str));
  app_crc (str, sizeof (str));
  mf_printf (str);
  mf_printf ("\r\n");

  mf_printf ("Bootloader Version: ");
  mf_printf (mico_get_bootloader_ver());
  mf_printf ("\r\n");
  sprintf (str, "Library Version: %s\r\n", system_lib_version());
  mf_printf (str);
  mf_printf ("APP Version: ");
  memset (str, 0, sizeof (str));
  system_version (str, sizeof (str));
  mf_printf (str);
  mf_printf ("\r\n");
  memset (str, 0, sizeof (str));
  wlan_driver_version (str, sizeof (str));
  mf_printf ("Driver: ");
  mf_printf (str);
  mf_printf ("\r\n");

#ifdef MICO_BLUETOOTH_ENABLE
  /* Initialise MICO SmartBridge */
  mico_bt_init( MICO_BT_HCI_MODE, "SmartBridge Device", 0, 0 );  //Client + server connections
  mico_bt_smartbridge_init( 0 );
  mico_bt_dev_read_local_addr( (uint8_t *)mac );
  sprintf( str, "Local Bluetooth Address: %02X-%02X-%02X-%02X-%02X-%02X\r\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] );
  mf_printf (str);
  ble_scan();
#endif

  wlan_get_mac_address (mac);
  sprintf (str, "MAC: %02X-%02X-%02X-%02X-%02X-%02X\r\n",
          mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  mf_printf(str);
  mfg_scan();

  if (test_for_app==0) {
  ssid = ssid_get();
    mfg_connect (ssid);
  }

exit:
  mico_thread_sleep(MICO_NEVER_TIMEOUT);
}
OSStatus _LocalConfigRespondInComingMessage(int fd, HTTPHeader_t* inHeader, mico_Context_t * const inContext)
{
  OSStatus err = kUnknownErr;
  const char *  json_str;
  uint8_t *httpResponse = NULL;
  size_t httpResponseLen = 0;
  json_object* report = NULL;
  config_log_trace();

  if(HTTPHeaderMatchURL( inHeader, kCONFIGURLRead ) == kNoErr){    
    report = ConfigCreateReportJsonMessage( inContext );
    require( report, exit );
    json_str = json_object_to_json_string(report);
    require_action( json_str, exit, err = kNoMemoryErr );
    config_log("Send config object=%s", json_str);
    err =  CreateSimpleHTTPMessageNoCopy( kMIMEType_JSON, strlen(json_str), &httpResponse, &httpResponseLen );
    require_noerr( err, exit );
    require( httpResponse, exit );
    err = SocketSend( fd, httpResponse, httpResponseLen );
    require_noerr( err, exit );
    err = SocketSend( fd, (uint8_t *)json_str, strlen(json_str) );
    require_noerr( err, exit );
    config_log("Current configuration sent");
    goto exit;
  }
  else if(HTTPHeaderMatchURL( inHeader, kCONFIGURLWrite ) == kNoErr){
    if(inHeader->contentLength > 0){
      config_log("Recv new configuration, apply and reset");
      err = ConfigIncommingJsonMessage( inHeader->extraDataPtr, inContext);
      require_noerr( err, exit );
      inContext->flashContentInRam.micoSystemConfig.configured = allConfigured;
      MICOUpdateConfiguration(inContext);

      err =  CreateSimpleHTTPOKMessage( &httpResponse, &httpResponseLen );
      require_noerr( err, exit );
      require( httpResponse, exit );
      err = SocketSend( fd, httpResponse, httpResponseLen );
      SocketClose(&fd);
      inContext->micoStatus.sys_state = eState_Software_Reset;
      if(inContext->micoStatus.sys_state_change_sem != NULL );
        mico_rtos_set_semaphore(&inContext->micoStatus.sys_state_change_sem);
      mico_thread_sleep(MICO_WAIT_FOREVER);
    }
    goto exit;
  }
else if(HTTPHeaderMatchURL( inHeader, kCONFIGURLWriteByUAP ) == kNoErr){
    if(inHeader->contentLength > 0){
      config_log("Recv new configuration from uAP, apply and connect to AP");
      err = ConfigIncommingJsonMessageUAP( inHeader->extraDataPtr, inContext);
      require_noerr( err, exit );
      MICOUpdateConfiguration(inContext);

      err =  CreateSimpleHTTPOKMessage( &httpResponse, &httpResponseLen );
      require_noerr( err, exit );
      require( httpResponse, exit );

      err = SocketSend( fd, httpResponse, httpResponseLen );
      require_noerr( err, exit );
      sleep(1);

      micoWlanSuspendSoftAP();
      _easylinkConnectWiFi( inContext );

      err = kConnectionErr; //Return an err to close socket and exit the current thread
    }
    goto exit;
  }
#ifdef MICO_FLASH_FOR_UPDATE
  else if(HTTPHeaderMatchURL( inHeader, kCONFIGURLOTA ) == kNoErr){
    if(inHeader->contentLength > 0){
      config_log("Receive OTA data!");
      memset(&inContext->flashContentInRam.bootTable, 0, sizeof(boot_table_t));
      inContext->flashContentInRam.bootTable.length = inHeader->contentLength;
      inContext->flashContentInRam.bootTable.start_address = UPDATE_START_ADDRESS;
      inContext->flashContentInRam.bootTable.type = 'A';
      inContext->flashContentInRam.bootTable.upgrade_type = 'U';
      if(inContext->flashContentInRam.micoSystemConfig.configured != allConfigured)
        inContext->flashContentInRam.micoSystemConfig.easyLinkByPass = EASYLINK_SOFT_AP_BYPASS;
      MICOUpdateConfiguration(inContext);
      SocketClose(&fd);
      inContext->micoStatus.sys_state = eState_Software_Reset;
      if(inContext->micoStatus.sys_state_change_sem != NULL );
        mico_rtos_set_semaphore(&inContext->micoStatus.sys_state_change_sem);
      mico_thread_sleep(MICO_WAIT_FOREVER);
    }
    goto exit;
  }
#endif
  else{
    return kNotFoundErr;
  };

 exit:
  if(inHeader->persistent == false)  //Return an err to close socket and exit the current thread
    err = kConnectionErr;
  if(httpResponse)  free(httpResponse);
  if(report)        json_object_put(report);

  return err;

}
/* user main function, called by AppFramework after system init done && wifi
 * station on in user_main thread.
 */
OSStatus user_main( app_context_t * const app_context )
{
  user_log_trace();
  OSStatus err = kUnknownErr;
  unsigned char rdata[64];
  unsigned char sdata[64];
  uint16_t datalen;

  require(app_context, exit);

  // platform initialize
  AaSysComInit();
  AaSysLogInit();

  // application initialize
  ControllerBusInit();
  OuterTriggerInit(NULL);
  TemperatureInit();  // will be support in release 2
  BatteryInit();

  // reset f411 and wait until it startup
  ResetF411();

#if 1
  MOInit();
#endif

  err = SntpInit(app_context);
  if(kNoErr != err) {
    AaSysLogPrint(LOGLEVEL_ERR, "SntpInit finished with err code %d", err);
  }
  else {
    AaSysLogPrint(LOGLEVEL_INF, "SntpInit success");
  }

#if 1
  DeviceInit(app_context);
  HealthInit(app_context);
  LightsInit(app_context);
  MusicInit(app_context);

  // start the downstream thread to handle user command
  err = mico_rtos_create_thread(&user_downstrem_thread_handle, MICO_APPLICATION_PRIORITY, "user_downstream", 
                                user_downstream_thread, STACK_SIZE_USER_DOWNSTREAM_THREAD, 
                                app_context );
  require_noerr_action( err, exit, user_log("ERROR: create user_downstream thread failed!") );
#endif


  user_log("[DBG]net_main: Appilcation Initialize success @"SOFTWAREVERSION);

  // user_main loop, update oled display every 1s
  while(1){

#if 1
    mico_thread_sleep(MICO_WAIT_FOREVER);
#else

    mico_thread_sleep(5);

    datalen = user_uartRecv(rdata, 5);
    if(datalen) {
      user_log("[DBG]user_main: Usart recevice datalen %d", datalen);
      user_log("[DBG]user_main: receive %.*s", datalen, rdata);
    }
    else {
      user_log("[DBG]user_main: Usart didn't recevice data");
    }

    mico_thread_sleep(2);

    sprintf(sdata, "hello, world!\r\n");
    user_uartSend(sdata, strlen(sdata));
#endif

  }

exit:
  if(kNoErr != err){
    user_log("[ERR]user_main: user_main thread exit with err=%d", err);
  }
  mico_rtos_delete_thread(NULL);  // delete current thread
  return err;
}
Exemple #30
0
void micokit_ext_mfg_test(mico_Context_t *inContext)
{
  OSStatus err = kUnknownErr;
  char str[64] = {'\0'};
  char mac[6];
  
  int rgb_led_hue = 0;
  
  uint8_t dht11_ret = 0;
  uint8_t dht11_temp_data = 0;
  uint8_t dht11_hum_data = 0;
  
  int light_ret = 0;
  uint16_t light_sensor_data = 0;
  
  int infrared_ret = 0;
  uint16_t infrared_reflective_data = 0;
  
  int32_t bme280_temp = 0;
  uint32_t bme280_hum = 0;
  uint32_t bme280_press = 0;
  
  UNUSED_PARAMETER(inContext);
  
  mico_rtos_init_semaphore(&mfg_test_state_change_sem, 1); 
  err = MICOAddNotification( mico_notify_WIFI_SCAN_COMPLETED, (void *)mico_notify_WifiScanCompleteHandler );
  require_noerr( err, exit );
  
  while(1){
    switch(mfg_test_module_number){
    case 0:  // mfg mode start
      {
        sprintf(str, "%s\r\nStart:\r\n%s\r\n%s", "TEST MODE", "  next: Key2", "  prev: Key1");
        mf_printf(str);
        while(kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, MICO_WAIT_FOREVER));
        break;
      }
    case 1:  // OLED
      {
        while(kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, 0))
        {
          sprintf(str, "%s OLED\r\n", OLED_MFG_TEST_PREFIX);
          mf_printf(str);
          mico_thread_msleep(300);
          
          mf_printf(mfg_test_oled_test_string);
          mico_thread_msleep(300);
        }
        OLED_Clear();
        break;
      }
    case 2:  // RGB_LED
      {
        sprintf(str, "%s RGB LED\r\nBlink: \r\n      R=>G=>B", OLED_MFG_TEST_PREFIX);
        mf_printf(str);
        
        while(kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, 0))
        {
          hsb2rgb_led_open(rgb_led_hue, 100, 50);
          rgb_led_hue += 120;
          if(rgb_led_hue >= 360){
            rgb_led_hue = 0;
          }
          mico_thread_msleep(300);
        }
        hsb2rgb_led_open(0, 0, 0);
        break;
      }
    case 3: // infrared sensor
      {
        while(kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, 0))
        {
          infrared_ret = infrared_reflective_read(&infrared_reflective_data);
          if(0 == infrared_ret){ 
            sprintf(str, "%s Infrared\r\nInfrared: %d", OLED_MFG_TEST_PREFIX,
                    infrared_reflective_data);
            mf_printf(str);
          }
          mico_thread_msleep(300);
        }
        break;
      }
    case 4: // DC Motor
      {
        sprintf(str, "%s DC Motor\r\nRun:\r\n     on : 500ms\r\n     off: 500ms", OLED_MFG_TEST_PREFIX);
        mf_printf(str);
        
        while(kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, 0))
        {
          dc_motor_set(1);
          mico_thread_msleep(500);
          dc_motor_set(0);
          mico_thread_msleep(500);
        }
        dc_motor_set(0);
        break;
      }
    case 5: // BME280
      {
        while(kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, 0))
        {
          err = bme280_sensor_init();
          if(kNoErr != err){
            sprintf(str, "%s BME280\r\nMoule not found!", OLED_MFG_TEST_PREFIX);
            mf_printf(str);
            // goto next mdoule
            mico_thread_msleep(500);
            mfg_test_module_number = (mfg_test_module_number+1)%(MFG_TEST_MAX_MODULE_NUM+1);
            break;
          }
          else{
            err = bme280_data_readout(&bme280_temp, &bme280_press, &bme280_hum);
            if(kNoErr == err){
              sprintf(str, "%s BME280\r\nT: %3.1fC\r\nH: %3.1f%%\r\nP: %5.2fkPa", OLED_MFG_TEST_PREFIX,
                      (float)bme280_temp/100, (float)bme280_hum/1024, (float)bme280_press/1000);
              mf_printf(str);
            }
            else{
              sprintf(str, "%s BME280\r\nRead error!", OLED_MFG_TEST_PREFIX);
              mf_printf(str);
            }
          }
          mico_thread_msleep(500);
        }
        break;
      }
    case 6: // DHT11
      {
        while(kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, 0))
        {
          dht11_ret = DHT11_Read_Data(&dht11_temp_data, &dht11_hum_data);
          if(0 == dht11_ret){
            sprintf(str, "%s DHT11\r\nT: %3.1fC\r\nH: %3.1f%%", OLED_MFG_TEST_PREFIX,
                    (float)dht11_temp_data, (float)dht11_hum_data);
            mf_printf(str);
          }
          mico_thread_sleep(1);   // DHT11 must >= 1s
        }
        break;
      }
    case 7:   // Light sensor
      {
        while(kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, 0))
        {
          light_ret = light_sensor_read(&light_sensor_data);
          if(0 == light_ret){
            sprintf(str, "%s Light\r\nLight: %d", OLED_MFG_TEST_PREFIX,
                    light_sensor_data);
            mf_printf(str);
          }
          mico_thread_msleep(300);
        }
        break;
      }
    case 8: // wifi
      {
        wlan_get_mac_address(mac);
        sprintf(str, "%s Wi-Fi\r\nMAC:\r\n    %02X%02X%02X%02X%02X%02X", OLED_MFG_TEST_PREFIX,
                mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        mf_printf(str);
        //mico_thread_msleep(500);
        
        scanap_done = false;
        micoWlanStartScan();
        while((!scanap_done) || (kNoErr != mico_rtos_get_semaphore(&mfg_test_state_change_sem, MICO_WAIT_FOREVER)));
        break;
      }
    default:
      goto exit;  // error
      break;
    }
  }
  
exit:
  mico_thread_sleep(MICO_NEVER_TIMEOUT);
}