OSStatus HealthInit(app_context_t *app_context) { u8 idx; OSStatus err; for(idx = 0; idx < MAX_DEPTH_PUTDOWN; idx++) { putdown_timer[idx].index = idx; } // check if schedule remind timneout every 1 minute for(idx = 0; idx < MAX_DEPTH_SCHEDULE; idx++) { schedule_timer[idx].index = idx; err = mico_init_timer(&schedule_timer[idx].timer, 60*UpTicksPerSecond(), ScheduleTimeout, &schedule_timer[idx]); if(kNoErr != err) { user_log("[ERR]HealthInit: create schedule_timer[%d] failed", idx); } else { user_log("[DBG]HealthInit: create schedule_timer[%d] success", idx); } err = mico_start_timer(&schedule_timer[idx].timer); if(kNoErr != err) { user_log("[ERR]HealthInit: start schedule_timer[%d] failed", idx); } else { user_log("[DBG]HealthInit: start schedule_timer[%d] success", idx); } } #if 0 // initialize if outTrigger is implement by semaphore err = mico_rtos_init_semaphore(&semaphore_getup, 1); require_noerr_action(err, exit, user_log("[ERR]HealthInit: create semaphore_getup failed")); user_log("[DBG]HealthInit: create semaphore_getup success"); err = mico_rtos_init_semaphore(&semaphore_putdown, 1); require_noerr_action(err, exit, user_log("[ERR]HealthInit: create semaphore_putdown failed")); user_log("[DBG]HealthInit: create semaphore_putdown success"); #endif /* err = mico_init_timer(&timer_health_notify, 2*UpTicksPerSecond(), MOChangedNotification, app_context); require_noerr_action(err, exit, user_log("[ERR]HealthInit: create timer_health_notify failed")); user_log("[DBG]HealthInit: create timer_health_notify success"); err = mico_start_timer(&timer_health_notify); require_noerr_action(err, exit, user_log("[ERR]HealthInit: start timer_health_notify failed")); user_log("[DBG]HealthInit: start timer_health_notify success"); */ // start the health monitor thread err = mico_rtos_create_thread(&health_monitor_thread_handle, MICO_APPLICATION_PRIORITY, "health_monitor", health_thread, STACK_SIZE_HEALTH_THREAD, app_context); require_noerr_action( err, exit, user_log("[ERR]HealthInit: create health thread failed!")); user_log("[DBG]HealthInit: create health thread success!"); exit: return err; }
OSStatus internal_uart_init( mico_uart_t uart, const mico_uart_config_t* config, ring_buffer_t* optional_rx_buffer ) { #ifndef NO_MICO_RTOS mico_rtos_init_semaphore(&uart_interfaces[uart].tx_complete, 1); mico_rtos_init_semaphore(&uart_interfaces[uart].rx_complete, 1); #else uart_interfaces[uart].tx_complete = false; uart_interfaces[uart].rx_complete = false; #endif MicoMcuPowerSaveConfig(false); /* Configure the UART TX/RX pins */ configure_uart_pins(BOARD_APP_UART_INSTANCE); #if ADD_OS_CODE #ifndef NO_MICO_RTOS if(config->flags & UART_WAKEUP_ENABLE){ current_uart = uart; mico_rtos_init_semaphore( &uart_interfaces[uart].sem_wakeup, 1 ); mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "UART_WAKEUP", thread_wakeup, 0x100, ¤t_uart); } #endif #endif //OSA_Init(); #ifdef UART_IRQ_APP /****************************************************************/ uartConfig.baudRate = 115200; uartConfig.bitCountPerChar = kUart8BitsPerChar; uartConfig.parityMode = kUartParityDisabled; uartConfig.stopBitCount = kUartOneStopBit; /***************************************************************/ UART_DRV_Init(BOARD_APP_UART_INSTANCE, &uartState, &uartConfig); #else userConfig_app.chnArbitration = kEDMAChnArbitrationRoundrobin; userConfig_app.notHaltOnError = false; uartConfig_app.bitCountPerChar = kUart8BitsPerChar; uartConfig_app.parityMode = kUartParityDisabled; uartConfig_app.stopBitCount = kUartOneStopBit; uartConfig_app.baudRate = 115200; EDMA_DRV_Init(&state_app, &userConfig_app); UART_DRV_EdmaInit(BOARD_APP_UART_INSTANCE, &uartStateEdma_app, &uartConfig_app); INT_SYS_EnableIRQ(g_uartRxTxIrqId[BOARD_APP_UART_INSTANCE]); #endif #if RING_BUFF_ON if (optional_rx_buffer != NULL) { // Note that the ring_buffer should've been initialised first uart_interfaces[uart].rx_buffer = optional_rx_buffer; uart_interfaces[uart].rx_size = 0; platform_uart_receive_bytes( uart, optional_rx_buffer->buffer, optional_rx_buffer->size, 0 ); } #endif MicoMcuPowerSaveConfig(true); return kNoErr; }
/* 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; }
OSStatus host_platform_bus_init( void ) { OSStatus result; MCU_CLOCKS_NEEDED(); result = mico_rtos_init_semaphore( &sdio_transfer_finished_semaphore, 1); //result = mico_rtos_set_semaphore( &sdio_transfer_finished_semaphore); if ( result != kNoErr ) { return result; } // mico_rtos_get_semaphore( &sdio_transfer_finished_semaphore, (uint32_t) 10000 ); GpioSdIoConfig(1); SdioControllerInit(); SdioSetClk(0); NVIC_EnableIRQ(SD_IRQn); //SdioEnableClk(); MCU_CLOCKS_NOT_NEEDED(); return kNoErr; }
void mvdNotify_WifiStatusHandler(WiFiEvent event, mico_Context_t * const inContext) { mvd_log_trace(); (void)inContext; switch (event) { case NOTIFY_STATION_UP: MVDDevInterfaceSend(DEFAULT_MVD_STATION_UP_MSG_2MCU, strlen(DEFAULT_MVD_STATION_UP_MSG_2MCU)); if(NULL == _wifi_station_on_sem){ mico_rtos_init_semaphore(&_wifi_station_on_sem, 1); } mico_rtos_set_semaphore(&_wifi_station_on_sem); break; case NOTIFY_STATION_DOWN: MVDDevInterfaceSend(DEFAULT_MVD_STATION_DOWN_MSG_2MCU, strlen(DEFAULT_MVD_STATION_DOWN_MSG_2MCU)); break; case NOTIFY_AP_UP: break; case NOTIFY_AP_DOWN: break; default: break; } return; }
int application_start( void ) { OSStatus err = kNoErr; IPStatusTypedef para; MicoInit( ); /*The notification message for the registered WiFi status change*/ err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler ); require_noerr( err, exit ); err = MICOAddNotification( mico_notify_WIFI_CONNECT_FAILED, (void *)micoNotify_ConnectFailedHandler ); require_noerr( err, exit ); err = mico_rtos_init_semaphore(&tcp_sem, 1); require_noerr( err, exit ); connect_ap( ); mico_rtos_get_semaphore(&tcp_sem, MICO_WAIT_FOREVER); micoWlanGetIPStatus(¶, Station); tcp_server_log("tcp server ip: %s", para.ip); err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "TCP_server", tcp_server_thread, 0x800, NULL ); require_noerr_action( err, exit, tcp_server_log("ERROR: Unable to start the tcp server thread.") ); return err; exit: tcp_server_log("ERROR, err: %d", err); return err; }
int application_start( void ) { OSStatus err = kNoErr; is_easylink_success = 0; MicoInit( ); /*The notification message for the registered WiFi status change*/ err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)micoNotify_WifiStatusHandler ); require_noerr( err, exit ); err = MICOAddNotification( mico_notify_WIFI_CONNECT_FAILED, (void *)micoNotify_ConnectFailedHandler ); require_noerr( err, exit ); err = MICOAddNotification( mico_notify_EASYLINK_WPS_COMPLETED, (void *)EasyLinkNotify_EasyLinkCompleteHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_EASYLINK_GET_EXTRA_DATA, (void *)EasyLinkNotify_EasyLinkGetExtraDataHandler ); require_noerr(err, exit); // Start the EasyLink thread mico_rtos_init_semaphore(&easylink_sem, 1); err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "EASYLINK", easylink_thread, 0x800, NULL ); require_noerr_action( err, exit, wifi_easylink_log("ERROR: Unable to start the EasyLink thread.") ); return err; exit: wifi_easylink_log("ERROR, err: %d", err); return err; }
void mvdNotify_WifiStatusHandler(WiFiEvent event, mico_Context_t * const inContext) { mvd_log_trace(); (void)inContext; switch (event) { case NOTIFY_STATION_UP: MVDDevInterfaceSend(DEFAULT_MVD_STATION_UP_MSG_2MCU, strlen(DEFAULT_MVD_STATION_UP_MSG_2MCU)); if(NULL == _wifi_station_on_sem){ mico_rtos_init_semaphore(&_wifi_station_on_sem, 1); } mico_rtos_set_semaphore(&_wifi_station_on_sem); // set LED to green means station down, data: on/off,H,S,B LedControlMsgHandler("1,120,100,100", strlen("1,120,100,100")); break; case NOTIFY_STATION_DOWN: MVDDevInterfaceSend(DEFAULT_MVD_STATION_DOWN_MSG_2MCU, strlen(DEFAULT_MVD_STATION_DOWN_MSG_2MCU)); // set LED to light green means station down, data: on/off,H,S,B LedControlMsgHandler("1,120,100,10", strlen("1,120,100,10")); break; case NOTIFY_AP_UP: break; case NOTIFY_AP_DOWN: break; default: break; } return; }
OSStatus MVDInit(mico_Context_t* const inContext) { OSStatus err = kUnknownErr; //init MVD status inContext->appStatus.virtualDevStatus.isCloudConnected = false; inContext->appStatus.virtualDevStatus.RecvRomFileSize = 0; //init MCU connect interface //err = MVDDevInterfaceInit(inContext); //require_noerr_action(err, exit, // mvd_log("ERROR: virtual device mcu interface init failed!") ); //init cloud service interface err = MVDCloudInterfaceInit(inContext); require_noerr_action(err, exit, mvd_log("ERROR: virtual device cloud interface init failed!") ); // wifi notify err = mico_rtos_init_semaphore(&_wifi_station_on_sem, 1); require_noerr_action(err, exit, mvd_log("ERROR: mico_rtos_init_semaphore (_wifi_station_on_sem) failed!") ); err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)mvdNotify_WifiStatusHandler ); require_noerr_action(err, exit, mvd_log("ERROR: MICOAddNotification (mico_notify_WIFI_STATUS_CHANGED) failed!") ); // start MVD main thread err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "MVD main", MVDMainThread, STACK_SIZE_MVD_MAIN_THREAD, inContext ); exit: return err; }
OSStatus startEasyLink( mico_Context_t * const inContext) { easylink_log_trace(); OSStatus err = kUnknownErr; easylinkClient_fd = -1; mico_mcu_powersave_config(true); err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)EasyLinkNotify_WifiStatusHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_WiFI_PARA_CHANGED, (void *)EasyLinkNotify_WiFIParaChangedHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_EASYLINK_COMPLETED, (void *)EasyLinkNotify_EasyLinkCompleteHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_EASYLINK_GET_EXTRA_DATA, (void *)EasyLinkNotify_EasyLinkGetExtraDataHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_DHCP_COMPLETED, (void *)EasyLinkNotify_DHCPCompleteHandler ); require_noerr( err, exit ); err = MICOAddNotification( mico_notify_SYS_WILL_POWER_OFF, (void *)EasyLinkNotify_SYSWillPoerOffHandler ); require_noerr( err, exit ); // Start the EasyLink thread ConfigWillStart(inContext); mico_rtos_init_semaphore(&easylink_sem, 1); err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "EASYLINK", easylink_thread, 0x1000, (void*)inContext ); require_noerr_action( err, exit, easylink_log("ERROR: Unable to start the EasyLink thread.") ); exit: return err; }
OSStatus sntp_client_start( int tz, char *ntpserv ) { ntp_time_zone = tz; NTP_Server = ntpserv; mico_rtos_init_semaphore(&_wifiConnected_sem, 1); return mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "NTP Client", NTPClient_thread, STACK_SIZE_NTP_CLIENT_THREAD, NULL ); }
/************************************************* * Function: MICOBlinkRfLed * Description: * Author: cxy * Returns: * Parameter: * History: *************************************************/ OSStatus MICOBlinkRfLed(mico_Context_t * const inContext) { OSStatus err = kUnknownErr; mico_rtos_init_semaphore(&query_sem, 1); err = mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "query", MICORfLed_thread, 0x500, (void*)inContext ); return err; }
OSStatus host_platform_bus_init( void ) { edma_user_config_t g_edmaUserConfig; /* Create a semephore to check for completed eDMA transfers. */ mico_rtos_init_semaphore(&spi_transfer_finished_semaphore, 1); MCU_CLOCKS_NEEDED(); configure_spi_pins(0); // initlize spi0 GPIO PORT_HAL_SetMuxMode(PORTD_BASE,0u,kPortMuxAsGpio); // configure CS as gpio, use software configure CS. GPIO_DRV_OutputPinInit(&spiCsPin[0]); SPI0_CS_DISABLE; /* Initialize eDMA & DMAMUX */ g_edmaUserConfig.chnArbitration = kEDMAChnArbitrationRoundrobin; g_edmaUserConfig.notHaltOnError = false; EDMA_DRV_Init(&g_edmaState, &g_edmaUserConfig); /* DSPI Master Configuration */ dspi_edma_master_setup(&dspiMasterState, 0, 10000000, 8); MCU_CLOCKS_NOT_NEEDED(); dmaSPITX.dmaChanNum = DMA_CH0; dmaSPITX.dmaCh = &dmaCh0; dmaSPITX.type = kEDMAMemoryToPeripheral; dmaSPITX.chSource = kDmaRequestMux0SPI0Tx; dmaSPITX.srcAddr = (uint32_t)NULL; dmaSPITX.destAddr = (uint32_t)&SPI0->PUSHR; dmaSPITX.length = 0; dmaSPITX.size = 4; dmaSPITX.watermark = 4; dmaSPITX.period = 0x01U; dmaSPITX.dmaCallBack = stop_edma_loop; dmaSPIRX.dmaChanNum = DMA_CH1; dmaSPIRX.dmaCh = &dmaCh1; dmaSPIRX.type = kEDMAPeripheralToMemory; dmaSPIRX.chSource = kDmaRequestMux0SPI0Rx; dmaSPIRX.srcAddr = (uint32_t)&SPI0->POPR; dmaSPIRX.destAddr = (uint32_t)NULL; dmaSPIRX.length = 0; dmaSPIRX.size = 1; dmaSPIRX.watermark = 1; dmaSPIRX.period = 0x01U; dmaSPIRX.dmaCallBack = stop_edma_loop_putsem; dmaSPIRX.dmaChStcd = (edma_software_tcd_t *)mem_align(2 * sizeof(edma_software_tcd_t) * dmaSPIRX.period, 32); spi_status_print(SPI0); return kNoErr; }
OSStatus mico_system_power_daemon_start( mico_Context_t* const in_context ) { OSStatus err = kNoErr; err = mico_rtos_init_semaphore( &in_context->micoStatus.sys_state_change_sem, 1 ); require_noerr(err, exit); in_context->micoStatus.current_sys_state = eState_Normal; mico_rtos_create_thread( NULL, MICO_APPLICATION_PRIORITY, "Power Daemon", _sys_state_thread, 800, (void *)in_context ); require_noerr(err, exit); exit: return kNoErr; }
OSStatus startEasyLink( mico_Context_t * const inContext) { easylink_log_trace(); OSStatus err = kUnknownErr; require_action(inContext->micoStatus.easylink_thread_handler==NULL, exit, err = kParamErr); require_action(inContext->micoStatus.easylink_sem==NULL, exit, err = kParamErr); inContext->micoStatus.easylinkClient_fd = -1; //ps_enable(); mico_mcu_powersave_config(true); mico_rtos_init_mutex(&_mutex); err = MICOAddNotification( mico_notify_WIFI_STATUS_CHANGED, (void *)EasyLinkNotify_WifiStatusHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_WiFI_PARA_CHANGED, (void *)EasyLinkNotify_WiFIParaChangedHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_EASYLINK_COMPLETED, (void *)EasyLinkNotify_EasyLinkCompleteHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_EASYLINK_GET_EXTRA_DATA, (void *)EasyLinkNotify_EasyLinkGetExtraDataHandler ); require_noerr(err, exit); err = MICOAddNotification( mico_notify_DHCP_COMPLETED, (void *)EasyLinkNotify_DHCPCompleteHandler ); require_noerr( err, exit ); err = MICOAddNotification( mico_notify_SYS_WILL_POWER_OFF, (void *)EasyLinkNotify_SYSWillPoerOffHandler ); require_noerr( err, exit ); /*Led trigger*/ mico_init_timer(&_Led_EL_timer, LED_EL_TRIGGER_INTERVAL, _led_EL_Timeout_handler, NULL); mico_start_timer(&_Led_EL_timer); // Start the EasyLink thread ConfigWillStart(inContext); mico_rtos_init_semaphore(&inContext->micoStatus.easylink_sem, 1); err = mico_rtos_create_thread(&inContext->micoStatus.easylink_thread_handler, MICO_APPLICATION_PRIORITY, "EASYLINK", easylink_thread, 0x1000, (void*)inContext ); require_noerr_action( err, exit, easylink_log("ERROR: Unable to start the EasyLink thread.") ); exit: return err; }
// reset default value void MVDRestoreDefault(mico_Context_t* const context) { // start a thread to reset device info on EasyCloud mico_rtos_init_semaphore(&_reset_cloud_info_sem, 1); mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "MVD resetCloudInfo", MVDDevCloudInfoResetThread, 0x800, context ); mico_rtos_get_semaphore(&_reset_cloud_info_sem, 5000); // 5s timeout // reset all MVD config params memset((void*)&(context->flashContentInRam.appConfig.virtualDevConfig), 0, sizeof(virtual_device_config_t)); context->flashContentInRam.appConfig.virtualDevConfig.USART_BaudRate = 115200; context->flashContentInRam.appConfig.virtualDevConfig.isActivated = false; sprintf(context->flashContentInRam.appConfig.virtualDevConfig.deviceId, DEFAULT_DEVICE_ID); sprintf(context->flashContentInRam.appConfig.virtualDevConfig.masterDeviceKey, DEFAULT_DEVICE_KEY); sprintf(context->flashContentInRam.appConfig.virtualDevConfig.romVersion, DEFAULT_ROM_VERSION); sprintf(context->flashContentInRam.appConfig.virtualDevConfig.loginId, DEFAULT_LOGIN_ID); sprintf(context->flashContentInRam.appConfig.virtualDevConfig.devPasswd, DEFAULT_DEV_PASSWD); //sprintf(context->flashContentInRam.appConfig.virtualDevConfig.userToken, context->micoStatus.mac); }
/** * @brief Configures TIM5 to measure the LSI oscillator frequency. * @param None * @retval LSI Frequency */ uint32_t GetLSIFrequency(void) { NVIC_InitTypeDef NVIC_InitStructure; TIM_ICInitTypeDef TIM_ICInitStructure; RCC_ClocksTypeDef RCC_ClockFreq; mico_rtos_init_semaphore(&_measureLSIComplete_SEM, 1); /* Enable the LSI oscillator ************************************************/ RCC_LSICmd(ENABLE); /* Wait till LSI is ready */ while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET) {} /* TIM5 configuration *******************************************************/ /* Enable TIM5 clock */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE); /* Connect internally the TIM5_CH4 Input Capture to the LSI clock output */ TIM_RemapConfig(TIM5, TIM5_LSI); /* Configure TIM5 presclaer */ TIM_PrescalerConfig(TIM5, 0, TIM_PSCReloadMode_Immediate); /* TIM5 configuration: Input Capture mode --------------------- The LSI oscillator is connected to TIM5 CH4 The Rising edge is used as active edge, The TIM5 CCR4 is used to compute the frequency value ------------------------------------------------------------ */ TIM_ICInitStructure.TIM_Channel = TIM_Channel_4; TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV8; TIM_ICInitStructure.TIM_ICFilter = 0; TIM_ICInit(TIM5, &TIM_ICInitStructure); /* Enable TIM5 Interrupt channel */ NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 15; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 8; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* Enable TIM5 counter */ TIM_Cmd(TIM5, ENABLE); /* Reset the flags */ TIM5->SR = 0; /* Enable the CC4 Interrupt Request */ TIM_ITConfig(TIM5, TIM_IT_CC4, ENABLE); /* Wait until the TIM5 get 2 LSI edges (refer to TIM5_IRQHandler()) *********/ mico_rtos_get_semaphore(&_measureLSIComplete_SEM, MICO_WAIT_FOREVER); /* Deinitialize the TIM5 peripheral registers to their default reset values */ TIM_ITConfig(TIM5, TIM_IT_CC4, DISABLE); TIM_DeInit(TIM5); NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 5; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 8; NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE; NVIC_Init(&NVIC_InitStructure); /* Compute the LSI frequency, depending on TIM5 input clock frequency (PCLK1)*/ /* Get SYSCLK, HCLK and PCLKx frequency */ RCC_GetClocksFreq(&RCC_ClockFreq); /* Get PCLK1 prescaler */ if ((RCC->CFGR & RCC_CFGR_PPRE1) == 0) { /* PCLK1 prescaler equal to 1 => TIMCLK = PCLK1 */ return ((RCC_ClockFreq.PCLK1_Frequency / PeriodValue) * 8); } else { /* PCLK1 prescaler different from 1 => TIMCLK = 2 * PCLK1 */ return (((2 * RCC_ClockFreq.PCLK1_Frequency) / PeriodValue) * 8) ; } }
OSStatus platform_uart_init( platform_uart_driver_t* driver, const platform_uart_t* peripheral, const platform_uart_config_t* config, ring_buffer_t* optional_ring_buffer ) { DMA_InitTypeDef dma_init_structure; USART_InitTypeDef uart_init_structure; uint32_t uart_number; OSStatus err = kNoErr; platform_mcu_powersave_disable(); require_action_quiet( ( driver != NULL ) && ( peripheral != NULL ) && ( config != NULL ), exit, err = kParamErr); require_action_quiet( (optional_ring_buffer == NULL) || ((optional_ring_buffer->buffer != NULL ) && (optional_ring_buffer->size != 0)), exit, err = kParamErr); uart_number = platform_uart_get_port_number( peripheral->port ); driver->rx_size = 0; driver->tx_size = 0; driver->last_transmit_result = kNoErr; driver->last_receive_result = kNoErr; driver->peripheral = (platform_uart_t*)peripheral; #ifndef NO_MICO_RTOS mico_rtos_init_semaphore( &driver->tx_complete, 1 ); mico_rtos_init_semaphore( &driver->rx_complete, 1 ); mico_rtos_init_semaphore( &driver->sem_wakeup, 1 ); mico_rtos_init_mutex ( &driver->tx_mutex ); #else driver->tx_complete = false; driver->rx_complete = false; #endif /* Configure TX and RX pin_mapping */ platform_gpio_set_alternate_function( peripheral->pin_tx->port, peripheral->pin_tx->pin_number, GPIO_OType_PP, GPIO_PuPd_NOPULL, uart_alternate_functions[ uart_number ] ); platform_gpio_set_alternate_function( peripheral->pin_rx->port, peripheral->pin_rx->pin_number, GPIO_OType_PP, GPIO_PuPd_NOPULL, uart_alternate_functions[ uart_number ] ); if ( ( peripheral->pin_cts != NULL ) && ( config->flow_control == FLOW_CONTROL_CTS || config->flow_control == FLOW_CONTROL_CTS_RTS ) ) { platform_gpio_set_alternate_function( peripheral->pin_cts->port, peripheral->pin_cts->pin_number, GPIO_OType_PP, GPIO_PuPd_NOPULL, uart_alternate_functions[ uart_number ] ); } if ( ( peripheral->pin_rts != NULL ) && ( config->flow_control == FLOW_CONTROL_RTS || config->flow_control == FLOW_CONTROL_CTS_RTS ) ) { platform_gpio_set_alternate_function( peripheral->pin_rts->port, peripheral->pin_rts->pin_number, GPIO_OType_PP, GPIO_PuPd_NOPULL, uart_alternate_functions[ uart_number ] ); } #ifndef NO_MICO_RTOS if(config->flags & UART_WAKEUP_ENABLE) { mico_rtos_init_semaphore( driver->sem_wakeup, 1 ); mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "UART_WAKEUP", thread_wakeup, 0x100, driver); } #endif /* Enable UART peripheral clock */ uart_peripheral_clock_functions[ uart_number ]( uart_peripheral_clocks[ uart_number ], ENABLE ); uart_init_structure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; uart_init_structure.USART_BaudRate = config->baud_rate; uart_init_structure.USART_WordLength = ( ( config->data_width == DATA_WIDTH_9BIT ) || ( ( config->data_width == DATA_WIDTH_8BIT ) && ( config->parity != NO_PARITY ) ) ) ? USART_WordLength_9b : USART_WordLength_8b; uart_init_structure.USART_StopBits = ( config->stop_bits == STOP_BITS_1 ) ? USART_StopBits_1 : USART_StopBits_2; switch ( config->parity ) { case NO_PARITY: uart_init_structure.USART_Parity = USART_Parity_No; break; case EVEN_PARITY: uart_init_structure.USART_Parity = USART_Parity_Even; break; case ODD_PARITY: uart_init_structure.USART_Parity = USART_Parity_Odd; break; default: err = kParamErr; goto exit; } switch ( config->flow_control ) { case FLOW_CONTROL_DISABLED: uart_init_structure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; break; case FLOW_CONTROL_CTS: uart_init_structure.USART_HardwareFlowControl = USART_HardwareFlowControl_CTS; break; case FLOW_CONTROL_RTS: uart_init_structure.USART_HardwareFlowControl = USART_HardwareFlowControl_RTS; break; case FLOW_CONTROL_CTS_RTS: uart_init_structure.USART_HardwareFlowControl = USART_HardwareFlowControl_RTS_CTS; break; default: err = kParamErr; goto exit; } /* Initialise USART peripheral */ USART_DeInit( peripheral->port ); USART_Init( peripheral->port, &uart_init_structure ); /************************************************************************** * Initialise STM32 DMA registers * Note: If DMA is used, USART interrupt isn't enabled. **************************************************************************/ /* Enable DMA peripheral clock */ if ( peripheral->tx_dma_config.controller == DMA1 ) { RCC->AHB1ENR |= RCC_AHB1Periph_DMA1; } else { RCC->AHB1ENR |= RCC_AHB1Periph_DMA2; } /* Fill init structure with common DMA settings */ dma_init_structure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; dma_init_structure.DMA_MemoryInc = DMA_MemoryInc_Enable; dma_init_structure.DMA_Priority = DMA_Priority_VeryHigh; dma_init_structure.DMA_FIFOMode = DMA_FIFOMode_Disable; dma_init_structure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full; dma_init_structure.DMA_MemoryBurst = DMA_MemoryBurst_Single; dma_init_structure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; if ( config->data_width == DATA_WIDTH_9BIT ) { dma_init_structure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord; dma_init_structure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord; } else { dma_init_structure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; dma_init_structure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; } /* Initialise TX DMA */ DMA_DeInit( peripheral->tx_dma_config.stream ); dma_init_structure.DMA_Channel = peripheral->tx_dma_config.channel; dma_init_structure.DMA_PeripheralBaseAddr = (uint32_t) &peripheral->port->DR; dma_init_structure.DMA_Memory0BaseAddr = (uint32_t) 0; dma_init_structure.DMA_DIR = DMA_DIR_MemoryToPeripheral; dma_init_structure.DMA_BufferSize = 0xFFFF; // This parameter will be configured during communication dma_init_structure.DMA_Mode = DMA_Mode_Normal; DMA_Init( peripheral->tx_dma_config.stream, &dma_init_structure ); /* Initialise RX DMA */ DMA_DeInit( peripheral->rx_dma_config.stream ); dma_init_structure.DMA_Channel = peripheral->rx_dma_config.channel; dma_init_structure.DMA_PeripheralBaseAddr = (uint32_t) &peripheral->port->DR; dma_init_structure.DMA_Memory0BaseAddr = (uint32_t) 0; dma_init_structure.DMA_DIR = DMA_DIR_PeripheralToMemory; dma_init_structure.DMA_BufferSize = 0xFFFF; // This parameter will be configured during communication dma_init_structure.DMA_Mode = DMA_Mode_Normal; DMA_Init( peripheral->rx_dma_config.stream, &dma_init_structure ); /************************************************************************** * Initialise STM32 DMA interrupts **************************************************************************/ /* Configure TX DMA interrupt on Cortex-M3 */ NVIC_EnableIRQ( peripheral->tx_dma_config.irq_vector ); /* Enable TC (transfer complete) and TE (transfer error) interrupts on source */ clear_dma_interrupts( peripheral->tx_dma_config.stream, peripheral->tx_dma_config.complete_flags | peripheral->tx_dma_config.error_flags ); DMA_ITConfig( peripheral->tx_dma_config.stream, DMA_INTERRUPT_FLAGS, ENABLE ); /* Enable USART interrupt vector in Cortex-M3 */ NVIC_EnableIRQ( uart_irq_vectors[uart_number] ); USART_DMACmd( driver->peripheral->port, USART_DMAReq_Tx, DISABLE ); /* Enable USART */ USART_Cmd( peripheral->port, ENABLE ); /* Enable both transmit and receive */ peripheral->port->CR1 |= USART_CR1_TE; peripheral->port->CR1 |= USART_CR1_RE; /* Setup ring buffer */ if ( optional_ring_buffer != NULL ) { /* Note that the ring_buffer should've been initialised first */ driver->rx_buffer = optional_ring_buffer; driver->rx_size = 0; receive_bytes( driver, optional_ring_buffer->buffer, optional_ring_buffer->size, 0 ); } else { /* Not using ring buffer. Configure RX DMA interrupt on Cortex-M3 */ NVIC_EnableIRQ( peripheral->rx_dma_config.irq_vector ); /* Enable TC (transfer complete) and TE (transfer error) interrupts on source */ clear_dma_interrupts( peripheral->rx_dma_config.stream, peripheral->rx_dma_config.complete_flags | peripheral->rx_dma_config.error_flags ); DMA_ITConfig( peripheral->rx_dma_config.stream, DMA_INTERRUPT_FLAGS, ENABLE ); } exit: MicoMcuPowerSaveConfig(true); return err; }
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(¶, Station); formatMACAddr(context->micoStatus.mac, (char *)¶.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; }
OSStatus MICOStartNTPClient ( mico_Context_t * const inContext ) { mico_rtos_init_semaphore(&_wifiConnected_sem, 1); return mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "NTP Client", NTPClient_thread, 0x500, (void*)inContext ); }
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(¶, Station); formatMACAddr(context->micoStatus.mac, (char *)¶.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; }
OSStatus internal_uart_init( mico_uart_t uart, const mico_uart_config_t* config, ring_buffer_t* optional_rx_buffer ) { GPIO_InitTypeDef gpio_init_structure; USART_InitTypeDef usart_init_structure; NVIC_InitTypeDef nvic_init_structure; DMA_InitTypeDef dma_init_structure; #ifndef NO_MICO_RTOS mico_rtos_init_semaphore(&uart_interfaces[uart].tx_complete, 1); mico_rtos_init_semaphore(&uart_interfaces[uart].rx_complete, 1); #else uart_interfaces[uart].tx_complete = false; uart_interfaces[uart].rx_complete = false; #endif MicoMcuPowerSaveConfig(false); /* Enable GPIO peripheral clocks for TX and RX pins */ RCC_AHB1PeriphClockCmd( uart_mapping[uart].pin_rx->peripheral_clock | uart_mapping[uart].pin_tx->peripheral_clock, ENABLE ); /* Configure USART TX Pin */ gpio_init_structure.GPIO_Pin = (uint32_t) ( 1 << uart_mapping[uart].pin_tx->number ); gpio_init_structure.GPIO_Mode = GPIO_Mode_AF; gpio_init_structure.GPIO_OType = GPIO_OType_PP; gpio_init_structure.GPIO_PuPd = GPIO_PuPd_NOPULL; gpio_init_structure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init( uart_mapping[uart].pin_tx->bank, &gpio_init_structure ); GPIO_PinAFConfig( uart_mapping[uart].pin_tx->bank, uart_mapping[uart].pin_tx->number, uart_mapping[uart].gpio_af ); /* Configure USART RX Pin */ gpio_init_structure.GPIO_Pin = (uint32_t) ( 1 << uart_mapping[uart].pin_rx->number ); gpio_init_structure.GPIO_Mode = GPIO_Mode_AF; gpio_init_structure.GPIO_OType = GPIO_OType_OD; gpio_init_structure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init( uart_mapping[uart].pin_rx->bank, &gpio_init_structure ); GPIO_PinAFConfig( uart_mapping[uart].pin_rx->bank, uart_mapping[uart].pin_rx->number, uart_mapping[uart].gpio_af ); #ifndef NO_MICO_RTOS if(config->flags & UART_WAKEUP_ENABLE){ current_uart = uart; mico_rtos_init_semaphore( &uart_interfaces[uart].sem_wakeup, 1 ); mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "UART_WAKEUP", thread_wakeup, 0x100, ¤t_uart); } #endif /* Check if any of the flow control is enabled */ if ( uart_mapping[uart].pin_cts && (config->flow_control == FLOW_CONTROL_CTS || config->flow_control == FLOW_CONTROL_CTS_RTS) ) { /* Enable peripheral clock */ RCC_AHB1PeriphClockCmd( uart_mapping[uart].pin_cts->peripheral_clock, ENABLE ); /* Configure CTS Pin */ gpio_init_structure.GPIO_Pin = (uint32_t) ( 1 << uart_mapping[uart].pin_cts->number ); gpio_init_structure.GPIO_Mode = GPIO_Mode_AF; gpio_init_structure.GPIO_OType = GPIO_OType_OD; gpio_init_structure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init( uart_mapping[uart].pin_cts->bank, &gpio_init_structure ); GPIO_PinAFConfig( uart_mapping[uart].pin_cts->bank, uart_mapping[uart].pin_cts->number, uart_mapping[uart].gpio_af ); } if ( uart_mapping[uart].pin_cts && (config->flow_control == FLOW_CONTROL_RTS || config->flow_control == FLOW_CONTROL_CTS_RTS) ) { /* Enable peripheral clock */ RCC_AHB1PeriphClockCmd( uart_mapping[uart].pin_rts->peripheral_clock, ENABLE ); /* Configure RTS Pin */ gpio_init_structure.GPIO_Pin = (uint32_t) ( 1 << uart_mapping[uart].pin_rts->number ); gpio_init_structure.GPIO_Mode = GPIO_Mode_AF; gpio_init_structure.GPIO_OType = GPIO_OType_OD; gpio_init_structure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init( uart_mapping[uart].pin_rts->bank, &gpio_init_structure ); GPIO_PinAFConfig( uart_mapping[uart].pin_rts->bank, uart_mapping[uart].pin_rts->number, uart_mapping[uart].gpio_af ); } /* Enable UART peripheral clock */ uart_mapping[uart].usart_peripheral_clock_func( uart_mapping[uart].usart_peripheral_clock, ENABLE ); /************************************************************************** * Initialise STM32 USART registers * NOTE: * - Both transmitter and receiver are disabled until usart_enable_transmitter/receiver is called. * - Only 1 and 2 stop bits are implemented at the moment. **************************************************************************/ usart_init_structure.USART_Mode = 0; usart_init_structure.USART_BaudRate = config->baud_rate; usart_init_structure.USART_WordLength = ( ( config->data_width == DATA_WIDTH_9BIT ) || ( ( config->data_width == DATA_WIDTH_8BIT ) && ( config->parity != NO_PARITY ) ) ) ? USART_WordLength_9b : USART_WordLength_8b; usart_init_structure.USART_StopBits = ( config->stop_bits == STOP_BITS_1 ) ? USART_StopBits_1 : USART_StopBits_2; switch ( config->parity ) { case NO_PARITY: usart_init_structure.USART_Parity = USART_Parity_No; break; case EVEN_PARITY: usart_init_structure.USART_Parity = USART_Parity_Even; break; case ODD_PARITY: usart_init_structure.USART_Parity = USART_Parity_Odd; break; default: return kParamErr; } switch ( config->flow_control ) { case FLOW_CONTROL_DISABLED: usart_init_structure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; break; case FLOW_CONTROL_CTS: usart_init_structure.USART_HardwareFlowControl = USART_HardwareFlowControl_CTS; break; case FLOW_CONTROL_RTS: usart_init_structure.USART_HardwareFlowControl = USART_HardwareFlowControl_RTS; break; case FLOW_CONTROL_CTS_RTS: usart_init_structure.USART_HardwareFlowControl = USART_HardwareFlowControl_RTS_CTS; break; default: return kParamErr; } /* Initialise USART peripheral */ USART_Init( uart_mapping[uart].usart, &usart_init_structure ); /************************************************************************** * Initialise STM32 DMA registers * Note: If DMA is used, USART interrupt isn't enabled. **************************************************************************/ /* Enable DMA peripheral clock */ uart_mapping[uart].tx_dma_peripheral_clock_func( uart_mapping[uart].tx_dma_peripheral_clock, ENABLE ); uart_mapping[uart].rx_dma_peripheral_clock_func( uart_mapping[uart].rx_dma_peripheral_clock, ENABLE ); /* Fill init structure with common DMA settings */ dma_init_structure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; dma_init_structure.DMA_MemoryInc = DMA_MemoryInc_Enable; dma_init_structure.DMA_Priority = DMA_Priority_VeryHigh; dma_init_structure.DMA_FIFOMode = DMA_FIFOMode_Disable; dma_init_structure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full; dma_init_structure.DMA_MemoryBurst = DMA_MemoryBurst_Single; dma_init_structure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; if ( config->data_width == DATA_WIDTH_9BIT ) { dma_init_structure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord; dma_init_structure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord; } else { dma_init_structure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; dma_init_structure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; } /* Initialise TX DMA */ DMA_DeInit( uart_mapping[uart].tx_dma_stream ); dma_init_structure.DMA_Channel = uart_mapping[uart].tx_dma_channel; dma_init_structure.DMA_PeripheralBaseAddr = (uint32_t) &uart_mapping[uart].usart->DR; dma_init_structure.DMA_Memory0BaseAddr = (uint32_t) 0; dma_init_structure.DMA_DIR = DMA_DIR_MemoryToPeripheral; dma_init_structure.DMA_BufferSize = 0; dma_init_structure.DMA_Mode = DMA_Mode_Normal; DMA_Init( uart_mapping[uart].tx_dma_stream, &dma_init_structure ); /* Initialise RX DMA */ DMA_DeInit( uart_mapping[uart].rx_dma_stream ); dma_init_structure.DMA_Channel = uart_mapping[uart].rx_dma_channel; dma_init_structure.DMA_PeripheralBaseAddr = (uint32_t) &uart_mapping[uart].usart->DR; dma_init_structure.DMA_Memory0BaseAddr = 0; dma_init_structure.DMA_DIR = DMA_DIR_PeripheralToMemory; dma_init_structure.DMA_BufferSize = 0; dma_init_structure.DMA_Mode = DMA_Mode_Normal; DMA_Init( uart_mapping[uart].rx_dma_stream, &dma_init_structure ); /************************************************************************** * Initialise STM32 DMA interrupts * Note: Only TX DMA interrupt is enabled. **************************************************************************/ /* Configure TX DMA interrupt on Cortex-M3 */ nvic_init_structure.NVIC_IRQChannel = uart_mapping[uart].tx_dma_irq; nvic_init_structure.NVIC_IRQChannelPreemptionPriority = (uint8_t) 0x5; nvic_init_structure.NVIC_IRQChannelSubPriority = 0x8; nvic_init_structure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init( &nvic_init_structure ); /* Enable TC (transfer complete) and TE (transfer error) interrupts on source */ DMA_ITConfig( uart_mapping[uart].tx_dma_stream, DMA_IT_TC | DMA_IT_TE | DMA_IT_DME | DMA_IT_FE, ENABLE ); /* Enable USART's RX DMA interfaces */ USART_DMACmd( uart_mapping[uart].usart, USART_DMAReq_Rx, ENABLE ); /************************************************************************** * Initialise STM32 USART interrupt **************************************************************************/ nvic_init_structure.NVIC_IRQChannel = uart_mapping[uart].usart_irq; nvic_init_structure.NVIC_IRQChannelPreemptionPriority = (uint8_t) 0x6; nvic_init_structure.NVIC_IRQChannelSubPriority = 0x7; nvic_init_structure.NVIC_IRQChannelCmd = ENABLE; /* Enable USART interrupt vector in Cortex-M3 */ NVIC_Init( &nvic_init_structure ); /* Enable USART */ USART_Cmd( uart_mapping[uart].usart, ENABLE ); /* Enable both transmit and receive */ uart_mapping[uart].usart->CR1 |= USART_CR1_TE; uart_mapping[uart].usart->CR1 |= USART_CR1_RE; /* Setup ring buffer */ if (optional_rx_buffer != NULL) { /* Note that the ring_buffer should've been initialised first */ uart_interfaces[uart].rx_buffer = optional_rx_buffer; uart_interfaces[uart].rx_size = 0; platform_uart_receive_bytes( uart, optional_rx_buffer->buffer, optional_rx_buffer->size, 0 ); } else { /* Not using ring buffer. Configure RX DMA interrupt on Cortex-M3 */ nvic_init_structure.NVIC_IRQChannel = uart_mapping[uart].rx_dma_irq; nvic_init_structure.NVIC_IRQChannelPreemptionPriority = (uint8_t) 0x5; nvic_init_structure.NVIC_IRQChannelSubPriority = 0x8; nvic_init_structure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init( &nvic_init_structure ); /* Enable TC (transfer complete) and TE (transfer error) interrupts on source */ DMA_ITConfig( uart_mapping[uart].rx_dma_stream, DMA_IT_TC | DMA_IT_TE | DMA_IT_DME | DMA_IT_FE, ENABLE ); } MicoMcuPowerSaveConfig(true); return kNoErr; }
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(¶, 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(¤tTime)); }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; }
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); }
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; }
OSStatus host_platform_bus_init( void ) { pdc_packet_t pdc_spi_packet; Pdc* spi_pdc = spi_get_pdc_base( wifi_spi.port ); platform_mcu_powersave_disable( ); mico_rtos_init_semaphore( &spi_transfer_finished_semaphore, 1 ); /* Setup the SPI lines */ platform_gpio_peripheral_pin_init( wifi_spi.mosi_pin, ( wifi_spi.mosi_pin_mux_mode | IOPORT_MODE_PULLUP ) ); platform_gpio_peripheral_pin_init( wifi_spi.miso_pin, ( wifi_spi.miso_pin_mux_mode | IOPORT_MODE_PULLUP ) ); platform_gpio_peripheral_pin_init( wifi_spi.clock_pin, ( wifi_spi.clock_pin_mux_mode | IOPORT_MODE_PULLUP ) ); /* Setup the interrupt input for WLAN_IRQ */ platform_gpio_init( &wifi_spi_pins[WIFI_PIN_SPI_IRQ], INPUT_HIGH_IMPEDANCE ); platform_gpio_irq_enable( &wifi_spi_pins[WIFI_PIN_SPI_IRQ], IRQ_TRIGGER_RISING_EDGE, spi_irq_handler, 0 ); /* Setup SPI slave select GPIOs */ platform_gpio_init( &wifi_spi_pins[WIFI_PIN_SPI_CS], OUTPUT_PUSH_PULL ); platform_gpio_output_high( &wifi_spi_pins[WIFI_PIN_SPI_CS] ); #if defined ( MICO_WIFI_USE_GPIO_FOR_BOOTSTRAP ) /* Set GPIO_B[1:0] to 01 to put WLAN module into gSPI mode */ platform_gpio_init( &wifi_control_pins[WIFI_PIN_BOOTSTRAP_0], OUTPUT_PUSH_PULL ); platform_gpio_output_high( &wifi_control_pins[WIFI_PIN_BOOTSTRAP_0] ); platform_gpio_init( &wifi_control_pins[WIFI_PIN_BOOTSTRAP_1], OUTPUT_PUSH_PULL ); platform_gpio_output_low( &wifi_control_pins[WIFI_PIN_BOOTSTRAP_1] ); #endif /* Enable the peripheral and set SPI mode. */ flexcom_enable( flexcom_base[ wifi_spi.spi_id ] ); flexcom_set_opmode( flexcom_base[ wifi_spi.spi_id ], FLEXCOM_SPI ); /* Init pdc, and clear RX TX. */ pdc_spi_packet.ul_addr = 0; pdc_spi_packet.ul_size = 1; pdc_tx_init( spi_pdc, &pdc_spi_packet, NULL ); pdc_rx_init( spi_pdc, &pdc_spi_packet, NULL ); spi_disable_interrupt(wifi_spi.port, 0xffffffff ); spi_disable( wifi_spi.port ); spi_reset( wifi_spi.port ); spi_set_lastxfer( wifi_spi.port ); spi_set_master_mode( wifi_spi.port ); spi_disable_mode_fault_detect( wifi_spi.port ); spi_set_clock_polarity( wifi_spi.port, 0, SPI_CLK_POLARITY ); spi_set_clock_phase( wifi_spi.port, 0, SPI_CLK_PHASE ); spi_set_bits_per_transfer( wifi_spi.port, 0, SPI_CSR_BITS_8_BIT ); spi_set_baudrate_div( wifi_spi.port, 0, (sysclk_get_cpu_hz() / SPI_BAUD_RATE) ); spi_set_transfer_delay( wifi_spi.port, 0, 0, 0 ); /* Must be lower priority than the value of configMAX_SYSCALL_INTERRUPT_PRIORITY */ /* otherwise FreeRTOS will not be able to mask the interrupt */ /* keep in mind that ARMCM4 interrupt priority logic is inverted, the highest value */ /* is the lowest priority */ /* Configure SPI interrupts . */ NVIC_EnableIRQ( platform_flexcom_irq_numbers[wifi_spi.spi_id] ); spi_enable(wifi_spi.port); platform_mcu_powersave_enable( ); return kNoErr; }
OSStatus host_platform_bus_init( void ) { #ifndef USE_OWN_SPI_DRV struct spi_master_vec_config spi; #else pdc_packet_t pdc_spi_packet; #endif OSStatus result; MCU_CLOCKS_NEEDED(); spi_disable_interrupt(SPI_MASTER_BASE, 0xffffffff); //Disable_global_interrupt();//TBD! result = mico_rtos_init_semaphore( &spi_transfer_finished_semaphore, 1 ); if ( result != kNoErr ) { return result; } mico_gpio_initialize( (mico_gpio_t)MICO_GPIO_9, INPUT_PULL_UP ); //ioport_port_mask_t ul_mask = ioport_pin_to_mask(CREATE_IOPORT_PIN(PORTA,24)); //pio_set_input(PIOA,ul_mask, PIO_PULLUP|PIO_DEBOUNCE); mico_gpio_enable_IRQ( (mico_gpio_t)MICO_GPIO_9, IRQ_TRIGGER_RISING_EDGE, spi_irq_handler, NULL ); #ifndef HARD_CS_NSS0 mico_gpio_initialize( MICO_GPIO_15, OUTPUT_PUSH_PULL);//spi ss/cs mico_gpio_output_high( MICO_GPIO_15 );//MICO_GPIO_15 TBD! #else ioport_set_pin_peripheral_mode(SPI_NPCS0_GPIO, SPI_NPCS0_FLAGS);//TBD! #endif /* set PORTB 01 to high to put WLAN module into g_SPI mode */ mico_gpio_initialize( (mico_gpio_t)WL_GPIO0, OUTPUT_PUSH_PULL ); mico_gpio_output_high( (mico_gpio_t)WL_GPIO0 ); #ifdef USE_OWN_SPI_DRV #if (SAMG55) /* Enable the peripheral and set SPI mode. */ flexcom_enable(BOARD_FLEXCOM_SPI); flexcom_set_opmode(BOARD_FLEXCOM_SPI, FLEXCOM_SPI); #else /* Configure an SPI peripheral. */ pmc_enable_periph_clk(SPI_ID); #endif //Init pdc, and clear RX TX. spi_m_pdc = spi_get_pdc_base(SPI_MASTER_BASE); pdc_spi_packet.ul_addr = NULL; pdc_spi_packet.ul_size = 3; pdc_tx_init(spi_m_pdc, &pdc_spi_packet, NULL); pdc_rx_init(spi_m_pdc, &pdc_spi_packet, NULL); spi_disable(SPI_MASTER_BASE); spi_reset(SPI_MASTER_BASE); spi_set_lastxfer(SPI_MASTER_BASE); spi_set_master_mode(SPI_MASTER_BASE); spi_disable_mode_fault_detect(SPI_MASTER_BASE); #ifdef HARD_CS_NSS0 //spi_enable_peripheral_select_decode(SPI_MASTER_BASE); //spi_set_peripheral_chip_select_value(SPI_MASTER_BASE, SPI_CHIP_SEL); spi_set_peripheral_chip_select_value(SPI_MASTER_BASE, SPI_CHIP_PCS); //use soft nss comment here #endif spi_set_clock_polarity(SPI_MASTER_BASE, SPI_CHIP_SEL, SPI_CLK_POLARITY); spi_set_clock_phase(SPI_MASTER_BASE, SPI_CHIP_SEL, SPI_CLK_PHASE); spi_set_bits_per_transfer(SPI_MASTER_BASE, SPI_CHIP_SEL, SPI_CSR_BITS_8_BIT); spi_set_baudrate_div(SPI_MASTER_BASE, SPI_CHIP_SEL, (sysclk_get_cpu_hz() / SPI_BAUD_RATE)); spi_set_transfer_delay(SPI_MASTER_BASE, SPI_CHIP_SEL, SPI_DLYBS, SPI_DLYBCT); /* Must be lower priority than the value of configMAX_SYSCALL_INTERRUPT_PRIORITY */ /* otherwise FreeRTOS will not be able to mask the interrupt */ /* keep in mind that ARMCM3 interrupt priority logic is inverted, the highest value */ /* is the lowest priority */ /* Configure SPI interrupts . */ spi_enable_interrupt(SPI_MASTER_BASE, SPI_IER_RXBUFF); //spi_enable_interrupt(SPI_MASTER_BASE, SPI_IER_NSSR | SPI_IER_RXBUFF); NVIC_DisableIRQ(SPI_IRQn); //irq_register_handler(SPI_IRQn, 3); NVIC_ClearPendingIRQ(SPI_IRQn); NVIC_SetPriority(SPI_IRQn, 3); NVIC_EnableIRQ(SPI_IRQn); spi_enable(SPI_MASTER_BASE); #else spi.baudrate = SPI_BAUD_RATE; if (STATUS_OK != spi_master_vec_init(&spi_master, SPI_MASTER_BASE, &spi)) { return -1; } spi_master_vec_enable(&spi_master); #endif //if (!Is_global_interrupt_enabled()) // Enable_global_interrupt(); MCU_CLOCKS_NOT_NEEDED(); return kNoErr; }
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(¤tTime)); micoWlanGetIPStatus(¶, Station); formatMACAddr(context->micoStatus.mac, (char *)¶.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; }
OSStatus host_platform_bus_init( void ) { SPI_InitTypeDef spi_init; DMA_InitTypeDef dma_init_structure; uint32_t a; platform_mcu_powersave_disable(); mico_rtos_init_semaphore(&spi_transfer_finished_semaphore, 1); /* Enable SPI_SLAVE DMA clock */ if ( wifi_spi.tx_dma.controller == DMA1 ) { RCC->AHB1ENR |= RCC_AHB1Periph_DMA1; } else { RCC->AHB1ENR |= RCC_AHB1Periph_DMA2; } if ( wifi_spi.rx_dma.controller == DMA1 ) { RCC->AHB1ENR |= RCC_AHB1Periph_DMA1; } else { RCC->AHB1ENR |= RCC_AHB1Periph_DMA2; } /* Enable SPI_SLAVE Periph clock */ (wifi_spi.peripheral_clock_func)( wifi_spi.peripheral_clock_reg, ENABLE ); /* Enable SYSCFG. Needed for selecting EXTI interrupt line */ RCC_APB2PeriphClockCmd( RCC_APB2Periph_SYSCFG, ENABLE ); /* Setup the interrupt input for WLAN_IRQ */ platform_gpio_init( &wifi_spi_pins[WIFI_PIN_SPI_IRQ], INPUT_HIGH_IMPEDANCE ); platform_gpio_irq_enable( &wifi_spi_pins[WIFI_PIN_SPI_IRQ], IRQ_TRIGGER_RISING_EDGE, spi_irq_handler, 0 ); /* Setup SPI slave select GPIOs */ platform_gpio_init( &wifi_spi_pins[WIFI_PIN_SPI_CS], OUTPUT_PUSH_PULL ); platform_gpio_output_high( &wifi_spi_pins[WIFI_PIN_SPI_CS] ); /* Setup the SPI lines */ for ( a = WIFI_PIN_SPI_CLK; a < WIFI_PIN_SPI_MAX; a++ ) { platform_gpio_set_alternate_function( wifi_spi_pins[ a ].port, wifi_spi_pins[ a ].pin_number, GPIO_OType_PP, GPIO_PuPd_NOPULL, wifi_spi.gpio_af ); } #if defined ( MICO_WIFI_USE_GPIO_FOR_BOOTSTRAP ) /* Set GPIO_B[1:0] to 01 to put WLAN module into gSPI mode */ platform_gpio_init( &wifi_control_pins[WIFI_PIN_BOOTSTRAP_0], OUTPUT_PUSH_PULL ); platform_gpio_output_high( &wifi_control_pins[WIFI_PIN_BOOTSTRAP_0] ); platform_gpio_init( &wifi_control_pins[WIFI_PIN_BOOTSTRAP_1], OUTPUT_PUSH_PULL ); platform_gpio_output_low( &wifi_control_pins[WIFI_PIN_BOOTSTRAP_1] ); #endif /* Setup DMA for SPIX RX */ DMA_DeInit( wifi_spi.rx_dma.stream ); dma_init_structure.DMA_Channel = wifi_spi.rx_dma.channel; dma_init_structure.DMA_PeripheralBaseAddr = (uint32_t) &(wifi_spi.port->DR); dma_init_structure.DMA_Memory0BaseAddr = 0; dma_init_structure.DMA_DIR = DMA_DIR_PeripheralToMemory; dma_init_structure.DMA_BufferSize = 0; dma_init_structure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; dma_init_structure.DMA_MemoryInc = DMA_MemoryInc_Enable; dma_init_structure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; dma_init_structure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; dma_init_structure.DMA_Mode = DMA_Mode_Normal; dma_init_structure.DMA_Priority = DMA_Priority_VeryHigh; dma_init_structure.DMA_FIFOMode = DMA_FIFOMode_Disable; dma_init_structure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full; dma_init_structure.DMA_MemoryBurst = DMA_MemoryBurst_Single; dma_init_structure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_Init( wifi_spi.rx_dma.stream, &dma_init_structure ); /* Setup DMA for SPIX TX */ DMA_DeInit( wifi_spi.tx_dma.stream ); dma_init_structure.DMA_Channel = wifi_spi.tx_dma.channel; dma_init_structure.DMA_PeripheralBaseAddr = (uint32_t) &(wifi_spi.port->DR); dma_init_structure.DMA_Memory0BaseAddr = 0; dma_init_structure.DMA_DIR = DMA_DIR_MemoryToPeripheral; dma_init_structure.DMA_BufferSize = 0; dma_init_structure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; dma_init_structure.DMA_MemoryInc = DMA_MemoryInc_Enable; dma_init_structure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; dma_init_structure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; dma_init_structure.DMA_Mode = DMA_Mode_Normal; dma_init_structure.DMA_Priority = DMA_Priority_VeryHigh; dma_init_structure.DMA_FIFOMode = DMA_FIFOMode_Disable; dma_init_structure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full; dma_init_structure.DMA_MemoryBurst = DMA_MemoryBurst_Single; dma_init_structure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_Init( wifi_spi.tx_dma.stream, &dma_init_structure ); /* Must be lower priority than the value of configMAX_SYSCALL_INTERRUPT_PRIORITY */ /* otherwise FreeRTOS will not be able to mask the interrupt */ /* keep in mind that ARMCM3 interrupt priority logic is inverted, the highest value */ /* is the lowest priority */ NVIC_EnableIRQ( wifi_spi.rx_dma.irq_vector ); /* Enable DMA for TX */ SPI_I2S_DMACmd( wifi_spi.port, SPI_I2S_DMAReq_Tx | SPI_I2S_DMAReq_Rx, ENABLE ); /* Setup SPI */ spi_init.SPI_Direction = SPI_Direction_2Lines_FullDuplex; spi_init.SPI_Mode = SPI_Mode_Master; spi_init.SPI_DataSize = SPI_DataSize_8b; spi_init.SPI_CPOL = SPI_CPOL_High; spi_init.SPI_CPHA = SPI_CPHA_2Edge; spi_init.SPI_NSS = SPI_NSS_Soft; spi_init.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2; spi_init.SPI_FirstBit = SPI_FirstBit_MSB; spi_init.SPI_CRCPolynomial = (uint16_t) 7; /* Init SPI and enable it */ SPI_Init( wifi_spi.port, &spi_init ); SPI_Cmd( wifi_spi.port, ENABLE ); platform_mcu_powersave_enable(); return kNoErr; }
void MVDMainThread(void *arg) { OSStatus err = kUnknownErr; mico_Context_t *inContext = (mico_Context_t *)arg; bool connected = false; MVDOTARequestData_t devOTARequestData; MVDActivateRequestData_t devDefaultActivateData; mvd_log("MVD main thread start."); while(kNoErr != mico_rtos_get_semaphore(&_wifi_station_on_sem, MICO_WAIT_FOREVER)); /* check reset cloud info */ if((inContext->flashContentInRam.appConfig.virtualDevConfig.needCloudReset) && (inContext->flashContentInRam.appConfig.virtualDevConfig.isActivated)){ // start a thread to reset device info on EasyCloud mico_rtos_init_semaphore(&_reset_cloud_info_sem, 1); mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY, "MVDResetCloudInfo", MVDDevCloudInfoResetThread, 0x800, inContext ); err = mico_rtos_get_semaphore(&_reset_cloud_info_sem, MICO_WAIT_FOREVER); if(kNoErr == err){ mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex); inContext->flashContentInRam.appConfig.virtualDevConfig.needCloudReset = false; inContext->flashContentInRam.appConfig.virtualDevConfig.isActivated = false; err = MICOUpdateConfiguration(inContext); mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex); mvd_log("MVD Cloud reset success!"); } else{ mvd_log("MVD Cloud reset failed!"); } mvd_log("Press reset button..."); goto exit; // do nothing after reset, please press reset button. } /* OTA check */ //mvd_log(DEFAULT_MVD_OTA_CHECK_MSG_2MCU); MVDDevInterfaceSend(DEFAULT_MVD_OTA_CHECK_MSG_2MCU, strlen(DEFAULT_MVD_OTA_CHECK_MSG_2MCU)); memset((void*)&devOTARequestData, 0, sizeof(devOTARequestData)); strncpy(devOTARequestData.loginId, inContext->flashContentInRam.appConfig.virtualDevConfig.loginId, MAX_SIZE_LOGIN_ID); strncpy(devOTARequestData.devPasswd, inContext->flashContentInRam.appConfig.virtualDevConfig.devPasswd, MAX_SIZE_DEV_PASSWD); strncpy(devOTARequestData.user_token, inContext->micoStatus.mac, MAX_SIZE_USER_TOKEN); err = MVDCloudInterfaceDevFirmwareUpdate(inContext, devOTARequestData); if(kNoErr == err){ if(inContext->appStatus.virtualDevStatus.RecvRomFileSize > 0){ //mvd_log(DEFAULT_MVD_OTA_UPDATE_MSG_2MCU); MVDDevInterfaceSend(DEFAULT_MVD_OTA_UPDATE_MSG_2MCU, strlen(DEFAULT_MVD_OTA_UPDATE_MSG_2MCU)); // set bootloader to reboot && update app fw memset(&inContext->flashContentInRam.bootTable, 0, sizeof(boot_table_t)); inContext->flashContentInRam.bootTable.length = inContext->appStatus.virtualDevStatus.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); 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{ //mvd_log(DEFAULT_MVD_OTA_UP_TO_DATE_MSG_2MCU); MVDDevInterfaceSend(DEFAULT_MVD_OTA_UP_TO_DATE_MSG_2MCU, strlen(DEFAULT_MVD_OTA_UP_TO_DATE_MSG_2MCU)); } } else{ //mvd_log(DEFAULT_MVD_OTA_DOWNLOAD_FAILED_MSG_2MCU); MVDDevInterfaceSend(DEFAULT_MVD_OTA_DOWNLOAD_FAILED_MSG_2MCU, strlen(DEFAULT_MVD_OTA_DOWNLOAD_FAILED_MSG_2MCU)); } /* activate when wifi on */ while(false == inContext->flashContentInRam.appConfig.virtualDevConfig.isActivated){ // auto activate, using default login_id/dev_pass/user_token //mvd_log(DEFAULT_MVD_DEV_ACTIVATE_START_MSG_2MCU); MVDDevInterfaceSend(DEFAULT_MVD_DEV_ACTIVATE_START_MSG_2MCU, strlen(DEFAULT_MVD_DEV_ACTIVATE_START_MSG_2MCU)); memset((void*)&devDefaultActivateData, 0, sizeof(devDefaultActivateData)); strncpy(devDefaultActivateData.loginId, inContext->flashContentInRam.appConfig.virtualDevConfig.loginId, MAX_SIZE_LOGIN_ID); strncpy(devDefaultActivateData.devPasswd, inContext->flashContentInRam.appConfig.virtualDevConfig.devPasswd, MAX_SIZE_DEV_PASSWD); strncpy(devDefaultActivateData.user_token, inContext->micoStatus.mac, MAX_SIZE_USER_TOKEN); err = MVDCloudInterfaceDevActivate(inContext, devDefaultActivateData); if(kNoErr == err){ //mvd_log("device activate success!"); MVDDevInterfaceSend(DEFAULT_MVD_DEV_ACTIVATE_OK_MSG_2MCU, strlen(DEFAULT_MVD_DEV_ACTIVATE_OK_MSG_2MCU)); } else{ //mvd_log("device activate failed, err = %d, retry in %d s ...", err, 1); MVDDevInterfaceSend(DEFAULT_MVD_DEV_ACTIVATE_FAILED_MSG_2MCU, strlen(DEFAULT_MVD_DEV_ACTIVATE_FAILED_MSG_2MCU)); } mico_thread_sleep(1); } mvd_log("[MVD]device already activated."); /* start EasyCloud service */ err = MVDCloudInterfaceStart(inContext); require_noerr_action(err, exit, mvd_log("ERROR: MVDCloudInterfaceStart failed!") ); /* loop connect status */ while(1) { if(inContext->appStatus.virtualDevStatus.isCloudConnected){ if (!connected){ connected = true; // set LED to blue means cloud connected, data: on/off,H,S,B LedControlMsgHandler("1,240,100,100", strlen("1,240,100,100")); //mvd_log("[MVD]Cloud: connected"); MVDDevInterfaceSend(DEFAULT_MVD_CLOUD_CONNECTED_MSG_2MCU, strlen(DEFAULT_MVD_CLOUD_CONNECTED_MSG_2MCU)); MVDCloudInterfaceSendtoChannel(PUBLISH_TOPIC_CHANNEL_STATUS, DEFAULT_MVD_CLOUD_CONNECTED_MSG_2CLOUD, strlen(DEFAULT_MVD_CLOUD_CONNECTED_MSG_2CLOUD)); } } else{ if (connected){ connected = false; // white means cloud disconnect. LedControlMsgHandler("1,0,0,10", strlen("1,0,0,10")); mvd_log("[MVD]cloud service disconnected!"); //mvd_log("[MVD]Cloud: disconnected"); MVDDevInterfaceSend(DEFAULT_MVD_CLOUD_DISCONNECTED_MSG_2MCU, strlen(DEFAULT_MVD_CLOUD_DISCONNECTED_MSG_2MCU)); } } mico_thread_sleep(1); } exit: mvd_log("[MVD]MVDMainThread exit err=%d.", err); mico_rtos_delete_thread(NULL); return; }