Beispiel #1
0
void tcp_server_thread(void *inContext)
{
  OSStatus err;
  int j;
  struct sockaddr_t addr;
  int sockaddr_t_size;
  fd_set readfds;
  char ip_address[16];
  
  int tcp_listener_fd = -1;

  /*Establish a TCP server fd that accept the tcp clients connections*/ 
  tcp_listener_fd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
  require_action(IsValidSocket( tcp_listener_fd ), exit, err = kNoResourcesErr );
  addr.s_ip = INADDR_ANY;
  addr.s_port = tcp_server_port;
  err = bind(tcp_listener_fd, &addr, sizeof(addr));
  require_noerr( err, exit );

  err = listen(tcp_listener_fd, 0);
  require_noerr( err, exit );

  tcp_server_log("Server established at port: %d, fd: %d", addr.s_port, tcp_listener_fd);
  
  while(1){
    FD_ZERO(&readfds);
    FD_SET(tcp_listener_fd, &readfds);  
    select(1, &readfds, NULL, NULL, NULL);

    /*Check tcp connection requests */
    if(FD_ISSET(tcp_listener_fd, &readfds)){
      sockaddr_t_size = sizeof(struct sockaddr_t);
      j = accept(tcp_listener_fd, &addr, &sockaddr_t_size);
      if (j > 0) {
        inet_ntoa(ip_address, addr.s_ip );
        tcp_server_log("Client %s:%d connected, fd: %d", ip_address, addr.s_port, j);
        if(kNoErr != mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "Local Clients", tcp_server_client_thread, 0x800, &j) ) 
          SocketClose(&j);
      }
    }
   }

exit:
    tcp_server_log("Exit: Local controller exit with err = %d", err);
    mico_rtos_delete_thread(NULL);
    return;
}
void fogCloudConfigServer_listener_thread(void *inContext)
{
  fogcloud_config_log_trace();
  OSStatus err = kUnknownErr;
  int j;
  Context = inContext;
  struct sockaddr_t addr;
  int sockaddr_t_size;
  fd_set readfds;
  char ip_address[16];
  int localConfiglistener_fd = -1;
  
  /*Establish a TCP server fd that accept the tcp clients connections*/
  localConfiglistener_fd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
  require_action(IsValidSocket( localConfiglistener_fd ), exit, err = kNoResourcesErr );
  addr.s_ip = INADDR_ANY;
  addr.s_port = FOGCLOUD_CONFIG_SERVER_PORT;
  err = bind(localConfiglistener_fd, &addr, sizeof(addr));
  require_noerr( err, exit );
  err = listen(localConfiglistener_fd, 0);
  require_noerr( err, exit );
  fogcloud_config_log("fogCloud Config Server established at port: %d, fd: %d", 
                      FOGCLOUD_CONFIG_SERVER_PORT, localConfiglistener_fd);
  
  while(1){
    FD_ZERO(&readfds);
    FD_SET(localConfiglistener_fd, &readfds);
    select(1, &readfds, NULL, NULL, NULL);
    
    /*Check tcp connection requests */
    if(FD_ISSET(localConfiglistener_fd, &readfds)){
      sockaddr_t_size = sizeof(struct sockaddr_t);
      j = accept(localConfiglistener_fd, &addr, &sockaddr_t_size);
      if (j > 0) {
        inet_ntoa(ip_address, addr.s_ip );
        fogcloud_config_log("fogCloud Config Client %s:%d connected, fd: %d", ip_address, addr.s_port, j);
        err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "fog_client", 
                                      fogCloudConfigClient_thread, STACK_SIZE_FOGCLOUD_CONFIG_CLIENT_THREAD, &j);
      }
    }
  }
  
exit:
  fogcloud_config_log("Exit: Local controller exit with err = %d", err);
  mico_rtos_delete_thread(NULL);
  return;
}
/* user main thread created by MICO APP thread */
void user_main_thread(void* arg)
{
  app_log_trace();
  OSStatus err = kUnknownErr;
  app_context_t *app_context = (app_context_t *)arg;
  
  // loop in user mian function && must not return
  err = user_main(app_context);
  
  // never get here only if user work error.
  app_log("ERROR: user_main thread exit err=%d, system will reboot...", err);
  
  err = mico_system_power_perform(app_context->mico_context, eState_Software_Reset);
  UNUSED_PARAMETER(err);
  
  mico_rtos_delete_thread(NULL);   
}
Beispiel #4
0
void easylink_thread(void *inContext)
{
  micoWlanStartEasyLink( 60 );
  wifi_easylink_log("Start Easylink configuration");
  mico_rtos_get_semaphore(&easylink_sem, MICO_WAIT_FOREVER);
  
  if ( is_easylink_success == 1 )
  {
    mico_thread_msleep(10);
    connect_ap( );
  } else {
    wifi_easylink_log("Easylink configuration fail");
  }
  
  clean_easylink_resource();
  mico_rtos_delete_thread(NULL);
}
Beispiel #5
0
void tcp_client_thread(void *arg)
{
  OSStatus err = kNoErr;
  int fd = (int)arg;
  int len = 0;
  fd_set readfds;
  char *buf = NULL; 
  struct timeval_t t;
  
  buf=(char*)malloc(1024);
  require_action(buf, exit, err = kNoMemoryErr); 
  
  t.tv_sec = 5;
  t.tv_usec = 0;
  
  while(1)
  {
    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);
    
    require_action( select(1, &readfds, NULL, NULL, &t) >= 0, exit, err = kConnectionErr );
    
    if( FD_ISSET( fd, &readfds ) ) /*one client has data*/
    {
      len = recv( fd, buf, 1024, 0 );
      require_action( len >= 0, exit, err = kConnectionErr );
      
      if( len == 0){
        tcp_server_log( "TCP Client is disconnected, fd: %d", fd );
        goto exit;
      }  
      
      tcp_server_log("fd: %d, recv data %d from client", fd, len);
      len = send( fd, buf, len, 0 );
      tcp_server_log("fd: %d, send data %d to client", fd, len);
    }
  }
