OSStatus platform_random_number_read( void *inBuffer, int inByteCount ) { // PLATFORM_TO_DO // PLATFORM_TO_DO int idx; uint32_t *pWord = inBuffer; uint32_t tempRDM; uint8_t *pByte = NULL; int inWordCount; int remainByteCount; inWordCount = inByteCount/4; remainByteCount = inByteCount%4; pByte = (uint8_t *)pWord+inWordCount*4; for(idx = 0; idx<inWordCount; idx++, pWord++){ srand(mico_get_time()); *pWord = rand(); } if(remainByteCount){ srand(mico_get_time()); tempRDM = rand(); memcpy(pByte, &tempRDM, (size_t)remainByteCount); } return kNoErr; }
//ftp.chdir([dir]) //=================================== static int lftp_chdir( lua_State* L ) { if ( (gL == NULL) || (ftpCmdSocket == NULL) || (!(status & FTP_LOGGED)) ) { ftp_log("[FTP usr] Login first\r\n" ); lua_pushinteger(L, -1); return 1; } _getFName(L, 1); free(ftpresponse); ftpresponse = NULL; cmd_done = 0; uint32_t tmo = mico_get_time(); ftpCmdSocket->clientFlag = REQ_ACTION_CHDIR; while (cmd_done == 0) { if ((mico_get_time() - tmo) > 4000) break; mico_thread_msleep(60); luaWdgReload(); } if (cmd_done == 0) { ftp_log("[FTP usr] Timeout\r\n" ); lua_pushinteger(L, -2); return 1; } lua_pushinteger(L, 0); if (ftpresponse != NULL) { lua_pushstring(L, ftpresponse); free(ftpresponse); ftpresponse = NULL; } else lua_pushstring(L, "?"); return 2; }
static void lua_usr_usart_thread(void *data) { uint16_t len=0,index=0; uint32_t lastTick=0; while(1) { if((len=MicoUartGetLengthInBuffer(LUA_USR_UART))==0) { if(index>0 && mico_get_time() - lastTick>=100) goto doUartData; mico_thread_msleep(10); continue; } if(index ==0) lastTick = mico_get_time(); if(index+len>=USR_UART_LENGTH) len = USR_UART_LENGTH - index; MicoUartRecv(LUA_USR_UART, pinbuf+index, len, 10); index = index+len;pinbuf[index]=0x00; doUartData: if(index>=USR_UART_LENGTH || mico_get_time() - lastTick>=100) { index = 0; if(usr_uart_cb_ref == LUA_NOREF) continue; lua_rawgeti(gL, LUA_REGISTRYINDEX, usr_uart_cb_ref); lua_pushstring(gL,(char const*)pinbuf); lua_call(gL, 1, 0); } } //mico_rtos_delete_thread(NULL); }
//ftp.stop() //=================================== static int lftp_stop( lua_State* L ) { if ( (ftp_thread_is_started) && (ftpCmdSocket != NULL) ) { ftpCmdSocket->clientFlag = REQ_ACTION_QUIT; if (ftpCmdSocket->disconnect_cb != LUA_NOREF) { lua_pushinteger(L, 0); return 1; } // wait max 10 sec for disconnect uint32_t tmo = mico_get_time(); while (ftp_thread_is_started) { if ((mico_get_time() - tmo) > 10000) break; mico_thread_msleep(100); luaWdgReload(); } if (!ftp_thread_is_started) { _ftp_deinit(0); lua_pushinteger(L, 0); } else lua_pushinteger(L, -1); } else lua_pushinteger(L, 0); return 1; }
//ftp.sendstring(file, str [,append]) //======================================== static int lftp_sendstring( lua_State* L ) { if ((gL != NULL) && (ftpCmdSocket != NULL)) { if ((status & FTP_LOGGED)) { if (lua_gettop(L) >= 3) { send_type = (uint8_t)luaL_checkinteger(L, 3); if (send_type != SEND_APPEND) send_type = SEND_OVERWRITTE; } else send_type = SEND_OVERWRITTE; send_type |= SEND_STRING; if (_getFName(L, 1) < 0) { ftp_log("[FTP fil] File name missing\r\n" ); lua_pushinteger(L, -13); return 1; } size_t len; sendDataBuf = (char*)luaL_checklstring( L, 2, &len ); if (sendDataBuf == NULL) { ftp_log("[FTP fil] Bad string\r\n"); lua_pushinteger(L, -14); } else { file_size = len; data_done = 0; ftpCmdSocket->clientFlag = REQ_ACTION_SEND; uint32_t tmo = mico_get_time(); while (!data_done) { if ((mico_get_time() - tmo) > 10000) break; mico_thread_msleep(60); luaWdgReload(); } if (!data_done) { ftp_log("[FTP usr] Timeout: string not sent\r\n" ); lua_pushinteger(L, -15); } else { ftp_log("[FTP usr] String sent\r\n" ); lua_pushinteger(L, file_status); } sendDataBuf = NULL; } } else { ftp_log("[FTP usr] Not logged\r\n" ); lua_pushinteger(L, -12); } } else { ftp_log("[FTP usr] Login first\r\n" ); lua_pushinteger(L, -11); } return 1; }
//tmr.delay() static int ltmr_delay( lua_State* L ) { uint32_t ms = luaL_checkinteger( L, 1 ); if ( ms <= 0 ) return luaL_error( L, "wrong arg range" ); uint32_t delay_start = mico_get_time(); while(1) { MicoWdgReload(); if(mico_get_time() >= delay_start + ms) break; } return 0; }
//ftp.send(file [,append]) //================================== static int lftp_send( lua_State* L ) { if ( (gL == NULL) || (ftpCmdSocket == NULL) || (!(status & FTP_LOGGED)) ) { ftp_log("[FTP usr] Login first\r\n" ); lua_pushinteger(L, -11); return 1; } if (lua_gettop(L) >= 2) { send_type = (uint8_t)luaL_checkinteger(L, 2); if (send_type != SEND_APPEND) send_type = SEND_OVERWRITTE; } else send_type = SEND_OVERWRITTE; if (_getFName(L, 1) < 0) { ftp_log("[FTP fil] File name missing\r\n" ); lua_pushinteger(L, -12); return 1; } if (_openFile("r") < 0) { lua_pushinteger(L, -13); return 1; } spiffs_stat s; // Get file size SPIFFS_fstat(&fs, file_fd, &s); file_size = s.size; data_done = 0; ftpCmdSocket->clientFlag = REQ_ACTION_SEND; if (ftpCmdSocket->sent_cb == LUA_NOREF) { // no cb function, wait until file received (max 10 sec) uint32_t tmo = mico_get_time(); while (!data_done) { if ((mico_get_time() - tmo) > 10000) break; mico_thread_msleep(60); luaWdgReload(); } if (!data_done) { ftp_log("[FTP usr] Timeout: file not sent\r\n" ); lua_pushinteger(L, -14); } else { ftp_log("[FTP usr] File sent\r\n" ); lua_pushinteger(L, file_status); } } else lua_pushinteger(L, 0); return 1; }
//stat = ftp.start() //=================================== static int lftp_start( lua_State* L ) { LinkStatusTypeDef wifi_link; int err = micoWlanGetLinkStatus( &wifi_link ); if ( wifi_link.is_connected == false ) { ftp_log("[FTP usr] WiFi NOT CONNECTED!\r\n" ); lua_pushinteger(L, -1); return 1; } if ( (gL == NULL) || (ftpCmdSocket == NULL) ) { ftp_log("[FTP usr] Execute ftp.new first!\r\n" ); lua_pushinteger(L, -2); return 1; } if (ftp_thread_is_started) { ftp_log("[FTP usr] Already started!\r\n" ); lua_pushinteger(L, -3); return 1; } mico_system_notify_register( mico_notify_TCP_CLIENT_CONNECTED, (void *)_micoNotify_FTPClientConnectedHandler, NULL ); // all setup, start the ftp thread if (!ftp_thread_is_started) { if (mico_rtos_create_thread(NULL, MICO_APPLICATION_PRIORITY-1, "Ftp_Thread", _thread_ftp, 1024, NULL) != kNoErr) { _ftp_deinit(0); ftp_log("[FTP usr] Create thread failed\r\n" ); lua_pushinteger(L, -4); return 1; } else ftp_thread_is_started = true; } if (ftpCmdSocket->logon_cb != LUA_NOREF) { lua_pushinteger(L, 0); return 1; } // wait max 10 sec for login uint32_t tmo = mico_get_time(); while ( (ftp_thread_is_started) && !(status & FTP_LOGGED) ) { if ((mico_get_time() - tmo) > 10000) break; mico_thread_msleep(100); luaWdgReload(); } if (!(status & FTP_LOGGED)) lua_pushinteger(L, -4); else lua_pushinteger(L, 0); return 1; }
//ftp.recv(file [,tostr]) //=================================== static int lftp_recv( lua_State* L ) { if ( (gL == NULL) || (ftpCmdSocket == NULL) || (!(status & FTP_LOGGED)) ) { ftp_log("[FTP usr] Login first\r\n" ); lua_pushinteger(L, -11); return 1; } if (_getFName(L, 1) < 0) { ftp_log("[FTP fil] File name missing\r\n" ); lua_pushinteger(L, -12); return 1; } if (_openFile("w") < 0) { lua_pushinteger(L, -13); return 1; } recv_type = RECV_TOFILE; if (lua_gettop(L) >= 2) { int tos = luaL_checkinteger(L, 2); if (tos == 1) recv_type = RECV_TOSTRING; } data_done = 0; ftpCmdSocket->clientFlag = REQ_ACTION_RECV; if (ftpCmdSocket->received_cb == LUA_NOREF) { // no cb function, wait until file received (max 10 sec) uint32_t tmo = mico_get_time(); while (!data_done) { if ((mico_get_time() - tmo) > 10000) break; mico_thread_msleep(60); luaWdgReload(); } if (!data_done) { ftp_log("[FTP usr] Timeout: file not received\r\n" ); lua_pushinteger(L, -14); } else { ftp_log("[FTP usr] File received\r\n" ); lua_pushinteger(L, file_status); if (recv_type == RECV_TOSTRING) { lua_pushstring(L, recvDataBuf); return 2; } } } else lua_pushinteger(L, 0); return 1; }
void mico_system_monitor_thread_main( void* arg ) { (void)arg; while (1) { int a; uint32_t current_time = mico_get_time(); for (a = 0; a < MAXIMUM_NUMBER_OF_SYSTEM_MONITORS; ++a) { if (system_monitors[a] != NULL) { if ((current_time - system_monitors[a]->last_update) > system_monitors[a]->longest_permitted_delay) { /* A system monitor update period has been missed */ while(1); } } } MicoWdgReload(); mico_thread_msleep(DEFAULT_SYSTEM_MONITOR_PERIOD); } }
//=================================== static int mcu_random( lua_State* L ) { int randn, minn, maxn; uint16_t i; uint8_t sd = 0; maxn = 0x7FFFFFFE; minn = 0; if (lua_gettop(L) >= 1) maxn = luaL_checkinteger( L, 1 ); if (lua_gettop(L) >= 2) minn = luaL_checkinteger( L, 2 ); if (lua_gettop(L) >= 3) sd = luaL_checkinteger( L, 3 ); if (maxn < minn) maxn = minn+1; if (maxn <= 0) maxn = 1; if (sd) srand(mico_get_time()); i = 0; do { //MicoRandomNumberRead(&rbuf, n); randn = rand(); if (randn > maxn) randn = randn % (maxn+1); i++; } while ((i < 10000) && (randn < minn)); if (randn < minn) randn = minn; lua_pushinteger(L,randn); return 1; }
static void _button_EL_irq_handler( void* arg ) { (void)(arg); if (GPIO_ReadInputDataBit(Button_EL_PORT, Button_EL_PIN) == 0) { _default_start_time = mico_get_time()+1; mico_start_timer(&_button_EL_timer); } else { if ( (_default_start_time != 0) && (mico_get_time() - _default_start_time) > 50){ /* EasyLink button clicked once */ PlatformEasyLinkButtonClickedCallback(); } mico_stop_timer(&_button_EL_timer); _default_start_time = 0; } }
static void _button_EL_irq_handler( void* arg ) { (void)(arg); int interval = -1; if (GPIO_ReadInputDataBit(Button_EL_PORT, Button_EL_PIN) == 0) { _default_start_time = mico_get_time()+1; mico_start_timer(&_button_EL_timer); } else { interval = mico_get_time() + 1 - _default_start_time; if ( (_default_start_time != 0) && interval > 50 && interval < RestoreDefault_TimeOut){ /* EasyLink button clicked once */ PlatformEasyLinkButtonClickedCallback(); } mico_stop_timer(&_button_EL_timer); _default_start_time = 0; } }
static void _user_key2_irq_handler( void* arg ) { (void)(arg); int interval = -1; if ( MicoGpioInputGet( (mico_gpio_t)USER_KEY2 ) == 0 ) { _default_key2_start_time = mico_get_time()+1; mico_start_timer(&_user_key2_timer); } else { interval = mico_get_time() + 1 - _default_key2_start_time; if ( (_default_key2_start_time != 0) && interval > 50 && interval < user_key2_long_press_timeout){ /* button clicked once */ user_key2_clicked_callback(); } mico_stop_timer(&_user_key2_timer); _default_key2_start_time = 0; } }
static void _button_EL_irq_handler( void* arg ) { (void)(arg); int interval = -1; if ( MicoGpioInputGet( (mico_gpio_t)EasyLink_BUTTON ) == 0 ) { _default_start_time = mico_get_time()+1; mico_start_timer(&_button_EL_timer); } else { interval = mico_get_time() + 1 - _default_start_time; if ( (_default_start_time != 0) && interval > 50 && interval < RestoreDefault_TimeOut){ /* EasyLink button clicked once */ PlatformEasyLinkButtonClickedCallback(); } mico_stop_timer(&_button_EL_timer); _default_start_time = 0; } }
LUALIB_API int luaopen_mcu(lua_State *L) { srand(mico_get_time()); #if LUA_OPTIMIZE_MEMORY > 0 return 0; #else luaL_register( L, EXLIB_MCU, mcu_map ); return 1; #endif }
//=================================== static int lwifi_scan( lua_State* L ) { OSStatus err = 0; int tmo = mico_get_time(); wifi_scanned_print = 0; if (lua_type(L, 1) == LUA_TFUNCTION || lua_type(L, 1) == LUA_TLIGHTFUNCTION) { lua_pushvalue(L, 1); // copy argument (func) to the top of stack if (wifi_scan_succeed != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, wifi_scan_succeed); wifi_scan_succeed = luaL_ref(L, LUA_REGISTRYINDEX); } else { if (wifi_scan_succeed != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, wifi_scan_succeed); wifi_scan_succeed = LUA_NOREF; if (lua_type(L, 1) == LUA_TNUMBER) { int prn = luaL_checkinteger( L, 1 ); if (prn == 1) wifi_scanned_print = 1; } } err = mico_system_notify_register( mico_notify_WIFI_SCAN_ADV_COMPLETED, (void *)_micoNotify_WiFi_Scan_OK, NULL ); require_noerr( err, exit ); gL = L; wifi_scanned = 0; micoWlanStartScanAdv(); tmo = mico_get_time(); if (wifi_scan_succeed == LUA_NOREF) { while (wifi_scanned == 0) { if ((mico_get_time() - tmo) > 8000) break; mico_thread_msleep(100); luaWdgReload(); } if ((wifi_scanned == 1) && (wifi_scanned_print == 0)) { return 2; } } exit: return 0; }
static void _user_key1_irq_handler( void* arg ) { (void)(arg); int interval = -1; if ( MicoGpioInputGet( (mico_gpio_t)USER_KEY1 ) == 0 ) { MicoGpioEnableIRQ( (mico_gpio_t)USER_KEY1, IRQ_TRIGGER_RISING_EDGE, _user_key1_irq_handler, NULL ); _default_key1_start_time = mico_get_time()+1; mico_start_timer(&_user_key1_timer); } else { interval = mico_get_time() + 1 - _default_key1_start_time; if ( (_default_key1_start_time != 0) && interval > 50 && interval < user_key1_long_press_timeout){ /* button clicked once */ user_key1_clicked_callback(); } MicoGpioEnableIRQ( (mico_gpio_t)USER_KEY1, IRQ_TRIGGER_FALLING_EDGE, _user_key1_irq_handler, NULL ); mico_stop_timer(&_user_key1_timer); _default_key1_start_time = 0; } }
OSStatus MICOUpdateSystemMonitor(mico_system_monitor_t* system_monitor, uint32_t permitted_delay) { uint32_t current_time = mico_get_time(); /* Update the system monitor if it hasn't already passed it's permitted delay */ if ((current_time - system_monitor->last_update) <= system_monitor->longest_permitted_delay) { system_monitor->last_update = current_time; system_monitor->longest_permitted_delay = permitted_delay; } return kNoErr; }
static void button_irq_handler( void* arg ) { button_context_t *_context = arg; int interval = -1; if ( MicoGpioInputGet( _context->gpio ) == 0 ) { MicoGpioEnableIRQ( _context->gpio, IRQ_TRIGGER_RISING_EDGE, button_irq_handler, _context ); _context->start_time = mico_get_time()+1; mico_start_timer(&_context->_user_button_timer); } else { interval = mico_get_time() + 1 - _context->start_time ; if ( (_context->start_time != 0) && interval > 50 && interval < _context->timeout){ /* button clicked once */ if( _context->pressed_func != NULL ) (_context->pressed_func)(); } MicoGpioEnableIRQ( _context->gpio, IRQ_TRIGGER_FALLING_EDGE, button_irq_handler, _context ); mico_stop_timer(&_context->_user_button_timer); _context->start_time = 0; } }
static void _button_EL_irq_handler( void* arg ) { (void)(arg); int interval = -1; mico_start_timer(&_button_EL_timer); if ( MicoGpioInputGet( (mico_gpio_t)EasyLink_BUTTON ) == 0 ) { _default_start_time = mico_get_time()+1; mico_start_timer(&_button_EL_timer); MicoGpioEnableIRQ( (mico_gpio_t)EasyLink_BUTTON, IRQ_TRIGGER_RISING_EDGE, _button_EL_irq_handler, NULL ); } else { interval = mico_get_time() + 1 - _default_start_time; if ( (_default_start_time != 0) && interval > 50 && interval < RestoreDefault_TimeOut){ /* EasyLink button clicked once */ PlatformEasyLinkButtonClickedCallback(); //platform_log("PlatformEasyLinkButtonClickedCallback!"); MicoGpioOutputLow( (mico_gpio_t)MICO_RF_LED ); MicoGpioEnableIRQ( (mico_gpio_t)EasyLink_BUTTON, IRQ_TRIGGER_FALLING_EDGE, _button_EL_irq_handler, NULL ); } mico_stop_timer(&_button_EL_timer); _default_start_time = 0; } }
OSStatus MICORegisterSystemMonitor(mico_system_monitor_t* system_monitor, uint32_t initial_permitted_delay) { int a; /* Find spare entry and add the new system monitor */ for ( a = 0; a < MAXIMUM_NUMBER_OF_SYSTEM_MONITORS; ++a ) { if (system_monitors[a] == NULL) { system_monitor->last_update = mico_get_time(); system_monitor->longest_permitted_delay = initial_permitted_delay; system_monitors[a] = system_monitor; return kNoErr; } } return kUnknownErr; }
void EasyLinkNotify_EasyLinkCompleteHandler(network_InitTypeDef_st *nwkpara, mico_Context_t * const inContext) { OSStatus err; easylink_log_trace(); easylink_log("EasyLink return @ %d", mico_get_time()); require_action(inContext, exit, err = kParamErr); require_action(nwkpara, exit, err = kTimeoutErr); mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex); memcpy(inContext->flashContentInRam.micoSystemConfig.ssid, nwkpara->wifi_ssid, maxSsidLen); memcpy(inContext->flashContentInRam.micoSystemConfig.user_key, nwkpara->wifi_key, maxKeyLen); inContext->flashContentInRam.micoSystemConfig.user_keyLength = strlen(nwkpara->wifi_key); mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex); easylink_log("Get SSID: %s, Key: %s", inContext->flashContentInRam.micoSystemConfig.ssid, inContext->flashContentInRam.micoSystemConfig.user_key); return; /*EasyLink is not start*/ exit: easylink_log("ERROR, err: %d", err); #if defined (CONFIG_MODE_EASYLINK_WITH_SOFTAP) EasylinkFailed = true; mico_rtos_set_semaphore(&inContext->micoStatus.easylink_sem); #else ConfigWillStop(inContext); /*so roll back to previous settings (if it has) and reboot*/ mico_rtos_lock_mutex(&inContext->flashContentInRam_mutex); if(inContext->flashContentInRam.micoSystemConfig.configured != unConfigured){ inContext->flashContentInRam.micoSystemConfig.configured = allConfigured; MICOUpdateConfiguration(inContext); PlatformSoftReboot(); } mico_rtos_unlock_mutex(&inContext->flashContentInRam_mutex); /*module should powd down in default setting*/ wifi_power_down(); mico_stop_timer(&_Led_EL_timer); Platform_LED_SYS_Set_Status(OFF); #endif return; }
int application_start( void ) { char time[16]={0}; ext_oled_log("OLED control demo!"); /*Init Organic Light-Emitting Diode*/ OLED_Init(); /*Starting position display string at the first row*/ OLED_ShowString(0, 0, "MXCHIP Inc."); /*Starting position display string at the second row*/ OLED_ShowString(0, 2, "MiCO run time:"); while(1) { memset(time, 0, sizeof(time)); /*Gets time in miiliseconds since MiCO RTOS start*/ sprintf(time, "%d ms", mico_get_time()); /*Starting position display time at the third row*/ OLED_ShowString(0, 4, (uint8_t *)time); mico_thread_sleep(1); } //OLED_Clear(); return 1; }
//tmr.tick() static int ltmr_tick( lua_State* L ) { uint32_t tick = mico_get_time(); lua_pushinteger( L, tick ); return 1; }
static unsigned long wait_mode_power_down_hook( unsigned long delay_ms ) { bool jtag_enabled = ( ( CoreDebug ->DHCSR & CoreDebug_DEMCR_TRCENA_Msk ) != 0 ) ? true : false; bool jtag_delay_elapsed = ( mico_get_time() > JTAG_DEBUG_SLEEP_DELAY_MS ) ? true : false; uint32_t elapsed_cycles = 0; /* Criteria to enter WAIT mode * 1. Clock needed counter is 0 and no JTAG debugging * 2. Clock needed counter is 0, in JTAG debugging session, and MiCO system tick has progressed over 3 seconds. * This is to give OpenOCD enough time to poke the JTAG tap before the CPU enters WAIT mode. */ if ( ( samg5x_clock_needed_counter == 0 ) && ( ( jtag_enabled == false ) || ( ( jtag_enabled == true ) && ( jtag_delay_elapsed == true ) ) ) ) { uint32_t total_sleep_cycles; uint32_t total_delay_cycles; /* Start real-time timer */ rtt_init( RTT, RTT_CLOCK_PRESCALER ); /* Start atomic operation */ DISABLE_INTERRUPTS; /* Ensure deep sleep bit is enabled, otherwise system doesn't go into deep sleep */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* Disable SysTick */ SysTick->CTRL &= ( ~( SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk ) ); /* End atomic operation */ ENABLE_INTERRUPTS; /* Expected total time CPU executing in this function (including WAIT mode time) */ total_sleep_cycles = MS_TO_CYCLES( delay_ms ); /* Total cycles in WAIT mode loop */ total_delay_cycles = ( total_sleep_cycles / RTT_MAX_CYCLES + 1 ) * RC_OSC_DELAY_CYCLES + WAIT_MODE_ENTER_DELAY_CYCLES + WAIT_MODE_EXIT_DELAY_CYCLES; if ( total_sleep_cycles > total_delay_cycles ) { /* Adjust total sleep cycle to exclude exit delay */ total_sleep_cycles -= WAIT_MODE_EXIT_DELAY_CYCLES; /* Prepare platform specific settings before entering powersave */ // platform_enter_powersave(); ///* Prepare WLAN bus before entering powersave */ //platform_bus_enter_powersave(); /* Disable brownout detector */ supc_disable_brownout_detector( SUPC ); /* Backup system I/0 functions and set all to GPIO to save power */ system_io_backup_value = matrix_get_system_io(); matrix_set_system_io( 0x0CF0 ); /* Switch Master Clock to Main Clock (internal fast RC oscillator) */ pmc_switch_mck_to_mainck( PMC_PCK_PRES_CLK_1 ); /* Switch on internal fast RC oscillator, switch Main Clock source to internal fast RC oscillator and disables external fast crystal */ pmc_switch_mainck_to_fastrc( CKGR_MOR_MOSCRCF_8_MHz ); /* Disable external fast crystal */ pmc_osc_disable_xtal( 0 ); /* Disable PLLA */ pmc_disable_pllack( ); /* This above process introduces certain delay. Add delay to the elapsed cycles */ elapsed_cycles += rtt_read_timer_value( RTT ); while ( wake_up_interrupt_triggered == false && elapsed_cycles < total_sleep_cycles ) { uint32_t current_sleep_cycles = total_sleep_cycles - elapsed_cycles; /* Start real-time timer and alarm */ rtt_init( RTT, RTT_CLOCK_PRESCALER ); rtt_write_alarm_time( RTT, ( current_sleep_cycles > RTT_MAX_CYCLES ) ? RTT_MAX_CYCLES - RC_OSC_DELAY_CYCLES : current_sleep_cycles - RC_OSC_DELAY_CYCLES ); __asm("wfi"); /* Enter WAIT mode */ //pmc_enable_waitmode(); /* Clear wake-up status */ rtt_get_status( RTT ); /* Add sleep time to the elapsed cycles */ elapsed_cycles += rtt_read_timer_value( RTT ); } /* Re-enable real-time timer to time clock reinitialisation delay */ rtt_init( RTT, RTT_CLOCK_PRESCALER ); /* Reinit fast clock. This takes ~19ms, but the timing has been compensated */ init_clocks(); /* Disable unused clock to save power */ pmc_osc_disable_fastrc(); /* Restore system I/O pins */ matrix_set_system_io( system_io_backup_value ); /* Restore WLAN bus */ //platform_bus_exit_powersave(); // /* Restore platform-specific settings */ // platform_exit_powersave(); /* Add clock reinitialisation delay to elapsed cycles */ elapsed_cycles += rtt_read_timer_value( RTT ); /* Disable RTT to save power */ RTT->RTT_MR = (uint32_t)( 1 << 20 ); } } /* Start atomic operation */ DISABLE_INTERRUPTS; /* Switch SysTick back on */ SysTick->CTRL |= ( SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk ); /* Clear flag indicating interrupt triggered by wake up pin */ wake_up_interrupt_triggered = false; /* End atomic operation */ ENABLE_INTERRUPTS; /* Return total time in milliseconds */ return CYCLES_TO_MS( elapsed_cycles ); }
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(Context->micoStatus.easylink_sem, threadexit, err = kParamErr); if(Context->flashContentInRam.micoSystemConfig.easyLinkEnable != false){ OpenEasylink2_withdata(EasyLink_TimeOut); easylink_log("Start easylink @ %d", mico_get_time()); mico_rtos_get_semaphore(&Context->micoStatus.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(&Context->micoStatus.easylink_sem, ConnectFTC_Timeout); require_noerr(err, reboot); httpHeader = malloc( sizeof( HTTPHeader_t ) ); require_action( httpHeader, threadexit, err = kNoMemoryErr ); HTTPHeaderClear( httpHeader ); t.tv_sec = 100; t.tv_usec = 0; while(1){ if(Context->micoStatus.easylinkClient_fd == -1){ err = _connectFTCServer(inContext, &Context->micoStatus.easylinkClient_fd); require_noerr(err, Reconn); }else{ FD_ZERO(&readfds); FD_SET(Context->micoStatus.easylinkClient_fd, &readfds); err = select(1, &readfds, NULL, NULL, &t); require(err > 0, Reconn); if(FD_ISSET(Context->micoStatus.easylinkClient_fd, &readfds)){ err = SocketReadHTTPHeader( Context->micoStatus.easylinkClient_fd, httpHeader ); switch ( err ) { case kNoErr: // Read the rest of the HTTP body if necessary err = SocketReadHTTPBody( Context->micoStatus.easylinkClient_fd, httpHeader ); require_noerr(err, Reconn); PrintHTTPHeader(httpHeader); // Call the HTTPServer owner back with the acquired HTTP header err = _FTCRespondInComingMessage( Context->micoStatus.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 ); close(Context->micoStatus.easylinkClient_fd); Context->micoStatus.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(); Context->micoStatus.easylink_thread_handler = NULL; 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; }
//====================================== static int lwifi_startap( lua_State* L ) { //4 stations Max network_InitTypeDef_st wNetConfig; size_t len=0; memset(&wNetConfig, 0x0, sizeof(network_InitTypeDef_st)); if (!lua_istable(L, 1)) { // ==== Call without parameters, return status === if (wifi_ap_started == 1) lua_pushboolean(L, true); else lua_pushboolean(L, false); return 1; } //ssid lua_getfield(L, 1, "ssid"); if (!lua_isnil(L, -1)) { if( lua_isstring(L, -1) ) { const char *ssid = luaL_checklstring( L, -1, &len ); if(len >= 32) return luaL_error( L, "ssid: <32" ); strncpy(wNetConfig.wifi_ssid,ssid,len); } else return luaL_error( L, "wrong arg type: ssid" ); } else return luaL_error( L, "arg: ssid needed" ); //pwd lua_getfield(L, 1, "pwd"); if (!lua_isnil(L, -1)) { if( lua_isstring(L, -1) ) { const char *pwd = luaL_checklstring( L, -1, &len ); if (len >= 64) return luaL_error( L, "pwd: <64" ); if (len > 0) strncpy(wNetConfig.wifi_key, pwd, len); else strcpy(wNetConfig.wifi_key, ""); } else return luaL_error( L, "wrong arg type: pwd" ); } else return luaL_error( L, "arg: pwd needed" ); //ip lua_getfield(L, 1, "ip"); if (!lua_isnil(L, -1)) { if( lua_isstring(L, -1) ) { const char *ip = luaL_checklstring( L, -1, &len ); if (len >= 16) return luaL_error( L, "ip: <16" ); if (is_valid_ip(ip) == false) return luaL_error( L, "ip invalid" ); strncpy(wNetConfig.local_ip_addr, ip, len); } else return luaL_error( L, "wrong arg type: ip" ); } else { strcpy(wNetConfig.local_ip_addr, "11.11.11.1"); } //netmask lua_getfield(L, 1, "netmask"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *netmask = luaL_checklstring( L, -1, &len ); if (len >= 16) return luaL_error( L, "netmask: <16" ); if (is_valid_ip(netmask) == false) return luaL_error( L, "netmask invalid" ); strncpy(wNetConfig.net_mask,netmask,len); } else return luaL_error( L, "wrong arg type: netmask" ); } else { strcpy(wNetConfig.net_mask, "255.255.255.0"); } //gateway lua_getfield(L, 1, "gateway"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *gateway = luaL_checklstring( L, -1, &len ); if (len >= 16) return luaL_error( L, "gateway: <16" ); if (is_valid_ip(gateway) == false) return luaL_error( L, "gateway invalid" ); strncpy(wNetConfig.gateway_ip_addr,gateway,len); } else return luaL_error( L, "wrong arg type: gateway" ); } else { strcpy(wNetConfig.gateway_ip_addr,"11.11.11.1"); } //dnsSrv lua_getfield(L, 1, "dnsSrv"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *dnsSrv = luaL_checklstring( L, -1, &len ); if (len >= 16) return luaL_error( L, "dnsSrv: <16" ); if (is_valid_ip(dnsSrv) == false) return luaL_error( L, "dnsSrv invalid" ); strncpy(wNetConfig.dnsServer_ip_addr,dnsSrv,len); } else return luaL_error( L, "wrong arg type: dnsSrv" ); } else { strcpy(wNetConfig.dnsServer_ip_addr, "11.11.11.1"); } //retry_interval signed retry_interval = 0; lua_getfield(L, 1, "retry_interval"); if (!lua_isnil(L, -1)) { retry_interval = (signed)luaL_checknumber( L, -1 ); if (retry_interval < 0) return luaL_error( L, "retry_interval: >=0ms" ); if (retry_interval == 0) retry_interval = 0x7FFFFFFF; } else retry_interval = 1000; wNetConfig.wifi_retry_interval = retry_interval; //notify gL = L; if (wifi_status_changed_AP != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, wifi_status_changed_AP); wifi_status_changed_AP = LUA_NOREF; if (lua_type(L, 2) == LUA_TFUNCTION || lua_type(L, 2) == LUA_TLIGHTFUNCTION) { lua_pushvalue(L, 2); // copy argument (func) to the top of stack if (wifi_status_changed_AP != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, wifi_status_changed_AP); wifi_status_changed_AP = luaL_ref(L, LUA_REGISTRYINDEX); } mico_system_notify_register( mico_notify_WIFI_STATUS_CHANGED, (void *)_micoNotify_WifiStatusHandler, NULL ); //start wifi_ap_started = 0; wNetConfig.dhcpMode = DHCP_Server; wNetConfig.wifi_mode = Soft_AP; micoWlanStart(&wNetConfig); int tmo = mico_get_time(); while (wifi_ap_started == 0) { if ((mico_get_time() - tmo) > 1000) break; mico_thread_msleep(10); luaWdgReload(); } if (wifi_ap_started == 1) lua_pushboolean(L, true); else lua_pushboolean(L, false); return 1; }
uint64_t UpTicks( void ) { return mico_get_time();; }
//======================================= static int lwifi_startsta( lua_State* L ) { LinkStatusTypeDef link; network_InitTypeDef_st wNetConfig; size_t len=0; lua_system_param_t lua_system_param; uint8_t has_default = 0; signed retry_interval = 0; int con_wait = 0; int tmo = mico_get_time(); // check if wifi is already connected memset(&link, 0x00, sizeof(link)); micoWlanGetLinkStatus(&link); if (!lua_istable(L, 1)) { // ==== Call without parameters, return connection status === if (link.is_connected != 0) lua_pushboolean(L, true); else lua_pushboolean(L, false); return 1; } // ==== parameters exists, configure and start ==== if (wifi_sta_started == 1) _stopWifiSta(); memset(&wNetConfig, 0x0, sizeof(network_InitTypeDef_st)); // check if default params exists if (getLua_systemParams(&lua_system_param) == 1) { if ((strlen(lua_system_param.wifi_ssid) > 0) && (strlen(lua_system_param.wifi_key) > 0)) { has_default = 1; } } //wait for connection lua_getfield(L, 1, "wait"); if (!lua_isnil(L, -1)) { int wfc = luaL_checkinteger( L, -1 ); if ((wfc > 0) && (wfc < 16)) con_wait = wfc * 1000; else return luaL_error( L, "wait must be 1 ~ 15"); } //ssid lua_getfield(L, 1, "ssid"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *ssid = luaL_checklstring( L, -1, &len ); if (len >= 32) return luaL_error( L, "ssid: <32" ); strncpy(wNetConfig.wifi_ssid,ssid,len); } else return luaL_error( L, "wrong arg type:ssid" ); } else if (has_default == 1) { strcpy(wNetConfig.wifi_ssid, lua_system_param.wifi_ssid); } else return luaL_error( L, "arg: ssid needed" ); //pwd lua_getfield(L, 1, "pwd"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *pwd = luaL_checklstring( L, -1, &len ); if (len >= 64) return luaL_error( L, "pwd: <64" ); if (len > 0) strncpy(wNetConfig.wifi_key,pwd,len); else strcpy(wNetConfig.wifi_key,""); } else return luaL_error( L, "wrong arg type: pwd" ); } else if (has_default == 1) { strcpy(wNetConfig.wifi_key, lua_system_param.wifi_key); } else return luaL_error( L, "arg: pwd needed" ); //dhcp wNetConfig.dhcpMode = DHCP_Client; lua_getfield(L, 1, "dhcp"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *pwd = luaL_checklstring( L, -1, &len ); if (strcmp(pwd, "disable") == 0) wNetConfig.dhcpMode = DHCP_Disable; } else return luaL_error( L, "wrong arg type: dhcp" ); } //ip lua_getfield(L, 1, "ip"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *ip = luaL_checklstring( L, -1, &len ); if (len >= 16) return luaL_error( L, "ip: <16" ); if (is_valid_ip(ip) == false) return luaL_error( L, "ip invalid" ); strncpy(wNetConfig.local_ip_addr,ip,len); } else return luaL_error( L, "wrong arg type:ip" ); } else if (wNetConfig.dhcpMode == DHCP_Disable) return luaL_error( L, "arg: ip needed" ); //netmask lua_getfield(L, 1, "netmask"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *netmask = luaL_checklstring( L, -1, &len ); if (len >= 16) return luaL_error( L, "netmask: <16" ); if (is_valid_ip(netmask) == false) return luaL_error( L, "netmask invalid" ); strncpy(wNetConfig.net_mask,netmask,len); } else return luaL_error( L, "wrong arg type: netmask" ); } else if (wNetConfig.dhcpMode == DHCP_Disable) return luaL_error( L, "arg: netmask needed" ); //gateway lua_getfield(L, 1, "gateway"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *gateway = luaL_checklstring( L, -1, &len ); if (len >= 16) return luaL_error( L, "gateway: <16" ); if (is_valid_ip(gateway) == false) return luaL_error( L, "gateway invalid" ); strncpy(wNetConfig.gateway_ip_addr,gateway,len); } else return luaL_error( L, "wrong arg type: gateway" ); } else if(wNetConfig.dhcpMode == DHCP_Disable) return luaL_error( L, "arg: gateway needed" ); //dnsSrv lua_getfield(L, 1, "dnsSrv"); if (!lua_isnil(L, -1)) { if ( lua_isstring(L, -1) ) { const char *dnsSrv = luaL_checklstring( L, -1, &len ); if (len >= 16) return luaL_error( L, "dnsSrv: <16" ); if (is_valid_ip(dnsSrv) == false) return luaL_error( L, "dnsSrv invalid" ); strncpy(wNetConfig.dnsServer_ip_addr,dnsSrv,len); } else return luaL_error( L, "wrong arg type: dnsSrv" ); } else if (wNetConfig.dhcpMode == DHCP_Disable) return luaL_error( L, "arg: dnsSrv needed" ); //retry_interval lua_getfield(L, 1, "retry_interval"); if (!lua_isnil(L, -1)) { retry_interval = (signed)luaL_checknumber( L, -1 ); if (retry_interval < 0) return luaL_error( L, "retry_interval: >=0ms" ); if (retry_interval == 0) retry_interval = 0x7FFFFFFF; } else retry_interval = 1000; wNetConfig.wifi_retry_interval = retry_interval; gL = L; //notify, set CB function for wifi state change if (wifi_status_changed_STA != LUA_NOREF) luaL_unref(L, LUA_REGISTRYINDEX, wifi_status_changed_STA); wifi_status_changed_STA = LUA_NOREF; if (lua_type(L, 2) == LUA_TFUNCTION || lua_type(L, 2) == LUA_TLIGHTFUNCTION) { lua_pushvalue(L, 2); // copy argument (func) to the top of stack wifi_status_changed_STA = luaL_ref(L, LUA_REGISTRYINDEX); } mico_system_notify_register( mico_notify_WIFI_STATUS_CHANGED, (void *)_micoNotify_WifiStatusHandler, NULL ); //start wNetConfig.wifi_mode = Station; micoWlanStart(&wNetConfig); wifi_sta_started = 1; if (con_wait == 0) { lua_pushboolean(L, false); return 1; } tmo = mico_get_time(); micoWlanGetLinkStatus(&link); while (link.is_connected == 0) { if ((mico_get_time() - tmo) > con_wait) break; mico_thread_msleep(50); luaWdgReload(); micoWlanGetLinkStatus(&link); } if (link.is_connected == 0) lua_pushboolean(L, false); else lua_pushboolean(L, true); return 1; }