diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..96b776d9 --- /dev/null +++ b/.clang-format @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# Note: The list of ForEachMacros can be obtained using: +# +# git grep -h '^#define [^[:space:]]*FOR_EACH[^[:space:]]*(' include/ \ +# | sed "s,^#define \([^[:space:]]*FOR_EACH[^[:space:]]*\)(.*$, - '\1'," \ +# | sort | uniq +# +# References: +# - https://clang.llvm.org/docs/ClangFormatStyleOptions.html + +--- +BasedOnStyle: LLVM +AlignOperands: Align +BreakBeforeTernaryOperators: false +EmptyLineBeforeAccessModifier: LogicalBlock +AlignConsecutiveMacros: AcrossComments +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AttributeMacros: + - __aligned + - __deprecated + - __packed + - __printf_like + - __syscall + - __syscall_always_inline + - __subsystem +BitFieldColonSpacing: After +BreakBeforeBraces: Attach +ColumnLimit: 100 +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +ForEachMacros: + - 'ARRAY_FOR_EACH' + - 'ARRAY_FOR_EACH_PTR' + - 'FOR_EACH' + - 'FOR_EACH_FIXED_ARG' + - 'FOR_EACH_IDX' + - 'FOR_EACH_IDX_FIXED_ARG' + - 'FOR_EACH_NONEMPTY_TERM' + - 'FOR_EACH_FIXED_ARG_NONEMPTY_TERM' + - 'RB_FOR_EACH' + - 'RB_FOR_EACH_CONTAINER' + - 'SYS_DLIST_FOR_EACH_CONTAINER' + - 'SYS_DLIST_FOR_EACH_CONTAINER_SAFE' + - 'SYS_DLIST_FOR_EACH_NODE' + - 'SYS_DLIST_FOR_EACH_NODE_SAFE' + - 'SYS_SEM_LOCK' + - 'SYS_SFLIST_FOR_EACH_CONTAINER' + - 'SYS_SFLIST_FOR_EACH_CONTAINER_SAFE' + - 'SYS_SFLIST_FOR_EACH_NODE' + - 'SYS_SFLIST_FOR_EACH_NODE_SAFE' + - 'SYS_SLIST_FOR_EACH_CONTAINER' + - 'SYS_SLIST_FOR_EACH_CONTAINER_SAFE' + - 'SYS_SLIST_FOR_EACH_NODE' + - 'SYS_SLIST_FOR_EACH_NODE_SAFE' + - '_WAIT_Q_FOR_EACH' + - 'Z_FOR_EACH' + - 'Z_FOR_EACH_ENGINE' + - 'Z_FOR_EACH_EXEC' + - 'Z_FOR_EACH_FIXED_ARG' + - 'Z_FOR_EACH_FIXED_ARG_EXEC' + - 'Z_FOR_EACH_IDX' + - 'Z_FOR_EACH_IDX_EXEC' + - 'Z_FOR_EACH_IDX_FIXED_ARG' + - 'Z_FOR_EACH_IDX_FIXED_ARG_EXEC' + - 'Z_GENLIST_FOR_EACH_CONTAINER' + - 'Z_GENLIST_FOR_EACH_CONTAINER_SAFE' + - 'Z_GENLIST_FOR_EACH_NODE' + - 'Z_GENLIST_FOR_EACH_NODE_SAFE' + - 'STRUCT_SECTION_FOREACH' + - 'STRUCT_SECTION_FOREACH_ALTERNATE' + - 'TYPE_SECTION_FOREACH' + - 'K_SPINLOCK' + - 'COAP_RESOURCE_FOREACH' + - 'COAP_SERVICE_FOREACH' + - 'COAP_SERVICE_FOREACH_RESOURCE' + - 'HTTP_RESOURCE_FOREACH' + - 'HTTP_SERVER_CONTENT_TYPE_FOREACH' + - 'HTTP_SERVICE_FOREACH' + - 'HTTP_SERVICE_FOREACH_RESOURCE' + - 'I3C_BUS_FOR_EACH_I3CDEV' + - 'I3C_BUS_FOR_EACH_I2CDEV' + - 'MIN_HEAP_FOREACH' +IfMacros: + - 'CHECKIF' +IncludeCategories: + - Regex: '^".*\.h"$' + Priority: 0 + - Regex: '^<(assert|complex|ctype|errno|fenv|float|inttypes|limits|locale|math|setjmp|signal|stdarg|stdbool|stddef|stdint|stdio|stdlib|string|tgmath|time|wchar|wctype)\.h>$' + Priority: 1 + - Regex: '^\$' + Priority: 2 + - Regex: '.*' + Priority: 3 +IndentCaseLabels: false +IndentGotoLabels: true +IndentAccessModifiers: false +AccessModifierOffset: -4 +IndentWidth: 4 +InsertBraces: true +InsertNewlineAtEOF: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SortIncludes: Never +SeparateDefinitionBlocks: Always +UseTab: ForContinuationAndIndentation +TabWidth: 4 +WhitespaceSensitiveMacros: + - COND_CODE_0 + - COND_CODE_1 + - IF_DISABLED + - IF_ENABLED + - LISTIFY + - STRINGIFY + - Z_STRINGIFY + - DT_FOREACH_PROP_ELEM_SEP diff --git a/.github/workflows/checkpatch.yml b/.github/workflows/checkpatch.yml deleted file mode 100644 index 5b4bad13..00000000 --- a/.github/workflows/checkpatch.yml +++ /dev/null @@ -1,31 +0,0 @@ -# This is a basic workflow to help you get started with Actions - -name: checkpatch review - -# Controls when the workflow will run -on: - # Triggers the workflow on push or pull request events but only for the "main" branch - push: - branches: [ "main", "next" ] - pull_request: - branches: [ "main", "next" ] - - # Allows you to run this workflow manually from the Actions tab - workflow_dispatch: - -# A workflow run is made up of one or more jobs that can run sequentially or in parallel -jobs: - my_review: - name: checkpatch review - runs-on: ubuntu-latest - continue-on-error: true - steps: - - name: 'Calculate PR commits + 1' - run: echo "PR_FETCH_DEPTH=$(( ${{ github.event.pull_request.commits }} + 1 ))" >> $GITHUB_ENV - - uses: actions/checkout@v3 - with: - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: ${{ env.PR_FETCH_DEPTH }} - - name: Run checkpatch review - uses: webispy/checkpatch-action@v9 - diff --git a/.github/workflows/commit_check.yml b/.github/workflows/commit_check.yml new file mode 100644 index 00000000..da0408a7 --- /dev/null +++ b/.github/workflows/commit_check.yml @@ -0,0 +1,35 @@ +name: 'Check Commit Message' + +on: + pull_request: + types: + - opened + - edited + - reopened + - synchronize + branches: + - 'main' + +jobs: + check-commit-messages: + runs-on: ubuntu-latest + steps: + - name: 'Check commit messages format' + uses: gsactions/commit-message-checker@v2 + with: + pattern: '^[^!]+: [A-Za-z]+.+ .+$' + flags: 'gm' + error: 'Commit subject line must match the following pattern: : ' + excludeTitle: 'false' + excludeDescription: 'true' + checkAllCommitMessages: 'true' + accessToken: ${{ secrets.GITHUB_TOKEN }} + - name: 'Check commit messages length' + uses: gsactions/commit-message-checker@v2 + with: + pattern: '^[^#].{10,80}$' + error: 'Commit subject line maximum line length of 80 characters is exceeded.' + excludeTitle: 'false' + excludeDescription: 'true' + checkAllCommitMessages: 'true' + accessToken: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/format_check.yml b/.github/workflows/format_check.yml new file mode 100644 index 00000000..e83ca71e --- /dev/null +++ b/.github/workflows/format_check.yml @@ -0,0 +1,60 @@ +name: 'Format Check' + +on: + push: + branches: + - 'main' + paths: + - '**/*.c' + - '**/*.cpp' + - '**/*.h' + - '**/*.hpp' + + pull_request: + types: + - opened + - edited + - reopened + - synchronize + branches: + - 'main' + paths: + - '**/*.c' + - '**/*.cpp' + - '**/*.h' + - '**/*.hpp' + + workflow_dispatch: + inputs: + logLevel: + description: 'Log level' + required: true + default: 'warning' + +jobs: + format-check: + runs-on: ubuntu-latest + strategy: + matrix: + path: + - check: 'cores/arduino/' + exclude: 'cores/arduino/api/' + - check: 'loader/' + exclude: 'loader/llext_exports\.c$' + - check: 'libraries/' + exclude: 'libraries/ea_malloc/' + fail-fast: false + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + submodules: false + persist-credentials: false + + - name: Run clang-format check + uses: jidicula/clang-format-action@v4.15.0 + with: + clang-format-version: '19' + check-path: ${{ matrix.path['check'] }} + exclude-regex: ${{ matrix.path['exclude'] }} diff --git a/cores/arduino/Arduino.h b/cores/arduino/Arduino.h index 0d07764c..588adfdb 100644 --- a/cores/arduino/Arduino.h +++ b/cores/arduino/Arduino.h @@ -25,9 +25,9 @@ /* Check all pins are defined only once */ #define DIGITAL_PIN_CHECK_UNIQUE(i, _) \ - ((DT_FOREACH_PROP_ELEM_SEP_VARGS( \ - DT_PATH(zephyr_user), digital_pin_gpios, DIGITAL_PIN_EXISTS, (+), \ - DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), digital_pin_gpios, i)), \ + ((DT_FOREACH_PROP_ELEM_SEP_VARGS( \ + DT_PATH(zephyr_user), digital_pin_gpios, DIGITAL_PIN_EXISTS, (+), \ + DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), digital_pin_gpios, i)), \ DT_PHA_BY_IDX(DT_PATH(zephyr_user), digital_pin_gpios, i, pin))) == 1) #if !LISTIFY(DT_PROP_LEN(DT_PATH(zephyr_user), digital_pin_gpios), DIGITAL_PIN_CHECK_UNIQUE, (&&)) @@ -44,36 +44,37 @@ (DIGITAL_PIN_EXISTS(n, p, i, dev, num) ? i : 0) /* Only matched pin returns non-zero value, so the sum is matched pin's index */ -#define DIGITAL_PIN_GPIOS_FIND_PIN(dev, pin) \ - DT_FOREACH_PROP_ELEM_SEP_VARGS(DT_PATH(zephyr_user), digital_pin_gpios, \ - LED_BUILTIN_INDEX_BY_REG_AND_PINNUM, (+), dev, pin) +#define DIGITAL_PIN_GPIOS_FIND_PIN(dev, pin) \ + DT_FOREACH_PROP_ELEM_SEP_VARGS(DT_PATH(zephyr_user), digital_pin_gpios, \ + LED_BUILTIN_INDEX_BY_REG_AND_PINNUM, (+), dev, pin) #if DT_NODE_HAS_PROP(DT_PATH(zephyr_user), builtin_led_gpios) && \ (DT_PROP_LEN(DT_PATH(zephyr_user), builtin_led_gpios) > 0) -#if !(DT_FOREACH_PROP_ELEM_SEP_VARGS( \ - DT_PATH(zephyr_user), digital_pin_gpios, DIGITAL_PIN_EXISTS, (+), \ - DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), builtin_led_gpios, 0)), \ - DT_PHA_BY_IDX(DT_PATH(zephyr_user), builtin_led_gpios, 0, pin)) > 0) +#if !(DT_FOREACH_PROP_ELEM_SEP_VARGS( \ + DT_PATH(zephyr_user), digital_pin_gpios, DIGITAL_PIN_EXISTS, (+), \ + DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), builtin_led_gpios, 0)), \ + DT_PHA_BY_IDX(DT_PATH(zephyr_user), builtin_led_gpios, 0, pin)) > 0) #warning "pin not found in digital_pin_gpios" #else #define LED_BUILTIN \ - DIGITAL_PIN_GPIOS_FIND_PIN( \ - DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), builtin_led_gpios, 0)), \ + DIGITAL_PIN_GPIOS_FIND_PIN( \ + DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), builtin_led_gpios, 0)), \ DT_PHA_BY_IDX(DT_PATH(zephyr_user), builtin_led_gpios, 0, pin)) #endif /* If digital-pin-gpios is not defined, tries to use the led0 alias */ #elif DT_NODE_EXISTS(DT_ALIAS(led0)) -#if !(DT_FOREACH_PROP_ELEM_SEP_VARGS(DT_PATH(zephyr_user), digital_pin_gpios, DIGITAL_PIN_EXISTS, \ - (+), DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_ALIAS(led0), gpios, 0)), \ - DT_PHA_BY_IDX(DT_ALIAS(led0), gpios, 0, pin)) > 0) +#if !(DT_FOREACH_PROP_ELEM_SEP_VARGS(DT_PATH(zephyr_user), digital_pin_gpios, DIGITAL_PIN_EXISTS, \ + (+), \ + DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_ALIAS(led0), gpios, 0)), \ + DT_PHA_BY_IDX(DT_ALIAS(led0), gpios, 0, pin)) > 0) #warning "pin not found in digital_pin_gpios" #else #define LED_BUILTIN \ - DIGITAL_PIN_GPIOS_FIND_PIN(DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_ALIAS(led0), gpios, 0)), \ - DT_PHA_BY_IDX(DT_ALIAS(led0), gpios, 0, pin)) + DIGITAL_PIN_GPIOS_FIND_PIN(DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_ALIAS(led0), gpios, 0)), \ + DT_PHA_BY_IDX(DT_ALIAS(led0), gpios, 0, pin)) #endif #endif // builtin_led_gpios @@ -95,11 +96,13 @@ enum digitalPins { #ifdef CONFIG_ADC -#define AN_ENUMS(n, p, i) A ## i = DIGITAL_PIN_GPIOS_FIND_PIN( \ - DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), p, i)), \ - DT_PHA_BY_IDX(DT_PATH(zephyr_user), p, i, pin)), -enum analogPins { DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), - adc_pin_gpios, AN_ENUMS) }; +#define AN_ENUMS(n, p, i) \ + A##i = DIGITAL_PIN_GPIOS_FIND_PIN(DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), p, i)), \ + DT_PHA_BY_IDX(DT_PATH(zephyr_user), p, i, pin)), + +enum analogPins { + DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), adc_pin_gpios, AN_ENUMS) +}; // We provide analogReadResolution APIs void analogReadResolution(int bits); @@ -112,8 +115,11 @@ void analogReadResolution(int bits); #undef DAC1 #undef DAC2 #undef DAC3 -#define DAC_ENUMS(n, p, i) DAC ## i = i, -enum dacPins { DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), dac_channels, DAC_ENUMS) NUM_OF_DACS }; +#define DAC_ENUMS(n, p, i) DAC##i = i, + +enum dacPins { + DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), dac_channels, DAC_ENUMS) NUM_OF_DACS +}; #endif @@ -122,10 +128,10 @@ void noInterrupts(void); int digitalPinToInterrupt(pin_size_t pin); -#define digitalPinToPort(x) (x) +#define digitalPinToPort(x) (x) #define digitalPinToBitMask(x) (x) -#define portOutputRegister(x) (x) -#define portInputRegister(x) (x) +#define portOutputRegister(x) (x) +#define portInputRegister(x) (x) void analogReadResolution(int bits); void analogWriteResolution(int bits); diff --git a/cores/arduino/SerialUSB.h b/cores/arduino/SerialUSB.h index be1377f8..f6459d3c 100644 --- a/cores/arduino/SerialUSB.h +++ b/cores/arduino/SerialUSB.h @@ -13,13 +13,22 @@ namespace arduino { class SerialUSB_ : public ZephyrSerial { public: - SerialUSB_(const struct device *dev) : ZephyrSerial(dev) { } + SerialUSB_(const struct device *dev) : ZephyrSerial(dev) { + } + void begin(unsigned long baudrate, uint16_t config); - void begin(unsigned long baudrate) { begin(baudrate, SERIAL_8N1); } + + void begin(unsigned long baudrate) { + begin(baudrate, SERIAL_8N1); + } operator bool() override; size_t write(const uint8_t *buffer, size_t size) override; - size_t write(const uint8_t data) override { return write(&data, 1); } + + size_t write(const uint8_t data) override { + return write(&data, 1); + } + void flush() override; protected: @@ -32,8 +41,9 @@ class SerialUSB_ : public ZephyrSerial { struct k_timer baud_timer; bool started = false; }; -} // namespace arduino +} // namespace arduino -#if (DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && (CONFIG_USB_CDC_ACM || CONFIG_USBD_CDC_ACM_CLASS)) +#if (DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && \ + (CONFIG_USB_CDC_ACM || CONFIG_USBD_CDC_ACM_CLASS)) extern arduino::SerialUSB_ Serial; -#endif \ No newline at end of file +#endif diff --git a/cores/arduino/USB.cpp b/cores/arduino/USB.cpp index 60f5fc7a..6e0179ea 100644 --- a/cores/arduino/USB.cpp +++ b/cores/arduino/USB.cpp @@ -10,53 +10,51 @@ #include #include -#if ((DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm)) && (CONFIG_USB_CDC_ACM || CONFIG_USBD_CDC_ACM_CLASS)) -const struct device *const usb_dev = DEVICE_DT_GET(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), cdc_acm, 0)); +#if ((DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm)) && \ + (CONFIG_USB_CDC_ACM || CONFIG_USBD_CDC_ACM_CLASS)) +const struct device *const usb_dev = + DEVICE_DT_GET(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), cdc_acm, 0)); void usb_status_cb(enum usb_dc_status_code cb_status, const uint8_t *param) { - (void)param; // unused - if (cb_status == USB_DC_CONFIGURED) { - - } + (void)param; // unused + if (cb_status == USB_DC_CONFIGURED) { + } } void __attribute__((weak)) _on_1200_bps() { - NVIC_SystemReset(); + NVIC_SystemReset(); } -void arduino::SerialUSB_::_baudChangeHandler() -{ - uart_line_ctrl_get(uart, UART_LINE_CTRL_BAUD_RATE, &baudrate); - if (baudrate == 1200) { - usb_disable(); - _on_1200_bps(); - } +void arduino::SerialUSB_::_baudChangeHandler() { + uart_line_ctrl_get(uart, UART_LINE_CTRL_BAUD_RATE, &baudrate); + if (baudrate == 1200) { + usb_disable(); + _on_1200_bps(); + } } -static void _baudChangeHandler(const struct device *dev, uint32_t rate) -{ - (void)dev; // unused - if (rate == 1200) { - usb_disable(); - _on_1200_bps(); - } +static void _baudChangeHandler(const struct device *dev, uint32_t rate) { + (void)dev; // unused + if (rate == 1200) { + usb_disable(); + _on_1200_bps(); + } } #if defined(CONFIG_USB_DEVICE_STACK_NEXT) extern "C" { - #include - struct usbd_context *usbd_init_device(usbd_msg_cb_t msg_cb); +#include +struct usbd_context *usbd_init_device(usbd_msg_cb_t msg_cb); } struct usbd_context *_usbd; int usb_disable() { - return usbd_disable(_usbd); + return usbd_disable(_usbd); } -static void usbd_next_cb(struct usbd_context *const ctx, const struct usbd_msg *msg) -{ +static void usbd_next_cb(struct usbd_context *const ctx, const struct usbd_msg *msg) { if (usbd_can_detect_vbus(ctx)) { if (msg->type == USBD_MSG_VBUS_READY) { usbd_enable(ctx); @@ -68,14 +66,13 @@ static void usbd_next_cb(struct usbd_context *const ctx, const struct usbd_msg * } if (msg->type == USBD_MSG_CDC_ACM_LINE_CODING) { - uint32_t baudrate; + uint32_t baudrate; uart_line_ctrl_get(ctx->dev, UART_LINE_CTRL_BAUD_RATE, &baudrate); - _baudChangeHandler(nullptr, baudrate); + _baudChangeHandler(nullptr, baudrate); } } -static int enable_usb_device_next(void) -{ +static int enable_usb_device_next(void) { int err; //_usbd = usbd_init_device(usbd_next_cb); @@ -95,44 +92,46 @@ static int enable_usb_device_next(void) #endif /* defined(CONFIG_USB_DEVICE_STACK_NEXT) */ void arduino::SerialUSB_::_baudChangeDispatch(struct k_timer *timer) { - arduino::SerialUSB_* dev = (arduino::SerialUSB_*)k_timer_user_data_get(timer); - dev->_baudChangeHandler(); + arduino::SerialUSB_ *dev = (arduino::SerialUSB_ *)k_timer_user_data_get(timer); + dev->_baudChangeHandler(); } - void arduino::SerialUSB_::begin(unsigned long baudrate, uint16_t config) { - if (!started) { - #ifndef CONFIG_USB_DEVICE_STACK_NEXT - usb_enable(NULL); - #ifndef CONFIG_CDC_ACM_DTE_RATE_CALLBACK_SUPPORT - k_timer_init(&baud_timer, SerialUSB_::_baudChangeDispatch, NULL); - k_timer_user_data_set(&baud_timer, this); - k_timer_start(&baud_timer, K_MSEC(100), K_MSEC(100)); - #else - cdc_acm_dte_rate_callback_set(usb_dev, ::_baudChangeHandler); - #endif - #else - enable_usb_device_next(); - #endif - ZephyrSerial::begin(baudrate, config); - started = true; - } + if (!started) { +#ifndef CONFIG_USB_DEVICE_STACK_NEXT + usb_enable(NULL); +#ifndef CONFIG_CDC_ACM_DTE_RATE_CALLBACK_SUPPORT + k_timer_init(&baud_timer, SerialUSB_::_baudChangeDispatch, NULL); + k_timer_user_data_set(&baud_timer, this); + k_timer_start(&baud_timer, K_MSEC(100), K_MSEC(100)); +#else + cdc_acm_dte_rate_callback_set(usb_dev, ::_baudChangeHandler); +#endif +#else + enable_usb_device_next(); +#endif + ZephyrSerial::begin(baudrate, config); + started = true; + } } arduino::SerialUSB_::operator bool() { - uart_line_ctrl_get(uart, UART_LINE_CTRL_DTR, &dtr); - return dtr; + uart_line_ctrl_get(uart, UART_LINE_CTRL_DTR, &dtr); + return dtr; } - -size_t arduino::SerialUSB_::write(const uint8_t *buffer, size_t size) { - if (!Serial) return 0; - return arduino::ZephyrSerial::write(buffer, size); +size_t arduino::SerialUSB_::write(const uint8_t *buffer, size_t size) { + if (!Serial) { + return 0; + } + return arduino::ZephyrSerial::write(buffer, size); } void arduino::SerialUSB_::flush() { - if (!Serial) return; - arduino::ZephyrSerial::flush(); + if (!Serial) { + return; + } + arduino::ZephyrSerial::flush(); } arduino::SerialUSB_ Serial(usb_dev); diff --git a/cores/arduino/abi.cpp b/cores/arduino/abi.cpp index 9e8fabd6..872c8d08 100644 --- a/cores/arduino/abi.cpp +++ b/cores/arduino/abi.cpp @@ -7,34 +7,44 @@ #include namespace std { - void __throw_length_error(const char* __s __attribute__((unused))) {} - void __throw_bad_alloc() {} - void __throw_bad_function_call() {} -}; +void __throw_length_error(const char *__s __attribute__((unused))) { +} + +void __throw_bad_alloc() { +} + +void __throw_bad_function_call() { +} +}; // namespace std extern "C" { -void* __dso_handle = (void*) &__dso_handle; +void *__dso_handle = (void *)&__dso_handle; + +void __cxa_pure_virtual(void) { +} + +void __cxa_deleted_virtual(void) { +} -void __cxa_pure_virtual(void) {} -void __cxa_deleted_virtual(void) {} -int __cxa_atexit(void (*func) (void *), void * arg, void * dso_handle) { - (void)func; (void)arg; (void)dso_handle; // unused - return 0; +int __cxa_atexit(void (*func)(void *), void *arg, void *dso_handle) { + (void)func; + (void)arg; + (void)dso_handle; // unused + return 0; } int atexit(void (*func)(void)) { - (void)func; - return 0; + (void)func; + return 0; } -int strcmp(const char* s1, const char* s2) { - while(*s1 && (*s1 == *s2)) - { - s1++; - s2++; - } - return *(const unsigned char*)s1 - *(const unsigned char*)s2; +int strcmp(const char *s1, const char *s2) { + while (*s1 && (*s1 == *s2)) { + s1++; + s2++; + } + return *(const unsigned char *)s1 - *(const unsigned char *)s2; } } /* extern "C" */ diff --git a/cores/arduino/itoa.cpp b/cores/arduino/itoa.cpp index 929ec4d0..193cd6ab 100644 --- a/cores/arduino/itoa.cpp +++ b/cores/arduino/itoa.cpp @@ -13,102 +13,93 @@ extern "C" { #include -extern char* itoa( int value, char *string, int radix ) -{ - return ltoa( value, string, radix ) ; +extern char *itoa(int value, char *string, int radix) { + return ltoa(value, string, radix); } -extern char* ltoa( long value, char *string, int radix ) -{ - char tmp[33]; - char *tp = tmp; - long i; - unsigned long v; - int sign; - char *sp; - - if ( string == NULL ) - { - return 0 ; - } - - if (radix > 36 || radix <= 1) - { - return 0 ; - } - - sign = (radix == 10 && value < 0); - if (sign) - { - v = -value; - } - else - { - v = (unsigned long)value; - } - - while (v || tp == tmp) - { - i = v % radix; - v = v / radix; - if (i < 10) - *tp++ = i+'0'; - else - *tp++ = i + 'a' - 10; - } - - sp = string; - - if (sign) - *sp++ = '-'; - while (tp > tmp) - *sp++ = *--tp; - *sp = 0; - - return string; +extern char *ltoa(long value, char *string, int radix) { + char tmp[33]; + char *tp = tmp; + long i; + unsigned long v; + int sign; + char *sp; + + if (string == NULL) { + return 0; + } + + if (radix > 36 || radix <= 1) { + return 0; + } + + sign = (radix == 10 && value < 0); + if (sign) { + v = -value; + } else { + v = (unsigned long)value; + } + + while (v || tp == tmp) { + i = v % radix; + v = v / radix; + if (i < 10) { + *tp++ = i + '0'; + } else { + *tp++ = i + 'a' - 10; + } + } + + sp = string; + + if (sign) { + *sp++ = '-'; + } + while (tp > tmp) { + *sp++ = *--tp; + } + *sp = 0; + + return string; } -extern char* utoa( unsigned int value, char *string, int radix ) -{ - return ultoa( value, string, radix ) ; +extern char *utoa(unsigned int value, char *string, int radix) { + return ultoa(value, string, radix); } -extern char* ultoa( unsigned long value, char *string, int radix ) -{ - char tmp[33]; - char *tp = tmp; - long i; - unsigned long v = value; - char *sp; - - if ( string == NULL ) - { - return 0; - } - - if (radix > 36 || radix <= 1) - { - return 0; - } - - while (v || tp == tmp) - { - i = v % radix; - v = v / radix; - if (i < 10) - *tp++ = i+'0'; - else - *tp++ = i + 'a' - 10; - } - - sp = string; - - - while (tp > tmp) - *sp++ = *--tp; - *sp = 0; - - return string; +extern char *ultoa(unsigned long value, char *string, int radix) { + char tmp[33]; + char *tp = tmp; + long i; + unsigned long v = value; + char *sp; + + if (string == NULL) { + return 0; + } + + if (radix > 36 || radix <= 1) { + return 0; + } + + while (v || tp == tmp) { + i = v % radix; + v = v / radix; + if (i < 10) { + *tp++ = i + '0'; + } else { + *tp++ = i + 'a' - 10; + } + } + + sp = string; + + while (tp > tmp) { + *sp++ = *--tp; + } + *sp = 0; + + return string; } #ifdef __cplusplus diff --git a/cores/arduino/main.cpp b/cores/arduino/main.cpp index 9359e745..bd37be8f 100644 --- a/cores/arduino/main.cpp +++ b/cores/arduino/main.cpp @@ -15,34 +15,32 @@ void start_static_threads(); #endif - // This function will be overwriten by most variants. -void __attribute__((weak))initVariant(void) { - +void __attribute__((weak)) initVariant(void) { } - int main(void) { #if (DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && CONFIG_USB_CDC_ACM) - Serial.begin(115200); + Serial.begin(115200); #endif - initVariant(); + initVariant(); #ifdef CONFIG_MULTITHREADING - start_static_threads(); + start_static_threads(); #endif - setup(); + setup(); - for (;;) { - loop(); - #if 0 //(DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && CONFIG_USB_CDC_ACM) || DT_NODE_HAS_PROP(DT_PATH(zephyr_user), serials) + for (;;) { + loop(); +#if 0 //(DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && CONFIG_USB_CDC_ACM) || + // DT_NODE_HAS_PROP(DT_PATH(zephyr_user), serials) if (arduino::serialEventRun) arduino::serialEventRun(); - #endif - } +#endif + } - return 0; + return 0; } #ifdef CONFIG_LLEXT @@ -50,49 +48,52 @@ LL_EXTENSION_SYMBOL(main); #endif /* These magic symbols are provided by the linker. */ -extern void (*__preinit_array_start []) (void) __attribute__((weak)); -extern void (*__preinit_array_end []) (void) __attribute__((weak)); -extern void (*__init_array_start []) (void) __attribute__((weak)); -extern void (*__init_array_end []) (void) __attribute__((weak)); - -static void __libc_init_array (void) -{ - size_t count; - size_t i; - - count = __preinit_array_end - __preinit_array_start; - for (i = 0; i < count; i++) - __preinit_array_start[i] (); - - count = __init_array_end - __init_array_start; - for (i = 0; i < count; i++) - __init_array_start[i] (); +extern void (*__preinit_array_start[])(void) __attribute__((weak)); +extern void (*__preinit_array_end[])(void) __attribute__((weak)); +extern void (*__init_array_start[])(void) __attribute__((weak)); +extern void (*__init_array_end[])(void) __attribute__((weak)); + +static void __libc_init_array(void) { + size_t count; + size_t i; + + count = __preinit_array_end - __preinit_array_start; + for (i = 0; i < count; i++) { + __preinit_array_start[i](); + } + + count = __init_array_end - __init_array_start; + for (i = 0; i < count; i++) { + __init_array_start[i](); + } } -extern "C" __attribute__((section(".entry_point"), used)) void entry_point(struct k_heap* stack, size_t stack_size) { - (void)stack; (void)stack_size; // unused - - // copy .data in the right place - // .bss should already be in the right place - // call constructors - extern uintptr_t _sidata; - extern uintptr_t _sdata; - extern uintptr_t _edata; - extern uintptr_t _sbss; - extern uintptr_t _ebss; - extern uintptr_t __heap_start; - extern uintptr_t __heap_end; - extern uintptr_t kheap_llext_heap; - extern uintptr_t kheap_llext_heap_size; - - //__asm volatile ("cpsie i"); - - printk("System Heap end: %p\n", &__heap_end); - printk("System Heap start: %p\n", &__heap_start); - printk("Sketch Heap start: %p, size %p\n", &kheap_llext_heap, &kheap_llext_heap_size); - - memcpy(&_sdata, &_sidata, (&_edata - &_sdata) * sizeof(uint32_t)); - memset(&_sbss, 0, &_ebss - &_sbss); - __libc_init_array(); - main(); +extern "C" __attribute__((section(".entry_point"), used)) void entry_point(struct k_heap *stack, + size_t stack_size) { + (void)stack; + (void)stack_size; // unused + + // copy .data in the right place + // .bss should already be in the right place + // call constructors + extern uintptr_t _sidata; + extern uintptr_t _sdata; + extern uintptr_t _edata; + extern uintptr_t _sbss; + extern uintptr_t _ebss; + extern uintptr_t __heap_start; + extern uintptr_t __heap_end; + extern uintptr_t kheap_llext_heap; + extern uintptr_t kheap_llext_heap_size; + + //__asm volatile ("cpsie i"); + + printk("System Heap end: %p\n", &__heap_end); + printk("System Heap start: %p\n", &__heap_start); + printk("Sketch Heap start: %p, size %p\n", &kheap_llext_heap, &kheap_llext_heap_size); + + memcpy(&_sdata, &_sidata, (&_edata - &_sdata) * sizeof(uint32_t)); + memset(&_sbss, 0, &_ebss - &_sbss); + __libc_init_array(); + main(); } diff --git a/cores/arduino/new.cpp b/cores/arduino/new.cpp index ed203f86..7b2a63a9 100644 --- a/cores/arduino/new.cpp +++ b/cores/arduino/new.cpp @@ -18,128 +18,141 @@ // #define NEW_TERMINATES_ON_FAILURE namespace std { - // Defined in abi.cpp - void terminate(); +// Defined in abi.cpp +void terminate(); - const nothrow_t nothrow; -} +const nothrow_t nothrow; +} // namespace std -static void * new_helper(std::size_t size) { - // Even zero-sized allocations should return a unique pointer, but - // malloc does not guarantee this - if (size == 0) - size = 1; - return malloc(size); +static void *new_helper(std::size_t size) { + // Even zero-sized allocations should return a unique pointer, but + // malloc does not guarantee this + if (size == 0) { + size = 1; + } + return malloc(size); } -void * operator new(std::size_t size) { - void *res = new_helper(size); +void *operator new(std::size_t size) { + void *res = new_helper(size); #if defined(NEW_TERMINATES_ON_FAILURE) - if (!res) - std::terminate(); + if (!res) { + std::terminate(); + } #endif - return res; + return res; } -void * operator new[](std::size_t size) { - return operator new(size); + +void *operator new[](std::size_t size) { + return operator new(size); } #if __cplusplus >= 201703L -void* operator new(std::size_t count, std::align_val_t al) { - (void)al; // unused - return operator new(count); +void *operator new(std::size_t count, std::align_val_t al) { + (void)al; // unused + return operator new(count); } -void* operator new[](std::size_t count, std::align_val_t al) { - (void)al; // unused - return operator new(count); +void *operator new[](std::size_t count, std::align_val_t al) { + (void)al; // unused + return operator new(count); } -void * operator new(std::size_t size, std::align_val_t al, const std::nothrow_t tag) noexcept { - (void)al; (void)tag; // unused +void *operator new(std::size_t size, std::align_val_t al, const std::nothrow_t tag) noexcept { + (void)al; + (void)tag; // unused #if defined(NEW_TERMINATES_ON_FAILURE) - // Cannot call throwing operator new as standard suggests, so call - // new_helper directly then - return new_helper(size); + // Cannot call throwing operator new as standard suggests, so call + // new_helper directly then + return new_helper(size); #else - return operator new(size); + return operator new(size); #endif } -void * operator new[](std::size_t size, std::align_val_t al, const std::nothrow_t& tag) noexcept { - (void)al; (void)tag; // unused +void *operator new[](std::size_t size, std::align_val_t al, const std::nothrow_t &tag) noexcept { + (void)al; + (void)tag; // unused #if defined(NEW_TERMINATES_ON_FAILURE) - // Cannot call throwing operator new[] as standard suggests, so call - // malloc directly then - return new_helper(size); + // Cannot call throwing operator new[] as standard suggests, so call + // malloc directly then + return new_helper(size); #else - return operator new[](size); + return operator new[](size); #endif } #endif -void * operator new(std::size_t size, const std::nothrow_t tag) noexcept { - (void)tag; // unused +void *operator new(std::size_t size, const std::nothrow_t tag) noexcept { + (void)tag; // unused #if defined(NEW_TERMINATES_ON_FAILURE) - // Cannot call throwing operator new as standard suggests, so call - // new_helper directly then - return new_helper(size); + // Cannot call throwing operator new as standard suggests, so call + // new_helper directly then + return new_helper(size); #else - return operator new(size); + return operator new(size); #endif } -void * operator new[](std::size_t size, const std::nothrow_t& tag) noexcept { - (void)tag; // unused + +void *operator new[](std::size_t size, const std::nothrow_t &tag) noexcept { + (void)tag; // unused #if defined(NEW_TERMINATES_ON_FAILURE) - // Cannot call throwing operator new[] as standard suggests, so call - // malloc directly then - return new_helper(size); + // Cannot call throwing operator new[] as standard suggests, so call + // malloc directly then + return new_helper(size); #else - return operator new[](size); + return operator new[](size); #endif } -void * operator new(std::size_t size, void *place) noexcept { - // Nothing to do - (void)size; // unused - return place; +void *operator new(std::size_t size, void *place) noexcept { + // Nothing to do + (void)size; // unused + return place; } -void * operator new[](std::size_t size, void *place) noexcept { - return operator new(size, place); + +void *operator new[](std::size_t size, void *place) noexcept { + return operator new(size, place); } -void operator delete(void * ptr) noexcept { - free(ptr); +void operator delete(void *ptr) noexcept { + free(ptr); } -void operator delete[](void * ptr) noexcept { - operator delete(ptr); + +void operator delete[](void *ptr) noexcept { + operator delete(ptr); } #if __cplusplus >= 201402L -void operator delete(void* ptr, std::size_t size) noexcept { - (void)size; // unused - operator delete(ptr); +void operator delete(void *ptr, std::size_t size) noexcept { + (void)size; // unused + operator delete(ptr); } -void operator delete[](void * ptr, std::size_t size) noexcept { - (void)size; // unused - operator delete[](ptr); + +void operator delete[](void *ptr, std::size_t size) noexcept { + (void)size; // unused + operator delete[](ptr); } #endif // __cplusplus >= 201402L -void operator delete(void* ptr, const std::nothrow_t& tag) noexcept { - (void)tag; // unused - operator delete(ptr); +void operator delete(void *ptr, const std::nothrow_t &tag) noexcept { + (void)tag; // unused + operator delete(ptr); } -void operator delete[](void* ptr, const std::nothrow_t& tag) noexcept { - (void)tag; // unused - operator delete[](ptr); + +void operator delete[](void *ptr, const std::nothrow_t &tag) noexcept { + (void)tag; // unused + operator delete[](ptr); } -void operator delete(void* ptr, void* place) noexcept { - (void)ptr; (void)place; // unused - // Nothing to do +void operator delete(void *ptr, void *place) noexcept { + (void)ptr; + (void)place; // unused + // Nothing to do } -void operator delete[](void* ptr, void* place) noexcept { - (void)ptr; (void)place; // unused - // Nothing to do + +void operator delete[](void *ptr, void *place) noexcept { + (void)ptr; + (void)place; // unused + // Nothing to do } diff --git a/cores/arduino/overloads.h b/cores/arduino/overloads.h index 5670b270..a96653d7 100644 --- a/cores/arduino/overloads.h +++ b/cores/arduino/overloads.h @@ -6,4 +6,4 @@ void analogWrite(enum dacPins pinNumber, int value); // In c++ mode, we also provide analogReadResolution and analogWriteResolution getters int analogReadResolution(); -int analogWriteResolution(); \ No newline at end of file +int analogWriteResolution(); diff --git a/cores/arduino/threads.cpp b/cores/arduino/threads.cpp index 99a4a141..f34a7f6d 100644 --- a/cores/arduino/threads.cpp +++ b/cores/arduino/threads.cpp @@ -8,25 +8,26 @@ #ifdef CONFIG_MULTITHREADING void start_static_threads() { - #define _FOREACH_STATIC_THREAD(thread_data) \ - STRUCT_SECTION_FOREACH(_static_thread_data, thread_data) +#define _FOREACH_STATIC_THREAD(thread_data) \ + STRUCT_SECTION_FOREACH (_static_thread_data, thread_data) - _FOREACH_STATIC_THREAD(thread_data) { - k_thread_create(thread_data->init_thread, thread_data->init_stack, thread_data->init_stack_size, thread_data->init_entry, - thread_data->init_p1, thread_data->init_p2, thread_data->init_p3, thread_data->init_prio, - thread_data->init_options, thread_data->init_delay); - k_thread_name_set(thread_data->init_thread, thread_data->init_name); - thread_data->init_thread->init_data = thread_data; - } + _FOREACH_STATIC_THREAD(thread_data) { + k_thread_create(thread_data->init_thread, thread_data->init_stack, + thread_data->init_stack_size, thread_data->init_entry, thread_data->init_p1, + thread_data->init_p2, thread_data->init_p3, thread_data->init_prio, + thread_data->init_options, thread_data->init_delay); + k_thread_name_set(thread_data->init_thread, thread_data->init_name); + thread_data->init_thread->init_data = thread_data; + } - /* - * Take a sched lock to prevent them from running - * until they are all started. - */ - k_sched_lock(); - _FOREACH_STATIC_THREAD(thread_data) { - k_thread_start(thread_data->init_thread); - } - k_sched_unlock(); + /* + * Take a sched lock to prevent them from running + * until they are all started. + */ + k_sched_lock(); + _FOREACH_STATIC_THREAD(thread_data) { + k_thread_start(thread_data->init_thread); + } + k_sched_unlock(); } -#endif \ No newline at end of file +#endif diff --git a/cores/arduino/usb_device_descriptor.c b/cores/arduino/usb_device_descriptor.c index 1c0eb887..39637937 100644 --- a/cores/arduino/usb_device_descriptor.c +++ b/cores/arduino/usb_device_descriptor.c @@ -21,9 +21,8 @@ static const char *const blocklist[] = { }; /* doc device instantiation start */ -USBD_DEVICE_DEFINE(usbd, - DEVICE_DT_GET(DT_NODELABEL(zephyr_udc0)), - CONFIG_USB_DEVICE_VID, CONFIG_USB_DEVICE_PID); +USBD_DEVICE_DEFINE(usbd, DEVICE_DT_GET(DT_NODELABEL(zephyr_udc0)), CONFIG_USB_DEVICE_VID, + CONFIG_USB_DEVICE_PID); /* doc device instantiation end */ /* doc string instantiation start */ @@ -40,14 +39,10 @@ USBD_DESC_CONFIG_DEFINE(hs_cfg_desc, "HS Configuration"); static const uint8_t attributes = 0; /* Full speed configuration */ -USBD_CONFIGURATION_DEFINE(sample_fs_config, - attributes, - 250, &fs_cfg_desc); +USBD_CONFIGURATION_DEFINE(sample_fs_config, attributes, 250, &fs_cfg_desc); /* High speed configuration */ -USBD_CONFIGURATION_DEFINE(sample_hs_config, - attributes, - 250, &hs_cfg_desc); +USBD_CONFIGURATION_DEFINE(sample_hs_config, attributes, 250, &hs_cfg_desc); /* doc configuration instantiation end */ /* @@ -63,28 +58,22 @@ static const struct usb_bos_capability_lpm bos_cap_lpm = { USBD_DESC_BOS_DEFINE(sample_usbext, sizeof(bos_cap_lpm), &bos_cap_lpm); -static void sample_fix_code_triple(struct usbd_context *uds_ctx, - const enum usbd_speed speed) -{ +static void sample_fix_code_triple(struct usbd_context *uds_ctx, const enum usbd_speed speed) { /* Always use class code information from Interface Descriptors */ - if (IS_ENABLED(CONFIG_USBD_CDC_ACM_CLASS) || - IS_ENABLED(CONFIG_USBD_CDC_ECM_CLASS) || - IS_ENABLED(CONFIG_USBD_CDC_NCM_CLASS) || - IS_ENABLED(CONFIG_USBD_AUDIO2_CLASS)) { + if (IS_ENABLED(CONFIG_USBD_CDC_ACM_CLASS) || IS_ENABLED(CONFIG_USBD_CDC_ECM_CLASS) || + IS_ENABLED(CONFIG_USBD_CDC_NCM_CLASS) || IS_ENABLED(CONFIG_USBD_AUDIO2_CLASS)) { /* * Class with multiple interfaces have an Interface * Association Descriptor available, use an appropriate triple * to indicate it. */ - usbd_device_set_code_triple(uds_ctx, speed, - USB_BCC_MISCELLANEOUS, 0x02, 0x01); + usbd_device_set_code_triple(uds_ctx, speed, USB_BCC_MISCELLANEOUS, 0x02, 0x01); } else { usbd_device_set_code_triple(uds_ctx, speed, 0, 0, 0); } } -struct usbd_context *usbd_setup_device(usbd_msg_cb_t msg_cb) -{ +struct usbd_context *usbd_setup_device(usbd_msg_cb_t msg_cb) { int err; /* doc add string descriptor start */ @@ -110,14 +99,12 @@ struct usbd_context *usbd_setup_device(usbd_msg_cb_t msg_cb) /* doc add string descriptor end */ if (usbd_caps_speed(&usbd) == USBD_SPEED_HS) { - err = usbd_add_configuration(&usbd, USBD_SPEED_HS, - &sample_hs_config); + err = usbd_add_configuration(&usbd, USBD_SPEED_HS, &sample_hs_config); if (err) { return NULL; } - err = usbd_register_all_classes(&usbd, USBD_SPEED_HS, 1, - blocklist); + err = usbd_register_all_classes(&usbd, USBD_SPEED_HS, 1, blocklist); if (err) { return NULL; } @@ -126,8 +113,7 @@ struct usbd_context *usbd_setup_device(usbd_msg_cb_t msg_cb) } /* doc configuration register start */ - err = usbd_add_configuration(&usbd, USBD_SPEED_FS, - &sample_fs_config); + err = usbd_add_configuration(&usbd, USBD_SPEED_FS, &sample_fs_config); if (err) { return NULL; } @@ -164,8 +150,7 @@ struct usbd_context *usbd_setup_device(usbd_msg_cb_t msg_cb) return &usbd; } -struct usbd_context *usbd_init_device(usbd_msg_cb_t msg_cb) -{ +struct usbd_context *usbd_init_device(usbd_msg_cb_t msg_cb) { int err; if (usbd_setup_device(msg_cb) == NULL) { @@ -182,4 +167,4 @@ struct usbd_context *usbd_init_device(usbd_msg_cb_t msg_cb) return &usbd; } -#endif \ No newline at end of file +#endif diff --git a/cores/arduino/zephyrCommon.cpp b/cores/arduino/zephyrCommon.cpp index f0b6e8ba..ca61ea57 100644 --- a/cores/arduino/zephyrCommon.cpp +++ b/cores/arduino/zephyrCommon.cpp @@ -7,7 +7,8 @@ #include #include "zephyrInternal.h" -static const struct gpio_dt_spec arduino_pins[] = {DT_FOREACH_PROP_ELEM_SEP( +static const struct gpio_dt_spec arduino_pins[] = { + DT_FOREACH_PROP_ELEM_SEP( DT_PATH(zephyr_user), digital_pin_gpios, GPIO_DT_SPEC_GET_BY_IDX, (, ))}; namespace { @@ -18,57 +19,49 @@ namespace { * Calculate GPIO ports/pins number statically from devicetree configuration */ -template constexpr N sum_of_list(const N sum, const Head &head) -{ - return sum + head; +template constexpr N sum_of_list(const N sum, const Head &head) { + return sum + head; } template -constexpr N sum_of_list(const N sum, const Head &head, const Tail &...tail) -{ - return sum_of_list(sum + head, tail...); +constexpr N sum_of_list(const N sum, const Head &head, const Tail &...tail) { + return sum_of_list(sum + head, tail...); } -template constexpr N max_in_list(const N max, const Head &head) -{ - return (max >= head) ? max : head; +template constexpr N max_in_list(const N max, const Head &head) { + return (max >= head) ? max : head; } template -constexpr N max_in_list(const N max, const Head &head, const Tail &...tail) -{ - return max_in_list((max >= head) ? max : head, tail...); +constexpr N max_in_list(const N max, const Head &head, const Tail &...tail) { + return max_in_list((max >= head) ? max : head, tail...); } template constexpr size_t is_first_appearance(const size_t &idx, const size_t &at, const size_t &found, - const Query &query, const Head &head) -{ - return ((found == ((size_t)-1)) && (query == head) && (idx == at)) ? 1 : 0; + const Query &query, const Head &head) { + return ((found == ((size_t)-1)) && (query == head) && (idx == at)) ? 1 : 0; } template constexpr size_t is_first_appearance(const size_t &idx, const size_t &at, const size_t &found, - const Query &query, const Head &head, - const Tail &...tail) -{ - return ((found == ((size_t)-1)) && (query == head) && (idx == at)) - ? 1 - : is_first_appearance(idx + 1, at, (query == head ? idx : found), query, - tail...); + const Query &query, const Head &head, const Tail &...tail) { + return ((found == ((size_t)-1)) && (query == head) && (idx == at)) ? + 1 : + is_first_appearance(idx + 1, at, (query == head ? idx : found), query, tail...); } #define GET_DEVICE_VARGS(n, p, i, _) DEVICE_DT_GET(DT_GPIO_CTLR_BY_IDX(n, p, i)) #define FIRST_APPEARANCE(n, p, i) \ - is_first_appearance(0, i, ((size_t)-1), DEVICE_DT_GET(DT_GPIO_CTLR_BY_IDX(n, p, i)), \ - DT_FOREACH_PROP_ELEM_SEP_VARGS(n, p, GET_DEVICE_VARGS, (, ), 0)) -const int port_num = - sum_of_list(0, DT_FOREACH_PROP_ELEM_SEP(DT_PATH(zephyr_user), digital_pin_gpios, + is_first_appearance(0, i, ((size_t)-1), DEVICE_DT_GET(DT_GPIO_CTLR_BY_IDX(n, p, i)), \ + DT_FOREACH_PROP_ELEM_SEP_VARGS(n, p, GET_DEVICE_VARGS, (, ), 0)) +const int port_num = sum_of_list( + 0, DT_FOREACH_PROP_ELEM_SEP(DT_PATH(zephyr_user), digital_pin_gpios, FIRST_APPEARANCE, (, ))); #define GPIO_NGPIOS(n, p, i) DT_PROP(DT_GPIO_CTLR_BY_IDX(n, p, i), ngpios) const int max_ngpios = max_in_list( - 0, DT_FOREACH_PROP_ELEM_SEP(DT_PATH(zephyr_user), digital_pin_gpios, GPIO_NGPIOS, (, ))); + 0, DT_FOREACH_PROP_ELEM_SEP(DT_PATH(zephyr_user), digital_pin_gpios, GPIO_NGPIOS, (, ))); #else @@ -82,137 +75,132 @@ const int max_ngpios = 0; */ struct arduino_callback { - voidFuncPtr handler; - bool enabled; + voidFuncPtr handler; + bool enabled; }; struct gpio_port_callback { - struct gpio_callback callback; - struct arduino_callback handlers[max_ngpios]; - gpio_port_pins_t pins; - const struct device *dev; + struct gpio_callback callback; + struct arduino_callback handlers[max_ngpios]; + gpio_port_pins_t pins; + const struct device *dev; } port_callback[port_num] = {0}; -struct gpio_port_callback *find_gpio_port_callback(const struct device *dev) -{ - for (size_t i = 0; i < ARRAY_SIZE(port_callback); i++) { - if (port_callback[i].dev == dev) { - return &port_callback[i]; - } - if (port_callback[i].dev == nullptr) { - port_callback[i].dev = dev; - return &port_callback[i]; - } - } +struct gpio_port_callback *find_gpio_port_callback(const struct device *dev) { + for (size_t i = 0; i < ARRAY_SIZE(port_callback); i++) { + if (port_callback[i].dev == dev) { + return &port_callback[i]; + } + if (port_callback[i].dev == nullptr) { + port_callback[i].dev = dev; + return &port_callback[i]; + } + } - return nullptr; + return nullptr; } -void setInterruptHandler(pin_size_t pinNumber, voidFuncPtr func) -{ - struct gpio_port_callback *pcb = find_gpio_port_callback(arduino_pins[pinNumber].port); +void setInterruptHandler(pin_size_t pinNumber, voidFuncPtr func) { + struct gpio_port_callback *pcb = find_gpio_port_callback(arduino_pins[pinNumber].port); - if (pcb) { - pcb->handlers[BIT(arduino_pins[pinNumber].pin)].handler = func; - } + if (pcb) { + pcb->handlers[BIT(arduino_pins[pinNumber].pin)].handler = func; + } } -void handleGpioCallback(const struct device *port, struct gpio_callback *cb, uint32_t pins) -{ - (void)port; // unused - struct gpio_port_callback *pcb = (struct gpio_port_callback *)cb; +void handleGpioCallback(const struct device *port, struct gpio_callback *cb, uint32_t pins) { + (void)port; // unused + struct gpio_port_callback *pcb = (struct gpio_port_callback *)cb; - for (uint32_t i = 0; i < max_ngpios; i++) { - if (pins & BIT(i) && pcb->handlers[BIT(i)].enabled) { - pcb->handlers[BIT(i)].handler(); - } - } + for (uint32_t i = 0; i < max_ngpios; i++) { + if (pins & BIT(i) && pcb->handlers[BIT(i)].enabled) { + pcb->handlers[BIT(i)].handler(); + } + } } #ifdef CONFIG_PWM -#define PWM_DT_SPEC(n,p,i) PWM_DT_SPEC_GET_BY_IDX(n, i), -#define PWM_PINS(n, p, i) \ - DIGITAL_PIN_GPIOS_FIND_PIN( \ - DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), p, i)), \ - DT_PHA_BY_IDX(DT_PATH(zephyr_user), p, i, pin)), +#define PWM_DT_SPEC(n, p, i) PWM_DT_SPEC_GET_BY_IDX(n, i), +#define PWM_PINS(n, p, i) \ + DIGITAL_PIN_GPIOS_FIND_PIN(DT_REG_ADDR(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), p, i)), \ + DT_PHA_BY_IDX(DT_PATH(zephyr_user), p, i, pin)), -const struct pwm_dt_spec arduino_pwm[] = - { DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), pwms, PWM_DT_SPEC) }; +const struct pwm_dt_spec arduino_pwm[] = { + DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), pwms, PWM_DT_SPEC)}; /* pwm-pins node provides a mapping digital pin numbers to pwm channels */ -const pin_size_t arduino_pwm_pins[] = - { DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), pwm_pin_gpios, PWM_PINS) }; +const pin_size_t arduino_pwm_pins[] = { + DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), pwm_pin_gpios, PWM_PINS)}; size_t pwm_pin_index(pin_size_t pinNumber) { - for(size_t i=0; i 0) { - timer = &arduino_pin_timers_timeout[pinNumber]; - k_timer_init(timer, tone_timeout_cb, NULL); - k_timer_user_data_set(timer, (void*)(uintptr_t)pinNumber); - k_timer_start(timer, K_MSEC(duration), K_NO_WAIT); - } + if (duration > 0) { + timer = &arduino_pin_timers_timeout[pinNumber]; + k_timer_init(timer, tone_timeout_cb, NULL); + k_timer_user_data_set(timer, (void *)(uintptr_t)pinNumber); + k_timer_start(timer, K_MSEC(duration), K_NO_WAIT); + } } void noTone(pin_size_t pinNumber) { - k_timer_stop(&arduino_pin_timers[pinNumber]); - gpio_pin_set_dt(&arduino_pins[pinNumber], 0); + k_timer_stop(&arduino_pin_timers[pinNumber]); + gpio_pin_set_dt(&arduino_pins[pinNumber], 0); } -void delay(unsigned long ms) { k_sleep(K_MSEC(ms)); } +void delay(unsigned long ms) { + k_sleep(K_MSEC(ms)); +} -void delayMicroseconds(unsigned int us) { k_sleep(K_USEC(us)); } +void delayMicroseconds(unsigned int us) { + k_sleep(K_USEC(us)); +} unsigned long micros(void) { #ifdef CONFIG_TIMER_HAS_64BIT_CYCLE_COUNTER - return k_cyc_to_us_floor32(k_cycle_get_64()); + return k_cyc_to_us_floor32(k_cycle_get_64()); #else - return k_cyc_to_us_floor32(k_cycle_get_32()); + return k_cyc_to_us_floor32(k_cycle_get_32()); #endif - } +} -unsigned long millis(void) { return k_uptime_get_32(); } +unsigned long millis(void) { + return k_uptime_get_32(); +} #if defined(CONFIG_DAC) || defined(CONFIG_PWM) static int _analog_write_resolution = 8; + void analogWriteResolution(int bits) { - _analog_write_resolution = bits; + _analog_write_resolution = bits; } + int analogWriteResolution() { - return _analog_write_resolution; + return _analog_write_resolution; } #endif #ifdef CONFIG_PWM -void analogWrite(pin_size_t pinNumber, int value) -{ - size_t idx = pwm_pin_index(pinNumber); +void analogWrite(pin_size_t pinNumber, int value) { + size_t idx = pwm_pin_index(pinNumber); - if (idx >= ARRAY_SIZE(arduino_pwm) ) { - return; - } + if (idx >= ARRAY_SIZE(arduino_pwm)) { + return; + } - if (!pwm_is_ready_dt(&arduino_pwm[idx])) { - return; - } + if (!pwm_is_ready_dt(&arduino_pwm[idx])) { + return; + } - value = map(value, 0, 1 << _analog_write_resolution, 0, arduino_pwm[idx].period); + value = map(value, 0, 1 << _analog_write_resolution, 0, arduino_pwm[idx].period); - if (((uint32_t)value) > arduino_pwm[idx].period) { - value = arduino_pwm[idx].period; - } else if (value < 0) { - value = 0; - } + if (((uint32_t)value) > arduino_pwm[idx].period) { + value = arduino_pwm[idx].period; + } else if (value < 0) { + value = 0; + } - /* - * A duty ratio determines by the period value defined in dts - * and the value arguments. So usually the period value sets as 255. - */ - (void)pwm_set_pulse_dt(&arduino_pwm[idx], value); + /* + * A duty ratio determines by the period value defined in dts + * and the value arguments. So usually the period value sets as 255. + */ + (void)pwm_set_pulse_dt(&arduino_pwm[idx], value); } #endif #ifdef CONFIG_DAC -void analogWrite(enum dacPins dacName, int value) -{ - if (dacName >= NUM_OF_DACS) { - return; - } +void analogWrite(enum dacPins dacName, int value) { + if (dacName >= NUM_OF_DACS) { + return; + } - dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]); + dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]); - const int max_dac_value = 1U << dac_ch_cfg[dacName].resolution; - dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id, map(value, 0, 1 << _analog_write_resolution, 0, max_dac_value)); + const int max_dac_value = 1U << dac_ch_cfg[dacName].resolution; + dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id, + map(value, 0, 1 << _analog_write_resolution, 0, max_dac_value)); } #endif - #ifdef CONFIG_ADC -void analogReference(uint8_t mode) -{ - /* - * The Arduino API not clearly defined what means of - * the mode argument of analogReference(). - * Treat the value as equivalent to zephyr's adc_reference. - */ - for (size_t i=0; i(mode); - } +void analogReference(uint8_t mode) { + /* + * The Arduino API not clearly defined what means of + * the mode argument of analogReference(). + * Treat the value as equivalent to zephyr's adc_reference. + */ + for (size_t i = 0; i < ARRAY_SIZE(channel_cfg); i++) { + channel_cfg[i].reference = static_cast(mode); + } } // Note: We can not update the arduino_adc structure as it is read only... static int read_resolution = 10; -void analogReadResolution(int bits) -{ - read_resolution = bits; +void analogReadResolution(int bits) { + read_resolution = bits; } -int analogReadResolution() -{ - return read_resolution; +int analogReadResolution() { + return read_resolution; } +int analogRead(pin_size_t pinNumber) { + int err; + uint16_t buf; + struct adc_sequence seq = {.buffer = &buf, .buffer_size = sizeof(buf)}; + size_t idx = analog_pin_index(pinNumber); -int analogRead(pin_size_t pinNumber) -{ - int err; - uint16_t buf; - struct adc_sequence seq = { .buffer = &buf, .buffer_size = sizeof(buf) }; - size_t idx = analog_pin_index(pinNumber); + if (idx >= ARRAY_SIZE(arduino_adc)) { + return -EINVAL; + } - if (idx >= ARRAY_SIZE(arduino_adc) ) { - return -EINVAL; - } + /* + * ADC that is on MCU supported by Zephyr exists + * only 16bit resolution, currently. + */ + if (arduino_adc[idx].resolution > 16) { + return -ENOTSUP; + } - /* - * ADC that is on MCU supported by Zephyr exists - * only 16bit resolution, currently. - */ - if (arduino_adc[idx].resolution > 16) { - return -ENOTSUP; - } + err = adc_channel_setup(arduino_adc[idx].dev, &arduino_adc[idx].channel_cfg); + if (err < 0) { + return err; + } - err = adc_channel_setup(arduino_adc[idx].dev, &arduino_adc[idx].channel_cfg); - if (err < 0) { - return err; - } + seq.channels = BIT(arduino_adc[idx].channel_id); + seq.resolution = arduino_adc[idx].resolution; + seq.oversampling = arduino_adc[idx].oversampling; - seq.channels = BIT(arduino_adc[idx].channel_id); - seq.resolution = arduino_adc[idx].resolution; - seq.oversampling = arduino_adc[idx].oversampling; + err = adc_read(arduino_adc[idx].dev, &seq); + if (err < 0) { + return err; + } - err = adc_read(arduino_adc[idx].dev, &seq); - if (err < 0) { - return err; - } - - /* - * If necessary map the return value to the - * number of bits the user has asked for - */ - if (read_resolution == seq.resolution) return buf; - if (read_resolution < seq.resolution) return buf >> (seq.resolution - read_resolution); - return buf << (read_resolution - seq.resolution) ; + /* + * If necessary map the return value to the + * number of bits the user has asked for + */ + if (read_resolution == seq.resolution) { + return buf; + } + if (read_resolution < seq.resolution) { + return buf >> (seq.resolution - read_resolution); + } + return buf << (read_resolution - seq.resolution); } #endif -void attachInterrupt(pin_size_t pinNumber, voidFuncPtr callback, PinStatus pinStatus) -{ - struct gpio_port_callback *pcb; - gpio_flags_t intmode = 0; +void attachInterrupt(pin_size_t pinNumber, voidFuncPtr callback, PinStatus pinStatus) { + struct gpio_port_callback *pcb; + gpio_flags_t intmode = 0; - if (!callback) { - return; - } + if (!callback) { + return; + } - if (pinStatus == LOW) { - intmode |= GPIO_INT_LEVEL_LOW; - } else if (pinStatus == HIGH) { - intmode |= GPIO_INT_LEVEL_HIGH; - } else if (pinStatus == CHANGE) { - intmode |= GPIO_INT_EDGE_BOTH; - } else if (pinStatus == FALLING) { - intmode |= GPIO_INT_EDGE_FALLING; - } else if (pinStatus == RISING) { - intmode |= GPIO_INT_EDGE_RISING; - } else { - return; - } + if (pinStatus == LOW) { + intmode |= GPIO_INT_LEVEL_LOW; + } else if (pinStatus == HIGH) { + intmode |= GPIO_INT_LEVEL_HIGH; + } else if (pinStatus == CHANGE) { + intmode |= GPIO_INT_EDGE_BOTH; + } else if (pinStatus == FALLING) { + intmode |= GPIO_INT_EDGE_FALLING; + } else if (pinStatus == RISING) { + intmode |= GPIO_INT_EDGE_RISING; + } else { + return; + } - pcb = find_gpio_port_callback(arduino_pins[pinNumber].port); - __ASSERT(pcb != nullptr, "gpio_port_callback not found"); + pcb = find_gpio_port_callback(arduino_pins[pinNumber].port); + __ASSERT(pcb != nullptr, "gpio_port_callback not found"); - pcb->pins |= BIT(arduino_pins[pinNumber].pin); - setInterruptHandler(pinNumber, callback); - enableInterrupt(pinNumber); + pcb->pins |= BIT(arduino_pins[pinNumber].pin); + setInterruptHandler(pinNumber, callback); + enableInterrupt(pinNumber); - gpio_pin_interrupt_configure(arduino_pins[pinNumber].port, arduino_pins[pinNumber].pin, intmode); - gpio_init_callback(&pcb->callback, handleGpioCallback, pcb->pins); - gpio_add_callback(arduino_pins[pinNumber].port, &pcb->callback); + gpio_pin_interrupt_configure(arduino_pins[pinNumber].port, arduino_pins[pinNumber].pin, + intmode); + gpio_init_callback(&pcb->callback, handleGpioCallback, pcb->pins); + gpio_add_callback(arduino_pins[pinNumber].port, &pcb->callback); } -void detachInterrupt(pin_size_t pinNumber) -{ - setInterruptHandler(pinNumber, nullptr); - disableInterrupt(pinNumber); +void detachInterrupt(pin_size_t pinNumber) { + setInterruptHandler(pinNumber, nullptr); + disableInterrupt(pinNumber); } #ifndef CONFIG_MINIMAL_LIBC_RAND @@ -493,80 +483,82 @@ long random(long max) { #ifdef CONFIG_GPIO_GET_DIRECTION unsigned long pulseIn(pin_size_t pinNumber, uint8_t state, unsigned long timeout) { - struct k_timer timer; - int64_t start, end, delta = 0; - const struct gpio_dt_spec *spec = &arduino_pins[pinNumber]; - - k_timer_init(&timer, NULL, NULL); - k_timer_start(&timer, K_MSEC(timeout), K_NO_WAIT); - - if (!gpio_is_ready_dt(spec)) { - goto cleanup; - } - - if (!gpio_pin_is_input_dt(spec)) { - goto cleanup; - } - - while(gpio_pin_get_dt(spec) == state && k_timer_status_get(&timer) == 0); - if (k_timer_status_get(&timer) > 0) { - goto cleanup; - } - - while(gpio_pin_get_dt(spec) != state && k_timer_status_get(&timer) == 0); - if (k_timer_status_get(&timer) > 0) { - goto cleanup; - } - - start = k_uptime_ticks(); - while(gpio_pin_get_dt(spec) == state && k_timer_status_get(&timer) == 0); - if (k_timer_status_get(&timer) > 0) { - goto cleanup; - } - end = k_uptime_ticks(); - - delta = k_ticks_to_us_floor64(end - start); + struct k_timer timer; + int64_t start, end, delta = 0; + const struct gpio_dt_spec *spec = &arduino_pins[pinNumber]; + + k_timer_init(&timer, NULL, NULL); + k_timer_start(&timer, K_MSEC(timeout), K_NO_WAIT); + + if (!gpio_is_ready_dt(spec)) { + goto cleanup; + } + + if (!gpio_pin_is_input_dt(spec)) { + goto cleanup; + } + + while (gpio_pin_get_dt(spec) == state && k_timer_status_get(&timer) == 0) + ; + if (k_timer_status_get(&timer) > 0) { + goto cleanup; + } + + while (gpio_pin_get_dt(spec) != state && k_timer_status_get(&timer) == 0) + ; + if (k_timer_status_get(&timer) > 0) { + goto cleanup; + } + + start = k_uptime_ticks(); + while (gpio_pin_get_dt(spec) == state && k_timer_status_get(&timer) == 0) + ; + if (k_timer_status_get(&timer) > 0) { + goto cleanup; + } + end = k_uptime_ticks(); + + delta = k_ticks_to_us_floor64(end - start); cleanup: - k_timer_stop(&timer); - return (unsigned long)delta; + k_timer_stop(&timer); + return (unsigned long)delta; } #endif // CONFIG_GPIO_GET_DIRECTION void enableInterrupt(pin_size_t pinNumber) { - struct gpio_port_callback *pcb = find_gpio_port_callback(arduino_pins[pinNumber].port); + struct gpio_port_callback *pcb = find_gpio_port_callback(arduino_pins[pinNumber].port); - if (pcb) { - pcb->handlers[BIT(arduino_pins[pinNumber].pin)].enabled = true; - } + if (pcb) { + pcb->handlers[BIT(arduino_pins[pinNumber].pin)].enabled = true; + } } void disableInterrupt(pin_size_t pinNumber) { - struct gpio_port_callback *pcb = find_gpio_port_callback(arduino_pins[pinNumber].port); + struct gpio_port_callback *pcb = find_gpio_port_callback(arduino_pins[pinNumber].port); - if (pcb) { - pcb->handlers[BIT(arduino_pins[pinNumber].pin)].enabled = false; - } + if (pcb) { + pcb->handlers[BIT(arduino_pins[pinNumber].pin)].enabled = false; + } } void interrupts(void) { - if (interrupts_disabled) { - irq_unlock(irq_key); - interrupts_disabled = false; - } + if (interrupts_disabled) { + irq_unlock(irq_key); + interrupts_disabled = false; + } } void noInterrupts(void) { - if (!interrupts_disabled) { - irq_key = irq_lock(); - interrupts_disabled = true; - } + if (!interrupts_disabled) { + irq_key = irq_lock(); + interrupts_disabled = true; + } } int digitalPinToInterrupt(pin_size_t pin) { - struct gpio_port_callback *pcb = - find_gpio_port_callback(arduino_pins[pin].port); + struct gpio_port_callback *pcb = find_gpio_port_callback(arduino_pins[pin].port); - return (pcb) ? pin : -1; + return (pcb) ? pin : -1; } diff --git a/cores/arduino/zephyrSerial.cpp b/cores/arduino/zephyrSerial.cpp index d2b44b51..2ebece7b 100644 --- a/cores/arduino/zephyrSerial.cpp +++ b/cores/arduino/zephyrSerial.cpp @@ -11,11 +11,9 @@ #include #include -namespace -{ +namespace { -enum uart_config_parity conf_parity(uint16_t conf) -{ +enum uart_config_parity conf_parity(uint16_t conf) { switch (conf & SERIAL_PARITY_MASK) { case SERIAL_PARITY_EVEN: return UART_CFG_PARITY_EVEN; @@ -26,8 +24,7 @@ enum uart_config_parity conf_parity(uint16_t conf) } } -enum uart_config_stop_bits conf_stop_bits(uint16_t conf) -{ +enum uart_config_stop_bits conf_stop_bits(uint16_t conf) { switch (conf & SERIAL_STOP_BIT_MASK) { case SERIAL_STOP_BIT_1_5: return UART_CFG_STOP_BITS_1_5; @@ -38,8 +35,7 @@ enum uart_config_stop_bits conf_stop_bits(uint16_t conf) } } -enum uart_config_data_bits conf_data_bits(uint16_t conf) -{ +enum uart_config_data_bits conf_data_bits(uint16_t conf) { switch (conf & SERIAL_DATA_MASK) { case SERIAL_DATA_5: return UART_CFG_DATA_BITS_5; @@ -54,8 +50,7 @@ enum uart_config_data_bits conf_data_bits(uint16_t conf) } // anonymous namespace -void arduino::ZephyrSerial::begin(unsigned long baud, uint16_t conf) -{ +void arduino::ZephyrSerial::begin(unsigned long baud, uint16_t conf) { struct uart_config config = { .baudrate = baud, .parity = conf_parity(conf), @@ -73,8 +68,7 @@ void arduino::ZephyrSerial::begin(unsigned long baud, uint16_t conf) uart_irq_rx_enable(uart); } -void arduino::ZephyrSerial::IrqHandler() -{ +void arduino::ZephyrSerial::IrqHandler() { uint8_t buf[8]; int length; int ret = 0; @@ -114,14 +108,12 @@ void arduino::ZephyrSerial::IrqHandler() k_sem_give(&tx.sem); } -void arduino::ZephyrSerial::IrqDispatch(const struct device *dev, void *data) -{ +void arduino::ZephyrSerial::IrqDispatch(const struct device *dev, void *data) { (void)dev; // unused reinterpret_cast(data)->IrqHandler(); } -int arduino::ZephyrSerial::available() -{ +int arduino::ZephyrSerial::available() { int ret; k_sem_take(&rx.sem, K_FOREVER); @@ -131,8 +123,7 @@ int arduino::ZephyrSerial::available() return ret; } -int arduino::ZephyrSerial::availableForWrite() -{ +int arduino::ZephyrSerial::availableForWrite() { int ret; k_sem_take(&rx.sem, K_FOREVER); @@ -142,35 +133,32 @@ int arduino::ZephyrSerial::availableForWrite() return ret; } -int arduino::ZephyrSerial::peek() -{ +int arduino::ZephyrSerial::peek() { uint8_t data; k_sem_take(&rx.sem, K_FOREVER); uint32_t cb_ret = ring_buf_peek(&rx.ringbuf, &data, 1); k_sem_give(&rx.sem); - return cb_ret? data : -1; + return cb_ret ? data : -1; } -int arduino::ZephyrSerial::read() -{ +int arduino::ZephyrSerial::read() { uint8_t data; k_sem_take(&rx.sem, K_FOREVER); uint32_t cb_ret = ring_buf_get(&rx.ringbuf, &data, 1); k_sem_give(&rx.sem); - return cb_ret? data : -1; + return cb_ret ? data : -1; } -size_t arduino::ZephyrSerial::write(const uint8_t *buffer, size_t size) -{ +size_t arduino::ZephyrSerial::write(const uint8_t *buffer, size_t size) { size_t idx = 0; while (1) { k_sem_take(&tx.sem, K_FOREVER); - auto ret = ring_buf_put(&tx.ringbuf, &buffer[idx], size-idx); + auto ret = ring_buf_put(&tx.ringbuf, &buffer[idx], size - idx); k_sem_give(&tx.sem); if (ret < 0) { return 0; @@ -194,7 +182,7 @@ void arduino::ZephyrSerial::flush() { while (ring_buf_size_get(&tx.ringbuf) > 0) { k_yield(); } - while (uart_irq_tx_complete(uart) == 0){ + while (uart_irq_tx_complete(uart) == 0) { k_yield(); } } @@ -206,9 +194,11 @@ void arduino::ZephyrSerial::flush() { #endif #if DT_NODE_HAS_PROP(DT_PATH(zephyr_user), serials) -#if !(DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && (CONFIG_USB_CDC_ACM || CONFIG_USBD_CDC_ACM_CLASS)) +#if !(DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && \ + (CONFIG_USB_CDC_ACM || CONFIG_USBD_CDC_ACM_CLASS)) // If CDC USB, use that object as Serial (and SerialUSB) -arduino::ZephyrSerial Serial(DEVICE_DT_GET(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), serials, FIRST_UART_INDEX))); +arduino::ZephyrSerial + Serial(DEVICE_DT_GET(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), serials, FIRST_UART_INDEX))); #endif #if (DT_PROP_LEN(DT_PATH(zephyr_user), serials) > 1) #define ARDUINO_SERIAL_DEFINED_0 1 @@ -220,13 +210,17 @@ arduino::ZephyrSerial Serial(DEVICE_DT_GET(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user COND_CODE_1(ARDUINO_SERIAL_DEFINED_##i, (DECL_SERIAL_0(n, p, i)), (DECL_SERIAL_N(n, p, i))) #define CALL_EVENT_0(n, p, i) -#define CALL_EVENT_N(n, p, i) if (_CONCAT(Serial, i).available()) _CONCAT(_CONCAT(serial, i), Event)(); -#define CALL_SERIALEVENT_N(n, p, i) \ +#define CALL_EVENT_N(n, p, i) \ + if (_CONCAT(Serial, i).available()) \ + _CONCAT(_CONCAT(serial, i), Event)(); +#define CALL_SERIALEVENT_N(n, p, i) \ COND_CODE_1(ARDUINO_SERIAL_DEFINED_##i, (CALL_EVENT_0(n, p, i)), (CALL_EVENT_N(n, p, i))); #define DECL_EVENT_0(n, p, i) -#define DECL_EVENT_N(n, p, i) __attribute__((weak)) void serial##i##Event() { } -#define DECLARE_SERIALEVENT_N(n, p, i) \ +#define DECL_EVENT_N(n, p, i) \ + __attribute__((weak)) void serial##i##Event() { \ + } +#define DECLARE_SERIALEVENT_N(n, p, i) \ COND_CODE_1(ARDUINO_SERIAL_DEFINED_##i, (DECL_EVENT_0(n, p, i)), (DECL_EVENT_N(n, p, i))); DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), serials, DECLARE_SERIAL_N) @@ -238,15 +232,16 @@ arduino::ZephyrSerial Serial(DEVICE_DT_GET(DT_NODELABEL(arduino_serial))); arduino::ZephyrSerialStub Serial; #endif - -__attribute__((weak)) void serialEvent() { } +__attribute__((weak)) void serialEvent() { +} #if (DT_PROP_LEN(DT_PATH(zephyr_user), serials) > 1) DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), serials, DECLARE_SERIALEVENT_N) #endif -void arduino::serialEventRun(void) -{ - if (Serial.available()) serialEvent(); +void arduino::serialEventRun(void) { + if (Serial.available()) { + serialEvent(); + } #if (DT_PROP_LEN(DT_PATH(zephyr_user), serials) > 1) DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), serials, CALL_SERIALEVENT_N) #endif diff --git a/cores/arduino/zephyrSerial.h b/cores/arduino/zephyrSerial.h index ecc18a81..5e1d15fe 100644 --- a/cores/arduino/zephyrSerial.h +++ b/cores/arduino/zephyrSerial.h @@ -12,58 +12,84 @@ namespace arduino { -class ZephyrSerialStub : public HardwareSerial -{ +class ZephyrSerialStub : public HardwareSerial { public: - void begin(__attribute__((unused)) unsigned long baudRate) { } - void begin(__attribute__((unused)) unsigned long baudrate, __attribute__((unused)) uint16_t config) { } - void end() { } - int available() { return 0; } - int peek() { return 0; } - int read() { return 0; } - void flush() { } - size_t write(const uint8_t data) - { + void begin(__attribute__((unused)) unsigned long baudRate) { + } + + void begin(__attribute__((unused)) unsigned long baudrate, + __attribute__((unused)) uint16_t config) { + } + + void end() { + } + + int available() { + return 0; + } + + int peek() { + return 0; + } + + int read() { + return 0; + } + + void flush() { + } + + size_t write(const uint8_t data) { printk("%c", static_cast(data)); return 1; } - operator bool() { return true; } + operator bool() { + return true; + } }; -class ZephyrSerial : public HardwareSerial -{ +class ZephyrSerial : public HardwareSerial { public: - template - class ZephyrSerialBuffer - { + template class ZephyrSerialBuffer { friend arduino::ZephyrSerial; struct ring_buf ringbuf; uint8_t buffer[SZ]; struct k_sem sem; - ZephyrSerialBuffer() - { + ZephyrSerialBuffer() { k_sem_init(&sem, 1, 1); ring_buf_init(&ringbuf, sizeof(buffer), buffer); } }; - ZephyrSerial(const struct device *dev) : uart(dev) { } + ZephyrSerial(const struct device *dev) : uart(dev) { + } + void begin(unsigned long baudrate, uint16_t config); - void begin(unsigned long baudrate) { begin(baudrate, SERIAL_8N1); } + + void begin(unsigned long baudrate) { + begin(baudrate, SERIAL_8N1); + } + void flush(); - void end() { } + + void end() { + } + size_t write(const uint8_t *buffer, size_t size); - size_t write(const uint8_t data) { return write(&data, 1); } + + size_t write(const uint8_t data) { + return write(&data, 1); + } + using Print::write; // pull in write(str) and write(buf, size) from Print int available(); - int availableForWrite(); + int availableForWrite(); int peek(); int read(); - operator bool() - { + operator bool() { return true; } @@ -78,17 +104,17 @@ class ZephyrSerial : public HardwareSerial ZephyrSerialBuffer rx; }; - -} // namespace arduino +} // namespace arduino #if DT_NODE_HAS_PROP(DT_PATH(zephyr_user), serials) -#if !(DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && (CONFIG_USB_CDC_ACM || CONFIG_USBD_CDC_ACM_CLASS)) +#if !(DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && \ + (CONFIG_USB_CDC_ACM || CONFIG_USBD_CDC_ACM_CLASS)) // If CDC USB, use that object as Serial (and SerialUSB) extern arduino::ZephyrSerial Serial; #endif #if (DT_PROP_LEN(DT_PATH(zephyr_user), serials) > 1) -#define SERIAL_DEFINED_0 1 -#define EXTERN_SERIAL_N(i) extern arduino::ZephyrSerial Serial##i; +#define SERIAL_DEFINED_0 1 +#define EXTERN_SERIAL_N(i) extern arduino::ZephyrSerial Serial##i; #define DECLARE_EXTERN_SERIAL_N(n, p, i) COND_CODE_1(SERIAL_DEFINED_##i, (), (EXTERN_SERIAL_N(i))) /* Declare Serial1, Serial2, ... */ diff --git a/libraries/Camera/examples/CameraCaptureRawBytes/CameraCaptureRawBytes.ino b/libraries/Camera/examples/CameraCaptureRawBytes/CameraCaptureRawBytes.ino index fca2252a..5f570e02 100644 --- a/libraries/Camera/examples/CameraCaptureRawBytes/CameraCaptureRawBytes.ino +++ b/libraries/Camera/examples/CameraCaptureRawBytes/CameraCaptureRawBytes.ino @@ -3,31 +3,31 @@ Camera cam; void fatal_error(const char *msg) { - Serial.println(msg); - pinMode(LED_BUILTIN, OUTPUT); - while (1) { - digitalWrite(LED_BUILTIN, HIGH); - delay(100); - digitalWrite(LED_BUILTIN, LOW); - delay(100); - } + Serial.println(msg); + pinMode(LED_BUILTIN, OUTPUT); + while (1) { + digitalWrite(LED_BUILTIN, HIGH); + delay(100); + digitalWrite(LED_BUILTIN, LOW); + delay(100); + } } void setup(void) { - Serial.begin(115200); - if (!cam.begin(320, 240, CAMERA_RGB565)) { - fatal_error("Camera begin failed"); - } - cam.setVerticalFlip(false); - cam.setHorizontalMirror(false); + Serial.begin(115200); + if (!cam.begin(320, 240, CAMERA_RGB565)) { + fatal_error("Camera begin failed"); + } + cam.setVerticalFlip(false); + cam.setHorizontalMirror(false); } void loop() { - FrameBuffer fb; - if (cam.grabFrame(fb)) { - if (Serial.read() == 1) { - Serial.write(fb.getBuffer(), fb.getBufferSize()); - } - cam.releaseFrame(fb); - } + FrameBuffer fb; + if (cam.grabFrame(fb)) { + if (Serial.read() == 1) { + Serial.write(fb.getBuffer(), fb.getBufferSize()); + } + cam.releaseFrame(fb); + } } diff --git a/libraries/Camera/extras/CameraRawBytesVisualizer/CameraRawBytesVisualizer.pde b/libraries/Camera/extras/CameraRawBytesVisualizer/CameraRawBytesVisualizer.pde index dcb2570b..a50db6df 100644 --- a/libraries/Camera/extras/CameraRawBytesVisualizer/CameraRawBytesVisualizer.pde +++ b/libraries/Camera/extras/CameraRawBytesVisualizer/CameraRawBytesVisualizer.pde @@ -25,7 +25,8 @@ final int baudRate = 115200; final int cameraBytesPerPixel = useGrayScale ? 1 : 2; final int cameraPixelCount = cameraWidth * cameraHeight; final int bytesPerFrame = cameraPixelCount * cameraBytesPerPixel; -final int timeout = int((bytesPerFrame / float(baudRate / 10)) * 1000 * 2); // Twice the transfer rate +final int timeout = + int((bytesPerFrame / float(baudRate / 10)) * 1000 * 2); // Twice the transfer rate PImage myImage; byte[] frameBuffer = new byte[bytesPerFrame]; @@ -33,96 +34,97 @@ int lastUpdate = 0; boolean shouldRedraw = false; void setup() { - size(640, 480); + size(640, 480); - // If you have only ONE serial port active you may use this: - //myPort = new Serial(this, Serial.list()[0], baudRate); // if you have only ONE serial port active + // If you have only ONE serial port active you may use this: + // myPort = new Serial(this, Serial.list()[0], baudRate); // if you have only ONE + // serial port active - // If you know the serial port name - //myPort = new Serial(this, "COM5", baudRate); // Windows - myPort = new Serial(this, "/dev/ttyACM0", baudRate); // Linux - //myPort = new Serial(this, "/dev/cu.usbmodem14301", baudRate); // Mac + // If you know the serial port name + // myPort = new Serial(this, "COM5", baudRate); // Windows + myPort = new Serial(this, "/dev/ttyACM0", baudRate); // Linux + // myPort = new Serial(this, "/dev/cu.usbmodem14301", baudRate); // Mac - // wait for a full frame of bytes - myPort.buffer(bytesPerFrame); + // wait for a full frame of bytes + myPort.buffer(bytesPerFrame); - myImage = createImage(cameraWidth, cameraHeight, ALPHA); - - // Let the Arduino sketch know we're ready to receive data - myPort.write(1); + myImage = createImage(cameraWidth, cameraHeight, ALPHA); + + // Let the Arduino sketch know we're ready to receive data + myPort.write(1); } void draw() { - // Time out after a few seconds and ask for new data - if(millis() - lastUpdate > timeout) { - println("Connection timed out."); - myPort.clear(); - myPort.write(1); - } - - if(shouldRedraw){ - PImage img = myImage.copy(); - img.resize(640, 480); - image(img, 0, 0); - shouldRedraw = false; - } + // Time out after a few seconds and ask for new data + if (millis() - lastUpdate > timeout) { + println("Connection timed out."); + myPort.clear(); + myPort.write(1); + } + + if (shouldRedraw) { + PImage img = myImage.copy(); + img.resize(640, 480); + image(img, 0, 0); + shouldRedraw = false; + } } -int[] convertRGB565ToRGB888(short pixelValue){ - //RGB565 - int r = (pixelValue >> (6+5)) & 0x01F; - int g = (pixelValue >> 5) & 0x03F; - int b = (pixelValue) & 0x01F; - //RGB888 - amplify - r <<= 3; - g <<= 2; - b <<= 3; - return new int[]{r,g,b}; +int[] convertRGB565ToRGB888(short pixelValue) { + // RGB565 + int r = (pixelValue >> (6 + 5)) & 0x01F; + int g = (pixelValue >> 5) & 0x03F; + int b = (pixelValue) & 0x01F; + // RGB888 - amplify + r <<= 3; + g <<= 2; + b <<= 3; + return new int[]{r, g, b}; } -void serialEvent(Serial myPort) { - lastUpdate = millis(); - - // read the received bytes - myPort.readBytes(frameBuffer); - - // Access raw bytes via byte buffer - ByteBuffer bb = ByteBuffer.wrap(frameBuffer); - - // Ensure proper endianness of the data for > 8 bit values. - // The 1 byte bb.get() function will always return the bytes in the correct order. - bb.order(ByteOrder.BIG_ENDIAN); - - int i = 0; - - while (bb.hasRemaining()) { - if(useGrayScale){ - // read 8-bit pixel data - byte pixelValue = bb.get(); - - // set pixel color - myImage.pixels[i++] = color(Byte.toUnsignedInt(pixelValue)); - } else { - // read 16-bit pixel data - int[] rgbValues = convertRGB565ToRGB888(bb.getShort()); - - // set pixel RGB color - myImage.pixels[i++] = color(rgbValues[0], rgbValues[1], rgbValues[2]); - } - } - - myImage.updatePixels(); - - // Ensures that the new image data is drawn in the next draw loop - shouldRedraw = true; - - // Let the Arduino sketch know we received all pixels - // and are ready for the next frame - myPort.write(1); +void serialEvent(Serial myPort) { + lastUpdate = millis(); + + // read the received bytes + myPort.readBytes(frameBuffer); + + // Access raw bytes via byte buffer + ByteBuffer bb = ByteBuffer.wrap(frameBuffer); + + // Ensure proper endianness of the data for > 8 bit values. + // The 1 byte bb.get() function will always return the bytes in the correct order. + bb.order(ByteOrder.BIG_ENDIAN); + + int i = 0; + + while (bb.hasRemaining()) { + if (useGrayScale) { + // read 8-bit pixel data + byte pixelValue = bb.get(); + + // set pixel color + myImage.pixels[i++] = color(Byte.toUnsignedInt(pixelValue)); + } else { + // read 16-bit pixel data + int[] rgbValues = convertRGB565ToRGB888(bb.getShort()); + + // set pixel RGB color + myImage.pixels[i++] = color(rgbValues[0], rgbValues[1], rgbValues[2]); + } + } + + myImage.updatePixels(); + + // Ensures that the new image data is drawn in the next draw loop + shouldRedraw = true; + + // Let the Arduino sketch know we received all pixels + // and are ready for the next frame + myPort.write(1); } void keyPressed() { - if (key == ' ') { - useGrayScale = !useGrayScale; // change boolean value of greyscale when space is pressed - } + if (key == ' ') { + useGrayScale = !useGrayScale; // change boolean value of greyscale when space is pressed + } } diff --git a/libraries/Camera/src/camera.cpp b/libraries/Camera/src/camera.cpp index fd4ac2ac..c8562094 100644 --- a/libraries/Camera/src/camera.cpp +++ b/libraries/Camera/src/camera.cpp @@ -25,89 +25,86 @@ #include FrameBuffer::FrameBuffer() : vbuf(NULL) { - } uint32_t FrameBuffer::getBufferSize() { - if (this->vbuf) { - return this->vbuf->bytesused; - } + if (this->vbuf) { + return this->vbuf->bytesused; + } } -uint8_t* FrameBuffer::getBuffer() { - if (this->vbuf) { - return this->vbuf->buffer; - } +uint8_t *FrameBuffer::getBuffer() { + if (this->vbuf) { + return this->vbuf->buffer; + } } Camera::Camera() : vdev(NULL), byte_swap(false), yuv_to_gray(false) { for (size_t i = 0; i < ARRAY_SIZE(this->vbuf); i++) { this->vbuf[i] = NULL; - } + } } bool Camera::begin(uint32_t width, uint32_t height, uint32_t pixformat, bool byte_swap) { - #if DT_HAS_CHOSEN(zephyr_camera) - this->vdev = DEVICE_DT_GET(DT_CHOSEN(zephyr_camera)); - #endif - - if (!this->vdev || !device_is_ready(this->vdev)) { - return false; - } - - switch (pixformat) { - case CAMERA_RGB565: - this->byte_swap = byte_swap; - pixformat = VIDEO_PIX_FMT_RGB565; - break; - case CAMERA_GRAYSCALE: - // There's no support for mono sensors. - this->yuv_to_gray = true; - pixformat = VIDEO_PIX_FMT_YUYV; - break; - default: - break; - } - - // Get capabilities - struct video_caps caps; - if (video_get_caps(this->vdev, &caps)) { - return false; - } - - for (size_t i=0; caps.format_caps[i].pixelformat != NULL; i++) { - const struct video_format_cap *fcap = &caps.format_caps[i]; - if (fcap->width_min == width && - fcap->height_min == height && - fcap->pixelformat == pixformat) { - break; - } - if (caps.format_caps[i+1].pixelformat == NULL) { - Serial.println("The specified format is not supported"); - return false; - } - } - - // Set format. - static struct video_format fmt = { - .pixelformat = pixformat, - .width = width, - .height = height, - .pitch = width * 2, - }; +#if DT_HAS_CHOSEN(zephyr_camera) + this->vdev = DEVICE_DT_GET(DT_CHOSEN(zephyr_camera)); +#endif + + if (!this->vdev || !device_is_ready(this->vdev)) { + return false; + } + + switch (pixformat) { + case CAMERA_RGB565: + this->byte_swap = byte_swap; + pixformat = VIDEO_PIX_FMT_RGB565; + break; + case CAMERA_GRAYSCALE: + // There's no support for mono sensors. + this->yuv_to_gray = true; + pixformat = VIDEO_PIX_FMT_YUYV; + break; + default: + break; + } + + // Get capabilities + struct video_caps caps; + if (video_get_caps(this->vdev, &caps)) { + return false; + } + + for (size_t i = 0; caps.format_caps[i].pixelformat != NULL; i++) { + const struct video_format_cap *fcap = &caps.format_caps[i]; + if (fcap->width_min == width && fcap->height_min == height && + fcap->pixelformat == pixformat) { + break; + } + if (caps.format_caps[i + 1].pixelformat == NULL) { + Serial.println("The specified format is not supported"); + return false; + } + } + + // Set format. + static struct video_format fmt = { + .pixelformat = pixformat, + .width = width, + .height = height, + .pitch = width * 2, + }; if (video_set_format(this->vdev, &fmt)) { - Serial.println("Failed to set video format"); + Serial.println("Failed to set video format"); return false; } // Allocate video buffers. for (size_t i = 0; i < ARRAY_SIZE(this->vbuf); i++) { this->vbuf[i] = video_buffer_aligned_alloc(fmt.pitch * fmt.height, - CONFIG_VIDEO_BUFFER_POOL_ALIGN, - K_FOREVER); + CONFIG_VIDEO_BUFFER_POOL_ALIGN, K_FOREVER); if (this->vbuf[i] == NULL) { - Serial.println("Failed to allocate video buffers"); + Serial.println("Failed to allocate video buffers"); return false; } video_enqueue(this->vdev, this->vbuf[i]); @@ -115,58 +112,58 @@ bool Camera::begin(uint32_t width, uint32_t height, uint32_t pixformat, bool byt // Start video capture if (video_stream_start(this->vdev, VIDEO_BUF_TYPE_OUTPUT)) { - Serial.println("Failed to start capture"); + Serial.println("Failed to start capture"); return false; } - return true; + return true; } bool Camera::grabFrame(FrameBuffer &fb, uint32_t timeout) { - if (this->vdev == NULL) { - return false; - } - - if (video_dequeue(this->vdev, &fb.vbuf, K_MSEC(timeout))) { - return false; - } - - if (this->byte_swap) { - uint16_t *pixels = (uint16_t *) fb.vbuf->buffer; - for (size_t i=0; ibytesused / 2; i++) { - pixels[i] = __REVSH(pixels[i]); - } - } - - if (this->yuv_to_gray) { - uint8_t *pixels = (uint8_t *) fb.vbuf->buffer; - for (size_t i=0; ibytesused / 2; i++) { - pixels[i] = pixels[i*2]; - } - fb.vbuf->bytesused /= 2; - } - - return true; + if (this->vdev == NULL) { + return false; + } + + if (video_dequeue(this->vdev, &fb.vbuf, K_MSEC(timeout))) { + return false; + } + + if (this->byte_swap) { + uint16_t *pixels = (uint16_t *)fb.vbuf->buffer; + for (size_t i = 0; i < fb.vbuf->bytesused / 2; i++) { + pixels[i] = __REVSH(pixels[i]); + } + } + + if (this->yuv_to_gray) { + uint8_t *pixels = (uint8_t *)fb.vbuf->buffer; + for (size_t i = 0; i < fb.vbuf->bytesused / 2; i++) { + pixels[i] = pixels[i * 2]; + } + fb.vbuf->bytesused /= 2; + } + + return true; } bool Camera::releaseFrame(FrameBuffer &fb) { - if (this->vdev == NULL) { - return false; - } + if (this->vdev == NULL) { + return false; + } - if (video_enqueue(this->vdev, fb.vbuf)) { - return false; + if (video_enqueue(this->vdev, fb.vbuf)) { + return false; } - return true; + return true; } bool Camera::setVerticalFlip(bool flip_enable) { - struct video_control ctrl = {.id = VIDEO_CID_VFLIP, .val = flip_enable}; - return video_set_ctrl(this->vdev, &ctrl) == 0; + struct video_control ctrl = {.id = VIDEO_CID_VFLIP, .val = flip_enable}; + return video_set_ctrl(this->vdev, &ctrl) == 0; } bool Camera::setHorizontalMirror(bool mirror_enable) { - struct video_control ctrl = {.id = VIDEO_CID_HFLIP, .val = mirror_enable}; - return video_set_ctrl(this->vdev, &ctrl) == 0; + struct video_control ctrl = {.id = VIDEO_CID_HFLIP, .val = mirror_enable}; + return video_set_ctrl(this->vdev, &ctrl) == 0; } diff --git a/libraries/Camera/src/camera.h b/libraries/Camera/src/camera.h index c456c5ff..d6f05e20 100644 --- a/libraries/Camera/src/camera.h +++ b/libraries/Camera/src/camera.h @@ -17,17 +17,18 @@ */ #ifndef __CAMERA_H__ #define __CAMERA_H__ -/** + +/** * @enum CameraPixelFormat * @brief Camera pixel format enumeration. - * + * * The different formats use different numbers of bits per pixel: * - Grayscale (8-bit) * - RGB565 (16-bit) */ enum CameraPixelFormat { - CAMERA_RGB565, /**< RGB565 format (16-bit). */ - CAMERA_GRAYSCALE, /**< Grayscale format (8-bit). */ + CAMERA_RGB565, /**< RGB565 format (16-bit). */ + CAMERA_GRAYSCALE, /**< Grayscale format (8-bit). */ }; /** @@ -35,31 +36,31 @@ enum CameraPixelFormat { * @brief Frame buffer class for storing captured frames. */ class FrameBuffer { - private: - struct video_buffer *vbuf; +private: + struct video_buffer *vbuf; - public: - /** - * @brief Construct a new FrameBuffer object. - */ - FrameBuffer(); +public: + /** + * @brief Construct a new FrameBuffer object. + */ + FrameBuffer(); - /** - * @brief Get the buffer size in bytes. - * @return uint32_t The buffer size in bytes. - */ - uint32_t getBufferSize(); + /** + * @brief Get the buffer size in bytes. + * @return uint32_t The buffer size in bytes. + */ + uint32_t getBufferSize(); - /** - * @brief Get a pointer to the frame buffer. - * - * This can be used to read the pixels from the frame buffer. - * For example, to print all pixels to the serial monitor as hex values. - * - * @return uint8_t* Pointer to the frame buffer. - */ - uint8_t* getBuffer(); - friend class Camera; + /** + * @brief Get a pointer to the frame buffer. + * + * This can be used to read the pixels from the frame buffer. + * For example, to print all pixels to the serial monitor as hex values. + * + * @return uint8_t* Pointer to the frame buffer. + */ + uint8_t *getBuffer(); + friend class Camera; }; /** @@ -67,61 +68,62 @@ class FrameBuffer { * @brief The main class for controlling a camera. */ class Camera { - private: - bool byte_swap; - bool yuv_to_gray; - const struct device *vdev; - struct video_buffer *vbuf[CONFIG_VIDEO_BUFFER_POOL_NUM_MAX]; +private: + bool byte_swap; + bool yuv_to_gray; + const struct device *vdev; + struct video_buffer *vbuf[CONFIG_VIDEO_BUFFER_POOL_NUM_MAX]; - public: - /** - * @brief Construct a new Camera object. - */ - Camera(); +public: + /** + * @brief Construct a new Camera object. + */ + Camera(); - /** - * @brief Initialize the camera. - * - * @param width Frame width in pixels. - * @param height Frame height in pixels. - * @param pixformat Initial pixel format (default: CAMERA_RGB565). - * @param byte_swap Enable byte swapping (default: false). - * @return true if the camera is successfully initialized, otherwise false. - */ - bool begin(uint32_t width, uint32_t height, uint32_t pixformat = CAMERA_RGB565, bool byte_swap = false); + /** + * @brief Initialize the camera. + * + * @param width Frame width in pixels. + * @param height Frame height in pixels. + * @param pixformat Initial pixel format (default: CAMERA_RGB565). + * @param byte_swap Enable byte swapping (default: false). + * @return true if the camera is successfully initialized, otherwise false. + */ + bool begin(uint32_t width, uint32_t height, uint32_t pixformat = CAMERA_RGB565, + bool byte_swap = false); - /** - * @brief Capture a frame. - * - * @param fb Reference to a FrameBuffer object to store the frame data. - * @param timeout Time in milliseconds to wait for a frame (default: 5000). - * @return true if the frame is successfully captured, otherwise false. - */ - bool grabFrame(FrameBuffer &fb, uint32_t timeout = 5000); + /** + * @brief Capture a frame. + * + * @param fb Reference to a FrameBuffer object to store the frame data. + * @param timeout Time in milliseconds to wait for a frame (default: 5000). + * @return true if the frame is successfully captured, otherwise false. + */ + bool grabFrame(FrameBuffer &fb, uint32_t timeout = 5000); - /** - * @brief Release a frame buffer. - * - * @param fb Reference to a FrameBuffer object to release. - * @return true if the frame buffer is successfully released, otherwise false. - */ - bool releaseFrame(FrameBuffer &fb); + /** + * @brief Release a frame buffer. + * + * @param fb Reference to a FrameBuffer object to release. + * @return true if the frame buffer is successfully released, otherwise false. + */ + bool releaseFrame(FrameBuffer &fb); - /** - * @brief Flip the camera image vertically. - * - * @param flip_enable Set to true to enable vertical flip, false to disable. - * @return true on success, false on failure. - */ - bool setVerticalFlip(bool flip_enable); + /** + * @brief Flip the camera image vertically. + * + * @param flip_enable Set to true to enable vertical flip, false to disable. + * @return true on success, false on failure. + */ + bool setVerticalFlip(bool flip_enable); - /** - * @brief Mirror the camera image horizontally. - * - * @param mirror_enable Set to true to enable horizontal mirror, false to disable. - * @return true on success, false on failure. - */ - bool setHorizontalMirror(bool mirror_enable); + /** + * @brief Mirror the camera image horizontally. + * + * @param mirror_enable Set to true to enable horizontal mirror, false to disable. + * @return true on success, false on failure. + */ + bool setHorizontalMirror(bool mirror_enable); }; #endif // __CAMERA_H__ diff --git a/libraries/SPI/SPI.cpp b/libraries/SPI/SPI.cpp index 897d57f2..8dd61f21 100644 --- a/libraries/SPI/SPI.cpp +++ b/libraries/SPI/SPI.cpp @@ -8,69 +8,70 @@ #include "zephyrInternal.h" #include -arduino::ZephyrSPI::ZephyrSPI(const struct device *spi) : spi_dev(spi) {} +arduino::ZephyrSPI::ZephyrSPI(const struct device *spi) : spi_dev(spi) { +} uint8_t arduino::ZephyrSPI::transfer(uint8_t data) { - int ret; - uint8_t rx; - const struct spi_buf tx_buf = {.buf = &data, .len = sizeof(data)}; - const struct spi_buf_set tx_buf_set = { - .buffers = &tx_buf, - .count = 1, - }; - const struct spi_buf rx_buf = {.buf = &rx, .len = sizeof(rx)}; - const struct spi_buf_set rx_buf_set = { - .buffers = &rx_buf, - .count = 1, - }; - - ret = spi_transceive(spi_dev, &config, &tx_buf_set, &rx_buf_set); - if (ret < 0) { - return 0; - } - - return rx; + int ret; + uint8_t rx; + const struct spi_buf tx_buf = {.buf = &data, .len = sizeof(data)}; + const struct spi_buf_set tx_buf_set = { + .buffers = &tx_buf, + .count = 1, + }; + const struct spi_buf rx_buf = {.buf = &rx, .len = sizeof(rx)}; + const struct spi_buf_set rx_buf_set = { + .buffers = &rx_buf, + .count = 1, + }; + + ret = spi_transceive(spi_dev, &config, &tx_buf_set, &rx_buf_set); + if (ret < 0) { + return 0; + } + + return rx; } uint16_t arduino::ZephyrSPI::transfer16(uint16_t data) { - int ret; - uint16_t rx; - const struct spi_buf tx_buf = {.buf = &data, .len = sizeof(data)}; - const struct spi_buf_set tx_buf_set = { - .buffers = &tx_buf, - .count = 1, - }; - const struct spi_buf rx_buf = {.buf = &rx, .len = sizeof(rx)}; - const struct spi_buf_set rx_buf_set = { - .buffers = &rx_buf, - .count = 1, - }; - - ret = spi_transceive(spi_dev, &config16, &tx_buf_set, &rx_buf_set); - if (ret < 0) { - return 0; - } - - return rx; + int ret; + uint16_t rx; + const struct spi_buf tx_buf = {.buf = &data, .len = sizeof(data)}; + const struct spi_buf_set tx_buf_set = { + .buffers = &tx_buf, + .count = 1, + }; + const struct spi_buf rx_buf = {.buf = &rx, .len = sizeof(rx)}; + const struct spi_buf_set rx_buf_set = { + .buffers = &rx_buf, + .count = 1, + }; + + ret = spi_transceive(spi_dev, &config16, &tx_buf_set, &rx_buf_set); + if (ret < 0) { + return 0; + } + + return rx; } void arduino::ZephyrSPI::transfer(void *buf, size_t count) { - int ret; - const struct spi_buf tx_buf = {.buf = buf, .len = count}; - const struct spi_buf_set tx_buf_set = { - .buffers = &tx_buf, - .count = 1, - }; - - uint8_t rx[count]; - const struct spi_buf rx_buf = {.buf = &rx, .len = count}; - const struct spi_buf_set rx_buf_set = { - .buffers = &rx_buf, - .count = 1, - }; - - spi_transceive(spi_dev, &config, &tx_buf_set, &rx_buf_set); - memcpy(buf, rx, count); + int ret; + const struct spi_buf tx_buf = {.buf = buf, .len = count}; + const struct spi_buf_set tx_buf_set = { + .buffers = &tx_buf, + .count = 1, + }; + + uint8_t rx[count]; + const struct spi_buf rx_buf = {.buf = &rx, .len = count}; + const struct spi_buf_set rx_buf_set = { + .buffers = &rx_buf, + .count = 1, + }; + + spi_transceive(spi_dev, &config, &tx_buf_set, &rx_buf_set); + memcpy(buf, rx, count); } void arduino::ZephyrSPI::usingInterrupt(int interruptNumber) { @@ -84,41 +85,52 @@ void arduino::ZephyrSPI::notUsingInterrupt(int interruptNumber) { #endif void arduino::ZephyrSPI::beginTransaction(SPISettings settings) { - memset(&config, 0, sizeof(config)); - memset(&config16, 0, sizeof(config16)); - config.frequency = settings.getClockFreq() > SPI_MIN_CLOCK_FEQUENCY ? settings.getClockFreq() : SPI_MIN_CLOCK_FEQUENCY; - config16.frequency = config.frequency; - - auto mode = SPI_MODE_CPOL | SPI_MODE_CPHA; - switch (settings.getDataMode()) { - case SPI_MODE0: - mode = 0; break; - case SPI_MODE1: - mode = SPI_MODE_CPHA; break; - case SPI_MODE2: - mode = SPI_MODE_CPOL; break; - case SPI_MODE3: - mode = SPI_MODE_CPOL | SPI_MODE_CPHA; break; - } - config.operation = SPI_WORD_SET(8) | (settings.getBitOrder() == MSBFIRST ? SPI_TRANSFER_MSB : SPI_TRANSFER_LSB) | mode; - config16.operation = SPI_WORD_SET(16) | (settings.getBitOrder() == MSBFIRST ? SPI_TRANSFER_MSB : SPI_TRANSFER_LSB) | mode; + memset(&config, 0, sizeof(config)); + memset(&config16, 0, sizeof(config16)); + config.frequency = settings.getClockFreq() > SPI_MIN_CLOCK_FEQUENCY ? settings.getClockFreq() : + SPI_MIN_CLOCK_FEQUENCY; + config16.frequency = config.frequency; + + auto mode = SPI_MODE_CPOL | SPI_MODE_CPHA; + switch (settings.getDataMode()) { + case SPI_MODE0: + mode = 0; + break; + case SPI_MODE1: + mode = SPI_MODE_CPHA; + break; + case SPI_MODE2: + mode = SPI_MODE_CPOL; + break; + case SPI_MODE3: + mode = SPI_MODE_CPOL | SPI_MODE_CPHA; + break; + } + config.operation = SPI_WORD_SET(8) | + (settings.getBitOrder() == MSBFIRST ? SPI_TRANSFER_MSB : SPI_TRANSFER_LSB) | + mode; + config16.operation = + SPI_WORD_SET(16) | + (settings.getBitOrder() == MSBFIRST ? SPI_TRANSFER_MSB : SPI_TRANSFER_LSB) | mode; } void arduino::ZephyrSPI::endTransaction(void) { - spi_release(spi_dev, &config); + spi_release(spi_dev, &config); } -void arduino::ZephyrSPI::attachInterrupt() {} - -void arduino::ZephyrSPI::detachInterrupt() {} +void arduino::ZephyrSPI::attachInterrupt() { +} +void arduino::ZephyrSPI::detachInterrupt() { +} void arduino::ZephyrSPI::begin() { - beginTransaction(SPISettings()); - endTransaction(); + beginTransaction(SPISettings()); + endTransaction(); } -void arduino::ZephyrSPI::end() {} +void arduino::ZephyrSPI::end() { +} #if DT_NODE_HAS_PROP(DT_PATH(zephyr_user), spis) #if (DT_PROP_LEN(DT_PATH(zephyr_user), spis) > 1) diff --git a/libraries/SPI/SPI.h b/libraries/SPI/SPI.h index ec3b6869..95c41ce2 100644 --- a/libraries/SPI/SPI.h +++ b/libraries/SPI/SPI.h @@ -19,43 +19,43 @@ #define CPOL 3 #define MSTR 4 #define DORD 5 -#define SPE 6 +#define SPE 6 #define SPIE 7 /* Count the number of GPIOs for limit of number of interrupts */ #define INTERRUPT_HELPER(n, p, i) 1 -#define INTERRUPT_COUNT \ - DT_FOREACH_PROP_ELEM_SEP(DT_PATH(zephyr_user), digital_pin_gpios, \ +#define INTERRUPT_COUNT \ + DT_FOREACH_PROP_ELEM_SEP(DT_PATH(zephyr_user), digital_pin_gpios, \ INTERRUPT_HELPER, (+)) namespace arduino { class ZephyrSPI : public HardwareSPI { public: - ZephyrSPI(const struct device *spi); + ZephyrSPI(const struct device *spi); - virtual uint8_t transfer(uint8_t data); - virtual uint16_t transfer16(uint16_t data); - virtual void transfer(void *buf, size_t count); + virtual uint8_t transfer(uint8_t data); + virtual uint16_t transfer16(uint16_t data); + virtual void transfer(void *buf, size_t count); - // Transaction Functions - virtual void usingInterrupt(int interruptNumber); - virtual void notUsingInterrupt(int interruptNumber); - virtual void beginTransaction(SPISettings settings); - virtual void endTransaction(void); + // Transaction Functions + virtual void usingInterrupt(int interruptNumber); + virtual void notUsingInterrupt(int interruptNumber); + virtual void beginTransaction(SPISettings settings); + virtual void endTransaction(void); - // SPI Configuration methods - virtual void attachInterrupt(); - virtual void detachInterrupt(); + // SPI Configuration methods + virtual void attachInterrupt(); + virtual void detachInterrupt(); - virtual void begin(); - virtual void end(); + virtual void begin(); + virtual void end(); protected: - const struct device *spi_dev; - struct spi_config config; - struct spi_config config16; - int interrupt[INTERRUPT_COUNT]; - size_t interrupt_pos = 0; + const struct device *spi_dev; + struct spi_config config; + struct spi_config config16; + int interrupt[INTERRUPT_COUNT]; + size_t interrupt_pos = 0; }; } // namespace arduino diff --git a/libraries/SocketWrapper/Ethernet.cpp b/libraries/SocketWrapper/Ethernet.cpp index 94802bb3..03300d43 100644 --- a/libraries/SocketWrapper/Ethernet.cpp +++ b/libraries/SocketWrapper/Ethernet.cpp @@ -2,4 +2,4 @@ #if DT_HAS_COMPAT_STATUS_OKAY(ethernet_phy) EthernetClass Ethernet; -#endif \ No newline at end of file +#endif diff --git a/libraries/SocketWrapper/Ethernet.h b/libraries/SocketWrapper/Ethernet.h index a3cbcd84..e9310729 100644 --- a/libraries/SocketWrapper/Ethernet.h +++ b/libraries/SocketWrapper/Ethernet.h @@ -5,60 +5,64 @@ #if DT_HAS_COMPAT_STATUS_OKAY(ethernet_phy) enum EthernetLinkStatus { - Unknown, - LinkON, - LinkOFF + Unknown, + LinkON, + LinkOFF }; enum EthernetHardwareStatus { - EthernetNoHardware, - EthernetOk + EthernetNoHardware, + EthernetOk }; -class EthernetClass: public NetworkInterface -{ +class EthernetClass : public NetworkInterface { public: - EthernetClass() {} - virtual ~EthernetClass() {} + EthernetClass() { + } - EthernetLinkStatus linkStatus() { - hardwareStatus(); - if (net_if_is_up(netif)) { - return LinkON; - } else { - return LinkOFF; - } - } + virtual ~EthernetClass() { + } - bool begin(bool blocking = true, uint32_t additional_event_mask = 0) { - hardwareStatus(); - return NetworkInterface::begin(blocking, additional_event_mask); - } + EthernetLinkStatus linkStatus() { + hardwareStatus(); + if (net_if_is_up(netif)) { + return LinkON; + } else { + return LinkOFF; + } + } - bool begin(uint8_t* mac_address, int _timeout, int _response_timeout) { - return begin(); - } + bool begin(bool blocking = true, uint32_t additional_event_mask = 0) { + hardwareStatus(); + return NetworkInterface::begin(blocking, additional_event_mask); + } - bool begin(uint8_t* mac_address, IPAddress _ip, IPAddress _dns, IPAddress _gateway, IPAddress _netmask, int _timeout, int _response_timeout) { - return begin(); - } + bool begin(uint8_t *mac_address, int _timeout, int _response_timeout) { + return begin(); + } - EthernetHardwareStatus hardwareStatus() { - const struct device *const dev = DEVICE_DT_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(ethernet_phy)); - if (device_is_ready(dev)) { - for (int i = 1; i < 4; i++) { - auto _if = net_if_get_by_index(i); - if (_if && !net_eth_type_is_wifi(_if)) { - netif = _if; - break; - } - } - return EthernetOk; - } else { - return EthernetNoHardware; - } - } + bool begin(uint8_t *mac_address, IPAddress _ip, IPAddress _dns, IPAddress _gateway, + IPAddress _netmask, int _timeout, int _response_timeout) { + return begin(); + } + + EthernetHardwareStatus hardwareStatus() { + const struct device *const dev = DEVICE_DT_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(ethernet_phy)); + if (device_is_ready(dev)) { + for (int i = 1; i < 4; i++) { + auto _if = net_if_get_by_index(i); + if (_if && !net_eth_type_is_wifi(_if)) { + netif = _if; + break; + } + } + return EthernetOk; + } else { + return EthernetNoHardware; + } + } }; + extern EthernetClass Ethernet; -#endif \ No newline at end of file +#endif diff --git a/libraries/SocketWrapper/SocketHelpers.h b/libraries/SocketWrapper/SocketHelpers.h index bc6ca6c7..acf510a4 100644 --- a/libraries/SocketWrapper/SocketHelpers.h +++ b/libraries/SocketWrapper/SocketHelpers.h @@ -24,145 +24,138 @@ class NetworkInterface { private: - - uint8_t ntp_server[4]; - static struct net_mgmt_event_callback mgmt_cb; - static struct net_dhcpv4_option_callback dhcp_cb; - - static void event_handler(struct net_mgmt_event_callback *cb, - uint64_t mgmt_event, - struct net_if *iface) - { - int i = 0; - - if (mgmt_event != NET_EVENT_IPV4_ADDR_ADD) { - return; - } - - for (i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) { - char buf[NET_IPV4_ADDR_LEN]; - - if (iface->config.ip.ipv4->unicast[i].ipv4.addr_type != - NET_ADDR_DHCP) { - continue; - } - - LOG_INF(" Address[%d]: %s", net_if_get_by_iface(iface), - net_addr_ntop(AF_INET, - &iface->config.ip.ipv4->unicast[i].ipv4.address.in_addr, - buf, sizeof(buf))); - LOG_INF(" Subnet[%d]: %s", net_if_get_by_iface(iface), - net_addr_ntop(AF_INET, - &iface->config.ip.ipv4->unicast[i].netmask, - buf, sizeof(buf))); - LOG_INF(" Router[%d]: %s", net_if_get_by_iface(iface), - net_addr_ntop(AF_INET, - &iface->config.ip.ipv4->gw, - buf, sizeof(buf))); - LOG_INF("Lease time[%d]: %u seconds", net_if_get_by_iface(iface), - iface->config.dhcpv4.lease_time); - } - } - - static void option_handler(struct net_dhcpv4_option_callback *cb, - size_t length, - enum net_dhcpv4_msg_type msg_type, - struct net_if *iface) - { - char buf[NET_IPV4_ADDR_LEN]; - - LOG_INF("DHCP Option %d: %s", cb->option, - net_addr_ntop(AF_INET, cb->data, buf, sizeof(buf))); - } + uint8_t ntp_server[4]; + static struct net_mgmt_event_callback mgmt_cb; + static struct net_dhcpv4_option_callback dhcp_cb; + + static void event_handler(struct net_mgmt_event_callback *cb, uint64_t mgmt_event, + struct net_if *iface) { + int i = 0; + + if (mgmt_event != NET_EVENT_IPV4_ADDR_ADD) { + return; + } + + for (i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) { + char buf[NET_IPV4_ADDR_LEN]; + + if (iface->config.ip.ipv4->unicast[i].ipv4.addr_type != NET_ADDR_DHCP) { + continue; + } + + LOG_INF(" Address[%d]: %s", net_if_get_by_iface(iface), + net_addr_ntop(AF_INET, &iface->config.ip.ipv4->unicast[i].ipv4.address.in_addr, + buf, sizeof(buf))); + LOG_INF(" Subnet[%d]: %s", net_if_get_by_iface(iface), + net_addr_ntop(AF_INET, &iface->config.ip.ipv4->unicast[i].netmask, buf, + sizeof(buf))); + LOG_INF(" Router[%d]: %s", net_if_get_by_iface(iface), + net_addr_ntop(AF_INET, &iface->config.ip.ipv4->gw, buf, sizeof(buf))); + LOG_INF("Lease time[%d]: %u seconds", net_if_get_by_iface(iface), + iface->config.dhcpv4.lease_time); + } + } + + static void option_handler(struct net_dhcpv4_option_callback *cb, size_t length, + enum net_dhcpv4_msg_type msg_type, struct net_if *iface) { + char buf[NET_IPV4_ADDR_LEN]; + + LOG_INF("DHCP Option %d: %s", cb->option, + net_addr_ntop(AF_INET, cb->data, buf, sizeof(buf))); + } protected: + struct net_if *netif = nullptr; - struct net_if *netif = nullptr; - int dhcp() - { - net_mgmt_init_event_callback(&mgmt_cb, event_handler, NET_EVENT_IPV4_ADDR_ADD | NET_EVENT_IF_UP | NET_EVENT_IF_DOWN); - net_mgmt_add_event_callback(&mgmt_cb); - - net_dhcpv4_init_option_callback(&dhcp_cb, option_handler, - DHCP_OPTION_NTP, ntp_server, - sizeof(ntp_server)); + int dhcp() { + net_mgmt_init_event_callback(&mgmt_cb, event_handler, + NET_EVENT_IPV4_ADDR_ADD | NET_EVENT_IF_UP | NET_EVENT_IF_DOWN); + net_mgmt_add_event_callback(&mgmt_cb); - net_dhcpv4_add_option_callback(&dhcp_cb); + net_dhcpv4_init_option_callback(&dhcp_cb, option_handler, DHCP_OPTION_NTP, ntp_server, + sizeof(ntp_server)); - net_dhcpv4_start(netif); + net_dhcpv4_add_option_callback(&dhcp_cb); - return 0; - } + net_dhcpv4_start(netif); - void enable_dhcpv4_server(struct net_if *netif, char* _netmask = "255.255.255.0") - { - static struct in_addr addr; - static struct in_addr netmaskAddr; + return 0; + } - if (net_addr_pton(AF_INET, String(localIP()).c_str(), &addr)) { - LOG_ERR("Invalid address: %s", String(localIP()).c_str()); - return; - } + void enable_dhcpv4_server(struct net_if *netif, char *_netmask = "255.255.255.0") { + static struct in_addr addr; + static struct in_addr netmaskAddr; - if (net_addr_pton(AF_INET, _netmask, &netmaskAddr)) { - LOG_ERR("Invalid netmask: %s", _netmask); - return; - } + if (net_addr_pton(AF_INET, String(localIP()).c_str(), &addr)) { + LOG_ERR("Invalid address: %s", String(localIP()).c_str()); + return; + } - net_if_ipv4_set_gw(netif, &addr); + if (net_addr_pton(AF_INET, _netmask, &netmaskAddr)) { + LOG_ERR("Invalid netmask: %s", _netmask); + return; + } - if (net_if_ipv4_addr_add(netif, &addr, NET_ADDR_MANUAL, 0) == NULL) { - LOG_ERR("unable to set IP address for AP interface"); - } + net_if_ipv4_set_gw(netif, &addr); - if (!net_if_ipv4_set_netmask_by_addr(netif, &addr, &netmaskAddr)) { - LOG_ERR("Unable to set netmask for AP interface: %s", _netmask); - } + if (net_if_ipv4_addr_add(netif, &addr, NET_ADDR_MANUAL, 0) == NULL) { + LOG_ERR("unable to set IP address for AP interface"); + } - addr.s4_addr[3] += 10; /* Starting IPv4 address for DHCPv4 address pool. */ + if (!net_if_ipv4_set_netmask_by_addr(netif, &addr, &netmaskAddr)) { + LOG_ERR("Unable to set netmask for AP interface: %s", _netmask); + } - if (net_dhcpv4_server_start(netif, &addr) != 0) { - LOG_ERR("DHCP server is not started for desired IP"); - return; - } + addr.s4_addr[3] += 10; /* Starting IPv4 address for DHCPv4 address pool. */ - LOG_INF("DHCPv4 server started...\n"); - } + if (net_dhcpv4_server_start(netif, &addr) != 0) { + LOG_ERR("DHCP server is not started for desired IP"); + return; + } + LOG_INF("DHCPv4 server started...\n"); + } public: - NetworkInterface() {} - ~NetworkInterface() {} - IPAddress localIP() { - return IPAddress(netif->config.ip.ipv4->unicast[0].ipv4.address.in_addr.s_addr); - } - - IPAddress subnetMask() { - return IPAddress(netif->config.ip.ipv4->unicast[0].netmask.s_addr); - } - IPAddress gatewayIP() { - return IPAddress(netif->config.ip.ipv4->gw.s_addr); - } - IPAddress dnsServerIP() { - return arduino::INADDR_NONE; - } - - IPAddress dnsIP(int n = 0); - - void setMACAddress(const uint8_t* mac); - - bool begin(bool blocking = true, uint32_t additional_event_mask = 0) { - dhcp(); - int ret = net_mgmt_event_wait_on_iface(netif, NET_EVENT_IPV4_ADDR_ADD | additional_event_mask, - NULL, NULL, NULL, blocking ? K_FOREVER : K_SECONDS(1)); - return (ret == 0); - } - - bool disconnect() { - return (net_if_down(netif) == 0); - } - - // TODO: manual functions for setting IP address, subnet mask, gateway, etc. - // net_if_ipv4_set_netmask_by_addr(iface, &addr4, &nm); - // net_if_ipv4_addr_add(iface, &addr4, NET_ADDR_MANUAL, 0); + NetworkInterface() { + } + + ~NetworkInterface() { + } + + IPAddress localIP() { + return IPAddress(netif->config.ip.ipv4->unicast[0].ipv4.address.in_addr.s_addr); + } + + IPAddress subnetMask() { + return IPAddress(netif->config.ip.ipv4->unicast[0].netmask.s_addr); + } + + IPAddress gatewayIP() { + return IPAddress(netif->config.ip.ipv4->gw.s_addr); + } + + IPAddress dnsServerIP() { + return arduino::INADDR_NONE; + } + + IPAddress dnsIP(int n = 0); + + void setMACAddress(const uint8_t *mac); + + bool begin(bool blocking = true, uint32_t additional_event_mask = 0) { + dhcp(); + int ret = + net_mgmt_event_wait_on_iface(netif, NET_EVENT_IPV4_ADDR_ADD | additional_event_mask, + NULL, NULL, NULL, blocking ? K_FOREVER : K_SECONDS(1)); + return (ret == 0); + } + + bool disconnect() { + return (net_if_down(netif) == 0); + } + + // TODO: manual functions for setting IP address, subnet mask, gateway, etc. + // net_if_ipv4_set_netmask_by_addr(iface, &addr4, &nm); + // net_if_ipv4_addr_add(iface, &addr4, NET_ADDR_MANUAL, 0); }; diff --git a/libraries/SocketWrapper/SocketWrapper.h b/libraries/SocketWrapper/SocketWrapper.h index ad5c36db..6165d5ac 100644 --- a/libraries/SocketWrapper/SocketWrapper.h +++ b/libraries/SocketWrapper/SocketWrapper.h @@ -10,260 +10,262 @@ class ZephyrSocketWrapper { protected: - int sock_fd; - bool is_ssl = false; - int ssl_sock_temp_char = -1; + int sock_fd; + bool is_ssl = false; + int ssl_sock_temp_char = -1; public: - ZephyrSocketWrapper() : sock_fd(-1) {} - ZephyrSocketWrapper(int sock_fd) : sock_fd(sock_fd) {} + ZephyrSocketWrapper() : sock_fd(-1) { + } - ~ZephyrSocketWrapper() { - if (sock_fd != -1) { - ::close(sock_fd); - } - } + ZephyrSocketWrapper(int sock_fd) : sock_fd(sock_fd) { + } - bool connect(const char* host, uint16_t port) { + ~ZephyrSocketWrapper() { + if (sock_fd != -1) { + ::close(sock_fd); + } + } - // Resolve address - struct addrinfo hints; - struct addrinfo *res; - bool rv = true; + bool connect(const char *host, uint16_t port) { - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; + // Resolve address + struct addrinfo hints; + struct addrinfo *res; + bool rv = true; - int resolve_attempts = 100; - int ret; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; - while (resolve_attempts--) { - ret = getaddrinfo(host, String(port).c_str(), &hints, &res); + int resolve_attempts = 100; + int ret; - if (ret == 0) { - break; - } else { - k_sleep(K_MSEC(1)); - } - } + while (resolve_attempts--) { + ret = getaddrinfo(host, String(port).c_str(), &hints, &res); - if (ret != 0) { - rv = false; - goto exit; - } + if (ret == 0) { + break; + } else { + k_sleep(K_MSEC(1)); + } + } - sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (sock_fd < 0) { - rv = false; + if (ret != 0) { + rv = false; + goto exit; + } - goto exit; - } + sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (sock_fd < 0) { + rv = false; - if (::connect(sock_fd, res->ai_addr, res->ai_addrlen) < 0) { - ::close(sock_fd); - sock_fd = -1; - rv = false; - goto exit; - } + goto exit; + } - exit: - if(res != nullptr) { - freeaddrinfo(res); - res = nullptr; - } + if (::connect(sock_fd, res->ai_addr, res->ai_addrlen) < 0) { + ::close(sock_fd); + sock_fd = -1; + rv = false; + goto exit; + } - return rv; - } + exit: + if (res != nullptr) { + freeaddrinfo(res); + res = nullptr; + } - bool connect(IPAddress host, uint16_t port) { + return rv; + } - const char* _host = host.toString().c_str(); + bool connect(IPAddress host, uint16_t port) { - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - inet_pton(AF_INET, _host, &addr.sin_addr); + const char *_host = host.toString().c_str(); - sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (sock_fd < 0) { - return false; - } + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + inet_pton(AF_INET, _host, &addr.sin_addr); - if (::connect(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { - ::close(sock_fd); - sock_fd = -1; - return false; - } + sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (sock_fd < 0) { + return false; + } - return true; - } + if (::connect(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + ::close(sock_fd); + sock_fd = -1; + return false; + } + + return true; + } #if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) - bool connectSSL(const char* host, uint16_t port, char* ca_certificate_pem = nullptr) { - - // Resolve address - struct addrinfo hints; - struct addrinfo *res; - - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - - int resolve_attempts = 100; - int ret; - bool rv = true; - - sec_tag_t sec_tag_opt[] = { - CA_CERTIFICATE_TAG, - }; - - uint32_t timeo_optval = 100; - - while (resolve_attempts--) { - ret = getaddrinfo(host, String(port).c_str(), &hints, &res); - - if (ret == 0) { - break; - } else { - k_sleep(K_MSEC(1)); - } - } - - if (ret != 0) { - rv = false; - goto exit; - } - - if (ca_certificate_pem != nullptr) { - ret = tls_credential_add(CA_CERTIFICATE_TAG, TLS_CREDENTIAL_CA_CERTIFICATE, - ca_certificate_pem, strlen(ca_certificate_pem) + 1); - } - - sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TLS_1_2); - if (sock_fd < 0) { - rv = false; - goto exit; - } - - setsockopt(sock_fd, SOL_TLS, TLS_SEC_TAG_LIST, - sec_tag_opt, sizeof(sec_tag_opt)); - - setsockopt(sock_fd, SOL_TLS, TLS_HOSTNAME, host, strlen(host)); - - setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &timeo_optval, sizeof(timeo_optval)); - - if (::connect(sock_fd, res->ai_addr, res->ai_addrlen) < 0) { - ::close(sock_fd); - sock_fd = -1; - rv = false; - goto exit; - } - is_ssl = true; - - exit: - if(res != nullptr) { - freeaddrinfo(res); - res = nullptr; - } - - return rv; - } + bool connectSSL(const char *host, uint16_t port, char *ca_certificate_pem = nullptr) { + + // Resolve address + struct addrinfo hints; + struct addrinfo *res; + + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + + int resolve_attempts = 100; + int ret; + bool rv = true; + + sec_tag_t sec_tag_opt[] = { + CA_CERTIFICATE_TAG, + }; + + uint32_t timeo_optval = 100; + + while (resolve_attempts--) { + ret = getaddrinfo(host, String(port).c_str(), &hints, &res); + + if (ret == 0) { + break; + } else { + k_sleep(K_MSEC(1)); + } + } + + if (ret != 0) { + rv = false; + goto exit; + } + + if (ca_certificate_pem != nullptr) { + ret = tls_credential_add(CA_CERTIFICATE_TAG, TLS_CREDENTIAL_CA_CERTIFICATE, + ca_certificate_pem, strlen(ca_certificate_pem) + 1); + } + + sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TLS_1_2); + if (sock_fd < 0) { + rv = false; + goto exit; + } + + setsockopt(sock_fd, SOL_TLS, TLS_SEC_TAG_LIST, sec_tag_opt, sizeof(sec_tag_opt)); + + setsockopt(sock_fd, SOL_TLS, TLS_HOSTNAME, host, strlen(host)); + + setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &timeo_optval, sizeof(timeo_optval)); + + if (::connect(sock_fd, res->ai_addr, res->ai_addrlen) < 0) { + ::close(sock_fd); + sock_fd = -1; + rv = false; + goto exit; + } + is_ssl = true; + + exit: + if (res != nullptr) { + freeaddrinfo(res); + res = nullptr; + } + + return rv; + } #endif - int available() { - int count = 0; - if (is_ssl) { - /* - TODO: HACK: - The correct colution would be to call - ::recv(sock_fd, &ssl_sock_temp_char, 1, MSG_PEEK | MSG_DONTWAIT); - but it doesn't seem to work. Instead, save a temporary variable - and use it in read() - */ - if (ssl_sock_temp_char != -1) { - return 1; - } - count = ::recv(sock_fd, &ssl_sock_temp_char, 1, MSG_DONTWAIT); - } else { - zsock_ioctl(sock_fd, ZFD_IOCTL_FIONREAD, &count); - } - if (count <= 0) { - delay(1); - count = 0; - } - return count; - } - - int recv(uint8_t* buffer, size_t size, int flags = MSG_DONTWAIT) { - if (sock_fd == -1) { - return -1; - } - // TODO: see available() - if (ssl_sock_temp_char != -1) { - int ret = ::recv(sock_fd, &buffer[1], size - 1, flags); - buffer[0] = ssl_sock_temp_char; - ssl_sock_temp_char = -1; - return ret + 1; - } - return ::recv(sock_fd, buffer, size, flags); - } - - int send(const uint8_t* buffer, size_t size) { - if (sock_fd == -1) { - return -1; - } - return ::send(sock_fd, buffer, size, 0); - } - - void close() { - if (sock_fd != -1) { - ::close(sock_fd); - sock_fd = -1; - } - } - - bool bind(uint16_t port) { - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = INADDR_ANY; - - sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); - if (sock_fd < 0) { - return false; - } - - zsock_ioctl(sock_fd, ZFD_IOCTL_FIONBIO); - - if (::bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) { - ::close(sock_fd); - sock_fd = -1; - return false; - } - - return true; - } - - bool listen(int backlog = 5) { - if (sock_fd == -1) { - return false; - } - - if (::listen(sock_fd, backlog) < 0) { - ::close(sock_fd); - sock_fd = -1; - return false; - } - - return true; - } - - int accept() { - if (sock_fd == -1) { - return -1; - } - - return ::accept(sock_fd, nullptr, nullptr); - } - - friend class ZephyrClient; + int available() { + int count = 0; + if (is_ssl) { + /* + TODO: HACK: + The correct colution would be to call + ::recv(sock_fd, &ssl_sock_temp_char, 1, MSG_PEEK | MSG_DONTWAIT); + but it doesn't seem to work. Instead, save a temporary variable + and use it in read() + */ + if (ssl_sock_temp_char != -1) { + return 1; + } + count = ::recv(sock_fd, &ssl_sock_temp_char, 1, MSG_DONTWAIT); + } else { + zsock_ioctl(sock_fd, ZFD_IOCTL_FIONREAD, &count); + } + if (count <= 0) { + delay(1); + count = 0; + } + return count; + } + + int recv(uint8_t *buffer, size_t size, int flags = MSG_DONTWAIT) { + if (sock_fd == -1) { + return -1; + } + // TODO: see available() + if (ssl_sock_temp_char != -1) { + int ret = ::recv(sock_fd, &buffer[1], size - 1, flags); + buffer[0] = ssl_sock_temp_char; + ssl_sock_temp_char = -1; + return ret + 1; + } + return ::recv(sock_fd, buffer, size, flags); + } + + int send(const uint8_t *buffer, size_t size) { + if (sock_fd == -1) { + return -1; + } + return ::send(sock_fd, buffer, size, 0); + } + + void close() { + if (sock_fd != -1) { + ::close(sock_fd); + sock_fd = -1; + } + } + + bool bind(uint16_t port) { + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = INADDR_ANY; + + sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (sock_fd < 0) { + return false; + } + + zsock_ioctl(sock_fd, ZFD_IOCTL_FIONBIO); + + if (::bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + ::close(sock_fd); + sock_fd = -1; + return false; + } + + return true; + } + + bool listen(int backlog = 5) { + if (sock_fd == -1) { + return false; + } + + if (::listen(sock_fd, backlog) < 0) { + ::close(sock_fd); + sock_fd = -1; + return false; + } + + return true; + } + + int accept() { + if (sock_fd == -1) { + return -1; + } + + return ::accept(sock_fd, nullptr, nullptr); + } + + friend class ZephyrClient; }; diff --git a/libraries/SocketWrapper/WiFi.h b/libraries/SocketWrapper/WiFi.h index c83846b2..df61620c 100644 --- a/libraries/SocketWrapper/WiFi.h +++ b/libraries/SocketWrapper/WiFi.h @@ -4,102 +4,107 @@ #include #define NET_EVENT_WIFI_MASK \ - (NET_EVENT_WIFI_CONNECT_RESULT | NET_EVENT_WIFI_DISCONNECT_RESULT | \ - NET_EVENT_WIFI_AP_ENABLE_RESULT | NET_EVENT_WIFI_AP_DISABLE_RESULT | \ - NET_EVENT_WIFI_AP_STA_CONNECTED | NET_EVENT_WIFI_AP_STA_DISCONNECTED | \ + (NET_EVENT_WIFI_CONNECT_RESULT | NET_EVENT_WIFI_DISCONNECT_RESULT | \ + NET_EVENT_WIFI_AP_ENABLE_RESULT | NET_EVENT_WIFI_AP_DISABLE_RESULT | \ + NET_EVENT_WIFI_AP_STA_CONNECTED | NET_EVENT_WIFI_AP_STA_DISCONNECTED | \ NET_EVENT_WIFI_SCAN_RESULT) - -class WiFiClass: public NetworkInterface -{ +class WiFiClass : public NetworkInterface { public: - WiFiClass() {} - ~WiFiClass() {} - - bool begin(const char* ssid, const char* passphrase, wl_enc_type security = ENC_TYPE_UNKNOWN, bool blocking = false) { - sta_iface = net_if_get_wifi_sta(); - netif = sta_iface; - sta_config.ssid = (const uint8_t *)ssid; - sta_config.ssid_length = strlen(ssid); - sta_config.psk = (const uint8_t *)passphrase; - sta_config.psk_length = strlen(passphrase); - // TODO: change these fields with scan() results - sta_config.security = WIFI_SECURITY_TYPE_PSK; - sta_config.channel = WIFI_CHANNEL_ANY; - sta_config.band = WIFI_FREQ_BAND_2_4_GHZ; - sta_config.bandwidth = WIFI_FREQ_BANDWIDTH_20MHZ; - - int ret = net_mgmt(NET_REQUEST_WIFI_CONNECT, sta_iface, &sta_config, - sizeof(struct wifi_connect_req_params)); - if (ret) { - return false; - } - - NetworkInterface::begin(false, NET_EVENT_WIFI_MASK); - if (blocking) { - net_mgmt_event_wait_on_iface(sta_iface, NET_EVENT_WIFI_AP_STA_CONNECTED, NULL, NULL, NULL, K_FOREVER); - } - - return true; - } - - bool beginAP(char* ssid, char* passphrase, int channel = WIFI_CHANNEL_ANY, bool blocking = false) { - if (ap_iface != NULL) { - return false; - } - ap_iface = net_if_get_wifi_sap(); - netif = ap_iface; - ap_config.ssid = (const uint8_t *)ssid; - ap_config.ssid_length = strlen(ssid); - ap_config.psk = (const uint8_t *)passphrase; - ap_config.psk_length = strlen(passphrase); - ap_config.security = WIFI_SECURITY_TYPE_PSK; - ap_config.channel = channel; - ap_config.band = WIFI_FREQ_BAND_2_4_GHZ; - ap_config.bandwidth = WIFI_FREQ_BANDWIDTH_20MHZ; - - int ret = net_mgmt(NET_REQUEST_WIFI_AP_ENABLE, ap_iface, &ap_config, - sizeof(struct wifi_connect_req_params)); - - if (ret) { - return false; - } - - enable_dhcpv4_server(ap_iface); - - if (blocking) { - net_mgmt_event_wait_on_iface(ap_iface, NET_EVENT_WIFI_AP_ENABLE_RESULT, NULL, NULL, NULL, K_FOREVER); - } - - return true; - } - - int status() { - struct wifi_iface_status status = { 0 }; - - if (net_mgmt(NET_REQUEST_WIFI_IFACE_STATUS, netif, &status, - sizeof(struct wifi_iface_status))) { - return WL_NO_SHIELD; - } - - if (status.state >= WIFI_STATE_ASSOCIATED) { - return WL_CONNECTED; - } else { - return WL_DISCONNECTED; - } - return WL_NO_SHIELD; - } - - int8_t scanNetworks() { - // TODO: borrow code from mbed core for scan results handling - } + WiFiClass() { + } + + ~WiFiClass() { + } + + bool begin(const char *ssid, const char *passphrase, wl_enc_type security = ENC_TYPE_UNKNOWN, + bool blocking = false) { + sta_iface = net_if_get_wifi_sta(); + netif = sta_iface; + sta_config.ssid = (const uint8_t *)ssid; + sta_config.ssid_length = strlen(ssid); + sta_config.psk = (const uint8_t *)passphrase; + sta_config.psk_length = strlen(passphrase); + // TODO: change these fields with scan() results + sta_config.security = WIFI_SECURITY_TYPE_PSK; + sta_config.channel = WIFI_CHANNEL_ANY; + sta_config.band = WIFI_FREQ_BAND_2_4_GHZ; + sta_config.bandwidth = WIFI_FREQ_BANDWIDTH_20MHZ; + + int ret = net_mgmt(NET_REQUEST_WIFI_CONNECT, sta_iface, &sta_config, + sizeof(struct wifi_connect_req_params)); + if (ret) { + return false; + } + + NetworkInterface::begin(false, NET_EVENT_WIFI_MASK); + if (blocking) { + net_mgmt_event_wait_on_iface(sta_iface, NET_EVENT_WIFI_AP_STA_CONNECTED, NULL, NULL, + NULL, K_FOREVER); + } + + return true; + } + + bool beginAP(char *ssid, char *passphrase, int channel = WIFI_CHANNEL_ANY, + bool blocking = false) { + if (ap_iface != NULL) { + return false; + } + ap_iface = net_if_get_wifi_sap(); + netif = ap_iface; + ap_config.ssid = (const uint8_t *)ssid; + ap_config.ssid_length = strlen(ssid); + ap_config.psk = (const uint8_t *)passphrase; + ap_config.psk_length = strlen(passphrase); + ap_config.security = WIFI_SECURITY_TYPE_PSK; + ap_config.channel = channel; + ap_config.band = WIFI_FREQ_BAND_2_4_GHZ; + ap_config.bandwidth = WIFI_FREQ_BANDWIDTH_20MHZ; + + int ret = net_mgmt(NET_REQUEST_WIFI_AP_ENABLE, ap_iface, &ap_config, + sizeof(struct wifi_connect_req_params)); + + if (ret) { + return false; + } + + enable_dhcpv4_server(ap_iface); + + if (blocking) { + net_mgmt_event_wait_on_iface(ap_iface, NET_EVENT_WIFI_AP_ENABLE_RESULT, NULL, NULL, + NULL, K_FOREVER); + } + + return true; + } + + int status() { + struct wifi_iface_status status = {0}; + + if (net_mgmt(NET_REQUEST_WIFI_IFACE_STATUS, netif, &status, + sizeof(struct wifi_iface_status))) { + return WL_NO_SHIELD; + } + + if (status.state >= WIFI_STATE_ASSOCIATED) { + return WL_CONNECTED; + } else { + return WL_DISCONNECTED; + } + return WL_NO_SHIELD; + } + + int8_t scanNetworks() { + // TODO: borrow code from mbed core for scan results handling + } private: - struct net_if *sta_iface = nullptr; - struct net_if *ap_iface = nullptr; + struct net_if *sta_iface = nullptr; + struct net_if *ap_iface = nullptr; - struct wifi_connect_req_params ap_config; - struct wifi_connect_req_params sta_config; + struct wifi_connect_req_params ap_config; + struct wifi_connect_req_params sta_config; }; extern WiFiClass WiFi; diff --git a/libraries/SocketWrapper/ZephyrClient.h b/libraries/SocketWrapper/ZephyrClient.h index 8d947963..94e135ca 100644 --- a/libraries/SocketWrapper/ZephyrClient.h +++ b/libraries/SocketWrapper/ZephyrClient.h @@ -7,53 +7,57 @@ class ZephyrClient : public arduino::Client, ZephyrSocketWrapper { private: - bool _connected = false; + bool _connected = false; protected: - void setSocket(int sock) { - sock_fd = sock; - _connected = true; - } + void setSocket(int sock) { + sock_fd = sock; + _connected = true; + } public: - int connect(const char* host, uint16_t port) override { - auto ret = ZephyrSocketWrapper::connect((char*)host, port); - if (ret) { - _connected = true; - } - return ret; - } - int connect(IPAddress ip, uint16_t port) { - auto ret = ZephyrSocketWrapper::connect(ip, port); - if (ret) { - _connected = true; - } - return ret; - } + int connect(const char *host, uint16_t port) override { + auto ret = ZephyrSocketWrapper::connect((char *)host, port); + if (ret) { + _connected = true; + } + return ret; + } + + int connect(IPAddress ip, uint16_t port) { + auto ret = ZephyrSocketWrapper::connect(ip, port); + if (ret) { + _connected = true; + } + return ret; + } #if defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) - int connectSSL(const char* host, uint16_t port, char* cert) { - auto ret = ZephyrSocketWrapper::connectSSL((char*)host, port, cert); - if (ret) { - _connected = true; - } - return ret; - } + int connectSSL(const char *host, uint16_t port, char *cert) { + auto ret = ZephyrSocketWrapper::connectSSL((char *)host, port, cert); + if (ret) { + _connected = true; + } + return ret; + } #endif - uint8_t connected() override { - return _connected; - } - int available() override { - return ZephyrSocketWrapper::available(); - } - int read() override { - uint8_t c; - read(&c, 1); - return c; - } - int read(uint8_t* buffer, size_t size) override { - auto received = recv(buffer, size); + uint8_t connected() override { + return _connected; + } + + int available() override { + return ZephyrSocketWrapper::available(); + } + + int read() override { + uint8_t c; + read(&c, 1); + return c; + } + + int read(uint8_t *buffer, size_t size) override { + auto received = recv(buffer, size); - if (received == 0) { + if (received == 0) { return 0; } else if (received < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { @@ -62,28 +66,34 @@ class ZephyrClient : public arduino::Client, ZephyrSocketWrapper { return 0; } } - return received; - } - size_t write(uint8_t c) override { - return write(&c, 1); - } - size_t write(const uint8_t* buffer, size_t size) override { - return send(buffer, size); - } - void flush() override { - // No-op - } - int peek() override { - uint8_t c; - recv(&c, 1, MSG_PEEK); - return c; - } - void stop() override { - ZephyrSocketWrapper::close(); - _connected = false; - } - operator bool() { - return sock_fd != -1; - } - friend class ZephyrServer; -}; \ No newline at end of file + return received; + } + + size_t write(uint8_t c) override { + return write(&c, 1); + } + + size_t write(const uint8_t *buffer, size_t size) override { + return send(buffer, size); + } + + void flush() override { + // No-op + } + + int peek() override { + uint8_t c; + recv(&c, 1, MSG_PEEK); + return c; + } + + void stop() override { + ZephyrSocketWrapper::close(); + _connected = false; + } + + operator bool() { + return sock_fd != -1; + } + friend class ZephyrServer; +}; diff --git a/libraries/SocketWrapper/ZephyrSSLClient.h b/libraries/SocketWrapper/ZephyrSSLClient.h index 71f47aed..2c7bd461 100644 --- a/libraries/SocketWrapper/ZephyrSSLClient.h +++ b/libraries/SocketWrapper/ZephyrSSLClient.h @@ -10,11 +10,12 @@ class ZephyrSSLClient : public ZephyrClient { public: - int connect(const char* host, uint16_t port) override { - return connectSSL(host, port, nullptr); - } - int connect(const char* host, uint16_t port, char* cert) { - return connectSSL(host, port, cert); - } + int connect(const char *host, uint16_t port) override { + return connectSSL(host, port, nullptr); + } + + int connect(const char *host, uint16_t port, char *cert) { + return connectSSL(host, port, cert); + } }; -#endif \ No newline at end of file +#endif diff --git a/libraries/SocketWrapper/ZephyrServer.h b/libraries/SocketWrapper/ZephyrServer.h index 286f9cc5..d5385588 100644 --- a/libraries/SocketWrapper/ZephyrServer.h +++ b/libraries/SocketWrapper/ZephyrServer.h @@ -7,50 +7,56 @@ class ZephyrServer : public arduino::Server, ZephyrSocketWrapper { private: - int _port; + int _port; public: - ZephyrServer() : _port(80){}; - ZephyrServer(uint16_t port) : _port(port){}; - - virtual ~ZephyrServer() { - end(); - } - void end() { - ZephyrSocketWrapper::close(); - } - void begin(uint16_t port) { - _port = port; - begin(); - } - void begin() { - ZephyrSocketWrapper::bind(_port); - ZephyrSocketWrapper::listen(5); - } - uint8_t status() { - return 0; - } - explicit operator bool() { - return sock_fd != -1; - } - - ZephyrClient accept(uint8_t* status = nullptr) { - ZephyrClient client; - int sock = ZephyrSocketWrapper::accept(); - client.setSocket(sock); - return client; - } - - ZephyrClient available(uint8_t* status = nullptr) __attribute__((deprecated("Use accept()."))) { - return accept(status); - } - - size_t write(uint8_t c) override { - return write(&c, 1); - } - size_t write(const uint8_t* buffer, size_t size) override { - return send(buffer, size); - } - - friend class ZephyrClient; -}; \ No newline at end of file + ZephyrServer() : _port(80) {}; + ZephyrServer(uint16_t port) : _port(port) {}; + + virtual ~ZephyrServer() { + end(); + } + + void end() { + ZephyrSocketWrapper::close(); + } + + void begin(uint16_t port) { + _port = port; + begin(); + } + + void begin() { + ZephyrSocketWrapper::bind(_port); + ZephyrSocketWrapper::listen(5); + } + + uint8_t status() { + return 0; + } + + explicit operator bool() { + return sock_fd != -1; + } + + ZephyrClient accept(uint8_t *status = nullptr) { + ZephyrClient client; + int sock = ZephyrSocketWrapper::accept(); + client.setSocket(sock); + return client; + } + + ZephyrClient available(uint8_t *status = nullptr) __attribute__((deprecated("Use accept()."))) { + return accept(status); + } + + size_t write(uint8_t c) override { + return write(&c, 1); + } + + size_t write(const uint8_t *buffer, size_t size) override { + return send(buffer, size); + } + + friend class ZephyrClient; +}; diff --git a/libraries/SocketWrapper/ZephyrUDP.h b/libraries/SocketWrapper/ZephyrUDP.h index d0620205..facf3722 100644 --- a/libraries/SocketWrapper/ZephyrUDP.h +++ b/libraries/SocketWrapper/ZephyrUDP.h @@ -31,300 +31,299 @@ class ZephyrUDP : public arduino::UDP { private: - int _socket; + int _socket; public: - ZephyrUDP() : _socket(-1) {} // Constructor - ~ZephyrUDP() { - stop(); - } - - // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t begin(uint16_t port) { - - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = INADDR_ANY; - - _socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - - zsock_ioctl(_socket, ZFD_IOCTL_FIONBIO); - - if (::bind(_socket, (struct sockaddr*)&addr, sizeof(addr)) < 0) { - ::close(_socket); - _socket = -1; - return false; - } - - return true; - } - - // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 if there are no sockets available to use - virtual uint8_t beginMulticast(IPAddress ip, uint16_t port) { - bool ret = begin(port); - if (ret == false) { - return false; - } - - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = ip; - - net_if_ipv4_maddr_join(net_if_get_by_index(1), net_if_ipv4_maddr_add(net_if_get_by_index(1), (struct in_addr*)&addr)); - return true; - } - - // Finish with the UDP socket - virtual void stop() { - if (_socket != -1) { - ::close(_socket); - _socket = -1; - } - } - - // Sending UDP packets - - // Start building up a packet to send to the remote host specific in ip and port - // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port - virtual int beginPacket(IPAddress ip, uint16_t port) { - _send_to_ip = ip; - _send_to_port = port; - - /* Make sure that the transmit data buffer is empty. */ - _tx_data.clear(); - return true; - } - - // Start building up a packet to send to the remote host specific in host and port - // Returns 1 if successful, 0 if there was a problem resolving the hostname or port - virtual int beginPacket(const char* host, uint16_t port) { - // Resolve address - struct addrinfo hints; - struct addrinfo *res; - - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_DGRAM; - - int resolve_attempts = 100; - int ret; - - while (resolve_attempts--) { - ret = getaddrinfo(host, String(port).c_str(), &hints, &res); - - if (ret == 0) { - break; - } else { - k_sleep(K_MSEC(1)); - } - } - - if (ret != 0) { - return false; - } - - return beginPacket(IPAddress(((sockaddr_in*)(res->ai_addr))->sin_addr.s_addr), port); - } - - // Finish off this packet and send it - // Returns 1 if the packet was sent successfully, 0 if there was an error - virtual int endPacket() { - struct sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(_send_to_port); - addr.sin_addr.s_addr = _send_to_ip; - return ::sendto(_socket, _tx_data.data(), _tx_data.size(), 0, (sockaddr*)&addr, sizeof(addr)); - } - - // Write a single byte into the packet - virtual size_t write(uint8_t data) { - _tx_data.push_back(data); - return 1; - } - - // Write size bytes from buffer into the packet - virtual size_t write(uint8_t* buffer, size_t size) { - std::copy(buffer, buffer + size, std::back_inserter(_tx_data)); - return size; - } - - // Write size bytes from buffer into the packet - virtual size_t write(const uint8_t* buffer, size_t size) { - std::copy(buffer, buffer + size, std::back_inserter(_tx_data)); - return size; - } - - using Print::write; - - int parsePacket() - { - struct sockaddr_in addr; - socklen_t addrlen = sizeof(addr); - uint8_t tmp_buf[512]; - - int ret = ::recvfrom(_socket, tmp_buf, sizeof(tmp_buf), 0, (sockaddr*)&addr, &addrlen); - if (ret > 0) - { - auto pkt = std::make_shared( - IPAddress(addr.sin_addr.s_addr), - ntohs(addr.sin_port), tmp_buf, ret); - - _rx_pkt_list.push_back(pkt); - - // drop the oldest packet if the list is full - if(_rx_pkt_list.size() > _rx_pkt_list_size) { - _rx_pkt_list.pop_front(); - } - } - - if (_rx_pkt_list.size()) - { - /* Discard UdpRxPacket object previously held by _rx_pkt - * and replace it with the new one. - */ - _rx_pkt = _rx_pkt_list.front(); - _rx_pkt_list.pop_front(); - return _rx_pkt->totalSize(); - } - else - { - /* Otherwise ensure that _rx_pkt definitely - * does not hold any UdpRxPacket object anymore. - */ - _rx_pkt.reset(); - return 0; - } - } - - int available() - { - if (_rx_pkt) - return _rx_pkt->available(); - else - return 0; - } - - int read() - { - if (_rx_pkt) - return _rx_pkt->read(); - else - return -1; - } - - int read(unsigned char* buffer, size_t len) - { - if (_rx_pkt) - return _rx_pkt->read(buffer, len); - else - return -1; - } - - int read(char* buffer, size_t len) - { - if (_rx_pkt) - return _rx_pkt->read(buffer, len); - else - return -1; - } - - int peek() - { - if (_rx_pkt) - return _rx_pkt->peek(); - else - return -1; - } - - void flush() - { - /* Delete UdpRxPacket object held by _rx_pkt. */ - if (_rx_pkt) - _rx_pkt.reset(); - } - - virtual IPAddress remoteIP() { - if (_rx_pkt) - return _rx_pkt->remoteIP(); - else - return IPAddress(); - } - - virtual uint16_t remotePort() { - if (_rx_pkt) - return _rx_pkt->remotePort(); - else - return 0; - } + ZephyrUDP() : _socket(-1) { + } // Constructor + + ~ZephyrUDP() { + stop(); + } + + // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no + // sockets available to use + virtual uint8_t begin(uint16_t port) { + + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + addr.sin_addr.s_addr = INADDR_ANY; + + _socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + zsock_ioctl(_socket, ZFD_IOCTL_FIONBIO); + + if (::bind(_socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + ::close(_socket); + _socket = -1; + return false; + } + + return true; + } + + // initialize, start listening on specified multicast IP address and port. Returns 1 if + // successful, 0 if there are no sockets available to use + virtual uint8_t beginMulticast(IPAddress ip, uint16_t port) { + bool ret = begin(port); + if (ret == false) { + return false; + } + + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = ip; + + net_if_ipv4_maddr_join( + net_if_get_by_index(1), + net_if_ipv4_maddr_add(net_if_get_by_index(1), (struct in_addr *)&addr)); + return true; + } + + // Finish with the UDP socket + virtual void stop() { + if (_socket != -1) { + ::close(_socket); + _socket = -1; + } + } + + // Sending UDP packets + + // Start building up a packet to send to the remote host specific in ip and port + // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port + virtual int beginPacket(IPAddress ip, uint16_t port) { + _send_to_ip = ip; + _send_to_port = port; + + /* Make sure that the transmit data buffer is empty. */ + _tx_data.clear(); + return true; + } + + // Start building up a packet to send to the remote host specific in host and port + // Returns 1 if successful, 0 if there was a problem resolving the hostname or port + virtual int beginPacket(const char *host, uint16_t port) { + // Resolve address + struct addrinfo hints; + struct addrinfo *res; + + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_DGRAM; + + int resolve_attempts = 100; + int ret; + + while (resolve_attempts--) { + ret = getaddrinfo(host, String(port).c_str(), &hints, &res); + + if (ret == 0) { + break; + } else { + k_sleep(K_MSEC(1)); + } + } + + if (ret != 0) { + return false; + } + + return beginPacket(IPAddress(((sockaddr_in *)(res->ai_addr))->sin_addr.s_addr), port); + } + + // Finish off this packet and send it + // Returns 1 if the packet was sent successfully, 0 if there was an error + virtual int endPacket() { + struct sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(_send_to_port); + addr.sin_addr.s_addr = _send_to_ip; + return ::sendto(_socket, _tx_data.data(), _tx_data.size(), 0, (sockaddr *)&addr, + sizeof(addr)); + } + + // Write a single byte into the packet + virtual size_t write(uint8_t data) { + _tx_data.push_back(data); + return 1; + } + + // Write size bytes from buffer into the packet + virtual size_t write(uint8_t *buffer, size_t size) { + std::copy(buffer, buffer + size, std::back_inserter(_tx_data)); + return size; + } + + // Write size bytes from buffer into the packet + virtual size_t write(const uint8_t *buffer, size_t size) { + std::copy(buffer, buffer + size, std::back_inserter(_tx_data)); + return size; + } + + using Print::write; + + int parsePacket() { + struct sockaddr_in addr; + socklen_t addrlen = sizeof(addr); + uint8_t tmp_buf[512]; + + int ret = ::recvfrom(_socket, tmp_buf, sizeof(tmp_buf), 0, (sockaddr *)&addr, &addrlen); + if (ret > 0) { + auto pkt = std::make_shared(IPAddress(addr.sin_addr.s_addr), + ntohs(addr.sin_port), tmp_buf, ret); + + _rx_pkt_list.push_back(pkt); + + // drop the oldest packet if the list is full + if (_rx_pkt_list.size() > _rx_pkt_list_size) { + _rx_pkt_list.pop_front(); + } + } + + if (_rx_pkt_list.size()) { + /* Discard UdpRxPacket object previously held by _rx_pkt + * and replace it with the new one. + */ + _rx_pkt = _rx_pkt_list.front(); + _rx_pkt_list.pop_front(); + return _rx_pkt->totalSize(); + } else { + /* Otherwise ensure that _rx_pkt definitely + * does not hold any UdpRxPacket object anymore. + */ + _rx_pkt.reset(); + return 0; + } + } + + int available() { + if (_rx_pkt) { + return _rx_pkt->available(); + } else { + return 0; + } + } + + int read() { + if (_rx_pkt) { + return _rx_pkt->read(); + } else { + return -1; + } + } + + int read(unsigned char *buffer, size_t len) { + if (_rx_pkt) { + return _rx_pkt->read(buffer, len); + } else { + return -1; + } + } + + int read(char *buffer, size_t len) { + if (_rx_pkt) { + return _rx_pkt->read(buffer, len); + } else { + return -1; + } + } + + int peek() { + if (_rx_pkt) { + return _rx_pkt->peek(); + } else { + return -1; + } + } + + void flush() { + /* Delete UdpRxPacket object held by _rx_pkt. */ + if (_rx_pkt) { + _rx_pkt.reset(); + } + } + + virtual IPAddress remoteIP() { + if (_rx_pkt) { + return _rx_pkt->remoteIP(); + } else { + return IPAddress(); + } + } + + virtual uint16_t remotePort() { + if (_rx_pkt) { + return _rx_pkt->remotePort(); + } else { + return 0; + } + } private: - - /* UDP TRANSMISSION */ - IPAddress _send_to_ip; - uint16_t _send_to_port; - std::vector _tx_data; - int _rx_pkt_list_size = 10; - /* UDP RECEPTION */ - class UdpRxPacket - { - private: - IPAddress const _remote_ip; - uint16_t const _remote_port; - size_t const _rx_data_len; - std::deque _rx_data; - - public: - UdpRxPacket( - IPAddress const remote_ip, - uint16_t const remote_port, - uint8_t const * p_data, - size_t const data_len) - : _remote_ip(remote_ip) - , _remote_port(remote_port) - , _rx_data_len(data_len) - , _rx_data(p_data, p_data + data_len) - { - } - - typedef std::shared_ptr SharedPtr; - - IPAddress remoteIP() const { return _remote_ip; } - uint16_t remotePort() const { return _remote_port; } - size_t totalSize() const { return _rx_data_len; } - - int available() - { - return _rx_data.size(); - } - - int read() - { - uint8_t const data = _rx_data.front(); - _rx_data.pop_front(); - return data; - } - - int read(unsigned char* buffer, size_t len) - { - size_t bytes_read = 0; - for (; bytes_read < len && !_rx_data.empty(); bytes_read++) - { - buffer[bytes_read] = _rx_data.front(); - _rx_data.pop_front(); - } - return bytes_read; - } - - int read(char* buffer, size_t len) - { - return read((unsigned char*)buffer, len); - } - - int peek() - { - return _rx_data.front(); - } - }; - std::list _rx_pkt_list; - UdpRxPacket::SharedPtr _rx_pkt; -}; \ No newline at end of file + /* UDP TRANSMISSION */ + IPAddress _send_to_ip; + uint16_t _send_to_port; + std::vector _tx_data; + int _rx_pkt_list_size = 10; + + /* UDP RECEPTION */ + class UdpRxPacket { + private: + IPAddress const _remote_ip; + uint16_t const _remote_port; + size_t const _rx_data_len; + std::deque _rx_data; + + public: + UdpRxPacket(IPAddress const remote_ip, uint16_t const remote_port, uint8_t const *p_data, + size_t const data_len) + : _remote_ip(remote_ip), _remote_port(remote_port), _rx_data_len(data_len), + _rx_data(p_data, p_data + data_len) { + } + + typedef std::shared_ptr SharedPtr; + + IPAddress remoteIP() const { + return _remote_ip; + } + + uint16_t remotePort() const { + return _remote_port; + } + + size_t totalSize() const { + return _rx_data_len; + } + + int available() { + return _rx_data.size(); + } + + int read() { + uint8_t const data = _rx_data.front(); + _rx_data.pop_front(); + return data; + } + + int read(unsigned char *buffer, size_t len) { + size_t bytes_read = 0; + for (; bytes_read < len && !_rx_data.empty(); bytes_read++) { + buffer[bytes_read] = _rx_data.front(); + _rx_data.pop_front(); + } + return bytes_read; + } + + int read(char *buffer, size_t len) { + return read((unsigned char *)buffer, len); + } + + int peek() { + return _rx_data.front(); + } + }; + + std::list _rx_pkt_list; + UdpRxPacket::SharedPtr _rx_pkt; +}; diff --git a/libraries/SocketWrapper/examples/TestClient/TestClient.ino b/libraries/SocketWrapper/examples/TestClient/TestClient.ino old mode 100755 new mode 100644 index dc5b98c3..41a4acb4 --- a/libraries/SocketWrapper/examples/TestClient/TestClient.ino +++ b/libraries/SocketWrapper/examples/TestClient/TestClient.ino @@ -6,26 +6,26 @@ IPAddress addr(93, 184, 215, 14); void setup() { - pinMode(LED_BUILTIN, OUTPUT); - Serial.begin(115200); + pinMode(LED_BUILTIN, OUTPUT); + Serial.begin(115200); - while (Ethernet.linkStatus() != LinkON) { - Serial.println("waiting for link on"); - delay(100); - } - Ethernet.begin(); - Serial.println(Ethernet.localIP()); + while (Ethernet.linkStatus() != LinkON) { + Serial.println("waiting for link on"); + delay(100); + } + Ethernet.begin(); + Serial.println(Ethernet.localIP()); - auto res = client.connect("example.com", 80); - res = client.println("GET / HTTP/1.0"); - client.println("Host: example.com"); - client.println("Connection: close"); - client.println(); + auto res = client.connect("example.com", 80); + res = client.println("GET / HTTP/1.0"); + client.println("Host: example.com"); + client.println("Connection: close"); + client.println(); } // the loop function runs over and over again forever void loop() { - while (client.available()) { - Serial.write(client.read()); - } + while (client.available()) { + Serial.write(client.read()); + } } diff --git a/libraries/SocketWrapper/examples/TestServer/TestServer.ino b/libraries/SocketWrapper/examples/TestServer/TestServer.ino index b74e6ce3..02798d1b 100644 --- a/libraries/SocketWrapper/examples/TestServer/TestServer.ino +++ b/libraries/SocketWrapper/examples/TestServer/TestServer.ino @@ -4,69 +4,70 @@ ZephyrServer server(80); void setup() { - Serial.begin(115200); + Serial.begin(115200); - while (Ethernet.linkStatus() != LinkON) { - Serial.println("waiting for link on"); - delay(100); - } - Ethernet.begin(); - Serial.println(Ethernet.localIP()); - server.begin(); + while (Ethernet.linkStatus() != LinkON) { + Serial.println("waiting for link on"); + delay(100); + } + Ethernet.begin(); + Serial.println(Ethernet.localIP()); + server.begin(); } void loop() { - ZephyrClient client = server.available(); - if (client) { - Serial.println("new client"); - // an http request ends with a blank line - bool currentLineIsBlank = true; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - Serial.write(c); - // if you've gotten to the end of the line (received a newline - // character) and the line is blank, the http request has ended, - // so you can send a reply - if (c == '\n' && currentLineIsBlank) { - // send a standard http response header - client.println("HTTP/1.1 200 OK"); - client.println("Content-Type: text/html"); - client.println("Connection: close"); // the connection will be closed after completion of the response - client.println("Refresh: 5"); // refresh the page automatically every 5 sec - client.println(); - client.println(""); - client.println(""); - // output the value of each analog input pin - for (int analogChannel = 0; analogChannel < 6; analogChannel++) { - int sensorReading = random(analogChannel, 100); - client.print("analog input "); - client.print(analogChannel); - client.print(" is "); - client.print(sensorReading); - client.println("
"); - } - client.println(""); - break; - } + ZephyrClient client = server.available(); + if (client) { + Serial.println("new client"); + // an http request ends with a blank line + bool currentLineIsBlank = true; + while (client.connected()) { + if (client.available()) { + char c = client.read(); + Serial.write(c); + // if you've gotten to the end of the line (received a newline + // character) and the line is blank, the http request has ended, + // so you can send a reply + if (c == '\n' && currentLineIsBlank) { + // send a standard http response header + client.println("HTTP/1.1 200 OK"); + client.println("Content-Type: text/html"); + client.println("Connection: close"); // the connection will be closed after + // completion of the response + client.println("Refresh: 5"); // refresh the page automatically every 5 sec + client.println(); + client.println(""); + client.println(""); + // output the value of each analog input pin + for (int analogChannel = 0; analogChannel < 6; analogChannel++) { + int sensorReading = random(analogChannel, 100); + client.print("analog input "); + client.print(analogChannel); + client.print(" is "); + client.print(sensorReading); + client.println("
"); + } + client.println(""); + break; + } - if (c == '\n') { - // you're starting a new line - currentLineIsBlank = true; + if (c == '\n') { + // you're starting a new line + currentLineIsBlank = true; - } else if (c != '\r') { - // you've gotten a character on the current line - currentLineIsBlank = false; - } - } - } - // give the web browser time to receive the data - delay(1); - // close the connection: - client.stop(); - Serial.println("client disconnected"); - } else { - delay(100); - } -} \ No newline at end of file + } else if (c != '\r') { + // you've gotten a character on the current line + currentLineIsBlank = false; + } + } + } + // give the web browser time to receive the data + delay(1); + // close the connection: + client.stop(); + Serial.println("client disconnected"); + } else { + delay(100); + } +} diff --git a/libraries/SocketWrapper/utility/wl_definitions.h b/libraries/SocketWrapper/utility/wl_definitions.h index 1c49a7af..59128dc7 100644 --- a/libraries/SocketWrapper/utility/wl_definitions.h +++ b/libraries/SocketWrapper/utility/wl_definitions.h @@ -24,54 +24,54 @@ #define WL_DEFINITIONS_H_ // Maximum size of a SSID -#define WL_SSID_MAX_LENGTH 32 +#define WL_SSID_MAX_LENGTH 32 // Length of passphrase. Valid lengths are 8-63. -#define WL_WPA_KEY_MAX_LENGTH 63 +#define WL_WPA_KEY_MAX_LENGTH 63 // Length of key in bytes. Valid values are 5 and 13. -#define WL_WEP_KEY_MAX_LENGTH 13 +#define WL_WEP_KEY_MAX_LENGTH 13 // Size of a MAC-address or BSSID -#define WL_MAC_ADDR_LENGTH 6 +#define WL_MAC_ADDR_LENGTH 6 // Size of a MAC-address or BSSID -#define WL_IPV4_LENGTH 4 +#define WL_IPV4_LENGTH 4 // Maximum size of a SSID list -#define WL_NETWORKS_LIST_MAXNUM 10 +#define WL_NETWORKS_LIST_MAXNUM 10 // Maxmium number of socket -#define MAX_SOCK_NUM 4 +#define MAX_SOCK_NUM 4 // Socket not available constant -#define SOCK_NOT_AVAIL 255 +#define SOCK_NOT_AVAIL 255 // Default state value for Wifi state field -#define NA_STATE -1 -//Maximum number of attempts to establish wifi connection -#define WL_MAX_ATTEMPT_CONNECTION 10 +#define NA_STATE -1 +// Maximum number of attempts to establish wifi connection +#define WL_MAX_ATTEMPT_CONNECTION 10 typedef enum { - WL_NO_SHIELD = 255, - WL_NO_MODULE = 255, - WL_IDLE_STATUS = 0, - WL_NO_SSID_AVAIL, - WL_SCAN_COMPLETED, - WL_CONNECTED, - WL_CONNECT_FAILED, - WL_CONNECTION_LOST, - WL_DISCONNECTED, - WL_AP_LISTENING, - WL_AP_CONNECTED, - WL_AP_FAILED + WL_NO_SHIELD = 255, + WL_NO_MODULE = 255, + WL_IDLE_STATUS = 0, + WL_NO_SSID_AVAIL, + WL_SCAN_COMPLETED, + WL_CONNECTED, + WL_CONNECT_FAILED, + WL_CONNECTION_LOST, + WL_DISCONNECTED, + WL_AP_LISTENING, + WL_AP_CONNECTED, + WL_AP_FAILED } wl_status_t; /* Encryption modes */ -enum wl_enc_type { /* Values map to 802.11 Cipher Algorithm Identifier */ - ENC_TYPE_WEP = 5, - ENC_TYPE_TKIP = 2, - ENC_TYPE_WPA = ENC_TYPE_TKIP, - ENC_TYPE_CCMP = 4, - ENC_TYPE_WPA2 = ENC_TYPE_CCMP, - ENC_TYPE_GCMP = 6, - ENC_TYPE_WPA3 = ENC_TYPE_GCMP, - /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ - ENC_TYPE_NONE = 7, - ENC_TYPE_UNKNOWN = 9, - ENC_TYPE_AUTO = 8 +enum wl_enc_type { /* Values map to 802.11 Cipher Algorithm Identifier */ + ENC_TYPE_WEP = 5, + ENC_TYPE_TKIP = 2, + ENC_TYPE_WPA = ENC_TYPE_TKIP, + ENC_TYPE_CCMP = 4, + ENC_TYPE_WPA2 = ENC_TYPE_CCMP, + ENC_TYPE_GCMP = 6, + ENC_TYPE_WPA3 = ENC_TYPE_GCMP, + /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ + ENC_TYPE_NONE = 7, + ENC_TYPE_UNKNOWN = 9, + ENC_TYPE_AUTO = 8 }; -#endif /* WL_DEFINITIONS_H_ */ \ No newline at end of file +#endif /* WL_DEFINITIONS_H_ */ diff --git a/libraries/Wire/Wire.cpp b/libraries/Wire/Wire.cpp index 0453db62..99cd2624 100644 --- a/libraries/Wire/Wire.cpp +++ b/libraries/Wire/Wire.cpp @@ -7,123 +7,122 @@ #include #include -arduino::ZephyrI2C::ZephyrI2C(const struct device *i2c) : i2c_dev(i2c) -{ +arduino::ZephyrI2C::ZephyrI2C(const struct device *i2c) : i2c_dev(i2c) { } void arduino::ZephyrI2C::begin() { - ring_buf_init(&rxRingBuffer.rb, sizeof(rxRingBuffer.buffer), rxRingBuffer.buffer); + ring_buf_init(&rxRingBuffer.rb, sizeof(rxRingBuffer.buffer), rxRingBuffer.buffer); } void arduino::ZephyrI2C::begin(uint8_t slaveAddr) { - } -void arduino::ZephyrI2C::end() {} +void arduino::ZephyrI2C::end() { +} void arduino::ZephyrI2C::setClock(uint32_t freq) { - uint8_t speed = I2C_SPEED_STANDARD; - if(freq > 0x06u ) { - if(freq == 100000) { - speed = I2C_SPEED_STANDARD; - } else if(freq == 400000) { - speed = I2C_SPEED_FAST; - } else if(freq == 1000000) { - speed = I2C_SPEED_FAST_PLUS; + uint8_t speed = I2C_SPEED_STANDARD; + if (freq > 0x06u) { + if (freq == 100000) { + speed = I2C_SPEED_STANDARD; + } else if (freq == 400000) { + speed = I2C_SPEED_FAST; + } else if (freq == 1000000) { + speed = I2C_SPEED_FAST_PLUS; } else { - speed = I2C_SPEED_STANDARD; + speed = I2C_SPEED_STANDARD; } } else { - speed = (uint8_t) freq; + speed = (uint8_t)freq; } - uint32_t i2c_cfg = I2C_MODE_CONTROLLER | - I2C_SPEED_SET(speed); + uint32_t i2c_cfg = I2C_MODE_CONTROLLER | I2C_SPEED_SET(speed); if (i2c_configure(i2c_dev, i2c_cfg)) { - //Serial.println("Failed to configure i2c interface."); + // Serial.println("Failed to configure i2c interface."); } } void arduino::ZephyrI2C::beginTransmission(uint8_t address) { // TODO for ADS1115 - _address = address; - usedTxBuffer = 0; + _address = address; + usedTxBuffer = 0; } uint8_t arduino::ZephyrI2C::endTransmission(bool stopBit) { - int ret = i2c_write(i2c_dev, txBuffer, usedTxBuffer, _address); - if (ret) { - return 1; // fail - } - return 0; + int ret = i2c_write(i2c_dev, txBuffer, usedTxBuffer, _address); + if (ret) { + return 1; // fail + } + return 0; } uint8_t arduino::ZephyrI2C::endTransmission(void) { // TODO for ADS1115 - return endTransmission(true); + return endTransmission(true); } -size_t arduino::ZephyrI2C::requestFrom(uint8_t address, size_t len, - bool stopBit) { - uint8_t buf[len]; - int ret = i2c_read(i2c_dev, buf, len, address); - if (ret != 0) - { - return 0; - } - ret = ring_buf_put(&rxRingBuffer.rb, buf, len); - if (ret == 0) - { - return 0; - } - return len; +size_t arduino::ZephyrI2C::requestFrom(uint8_t address, size_t len, bool stopBit) { + uint8_t buf[len]; + int ret = i2c_read(i2c_dev, buf, len, address); + if (ret != 0) { + return 0; + } + ret = ring_buf_put(&rxRingBuffer.rb, buf, len); + if (ret == 0) { + return 0; + } + return len; } size_t arduino::ZephyrI2C::requestFrom(uint8_t address, size_t len) { // TODO for ADS1115 - return requestFrom(address, len, true); + return requestFrom(address, len, true); } -size_t arduino::ZephyrI2C::write(uint8_t data) { // TODO for ADS1115 - txBuffer[usedTxBuffer++] = data; - return 1; +size_t arduino::ZephyrI2C::write(uint8_t data) { // TODO for ADS1115 + txBuffer[usedTxBuffer++] = data; + return 1; } size_t arduino::ZephyrI2C::write(const uint8_t *buffer, size_t size) { - if (usedTxBuffer + size > 256) { - size = 256 - usedTxBuffer; - } + if (usedTxBuffer + size > 256) { + size = 256 - usedTxBuffer; + } memcpy(txBuffer + usedTxBuffer, buffer, size); - usedTxBuffer += size; - return size; + usedTxBuffer += size; + return size; } int arduino::ZephyrI2C::read() { - uint8_t buf[1]; - if (ring_buf_size_get(&rxRingBuffer.rb)) { - int ret = ring_buf_get(&rxRingBuffer.rb, buf, 1); - if (ret == 0) { - return -1; - } + uint8_t buf[1]; + if (ring_buf_size_get(&rxRingBuffer.rb)) { + int ret = ring_buf_get(&rxRingBuffer.rb, buf, 1); + if (ret == 0) { + return -1; + } return (int)buf[0]; - } - return -1; + } + return -1; } int arduino::ZephyrI2C::available() { - return ring_buf_size_get(&rxRingBuffer.rb); + return ring_buf_size_get(&rxRingBuffer.rb); } int arduino::ZephyrI2C::peek() { - uint8_t buf[1]; - int bytes_read = ring_buf_peek(&rxRingBuffer.rb, buf, 1); - if (bytes_read == 0){ - return 0; - } - return (int)buf[0]; + uint8_t buf[1]; + int bytes_read = ring_buf_peek(&rxRingBuffer.rb, buf, 1); + if (bytes_read == 0) { + return 0; + } + return (int)buf[0]; +} + +void arduino::ZephyrI2C::flush() { } -void arduino::ZephyrI2C::flush() {} +void arduino::ZephyrI2C::onReceive(voidFuncPtrParamInt cb) { +} -void arduino::ZephyrI2C::onReceive(voidFuncPtrParamInt cb) {} -void arduino::ZephyrI2C::onRequest(voidFuncPtr cb) {} +void arduino::ZephyrI2C::onRequest(voidFuncPtr cb) { +} #if DT_NODE_HAS_PROP(DT_PATH(zephyr_user), i2cs) #if (DT_PROP_LEN(DT_PATH(zephyr_user), i2cs) > 1) diff --git a/libraries/Wire/Wire.h b/libraries/Wire/Wire.h index 6e289f8c..6ca0ac9d 100644 --- a/libraries/Wire/Wire.h +++ b/libraries/Wire/Wire.h @@ -17,42 +17,47 @@ namespace arduino { class ZephyrI2C : public HardwareI2C { public: - ZephyrI2C(const struct device* i2c); + ZephyrI2C(const struct device *i2c); - virtual void begin(); - virtual void end(); - virtual void begin(uint8_t address); - virtual void setClock(uint32_t freq); + virtual void begin(); + virtual void end(); + virtual void begin(uint8_t address); + virtual void setClock(uint32_t freq); - virtual void beginTransmission(uint8_t address); - virtual uint8_t endTransmission(bool stopBit); - virtual uint8_t endTransmission(void); + virtual void beginTransmission(uint8_t address); + virtual uint8_t endTransmission(bool stopBit); + virtual uint8_t endTransmission(void); - virtual size_t requestFrom(uint8_t address, size_t len, bool stopBit); - virtual size_t requestFrom(uint8_t address, size_t len); + virtual size_t requestFrom(uint8_t address, size_t len, bool stopBit); + virtual size_t requestFrom(uint8_t address, size_t len); - virtual void onReceive(void (*)(int)); - virtual void onRequest(void (*)(void)); + virtual void onReceive(void (*)(int)); + virtual void onRequest(void (*)(void)); - virtual size_t write(uint8_t data); - virtual size_t write(int data) { return write((uint8_t)data); }; - virtual size_t write(const uint8_t *buffer, size_t size); - using Print::write; - virtual int read(); - virtual int peek(); - virtual void flush(); - virtual int available(); + virtual size_t write(uint8_t data); + + virtual size_t write(int data) { + return write((uint8_t)data); + }; + + virtual size_t write(const uint8_t *buffer, size_t size); + using Print::write; + virtual int read(); + virtual int peek(); + virtual void flush(); + virtual int available(); private: - int _address; - uint8_t txBuffer[256]; - uint32_t usedTxBuffer; - struct rx_ring_buf{ - struct ring_buf rb; - uint8_t buffer[256]; - }; - struct rx_ring_buf rxRingBuffer; - const struct device* i2c_dev; + int _address; + uint8_t txBuffer[256]; + uint32_t usedTxBuffer; + + struct rx_ring_buf { + struct ring_buf rb; + uint8_t buffer[256]; + }; + struct rx_ring_buf rxRingBuffer; + const struct device *i2c_dev; }; } // namespace arduino diff --git a/libraries/Zephyr_SDRAM/examples/SDRAM_operations/SDRAM_operations.ino b/libraries/Zephyr_SDRAM/examples/SDRAM_operations/SDRAM_operations.ino index c55795ea..14993374 100644 --- a/libraries/Zephyr_SDRAM/examples/SDRAM_operations/SDRAM_operations.ino +++ b/libraries/Zephyr_SDRAM/examples/SDRAM_operations/SDRAM_operations.ino @@ -1,68 +1,67 @@ /* - How to interact with external SDRAM on Portenta H7 + How to interact with external SDRAM on Portenta H7 - The board comes with an hefty 8MB of external fast RAM, which can be used: - - as a framebuffer (raw mode) - - as an expansion of on-chip RAM to store "standard" data + The board comes with an hefty 8MB of external fast RAM, which can be used: + - as a framebuffer (raw mode) + - as an expansion of on-chip RAM to store "standard" data - This example shows both the usages + This example shows both the usages */ #include "SDRAM.h" void nonFrameBuffer() { - // Initilize SDRAM for non-framebuffer operations - SDRAM.begin(); // is the same as SDRAM.begin(SDRAM_START_ADDRESS); + // Initilize SDRAM for non-framebuffer operations + SDRAM.begin(); // is the same as SDRAM.begin(SDRAM_START_ADDRESS); - // Now we can malloc() and free() in the whole RAM space - // For example, let's create a 7MB array - uint8_t* myVeryBigArray = (uint8_t*)SDRAM.malloc(7 * 1024 * 1024); + // Now we can malloc() and free() in the whole RAM space + // For example, let's create a 7MB array + uint8_t *myVeryBigArray = (uint8_t *)SDRAM.malloc(7 * 1024 * 1024); - // and a small one - uint8_t* mySmallArray = (uint8_t*)SDRAM.malloc(128); + // and a small one + uint8_t *mySmallArray = (uint8_t *)SDRAM.malloc(128); - // and use then as usual - for (int i = 0; i<128; i++) { - myVeryBigArray[i] = i; - mySmallArray[i] = i*2; - } + // and use then as usual + for (int i = 0; i < 128; i++) { + myVeryBigArray[i] = i; + mySmallArray[i] = i * 2; + } - // free the memory when you don't need them anymore - SDRAM.free(myVeryBigArray); + // free the memory when you don't need them anymore + SDRAM.free(myVeryBigArray); } void frameBuffer() { - // In case we want a framebuffer-like area at the beginning of the flash, - // simply initialize the memory as + // In case we want a framebuffer-like area at the beginning of the flash, + // simply initialize the memory as - SDRAM.begin(SDRAM_START_ADDRESS + 2 * 1024 * 1024); - // 2MB of contiguous memory available at the beginning + SDRAM.begin(SDRAM_START_ADDRESS + 2 * 1024 * 1024); + // 2MB of contiguous memory available at the beginning - uint32_t* framebuffer = (uint32_t*)SDRAM_START_ADDRESS; + uint32_t *framebuffer = (uint32_t *)SDRAM_START_ADDRESS; - // We can't allocate anymore the huge 7MB array - - uint8_t* myVeryBigArray = (uint8_t*)SDRAM.malloc(7 * 1024 * 1024); - if (myVeryBigArray == NULL) { - Serial.println("Oops, too big :)"); - } + // We can't allocate anymore the huge 7MB array + uint8_t *myVeryBigArray = (uint8_t *)SDRAM.malloc(7 * 1024 * 1024); + if (myVeryBigArray == NULL) { + Serial.println("Oops, too big :)"); + } } void setup() { - Serial.begin(115200); - while (!Serial); - - frameBuffer(); - // Uncomment to test the other functionality - // nonFrameBuffer(); - - // Sort of memtest for stability, useful for testing when overclocking - if (SDRAM.test()) { - Serial.println("SDRAM completely functional"); - } + Serial.begin(115200); + while (!Serial) + ; + + frameBuffer(); + // Uncomment to test the other functionality + // nonFrameBuffer(); + + // Sort of memtest for stability, useful for testing when overclocking + if (SDRAM.test()) { + Serial.println("SDRAM completely functional"); + } } void loop() { - -} \ No newline at end of file +} diff --git a/libraries/Zephyr_SDRAM/src/SDRAM.cpp b/libraries/Zephyr_SDRAM/src/SDRAM.cpp index 23c93f03..76fa2f85 100644 --- a/libraries/Zephyr_SDRAM/src/SDRAM.cpp +++ b/libraries/Zephyr_SDRAM/src/SDRAM.cpp @@ -3,67 +3,70 @@ int SDRAMClass::begin(uint32_t start_address) { if (start_address) { - malloc_addblock((void*)start_address, SDRAM_END_ADDRESS - start_address); + malloc_addblock((void *)start_address, SDRAM_END_ADDRESS - start_address); } return 1; } -void* SDRAMClass::malloc(size_t size) { +void *SDRAMClass::malloc(size_t size) { return ea_malloc(size); } -void SDRAMClass::free(void* ptr) { +void SDRAMClass::free(void *ptr) { ea_free(ptr); } -bool SDRAMClass::test(bool fast, Stream& _serial) { - uint8_t const pattern = 0xaa; - uint8_t const antipattern = 0x55; - uint8_t *const mem_base = (uint8_t*)SDRAM_START_ADDRESS; +bool SDRAMClass::test(bool fast, Stream &_serial) { + uint8_t const pattern = 0xaa; + uint8_t const antipattern = 0x55; + uint8_t *const mem_base = (uint8_t *)SDRAM_START_ADDRESS; - /* test data bus */ - for (uint8_t i = 1; i; i <<= 1) { - *mem_base = i; - if (*mem_base != i) { - _serial.println("data bus lines test failed! data (" + String(i) + ")"); - __asm__ volatile ("BKPT"); - } - } + /* test data bus */ + for (uint8_t i = 1; i; i <<= 1) { + *mem_base = i; + if (*mem_base != i) { + _serial.println("data bus lines test failed! data (" + String(i) + ")"); + __asm__ volatile("BKPT"); + } + } - /* test address bus */ - /* Check individual address lines */ - for (uint32_t i = 1; i < HW_SDRAM_SIZE; i <<= 1) { - mem_base[i] = pattern; - if (mem_base[i] != pattern) { - _serial.println("address bus lines test failed! address ("+ String((uint32_t)&mem_base[i], HEX) + ")"); - __asm__ volatile ("BKPT"); - } - } + /* test address bus */ + /* Check individual address lines */ + for (uint32_t i = 1; i < HW_SDRAM_SIZE; i <<= 1) { + mem_base[i] = pattern; + if (mem_base[i] != pattern) { + _serial.println("address bus lines test failed! address (" + + String((uint32_t)&mem_base[i], HEX) + ")"); + __asm__ volatile("BKPT"); + } + } - /* Check for aliasing (overlaping addresses) */ - mem_base[0] = antipattern; - for (uint32_t i = 1; i < HW_SDRAM_SIZE; i <<= 1) { - if (mem_base[i] != pattern) { - _serial.println("address bus overlap! address ("+ String((uint32_t)&mem_base[i], HEX) + ")"); - __asm__ volatile ("BKPT"); - } - } + /* Check for aliasing (overlaping addresses) */ + mem_base[0] = antipattern; + for (uint32_t i = 1; i < HW_SDRAM_SIZE; i <<= 1) { + if (mem_base[i] != pattern) { + _serial.println("address bus overlap! address (" + String((uint32_t)&mem_base[i], HEX) + + ")"); + __asm__ volatile("BKPT"); + } + } - /* test all ram cells */ - if (!fast) { - for (uint32_t i = 0; i < HW_SDRAM_SIZE; ++i) { - mem_base[i] = pattern; - if (mem_base[i] != pattern) { - _serial.println("address bus test failed! address ("+ String((uint32_t)&mem_base[i], HEX) + ")"); - __asm__ volatile ("BKPT"); - } - } - } else { - memset(mem_base, pattern, HW_SDRAM_SIZE); - } + /* test all ram cells */ + if (!fast) { + for (uint32_t i = 0; i < HW_SDRAM_SIZE; ++i) { + mem_base[i] = pattern; + if (mem_base[i] != pattern) { + _serial.println("address bus test failed! address (" + + String((uint32_t)&mem_base[i], HEX) + ")"); + __asm__ volatile("BKPT"); + } + } + } else { + memset(mem_base, pattern, HW_SDRAM_SIZE); + } - return true; + return true; } -SDRAMClass SDRAM; \ No newline at end of file +SDRAMClass SDRAM; diff --git a/libraries/Zephyr_SDRAM/src/SDRAM.h b/libraries/Zephyr_SDRAM/src/SDRAM.h index 853b705a..f7991cbf 100644 --- a/libraries/Zephyr_SDRAM/src/SDRAM.h +++ b/libraries/Zephyr_SDRAM/src/SDRAM.h @@ -7,20 +7,23 @@ #include "Arduino.h" -#define SDRAM_END_ADDRESS (0xc0800000) -#define SDRAM_START_ADDRESS (0xc0000000) -#define HW_SDRAM_SIZE (8 * 1024 * 1024) +#define SDRAM_END_ADDRESS (0xc0800000) +#define SDRAM_START_ADDRESS (0xc0000000) +#define HW_SDRAM_SIZE (8 * 1024 * 1024) class SDRAMClass { public: - SDRAMClass() {} + SDRAMClass() { + } + int begin(uint32_t start_address = SDRAM_START_ADDRESS); - void* malloc(size_t size); - void free(void* ptr); - bool test(bool fast = false, Stream& _serial = Serial); -private: + void *malloc(size_t size); + void free(void *ptr); + bool test(bool fast = false, Stream &_serial = Serial); +private: }; + extern SDRAMClass SDRAM; #endif diff --git a/loader/fixups.c b/loader/fixups.c index cf5e60cd..8d6277b0 100644 --- a/loader/fixups.c +++ b/loader/fixups.c @@ -1,7 +1,7 @@ #include #include -int disable_mpu_rasr_xn(void) -{ + +int disable_mpu_rasr_xn(void) { uint32_t index; /* Kept the max index as 8(irrespective of soc) because the sram * would most likely be set at index 2. @@ -30,8 +30,9 @@ int disable_bootloader_mpu() { __DMB(); MPU->CTRL = 0; __enable_irq(); - return 0; + return 0; } + SYS_INIT(disable_bootloader_mpu, PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT); #endif @@ -45,8 +46,7 @@ SYS_INIT(disable_mpu_rasr_xn, PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT) #include #include -int camera_ext_clock_enable(void) -{ +int camera_ext_clock_enable(void) { int ret; uint32_t rate; const struct device *cam_ext_clk_dev = DEVICE_DT_GET(DT_NODELABEL(pwmclock)); @@ -77,25 +77,25 @@ SYS_INIT(camera_ext_clock_enable, POST_KERNEL, CONFIG_CLOCK_CONTROL_PWM_INIT_PRI #include #include -__stm32_sdram1_section static uint8_t __aligned(32) smh_pool[4*1024*1024]; +__stm32_sdram1_section static uint8_t __aligned(32) smh_pool[4 * 1024 * 1024]; int smh_init(void) { - int ret = 0; - ret = shared_multi_heap_pool_init(); - if (ret != 0) { - return ret; - } - - struct shared_multi_heap_region smh_sdram = { - .addr = (uintptr_t) smh_pool, - .size = sizeof(smh_pool), - .attr = SMH_REG_ATTR_EXTERNAL, - }; - - ret = shared_multi_heap_add(&smh_sdram, NULL); - if (ret != 0) { - return ret; - } + int ret = 0; + ret = shared_multi_heap_pool_init(); + if (ret != 0) { + return ret; + } + + struct shared_multi_heap_region smh_sdram = { + .addr = (uintptr_t)smh_pool, + .size = sizeof(smh_pool), + .attr = SMH_REG_ATTR_EXTERNAL, + }; + + ret = shared_multi_heap_add(&smh_sdram, NULL); + if (ret != 0) { + return ret; + } return 0; } @@ -106,12 +106,11 @@ SYS_INIT(smh_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT); #include #include -int maybe_flash_bootloader(void) -{ +int maybe_flash_bootloader(void) { // memcmp the first 256bytes of "embedded bootloader" and address 0x0 // if they are different, flash the bootloader const uint8_t embedded_bootloader[] = { - #include "c33_bl_patch/c33_bl.bin.inc" +#include "c33_bl_patch/c33_bl.bin.inc" }; const struct flash_area *fa; diff --git a/loader/main.c b/loader/main.c index 643da9d7..6aa2b4c8 100644 --- a/loader/main.c +++ b/loader/main.c @@ -27,25 +27,24 @@ struct sketch_header_v1 { uint32_t len; // @ 0x08 uint16_t magic; // @ 0x0c uint8_t flags; // @ 0x0e -} __attribute__ ((packed)); +} __attribute__((packed)); -#define SKETCH_FLAG_DEBUG 0x01 -#define SKETCH_FLAG_LINKED 0x02 +#define SKETCH_FLAG_DEBUG 0x01 +#define SKETCH_FLAG_LINKED 0x02 -#define TARGET_HAS_USB_CDC_SHELL \ - DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && CONFIG_SHELL && CONFIG_USB_DEVICE_STACK +#define TARGET_HAS_USB_CDC_SHELL \ + DT_NODE_HAS_PROP(DT_PATH(zephyr_user), cdc_acm) && CONFIG_SHELL &&CONFIG_USB_DEVICE_STACK #if TARGET_HAS_USB_CDC_SHELL -const struct device *const usb_dev = DEVICE_DT_GET(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), cdc_acm, 0)); +const struct device *const usb_dev = + DEVICE_DT_GET(DT_PHANDLE_BY_IDX(DT_PATH(zephyr_user), cdc_acm, 0)); -static int enable_shell_usb(void) -{ +static int enable_shell_usb(void) { bool log_backend = CONFIG_SHELL_BACKEND_SERIAL_LOG_LEVEL > 0; - uint32_t level = - (CONFIG_SHELL_BACKEND_SERIAL_LOG_LEVEL > LOG_LEVEL_DBG) ? - CONFIG_LOG_MAX_LEVEL : CONFIG_SHELL_BACKEND_SERIAL_LOG_LEVEL; - static const struct shell_backend_config_flags cfg_flags = - SHELL_DEFAULT_BACKEND_CONFIG_FLAGS; + uint32_t level = (CONFIG_SHELL_BACKEND_SERIAL_LOG_LEVEL > LOG_LEVEL_DBG) ? + CONFIG_LOG_MAX_LEVEL : + CONFIG_SHELL_BACKEND_SERIAL_LOG_LEVEL; + static const struct shell_backend_config_flags cfg_flags = SHELL_DEFAULT_BACKEND_CONFIG_FLAGS; shell_init(shell_backend_uart_get_ptr(), usb_dev, cfg_flags, log_backend, level); @@ -57,19 +56,17 @@ static int enable_shell_usb(void) K_THREAD_STACK_DEFINE(llext_stack, CONFIG_MAIN_STACK_SIZE); struct k_thread llext_thread; -void llext_entry(void *arg0, void *arg1, void *arg2) -{ - void (*fn)(struct llext_loader*, struct llext*) = arg0; +void llext_entry(void *arg0, void *arg1, void *arg2) { + void (*fn)(struct llext_loader *, struct llext *) = arg0; fn(arg1, arg2); } #endif /* CONFIG_USERSPACE */ -__attribute__((retain)) const uintptr_t sketch_base_addr = DT_REG_ADDR(DT_GPARENT(DT_NODELABEL(user_sketch))) + - DT_REG_ADDR(DT_NODELABEL(user_sketch)); +__attribute__((retain)) const uintptr_t sketch_base_addr = + DT_REG_ADDR(DT_GPARENT(DT_NODELABEL(user_sketch))) + DT_REG_ADDR(DT_NODELABEL(user_sketch)); __attribute__((retain)) const uintptr_t sketch_max_size = DT_REG_SIZE(DT_NODELABEL(user_sketch)); -static int loader(const struct shell *sh) -{ +static int loader(const struct shell *sh) { const struct flash_area *fa; int rc; @@ -80,8 +77,8 @@ static int loader(const struct shell *sh) return rc; } - uintptr_t base_addr = DT_REG_ADDR(DT_GPARENT(DT_NODELABEL(user_sketch))) + - DT_REG_ADDR(DT_NODELABEL(user_sketch)); + uintptr_t base_addr = + DT_REG_ADDR(DT_GPARENT(DT_NODELABEL(user_sketch))) + DT_REG_ADDR(DT_NODELABEL(user_sketch)); char header[HEADER_LEN]; rc = flash_area_read(fa, 0, header, sizeof(header)); @@ -117,17 +114,17 @@ static int loader(const struct shell *sh) #endif if (sketch_hdr->flags & SKETCH_FLAG_LINKED) { - #ifdef CONFIG_BOARD_ARDUINO_PORTENTA_C33 - #if CONFIG_MPU +#ifdef CONFIG_BOARD_ARDUINO_PORTENTA_C33 +#if CONFIG_MPU barrier_dmem_fence_full(); - #endif - #if CONFIG_DCACHE +#endif +#if CONFIG_DCACHE barrier_dsync_fence_full(); - #endif - #if CONFIG_ICACHE +#endif +#if CONFIG_ICACHE barrier_isync_fence_full(); - #endif - #endif +#endif +#endif extern struct k_heap llext_heap; typedef void (*entry_point_t)(struct k_heap *heap, size_t heap_size); @@ -140,7 +137,7 @@ static int loader(const struct shell *sh) } #if defined(CONFIG_LLEXT_STORAGE_WRITABLE) - uint8_t* sketch_buf = k_aligned_alloc(4096, sketch_buf_len); + uint8_t *sketch_buf = k_aligned_alloc(4096, sketch_buf_len); if (!sketch_buf) { printk("Unable to allocate %d bytes\n", sketch_buf_len); @@ -153,7 +150,7 @@ static int loader(const struct shell *sh) } #else // Assuming the sketch is stored in the same flash device as the loader - uint8_t* sketch_buf = (uint8_t*)base_addr; + uint8_t *sketch_buf = (uint8_t *)base_addr; #endif #ifdef CONFIG_LLEXT @@ -203,10 +200,8 @@ static int loader(const struct shell *sh) return -1; } - k_thread_create(&llext_thread, llext_stack, - K_THREAD_STACK_SIZEOF(llext_stack), - &llext_entry, llext_bootstrap, ext, main_fn, - 1, K_INHERIT_PERMS, K_FOREVER); + k_thread_create(&llext_thread, llext_stack, K_THREAD_STACK_SIZEOF(llext_stack), &llext_entry, + llext_bootstrap, ext, main_fn, 1, K_INHERIT_PERMS, K_FOREVER); k_mem_domain_add_thread(&domain, &llext_thread); @@ -227,8 +222,7 @@ static int loader(const struct shell *sh) SHELL_CMD_REGISTER(sketch, NULL, "Run sketch", loader); #endif -int main(void) -{ +int main(void) { loader(NULL); return 0; }