exit:
  if( err != kNoErr ) tcp_server_log( "TCP client thread exit with err: %d", err );
  if( buf != NULL ) free( buf );
  SocketClose( &fd );
  mico_rtos_delete_thread( NULL );
}
Beispiel #6
0
/* TCP server listener thread */
void tcp_server_thread( void *arg )
{
  OSStatus err = kNoErr;
  struct sockaddr_t server_addr,client_addr;
  socklen_t sockaddr_t_size = sizeof( client_addr );
  char  client_ip_str[16];
  int tcp_listen_fd = -1, client_fd = -1;
  fd_set readfds;
  
  tcp_listen_fd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
  require_action(IsValidSocket( tcp_listen_fd ), exit, err = kNoResourcesErr );
  
  server_addr.s_ip =  INADDR_ANY;  /* Accept conenction request on all network interface */
  server_addr.s_port = SERVER_PORT;/* Server listen on port: 20000 */
  err = bind( tcp_listen_fd, &server_addr, sizeof( server_addr ) );
  require_noerr( err, exit );
  
  err = listen( tcp_listen_fd, 0);
  require_noerr( err, exit );
  
  while(1)
  {
    FD_ZERO( &readfds );
    FD_SET( tcp_listen_fd, &readfds );
    
    require( select(1, &readfds, NULL, NULL, NULL) >= 0, exit );
    
    if(FD_ISSET(tcp_listen_fd, &readfds)){
      client_fd = accept( tcp_listen_fd, &client_addr, &sockaddr_t_size );
      if( IsValidSocket( client_fd ) ) {
        inet_ntoa( client_ip_str, client_addr.s_ip );
        tcp_server_log( "TCP Client %s:%d connected, fd: %d", client_ip_str, client_addr.s_port, client_fd );
        if ( kNoErr !=  mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY, "TCP Clients", tcp_client_thread, 0x800, (void *)client_fd ) )
          SocketClose( &client_fd );      
      }
    }
  }
exit:
  if( err != kNoErr ) tcp_server_log( "Server listerner thread exit with err: %d", err );
  SocketClose( &tcp_listen_fd );
  mico_rtos_delete_thread(NULL );
}
Beispiel #7
0
int application_start( void )
{
  OSStatus err = kNoErr;
  
  /*Register user function for MiCO nitification: WiFi status changed */
  err = mico_system_notify_register( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler, NULL );
  require_noerr( err, exit ); 
  
  /* Start MiCO system functions according to mico_config.h */
  err = mico_system_init( mico_system_context_init( 0 ) );
  require_noerr( err, exit ); 
  
  /* Start TCP server listener thread*/
  err = mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY, "TCP_server", tcp_server_thread, 0x800, NULL );
  require_noerr_string( err, exit, "ERROR: Unable to start the tcp server thread." );
  
exit:
  mico_rtos_delete_thread( NULL );
  return err;
}
Beispiel #8
0
int application_start( void )
{
//start
//  lua_printf( "\r\n\r\nMiCO starting...(Free memory %d bytes)\r\n",MicoGetMemoryInfo()->free_memory);
  MicoInit();

//watch dog 
  MicoWdgInitialize( DEFAULT_WATCHDOG_TIMEOUT);
  mico_init_timer(&_watchdog_reload_timer,DEFAULT_WATCHDOG_TIMEOUT/2, _watchdog_reload_timer_handler, NULL);
  mico_start_timer(&_watchdog_reload_timer);
  
#if 0
  #include "tm_stm32f4_usb_vcp.h"
  lua_printf("\r\n\r\n TM_USB_VCP_Init:%d",TM_USB_VCP_Init());
  uint8_t c;
  //NVIC_SetVectorTable(NVIC_VectTab_FLASH, new_addr);
  while(1)
  {
   if (TM_USB_VCP_GetStatus() == TM_USB_VCP_CONNECTED)
   {
     if (TM_USB_VCP_Getc(&c) == TM_USB_VCP_DATA_OK) 
     {
       TM_USB_VCP_Putc(c);/* Return data back */
     }
   }
  }
#endif
//usrinterface
  //MicoCliInit();
#if 1
//  lua_printf("Free memory %d bytes\r\n", MicoGetMemoryInfo()->free_memory); 
  lua_rx_data = (uint8_t*)malloc(INBUF_SIZE);
  ring_buffer_init( (ring_buffer_t*)&lua_rx_buffer, (uint8_t*)lua_rx_data, INBUF_SIZE );
  MicoUartInitialize( LUA_UART, &lua_uart_config, (ring_buffer_t*)&lua_rx_buffer );
  mico_rtos_create_thread(NULL, MICO_DEFAULT_WORKER_PRIORITY, "lua_main_thread", lua_main_thread, 20*1024, 0);
#endif
//  while(1) {;}
  mico_rtos_delete_thread(NULL);
  lua_printf("application_start exit\r\n");
  return 0;
 }
Beispiel #9
0
int application_start( void )
{
  OSStatus err = kNoErr;

  /*Register user function for MiCO nitification: WiFi status changed */
  err = mico_system_notify_register( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler, NULL );
  require_noerr( err, exit ); 

  /* Start MiCO system functions according to mico_config.h */
  err = mico_system_init( mico_system_context_init( 0 ) );
  require_noerr( err, exit ); 

  err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "udp_unicast", udp_unicast_thread, 0x800, NULL );
  require_noerr_string( err, exit, "ERROR: Unable to start the UDP thread." );
  
exit:
  if( err != kNoErr )
    udp_unicast_log("Thread exit with err: %d", err);
  mico_rtos_delete_thread( NULL );
  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;
}
Beispiel #11
0
void tcp_server_client_thread( void *inFd )
{
  OSStatus err;
  struct sockaddr_t addr;
  struct timeval_t t;
  fd_set readfds;
  int client_fd = *(int *)inFd; 
  int len;
  char *buf;
  
  buf = (char*)malloc(BUF_LEN);
  require_action(buf, exit, err = kNoMemoryErr);
  
  t.tv_sec = 4;
  t.tv_usec = 0;
      
  while(1)
  {
    /*Check status on erery sockets */
    FD_ZERO(&readfds);
    FD_SET(client_fd, &readfds);

    select(1, &readfds, NULL, NULL, &t);

    /*recv wlan data using remote server fd*/
    if (FD_ISSET( client_fd, &readfds )) 
    {
      len = recv(client_fd, buf, BUF_LEN, 0); 
      require_action_quiet(len>0, exit, err = kConnectionErr);
      tcp_server_log("[tcp_rec][%d] = %.*s", len, len, buf);
      sendto(client_fd, buf, len, 0, &addr, sizeof(struct sockaddr_t));
    }
  }
  
exit:
  tcp_server_log("Exit: Client exit with err = %d, fd:%d", err, client_fd);
  SocketClose(&client_fd);
  if(buf) free(buf);
  mico_rtos_delete_thread(NULL);
}
Beispiel #12
0
int application_start( void )
{
  network_InitTypeDef_st wNetConfig;
#if MCU_POWERSAVE_ENABLED
  MicoMcuPowerSaveConfig(true);
#endif
  power_log( "Power measure program: RTOS and wlan initialized and setup soft ap" );
  MicoInit( );
  
  memset(&wNetConfig, 0, sizeof(network_InitTypeDef_st));
  wNetConfig.wifi_mode = Soft_AP;
  snprintf(wNetConfig.wifi_ssid, 32, "EasyLink_PM" );
  strcpy((char*)wNetConfig.wifi_key, "");
  strcpy((char*)wNetConfig.local_ip_addr, "10.10.10.1");
  strcpy((char*)wNetConfig.net_mask, "255.255.255.0");
  strcpy((char*)wNetConfig.gateway_ip_addr, "10.10.10.1");
  wNetConfig.dhcpMode = DHCP_Server;
  micoWlanStart(&wNetConfig);
    
  mico_rtos_delete_thread( NULL );
  return 0;
}
Beispiel #13
0
void uartRecv_thread(void *inContext)
{
    uart_recv_log_trace();
    app_context_t *Context = inContext;
    int recvlen;
    uint8_t *inDataBuffer;

    inDataBuffer = malloc(UART_ONE_PACKAGE_LENGTH);
    require(inDataBuffer, exit);

    while(1)
    {
        recvlen = _uart_get_one_packet(inDataBuffer, UART_ONE_PACKAGE_LENGTH);
        if (recvlen <= 0)
            continue;
        sppUartCommandProcess(inDataBuffer, recvlen, Context);
    }

exit:
    if(inDataBuffer) free(inDataBuffer);
    mico_rtos_delete_thread(NULL);
}
Beispiel #14
0
void MVDDevCloudInfoResetThread(void *arg)
{
  OSStatus err = kUnknownErr;
  mico_Context_t *inContext = (mico_Context_t *)arg;
  
  // stop EasyCloud service first
  err = MVDCloudInterfaceStop(inContext);
  require_noerr_action( err, exit, mvd_log("ERROR: stop EasyCloud service failed!") );
  
  // cloud reset request
  MVDDevInterfaceSend(DEFAULT_MVD_RESET_CLOUD_INFO_START_MSG_2MCU, 
                      strlen(DEFAULT_MVD_RESET_CLOUD_INFO_START_MSG_2MCU));     
  err = easycloud_reset_cloud_info(inContext);
  if(kNoErr == err){
    inContext->appStatus.virtualDevStatus.isCloudConnected = false;
        
    mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex);
    inContext->flashContentInRam.appConfig.virtualDevConfig.isActivated = false;
    MICOUpdateConfiguration(inContext);
    mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex);
    
    //mvd_log("[MVD]MVDDevCloudInfoResetThread: cloud reset success!");
    MVDDevInterfaceSend(DEFAULT_MVD_RESET_CLOUD_INFO_OK_MSG_2MCU, 
                        strlen(DEFAULT_MVD_RESET_CLOUD_INFO_OK_MSG_2MCU));
    
    // send ok semaphore
    mico_rtos_set_semaphore(&_reset_cloud_info_sem);
  }
  
exit:
  if(kNoErr != err){
    mvd_log("[MVD]MVDDevCloudInfoResetThread EXIT: err=%d",err);
    MVDDevInterfaceSend(DEFAULT_MVD_RESET_CLOUD_INFO_FAILED_MSG_2MCU, 
                        strlen(DEFAULT_MVD_RESET_CLOUD_INFO_FAILED_MSG_2MCU));
  }
  mico_rtos_delete_thread(NULL);
  return;
}
Beispiel #15
0
int application_start( void )
{
  OSStatus err = kNoErr;
  mico_thread_t t_handler = NULL;
  
  /* Create a new thread */
  err = mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY, "Thread 1", thread_1, 500, NULL );
  require_noerr_string( err, exit, "ERROR: Unable to start the thread 1." );
  
  while(1){
    /* Create a new thread, and this thread will delete its self and clean its resource */
    err = mico_rtos_create_thread( &t_handler, MICO_APPLICATION_PRIORITY, "Thread 2", thread_2, 500, NULL );
    require_noerr_string( err, exit, "ERROR: Unable to start the thread 2." );
    mico_rtos_thread_join( &t_handler );
  }
  
exit:
  if( err != kNoErr )
    os_thread_log( "Thread exit with err: %d", err );
  
  mico_rtos_delete_thread(NULL);
  return err;  
}
static void _sys_state_thread(void *arg)
{
    UNUSED_PARAMETER(arg);
    mico_Context_t* context = arg;

    /*System status changed*/
    while(mico_rtos_get_semaphore( &context->micoStatus.sys_state_change_sem, MICO_WAIT_FOREVER) == kNoErr ) {

        if(needs_update == true)
            mico_system_context_update( context );

        switch( context->micoStatus.current_sys_state ) {
        case eState_Normal:
            break;
        case eState_Software_Reset:
            sendNotifySYSWillPowerOff( );
            mico_thread_msleep( 500 );
            MicoSystemReboot( );
            break;
        case eState_Wlan_Powerdown:
            sendNotifySYSWillPowerOff( );
            mico_thread_msleep( 500 );
            micoWlanPowerOff( );
            break;
        case eState_Standby:
            sendNotifySYSWillPowerOff( );
            mico_thread_msleep( 500 );
            micoWlanPowerOff( );
            MicoSystemStandBy( MICO_WAIT_FOREVER );
            break;
        default:
            break;
        }
    }
    mico_rtos_delete_thread( NULL );
}
void run( void *arg )
{
  char *name = (char *)arg;
  char debug[20];

  while(1)
  {
    MUTEX_LOCK();
    if( g_tickets <= 0 ){
      MUTEX_UNLOCK();
      goto exit;
    }

    g_tickets--;
    sprintf( debug, "Thread %s, %d\r\n", name, g_tickets );
    MicoUartSend(STDIO_UART, debug, strlen(debug) );

    MUTEX_UNLOCK();
  } 

exit:
  os_mutex_log( "thread: %s exit now", name );
  mico_rtos_delete_thread(NULL);
}
Beispiel #18
0
void homeKitClient_thread(void *inFd)
{
  ha_log_trace();
  OSStatus err;
  int clientFd = *(int *)inFd;
  struct timeval_t t;
  HTTPHeader_t *httpHeader = NULL;
  int selectResult;
  fd_set      readfds;
  HK_Context_t hkContext;
  int aid, iid, serviceID, characteristicID;
  value_union value, newValue;
  struct _hapCharacteristic_t pCharacteristic;
  json_object *outEventJsonObject = NULL, *outCharacteristics, *outCharacteristic;
  const char *buffer = NULL;

  memset(&hkContext, 0x0, sizeof(HK_Context_t));
  hkContext.session = HKSNewSecuritySession();
  require_action(hkContext.session, exit, err = kNoMemoryErr);

  httpHeader = calloc(1, sizeof( HTTPHeader_t ) );
  require_action( httpHeader, exit, err = kNoMemoryErr );

  HK_Notify_t *notifyList = NULL, *temp;

  bool isChanged;

  t.tv_sec = 1;
  t.tv_usec = 0;  //Check for notify every 1 second
  ha_log("Free memory1: %d", mico_memory_info()->free_memory);

  while(1){
    if(hkContext.session->established == true && hkContext.session->recvedDataLen > 0){
       err = HKhandleIncomeingMessage(clientFd, httpHeader, &notifyList, &hkContext, Context);
    }else{
      FD_ZERO(&readfds);
      FD_SET(clientFd, &readfds);
      selectResult = select(clientFd + 1, &readfds, NULL, NULL, &t);
      require( selectResult >= 0, exit );
      if(FD_ISSET(clientFd, &readfds)){
        err = HKhandleIncomeingMessage(clientFd, httpHeader, &notifyList, &hkContext, Context);
        require_noerr(err, exit);
      }

      if(hkContext.session->established == false) // No nofification in no paired session
        continue;

      outEventJsonObject = json_object_new_object();
      require_action(outEventJsonObject, exit, err = kNoMemoryErr);
      outCharacteristics = json_object_new_array();
      require_action(outCharacteristics, exit, err = kNoMemoryErr);
      json_object_object_add( outEventJsonObject, "characteristics", outCharacteristics);
      temp = notifyList;

      while(HKNotifyGetNext( temp, &aid, &iid, &value, &temp) == kNoErr){
        FindCharacteristicByIID(hapObjects, aid, iid, &serviceID, &characteristicID);   
        if(HKReadCharacteristicValue(aid, serviceID, characteristicID, &newValue, Context)==kHKNoErr){
          pCharacteristic = ((hapObjects[aid-1]).services[serviceID-1]).characteristic[characteristicID-1];

          switch(pCharacteristic.valueType){
            case ValueType_bool:
              if( value.boolValue != newValue.boolValue ){
                outCharacteristic = json_object_new_object();
                json_object_object_add( outCharacteristic, "aid", json_object_new_int(aid));
                json_object_object_add( outCharacteristic, "iid", json_object_new_int(iid));
                json_object_object_add( outCharacteristic, "value", json_object_new_boolean(newValue.boolValue));
                json_object_array_add( outCharacteristics, outCharacteristic );
                HKNotificationAdd( aid, iid, newValue, &notifyList );
              }
              break;
            case ValueType_int:
              if( value.intValue != newValue.intValue ){
                outCharacteristic = json_object_new_object();
                json_object_object_add( outCharacteristic, "aid", json_object_new_int(aid));
                json_object_object_add( outCharacteristic, "iid", json_object_new_int(iid));
                json_object_object_add( outCharacteristic, "value", json_object_new_int(newValue.intValue));
                json_object_array_add( outCharacteristics, outCharacteristic );
                HKNotificationAdd( aid, iid, newValue, &notifyList );
              }
              break;
            case ValueType_float:
              if( value.floatValue != newValue.floatValue ){
                outCharacteristic = json_object_new_object();
                json_object_object_add( outCharacteristic, "aid", json_object_new_int(aid));
                json_object_object_add( outCharacteristic, "iid", json_object_new_int(iid));
                json_object_object_add( outCharacteristic, "value", json_object_new_double(newValue.floatValue));
                json_object_array_add( outCharacteristics, outCharacteristic );
                HKNotificationAdd( aid, iid, newValue, &notifyList );
              }
              break;
            case ValueType_string:
              if( !strcmp(value.stringValue, newValue.stringValue) ){
                outCharacteristic = json_object_new_object();
                json_object_object_add( outCharacteristic, "aid", json_object_new_int(aid));
                json_object_object_add( outCharacteristic, "iid", json_object_new_int(iid));
                json_object_object_add( outCharacteristic, "value", json_object_new_string(newValue.stringValue));
                json_object_array_add( outCharacteristics, outCharacteristic );
                HKNotificationAdd( aid, iid, newValue, &notifyList );
              }
              break;
            case ValueType_date:
              if( !strcmp(value.dateValue, newValue.dateValue) ){
                outCharacteristic = json_object_new_object();
                json_object_object_add( outCharacteristic, "aid", json_object_new_int(aid));
                json_object_object_add( outCharacteristic, "iid", json_object_new_int(iid));
                json_object_object_add( outCharacteristic, "value", json_object_new_string(newValue.dateValue));
                json_object_array_add( outCharacteristics, outCharacteristic );
                HKNotificationAdd( aid, iid, newValue, &notifyList );
              }
              break;
            default:
              break;
          }
        }
      }
            
      if(json_object_array_length(outCharacteristics)){
        buffer = json_object_to_json_string(outEventJsonObject);
        ha_log("Notification json cstring generated, memory remains %d, %s", mico_memory_info()->free_memory, buffer);  
        err = HKSendNotifyMessage( clientFd, (uint8_t *)buffer, strlen(buffer), hkContext.session );
        require_noerr(err, exit);

      }
      
      json_object_put(outEventJsonObject);
      outEventJsonObject = NULL;
          //err = HKSendResponseMessage(sockfd, status, (uint8_t *)buffer->buf, strlen(buffer->buf), inHkContext);
          //require_noerr(err, exit);
    }
  }

exit:
  SocketClose(&clientFd);
  HTTPHeaderClear( httpHeader );
  if(httpHeader)    free(httpHeader);
  HKNotificationClean( &notifyList );
  if(outEventJsonObject) json_object_put(outEventJsonObject);
  HKCleanPairSetupInfo(&hkContext.pairInfo, Context);
  HKCleanPairVerifyInfo(&hkContext.pairVerifyInfo);
  free(hkContext.session);
  ha_log("Last Free memory1: %d", mico_memory_info()->free_memory);
  mico_rtos_delete_thread(NULL);
  return;
}
Beispiel #19
0
int application_start(void)
{
  OSStatus err = kNoErr;
  net_para_st para;

  Platform_Init();
  /*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);
  mico_rtos_init_semaphore(&context->micoStatus.sys_state_change_sem, 1); 

  MICOReadConfiguration( context );

  err = MICOInitNotificationCenter  ( context );

  err = MICOAddNotification( mico_notify_READ_APP_INFO, (void *)micoNotify_ReadAppInfoHandler );
  require_noerr( err, exit );  
  
  /*wlan driver and tcpip init*/
  mxchipInit();
  getNetPara(&para, Station);
  formatMACAddr(context->micoStatus.mac, (char *)&para.mac);
  
  mico_log_trace(); 
  mico_log("%s mxchipWNet library version: %s", APP_INFO, system_lib_version());

  /*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-100, _watchdog_reload_timer_handler, NULL);
  mico_start_timer(&_watchdog_reload_timer);
  
  if(context->flashContentInRam.micoSystemConfig.configured != allConfigured){
    mico_log("Empty configuration. Starting configuration mode...");

#ifdef CONFIG_MODE_EASYLINK
    err = startEasyLink( context );
    require_noerr( err, exit );
#endif

#ifdef CONFIG_MODE_WAC
    err = startMfiWac( context );
    require_noerr( err, exit );
#endif
  }
  else{
    mico_log("Available configuration. Starting Wi-Fi connection...");
    
    /* Regisist notifications */
    err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler );
    require_noerr( err, exit ); 
    
    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){
      ps_enable();
    }

    if(context->flashContentInRam.micoSystemConfig.mcuPowerSaveEnable == true){
      mico_mcu_powersave_config(true);
    }

    /*Bonjour service for searching*/
    if(context->flashContentInRam.micoSystemConfig.bonjourEnable == true){
      err = MICOStartBonjourService( Station, context );
      require_noerr( err, exit );
    }

    /*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.") );
    }

    /*Start mico application*/
    err = MICOStartApplication( context );
    require_noerr( err, exit );
    
    _ConnectToAP( context );
  }


  /*System status changed*/
  while(mico_rtos_get_semaphore(&context->micoStatus.sys_state_change_sem, MICO_WAIT_FOREVER)==kNoErr){
    switch(context->micoStatus.sys_state){
      case eState_Normal:
        break;
      case eState_Software_Reset:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        PlatformSoftReboot();
        break;
      case eState_Wlan_Powerdown:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        wifi_power_down();
        break;
      case eState_Standby:
        mico_log("Enter standby mode");
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(100);
        wifi_power_down();
        Platform_Enter_STANDBY();
        break;
      default:
        break;
    }
  }
    
  require_noerr_action( err, exit, mico_log("Closing main thread with err num: %d.", err) );

exit:
  mico_rtos_delete_thread(NULL);
  return kNoErr;
}
Beispiel #20
0
void localTcpClient_thread(void *inFd)
{
  OSStatus err;
  int i;
  int indexForPortTable;
  int clientFd = *(int *)inFd;
  int currentRecved = 0;
  int clientLoopBackFd = -1;
  uint8_t *inDataBuffer = NULL;
  uint8_t *outDataBuffer = NULL;
  int len;
  struct sockaddr_t addr;
  fd_set readfds;
  struct timeval_t t;

  inDataBuffer = malloc(wlanBufferLen);
  require_action(inDataBuffer, exit, err = kNoMemoryErr);
  outDataBuffer = malloc(wlanBufferLen);
  require_action(outDataBuffer, exit, err = kNoMemoryErr);

  for(i=0; i < MAX_Local_Client_Num; i++) {
    if( Context->appStatus.loopBack_PortList[i] == 0 ){
      Context->appStatus.loopBack_PortList[i] = loopBackPortTable[clientFd];
      indexForPortTable = i;
      break;
    }
  }

  /*Loopback fd, recv data from other thread */
  clientLoopBackFd = socket( AF_INET, SOCK_DGRM, IPPROTO_UDP );
  require_action(IsValidSocket( clientLoopBackFd ), exit, err = kNoResourcesErr );
  addr.s_ip = IPADDR_LOOPBACK;
  addr.s_port = Context->appStatus.loopBack_PortList[indexForPortTable];
  err = bind( clientLoopBackFd, &addr, sizeof(addr) );
  require_noerr( err, exit );

  t.tv_sec = 4;
  t.tv_usec = 0;
  
  while(1){

    FD_ZERO(&readfds);
    FD_SET(clientFd, &readfds); 
    FD_SET(clientLoopBackFd, &readfds); 

    select(1, &readfds, NULL, NULL, &t);

    /*recv UART data using loopback fd*/
    if (FD_ISSET( clientLoopBackFd, &readfds )) {
      len = recv( clientLoopBackFd, outDataBuffer, wlanBufferLen, 0 );
      SocketSend( clientFd, outDataBuffer, len );
    }

    /*Read data from tcp clients and process these data using HA protocol */ 
    if (FD_ISSET(clientFd, &readfds)) {
      len = recv(clientFd, inDataBuffer+currentRecved, wlanBufferLen-currentRecved, 0);
      require_action_quiet(len>0, exit, err = kConnectionErr);
      currentRecved += len;    
      haWlanCommandProcess(inDataBuffer, &currentRecved, clientFd, Context);
    }
  }

exit:
    server_log("Exit: Client exit with err = %d", err);
    Context->appStatus.loopBack_PortList[indexForPortTable] = 0;
    if(clientLoopBackFd != -1)
      SocketClose(&clientLoopBackFd);
    SocketClose(&clientFd);
    if(inDataBuffer) free(inDataBuffer);
    if(outDataBuffer) free(outDataBuffer);
    mico_rtos_delete_thread(NULL);
    return;
}
Beispiel #21
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;
}
Beispiel #22
0
int application_start(void)
{
  OSStatus err = kNoErr;
  net_para_st para;

  Platform_Init();
  /*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);
  mico_rtos_init_semaphore(&context->micoStatus.sys_state_change_sem, 1); 

  MICOReadConfiguration( context );

  err = MICOInitNotificationCenter  ( context );

  err = MICOAddNotification( mico_notify_READ_APP_INFO, (void *)micoNotify_ReadAppInfoHandler );
  require_noerr( err, exit );  
  
  /*wlan driver and tcpip init*/
  mxchipInit();
  getNetPara(&para, Station);
  formatMACAddr(context->micoStatus.mac, (char *)&para.mac);
  
  mico_log_trace(); 
  mico_log("%s mxchipWNet library version: %s", APP_INFO, system_lib_version());

  /*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-100, _watchdog_reload_timer_handler, NULL);
  mico_start_timer(&_watchdog_reload_timer);
  
  if(context->flashContentInRam.micoSystemConfig.configured != allConfigured){
    mico_log("Empty configuration. Starting configuration mode...");

#ifdef CONFIG_MODE_EASYLINK
  err = startEasyLink( context );
  require_noerr( err, exit );
#endif

#ifdef 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, 1200);
  free(WAC_Params);
  require_noerr( err, exit );
#endif
  }
  else{
    mico_log("Available configuration. Starting Wi-Fi connection...");
    
    /* Regisist notifications */
    err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler );
    require_noerr( err, exit ); 
    
    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){
      ps_enable();
    }

    if(context->flashContentInRam.micoSystemConfig.mcuPowerSaveEnable == true){
      mico_mcu_powersave_config(true);
    }

    /*Bonjour service for searching*/
    // if(context->flashContentInRam.micoSystemConfig.bonjourEnable == true){
    //   err = MICOStartBonjourService( Station, context );
    //   require_noerr( err, exit );
    // }

    err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "mDNSResponder", mDNSResponder_thread, 0x1000, (void*)context );
    require_noerr_action( err, exit, mico_log("ERROR: Unable to start mDNSResponder thread.") );

    /*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.") );
    }

    /*Start mico application*/
    err = MICOStartApplication( context );
    require_noerr( err, exit );
    
    _ConnectToAP( context );
  }


  /*System status changed*/
  while(mico_rtos_get_semaphore(&context->micoStatus.sys_state_change_sem, MICO_WAIT_FOREVER)==kNoErr){
    switch(context->micoStatus.sys_state){
      case eState_Normal:
        break;
      case eState_Software_Reset:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        PlatformSoftReboot();
        break;
      case eState_Wlan_Powerdown:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        wifi_power_down();
        break;
      case eState_Standby:
        mico_log("Enter standby mode");
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(200);
        wifi_power_down();
        Platform_Enter_STANDBY();
        break;
      default:
        break;
    }
  }
    
  require_noerr_action( err, exit, mico_log("Closing main thread with err num: %d.", err) );

exit:
  mico_rtos_delete_thread(NULL);
  return kNoErr;
}
Beispiel #23
0
void localConfig_thread(void *inFd)
{
  OSStatus err;
  int clientFd = *(int *)inFd;
  int clientFdIsSet;
  fd_set readfds;
  struct timeval_t t;
  HTTPHeader_t *httpHeader = NULL;
  configContext_t httpContext = {0, false};

  config_log_trace();
  httpHeader = HTTPHeaderCreateWithCallback(onReceivedData, onClearHTTPHeader, &httpContext);
  require_action( httpHeader, exit, err = kNoMemoryErr );
  HTTPHeaderClear( httpHeader );

  t.tv_sec = 60;
  t.tv_usec = 0;
  config_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory) ; 

  while(1){
    FD_ZERO(&readfds);
    FD_SET(clientFd, &readfds);
    clientFdIsSet = 0;

    if(httpHeader->len == 0){
      require(select(1, &readfds, NULL, NULL, &t) >= 0, exit);
      clientFdIsSet = FD_ISSET(clientFd, &readfds);
    }
  
    if(clientFdIsSet||httpHeader->len){
      err = SocketReadHTTPHeader( clientFd, httpHeader );

      switch ( err )
      {
        case kNoErr:
          // Read the rest of the HTTP body if necessary
          //do{
          err = SocketReadHTTPBody( clientFd, httpHeader );
          
          if(httpHeader->dataEndedbyClose == true){
            err = _LocalConfigRespondInComingMessage( clientFd, httpHeader, Context );
            require_noerr(err, exit);
            err = kConnectionErr;
            goto exit;
          }else{
            require_noerr(err, exit);
            err = _LocalConfigRespondInComingMessage( clientFd, httpHeader, Context );
            require_noerr(err, exit);
          }
          


          //  if(httpHeader->contentLength == 0)
          //    break;
          //} while( httpHeader->chunkedData == true || httpHeader->dataEndedbyClose == true);

          // Call the HTTPServer owner back with the acquired HTTP header
          //err = _LocalConfigRespondInComingMessage( clientFd, httpHeader, Context );
          //
          //Exit if connection is closed
          //require_noerr(err, exit); 
      
          // Reuse HTTPHeader
          HTTPHeaderClear( httpHeader );
        break;

        case EWOULDBLOCK:
            // NO-OP, keep reading
        break;

        case kNoSpaceErr:
          config_log("ERROR: Cannot fit HTTPHeader.");
          goto exit;
        
        case kConnectionErr:
          // NOTE: kConnectionErr from SocketReadHTTPHeader means it's closed
          config_log("ERROR: Connection closed.");
          goto exit;

        default:
          config_log("ERROR: HTTP Header parse internal error: %d", err);
          goto exit;
      }
    }
  }

exit:
  config_log("Exit: Client exit with err = %d", err);
  SocketClose(&clientFd);
  if(httpHeader) {
    HTTPHeaderClear( httpHeader );
    free(httpHeader);
  }
  mico_rtos_delete_thread(NULL);
  return;
}
void fogCloudConfigClient_thread(void *inFd)
{
  OSStatus err;
  int clientFd = *(int *)inFd;
  int clientFdIsSet;
  fd_set readfds;
  struct timeval_t t;
  ECS_HTTPHeader_t *httpHeader = NULL;
  fogcloud_config_log_trace();
  httpHeader = ECS_HTTPHeaderCreate();
  require_action( httpHeader, exit, err = kNoMemoryErr );
  ECS_HTTPHeaderClear( httpHeader );
  t.tv_sec = 10;
  t.tv_usec = 0;
  while(1){
    FD_ZERO(&readfds);
    FD_SET(clientFd, &readfds);
    clientFdIsSet = 0;
    if(httpHeader->len == 0){
      err = select(1, &readfds, NULL, NULL, &t);
      require( err > 0, exit );
      clientFdIsSet = FD_ISSET(clientFd, &readfds);
    }
    if(clientFdIsSet||httpHeader->len){
      err = ECS_SocketReadHTTPHeader( clientFd, httpHeader );
      fogcloud_config_log("httpHeader: %s", httpHeader->buf);
      switch ( err )
      {
      case kNoErr:
        // Read the rest of the HTTP body if necessary
        err = ECS_SocketReadHTTPBody( clientFd, httpHeader );
        if(httpHeader->dataEndedbyClose == true){
          err = _LocalConfigRespondInComingMessage( clientFd, httpHeader, Context );
          require_noerr(err, exit);
          err = kConnectionErr;
          goto exit;
        }else{
          require_noerr(err, exit);
          err = _LocalConfigRespondInComingMessage( clientFd, httpHeader, Context );
          //require_noerr(err, exit);
          goto exit;
        }
        break;
      case EWOULDBLOCK:
        // NO-OP, keep reading
        break;
      case kNoSpaceErr:
        fogcloud_config_log("ERROR: Cannot fit HTTPHeader.");
        goto exit;
        break;
      case kConnectionErr:
        // NOTE: kConnectionErr from ECS_SocketReadHTTPHeader means it's closed
        fogcloud_config_log("ERROR: Connection closed.");
        goto exit;
        //goto Reconn;
        break;
      default:
        fogcloud_config_log("ERROR: HTTP Header parse internal error: %d", err);
        goto exit;
      }
    }
  }
  
exit:
  if(kNoErr != err){
    fogcloud_config_log("Exit: fogCloud config client exit with err = %d", err);
  }
  else{
    fogcloud_config_log("Exit: fogcloud config client exit with success!");
  }
  SocketClose(&clientFd);
  ECS_HTTPHeaderClear( httpHeader );
  if(httpHeader) free(httpHeader);
  mico_rtos_delete_thread(NULL);
  return;
}
Beispiel #25
0
void easylink_thread(void *inContext)
{
  OSStatus err = kNoErr;
  mico_Context_t *Context = inContext;
  fd_set readfds;
  struct timeval_t t;
  int reConnCount = 0;

  easylink_log_trace();
  require_action(easylink_sem, threadexit, err = kNotPreparedErr);
  
  if(Context->flashContentInRam.micoSystemConfig.easyLinkEnable != false){
    OpenEasylink2_withdata(EasyLink_TimeOut); 
    easylink_log("Start easylink");
    mico_rtos_get_semaphore(&easylink_sem, MICO_WAIT_FOREVER);
    if(EasylinkFailed == false)
      _easylinkConnectWiFi(Context);
    else{
      _easylinkStartSoftAp(Context);
      mico_rtos_delete_thread(NULL);
      return;
    }
      
  }else{
    mico_rtos_lock_mutex(&Context->flashContentInRam_mutex);
    Context->flashContentInRam.micoSystemConfig.easyLinkEnable = true;
    MICOUpdateConfiguration(Context);
    mico_rtos_unlock_mutex(&Context->flashContentInRam_mutex);
    _easylinkConnectWiFi_fast(Context);
  }

  err = mico_rtos_get_semaphore(&easylink_sem, ConnectFTC_Timeout);
  require_noerr(err, reboot);

  httpHeader = HTTPHeaderCreate();
  require_action( httpHeader, threadexit, err = kNoMemoryErr );
  HTTPHeaderClear( httpHeader );
  
  t.tv_sec = 100;
  t.tv_usec = 0;
    
  while(1){
    if(easylinkClient_fd == -1){
      err = _connectFTCServer(inContext, &easylinkClient_fd);
      require_noerr(err, Reconn);
    }else{
      FD_ZERO(&readfds);  
      FD_SET(easylinkClient_fd, &readfds);

      err = select(1, &readfds, NULL, NULL, &t);
    
      if(FD_ISSET(easylinkClient_fd, &readfds)){
        err = SocketReadHTTPHeader( easylinkClient_fd, httpHeader );

        switch ( err )
        {
          case kNoErr:
            // Read the rest of the HTTP body if necessary
            err = SocketReadHTTPBody( easylinkClient_fd, httpHeader );
            require_noerr(err, Reconn);

            PrintHTTPHeader(httpHeader);
            // Call the HTTPServer owner back with the acquired HTTP header
            err = _FTCRespondInComingMessage( easylinkClient_fd, httpHeader, Context );
            require_noerr( err, Reconn );
            // Reuse HTTPHeader
            HTTPHeaderClear( httpHeader );
          break;

          case EWOULDBLOCK:
              // NO-OP, keep reading
          break;

          case kNoSpaceErr:
            easylink_log("ERROR: Cannot fit HTTPHeader.");
            goto Reconn;
          break;

          case kConnectionErr:
            // NOTE: kConnectionErr from SocketReadHTTPHeader means it's closed
            easylink_log("ERROR: Connection closed.");
            goto threadexit;
             //goto Reconn;
          break;
          default:
            easylink_log("ERROR: HTTP Header parse internal error: %d", err);
            goto Reconn;
        }
      }
    }
    continue;
Reconn:
    HTTPHeaderClear( httpHeader );
    SocketClose(&easylinkClient_fd);
    easylinkClient_fd = -1;
    require(reConnCount < 6, threadexit);
    reConnCount++;
    sleep(5);
  }  

/*Module is ignored by FTC server, */    
threadexit:
  ConfigWillStop( Context );
  _cleanEasyLinkResource( Context );

  /*Roll back to previous settings (if it has) and reboot*/
  mico_rtos_lock_mutex(&Context->flashContentInRam_mutex);
  if(Context->flashContentInRam.micoSystemConfig.configured != unConfigured){
    Context->flashContentInRam.micoSystemConfig.configured = allConfigured;
    MICOUpdateConfiguration( Context );
    PlatformSoftReboot();
  }
  mico_rtos_unlock_mutex(&Context->flashContentInRam_mutex);


  wifi_power_down();
  mico_rtos_delete_thread( NULL );
  return;

/*SSID or Password is not correct, module cannot connect to wlan, so reboot and enter EasyLink again*/
reboot:
  ConfigWillStop( Context );
  PlatformSoftReboot();
  return;
}
Beispiel #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;
}
/* 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;
}
int application_start(void)
{
  OSStatus err = kNoErr;
  IPStatusTypedef para;
  struct tm currentTime;
  mico_rtc_time_t time;
  char wifi_ver[64];
  mico_log_trace();  
#if 1 
  /*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);
  mico_rtos_init_semaphore(&context->micoStatus.sys_state_change_sem, 1); 

  MICOReadConfiguration( context );

  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 ); 
#endif
  /*wlan driver and tcpip init*/
  MicoInit();
  MicoSysLed(true);
  
  /**********************add ethernet**********************/
  add_ethernet();
  //sleep(5000);
  /*********************************************************/
  
  mico_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory) ; 

  /* Enter test mode, call a build-in test function amd output on STDIO */
  if(MicoShouldEnterMFGMode()==true)
    mico_mfg_test();

  /*Read current time from RTC.*/
  MicoRtcGetTime(&time);
  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));

  micoWlanGetIPStatus(&para, Station);
  formatMACAddr(context->micoStatus.mac, (char *)&para.mac);
  MicoGetRfVer(wifi_ver, sizeof(wifi_ver));
  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 - 100, _watchdog_reload_timer_handler, NULL);
  mico_start_timer(&_watchdog_reload_timer);

  /* Regisist notifications */
  err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler );
  require_noerr( err, exit ); 

  
  /*************add ethernet********Why add twice?***********/
  //add_ethernet();
  
  if(context->flashContentInRam.micoSystemConfig.configured != allConfigured){
    mico_log("Empty configuration. Starting configuration mode...");

#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, 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...");
    
    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 );

    _ConnectToAP( context );
  }

  mico_log("Free memory %d bytes", MicoGetMemoryInfo()->free_memory) ; 
  
  /*System status changed*/
  while(mico_rtos_get_semaphore(&context->micoStatus.sys_state_change_sem, MICO_WAIT_FOREVER)==kNoErr){
    switch(context->micoStatus.sys_state){
      case eState_Normal:
        break;
      case eState_Software_Reset:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        MicoSystemReboot();
        break;
      case eState_Wlan_Powerdown:
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(500);
        micoWlanPowerOff();
        break;
      case eState_Standby:
        mico_log("Enter standby mode");
        sendNotifySYSWillPowerOff();
        mico_thread_msleep(200);
        micoWlanPowerOff();
        MicoSystemStandBy(MICO_WAIT_FOREVER);
        break;
      default:
        break;
    }
  }
    
  require_noerr_action( err, exit, mico_log("Closing main thread with err num: %d.", err) );

exit:
  mico_rtos_delete_thread(NULL);
  return kNoErr;
}
Beispiel #29
0
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;
}
Beispiel #30
0
void remoteTcpClient_thread(void *inContext)
{
  client_log_trace();
  OSStatus err = kUnknownErr;
  int len;
  mico_Context_t *Context = inContext;
  struct sockaddr_t addr;
  fd_set readfds;
  char ipstr[16];
  struct timeval_t t;
  int remoteTcpClient_loopBack_fd = -1;
  int remoteTcpClient_fd = -1;
  uint8_t *inDataBuffer = NULL;
  uint8_t *outDataBuffer = NULL;  
  
  mico_rtos_init_semaphore(&_wifiConnected_sem, 1);
  
  /* Regisist notifications */
  err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)clientNotify_WifiStatusHandler );
  require_noerr( err, exit ); 
  
  inDataBuffer = malloc(wlanBufferLen);
  require_action(inDataBuffer, exit, err = kNoMemoryErr);
  outDataBuffer = malloc(wlanBufferLen);
  require_action(inDataBuffer, exit, err = kNoMemoryErr);
  
  /*Loopback fd, recv data from other thread */
  remoteTcpClient_loopBack_fd = socket( AF_INET, SOCK_DGRM, IPPROTO_UDP );
  require_action(IsValidSocket( remoteTcpClient_loopBack_fd ), exit, err = kNoResourcesErr );
  addr.s_ip = IPADDR_LOOPBACK;
  addr.s_port = REMOTE_TCP_CLIENT_LOOPBACK_PORT;
  err = bind( remoteTcpClient_loopBack_fd, &addr, sizeof(addr) );
  require_noerr( err, exit );
  
  t.tv_sec = 4;
  t.tv_usec = 0;
  
  while(1) {
    if(remoteTcpClient_fd == -1 ) {
      if(_wifiConnected == false){
        require_action_quiet(mico_rtos_get_semaphore(&_wifiConnected_sem, 200000) == kNoErr, Continue, err = kTimeoutErr);
      }
      err = gethostbyname((char *)Context->flashContentInRam.appConfig.remoteServerDomain, (uint8_t *)ipstr, 16);
      require_noerr(err, ReConnWithDelay);
      
      remoteTcpClient_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
      addr.s_ip = inet_addr(ipstr); 
      addr.s_port = Context->flashContentInRam.appConfig.remoteServerPort;
      
      err = connect(remoteTcpClient_fd, &addr, sizeof(addr));
      require_noerr_quiet(err, ReConnWithDelay);
      
      Context->appStatus.isRemoteConnected = true;
      client_log("Remote server connected at port: %d, fd: %d",  Context->flashContentInRam.appConfig.remoteServerPort,
                 remoteTcpClient_fd);
    }else{
      FD_ZERO(&readfds);
      FD_SET(remoteTcpClient_fd, &readfds);
      FD_SET(remoteTcpClient_loopBack_fd, &readfds);
      
      select(1, &readfds, NULL, NULL, &t);
      
      /*recv UART data using loopback fd*/
      if (FD_ISSET( remoteTcpClient_loopBack_fd, &readfds) ) {
        len = recv( remoteTcpClient_loopBack_fd, outDataBuffer, wlanBufferLen, 0 );
        SocketSend( remoteTcpClient_fd, outDataBuffer, len );
      }
      
      /*recv wlan data using remote client fd*/
      if (FD_ISSET(remoteTcpClient_fd, &readfds)) {
        len = recv(remoteTcpClient_fd, inDataBuffer, wlanBufferLen, 0);
        if(len <= 0) {
          client_log("Remote client closed, fd: %d", remoteTcpClient_fd);
          Context->appStatus.isRemoteConnected = false;
          goto ReConnWithDelay;
        }
        sppWlanCommandProcess(inDataBuffer, &len, remoteTcpClient_fd, Context);

      }

    Continue:    
      continue;
      
    ReConnWithDelay:
      if(remoteTcpClient_fd != -1){
        SocketClose(&remoteTcpClient_fd);
      }
      sleep(CLOUD_RETRY);
    }
  }
exit:
  if(inDataBuffer) free(inDataBuffer);
  if(outDataBuffer) free(outDataBuffer);
  if(remoteTcpClient_loopBack_fd != -1)
    SocketClose(&remoteTcpClient_loopBack_fd);
  client_log("Exit: Remote TCP client exit with err = %d", err);
  mico_rtos_delete_thread(NULL);
  return;
}