diff --git a/Inc/communication/binary_download.h b/Inc/communication/binary_download.h new file mode 100644 index 0000000..07db769 --- /dev/null +++ b/Inc/communication/binary_download.h @@ -0,0 +1,24 @@ +#ifndef _BINARY_DOWNLOAD_H +#define _BINARY_DOWNLOAD_H + +#include "object_target.h" + +// Downlaod States +#define NO_DOWNLOAD_DATA 0 +#define DOWNLOAD_IN_PROGRESS 1 +#define DOWNLOAD_ERROR 2 +#define DOWNLOAD_COMPLETED 3 + +// Download Errors +#define NO_ERROR 0 +#define UNKNOWN_ERROR -1 +#define SOCKET_ERROR -2 +#define CONNECTION_ERROR -3 +#define REQUEST_ERROR -4 +#define RECEIVE_ERROR -5 +#define USB_ERROR -6 +#define ERROR_PARSING_URL -7 +#define HOST_UNKNOWN_ERROR -8 + +int startDownload(target_instance_t *targetP); +#endif \ No newline at end of file diff --git a/Inc/communication/wakaama_client/objects/object_target.h b/Inc/communication/wakaama_client/objects/object_target.h index 4d10681..8cfee81 100644 --- a/Inc/communication/wakaama_client/objects/object_target.h +++ b/Inc/communication/wakaama_client/objects/object_target.h @@ -1,9 +1,30 @@ -#ifndef _TARGET_H -#define _TARGET_H - -// Downlaod States -#define NO_DOWNLOAD_DATA 0 -#define DOWNLOAD_IN_PROGRESS 1 -#define DOWNLOAD_ERROR 2 -#define DOWNLOAD_COMPLETED 3 +#ifndef __OBJECT_TARGET_H +#define __OBJECT_TARGET_H + + +/* + * Multiple instance objects can use userdata to store data that will be shared between the different instances. + * The lwm2m_object_t object structure - which represent every object of the liblwm2m as seen in the single instance + * object - contain a chained list called instanceList with the object specific structure target_instance_t: + */ +typedef struct _target_instance_ +{ + /* + * The first two are mandatories and represent the pointer to the next instance and the ID of this one. The rest + * is the instance scope user data (uint8_t target in this case) + */ + struct _target_instance_ * next; // matches lwm2m_list_t::next + uint16_t shortID; // matches lwm2m_list_t::id + + uint8_t flash_state; + uint32_t * target_type; + char * firmware_url; + uint8_t download_state; + int16_t download_error; + uint32_t firmware_version; + char * binary_filename; + uint8_t download_progress; +} target_instance_t; + + #endif \ No newline at end of file diff --git a/Inc/communication/yuarel.h b/Inc/communication/yuarel.h new file mode 100644 index 0000000..8a8c1cd --- /dev/null +++ b/Inc/communication/yuarel.h @@ -0,0 +1,115 @@ +/** + * Copyright (C) 2016 Jack Engqvist Johansson + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef INC_YUAREL_H +#define INC_YUAREL_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The struct where the parsed values will be stored: + * + * scheme ":" [ "//" ] [ username ":" password "@" ] host [ ":" port ] [ "/" ] [ path ] [ "?" query ] + * + * Note: to make sure that no strings are copied, the first slash "/" in the + * path will be used to null terminate the hostname if no port is supplied. + */ +struct yuarel { + char *scheme; /* scheme, without ":" and "//" */ + char *username; /* username, default: NULL */ + char *password; /* password, default: NULL */ + char *host; /* hostname or IP address */ + int port; /* port, default: 0 */ + char *path; /* path, without leading "/", default: NULL */ + char *query; /* query, default: NULL */ + char *fragment; /* fragment, default: NULL */ +}; + +/* A struct to hold the query string parameter values. */ +struct yuarel_param { + char *key; + char *val; +}; + +/** + * Parse a URL to a struct. + * + * The URL string should be in one of the following formats: + * + * Absolute URL: + * scheme ":" [ "//" ] [ username ":" password "@" ] host [ ":" port ] [ "/" ] [ path ] [ "?" query ] [ "#" fragment ] + * + * Relative URL: + * path [ "?" query ] [ "#" fragment ] + * + * The following parts will be parsed to the corresponding struct member. + * + * *url: a pointer to the struct where to store the parsed values. + * *url_str: a pointer to the url to be parsed (null terminated). The string + * will be modified. + * + * Returns 0 on success, otherwise -1. + */ +extern int yuarel_parse(struct yuarel *url, char *url_str); + +/** + * Split a path into several strings. + * + * No data is copied, the slashed are used as null terminators and then + * pointers to each path part will be stored in **parts. Double slashes will be + * treated as one. + * + * *path: the path to split. The string will be modified. + * **parts: a pointer to an array of (char *) where to store the result. + * max_parts: max number of parts to parse. + * + * Returns the number of parsed items. -1 on error. + */ +extern int yuarel_split_path(char *path, char **parts, int max_parts); + +/** + * Parse a query string into a key/value struct. + * + * The query string should be a null terminated string of parameters separated by + * a delimiter. Each parameter are checked for the equal sign character. If it + * appears in the parameter, it will be used as a null terminator and the part + * that comes after it will be the value of the parameter. + * + * No data are copied, the equal sign and delimiters are used as null + * terminators and then pointers to each parameter key and value will be stored + * in the yuarel_param struct. + * + * *query: the query string to parse. The string will be modified. + * delimiter: the character that separates the key/value pairs from eachother. + * *params: an array of (struct yuarel_param) where to store the result. + * max_values: max number of parameters to parse. + * + * Returns the number of parsed items. -1 on error. + */ +extern int yuarel_parse_query(char *query, char delimiter, struct yuarel_param *params, int max_params); + +#ifdef __cplusplus +} +#endif + +#endif /* INC_YUAREL_H */ diff --git a/Inc/fatfs.h b/Inc/fatfs.h index 53a50c6..91b370f 100644 --- a/Inc/fatfs.h +++ b/Inc/fatfs.h @@ -1,80 +1,80 @@ -/** - ****************************************************************************** - * @file fatfs.h - * @brief Header for fatfs applications - ****************************************************************************** - * This notice applies to any and all portions of this file - * that are not between comment pairs USER CODE BEGIN and - * USER CODE END. Other portions of this file, whether - * inserted by the user or by software development tools - * are owned by their respective copyright owners. - * - * Copyright (c) 2018 STMicroelectronics International N.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __fatfs_H -#define __fatfs_H -#ifdef __cplusplus - extern "C" { -#endif - -#include "ff.h" -#include "ff_gen_drv.h" -#include "usbh_diskio.h" /* defines USBH_Driver as external */ - -/* USER CODE BEGIN Includes */ - -/* USER CODE END Includes */ - -extern uint8_t retUSBH; /* Return value for USBH */ -extern char USBHPath[4]; /* USBH logical drive path */ -extern FATFS USBHFatFS; /* File system object for USBH logical drive */ -extern FIL USBHFile; /* File object for USBH */ - -void MX_FATFS_Init(void); - -/* USER CODE BEGIN Prototypes */ -void usb_ls(); -int usb_write(const void *bytes, size_t size); -/* USER CODE END Prototypes */ -#ifdef __cplusplus -} -#endif -#endif /*__fatfs_H */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ +/** + ****************************************************************************** + * @file fatfs.h + * @brief Header for fatfs applications + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __fatfs_H +#define __fatfs_H +#ifdef __cplusplus + extern "C" { +#endif + +#include "ff.h" +#include "ff_gen_drv.h" +#include "usbh_diskio.h" /* defines USBH_Driver as external */ + +/* USER CODE BEGIN Includes */ + +/* USER CODE END Includes */ + +extern uint8_t retUSBH; /* Return value for USBH */ +extern char USBHPath[4]; /* USBH logical drive path */ +extern FATFS USBHFatFS; /* File system object for USBH logical drive */ +extern FIL USBHFile; /* File object for USBH */ + +void MX_FATFS_Init(void); + +/* USER CODE BEGIN Prototypes */ +void usb_ls(); +int usb_write(const void *bytes, const char *filename, size_t size); +/* USER CODE END Prototypes */ +#ifdef __cplusplus +} +#endif +#endif /*__fatfs_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/Inc/main.h b/Inc/main.h index 93eeb8c..7129b56 100644 --- a/Inc/main.h +++ b/Inc/main.h @@ -1,106 +1,106 @@ -/** - ****************************************************************************** - * @file : main.h - * @brief : Header for main.c file. - * This file contains the common defines of the application. - ****************************************************************************** - * This notice applies to any and all portions of this file - * that are not between comment pairs USER CODE BEGIN and - * USER CODE END. Other portions of this file, whether - * inserted by the user or by software development tools - * are owned by their respective copyright owners. - * - * Copyright (c) 2018 STMicroelectronics International N.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/* Define to prevent recursive inclusion -------------------------------------*/ -#ifndef __MAIN_H__ -#define __MAIN_H__ - -/* Includes ------------------------------------------------------------------*/ - -/* USER CODE BEGIN Includes */ - -/* USER CODE END Includes */ - -/* Private define ------------------------------------------------------------*/ - -#define LED_G_Pin GPIO_PIN_0 -#define LED_G_GPIO_Port GPIOB -#define LED_R_Pin GPIO_PIN_14 -#define LED_R_GPIO_Port GPIOB -#define USB_GPIO_OUT_Pin GPIO_PIN_6 -#define USB_GPIO_OUT_GPIO_Port GPIOG -#define USB_GPIO_IN_Pin GPIO_PIN_7 -#define USB_GPIO_IN_GPIO_Port GPIOG -#define JTAG_TRST_Pin GPIO_PIN_8 -#define JTAG_TRST_GPIO_Port GPIOC -#define JTAG_TDI_Pin GPIO_PIN_9 -#define JTAG_TDI_GPIO_Port GPIOC -#define JTAG_TDO_Pin GPIO_PIN_10 -#define JTAG_TDO_GPIO_Port GPIOC -#define JTAG_TMS_Pin GPIO_PIN_11 -#define JTAG_TMS_GPIO_Port GPIOC -#define JTAG_TCLK_Pin GPIO_PIN_12 -#define JTAG_TCLK_GPIO_Port GPIOC -#define LED_B_Pin GPIO_PIN_7 -#define LED_B_GPIO_Port GPIOB - -/* ########################## Assert Selection ############################## */ -/** - * @brief Uncomment the line below to expanse the "assert_param" macro in the - * HAL drivers code - */ -/* #define USE_FULL_ASSERT 1U */ - -/* USER CODE BEGIN Private defines */ - -/* USER CODE END Private defines */ - -#ifdef __cplusplus - extern "C" { -#endif -void _Error_Handler(char *, int); - -#define Error_Handler() _Error_Handler(__FILE__, __LINE__) -#ifdef __cplusplus -} -#endif - -#endif /* __MAIN_H__ */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ +/** + ****************************************************************************** + * @file : main.h + * @brief : Header for main.c file. + * This file contains the common defines of the application. + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __MAIN_H__ +#define __MAIN_H__ + +/* Includes ------------------------------------------------------------------*/ + +/* USER CODE BEGIN Includes */ + +/* USER CODE END Includes */ + +/* Private define ------------------------------------------------------------*/ + +#define LED_G_Pin GPIO_PIN_0 +#define LED_G_GPIO_Port GPIOB +#define LED_R_Pin GPIO_PIN_14 +#define LED_R_GPIO_Port GPIOB +#define USB_GPIO_OUT_Pin GPIO_PIN_6 +#define USB_GPIO_OUT_GPIO_Port GPIOG +#define USB_GPIO_IN_Pin GPIO_PIN_7 +#define USB_GPIO_IN_GPIO_Port GPIOG +#define JTAG_TRST_Pin GPIO_PIN_8 +#define JTAG_TRST_GPIO_Port GPIOC +#define JTAG_TDI_Pin GPIO_PIN_9 +#define JTAG_TDI_GPIO_Port GPIOC +#define JTAG_TDO_Pin GPIO_PIN_10 +#define JTAG_TDO_GPIO_Port GPIOC +#define JTAG_TMS_Pin GPIO_PIN_11 +#define JTAG_TMS_GPIO_Port GPIOC +#define JTAG_TCLK_Pin GPIO_PIN_12 +#define JTAG_TCLK_GPIO_Port GPIOC +#define LED_B_Pin GPIO_PIN_7 +#define LED_B_GPIO_Port GPIOB + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/* #define USE_FULL_ASSERT 1U */ + +/* USER CODE BEGIN Private defines */ + +/* USER CODE END Private defines */ + +#ifdef __cplusplus + extern "C" { +#endif +void _Error_Handler(char *, int); + +#define Error_Handler() _Error_Handler(__FILE__, __LINE__) +#ifdef __cplusplus +} +#endif + +#endif /* __MAIN_H__ */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/Makefile b/Makefile index 7698eae..3f10426 100644 --- a/Makefile +++ b/Makefile @@ -161,7 +161,9 @@ Src/stm32f4xx_it.c \ Src/stm32f4xx_hal_msp.c \ Src/communication/dbgu.c \ Src/communication/term_io.c \ -Src/communication/wakaama_client/wakaama.c +Src/communication/binary_download.c \ +Src/communication/wakaama_client/wakaama.c \ +Src/communication/yuarel.c # ASM sources ASM_SOURCES = \ diff --git a/Src/communication/binary_download.c b/Src/communication/binary_download.c new file mode 100644 index 0000000..f888def --- /dev/null +++ b/Src/communication/binary_download.c @@ -0,0 +1,129 @@ +#include "lwip/inet.h" +#include "lwip/sockets.h" +#include "communication_config.h" +#include "binary_download.h" +#include "errno.h" +#include "yuarel.h" +#include "FreeRTOS.h" + + + +static void download_error(target_instance_t *targetP, int err, int socket, char *url_str) { + targetP->download_state = DOWNLOAD_ERROR; + targetP->download_error = err; + if(err != SOCKET_ERROR && err != ERROR_PARSING_URL){ + lwip_close(socket); + } + lwm2m_free(url_str); + vTaskDelete(NULL); +} + +int startDownload(target_instance_t *targetP) { + struct yuarel url; + char *url_str = lwm2m_strdup(targetP->firmware_url); + if(yuarel_parse(&url, url_str) != 0) { + printf("Error parsing URL\r\n"); + download_error(targetP, ERROR_PARSING_URL, 0, url_str); + } + int socket; + socket = lwip_socket(AF_INET, SOCK_STREAM, 0); + if (socket < 0 ) { + printf("cannot create socket: %d\r\n", errno); + download_error(targetP, SOCKET_ERROR, socket, url_str); + } + + ip_addr_t *addr = NULL; + if (netconn_gethostbyname(url.host, &addr) != ERR_OK) { + printf("cannot resolve hostname\r\n"); + download_error(targetP, HOST_UNKNOWN_ERROR, socket, url_str); + } + + struct sockaddr_in clientAddressv4; + clientAddressv4.sin_family = AF_INET; + clientAddressv4.sin_port = htons(80); + clientAddressv4.sin_addr.s_addr = addr; + + int result = lwip_connect(socket, (struct sockaddr *) &clientAddressv4, sizeof (struct sockaddr_in)); + if (result < 0) { + printf("cannot connect to server, err: %d\r\n", result); + lwip_close(socket); + download_error(targetP,CONNECTION_ERROR, socket, url_str); + } + + char message[200]; + sprintf(message, "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n Connection: keep-alive\r\n\r\n Keep-Alive: 300\r\n", url.path, url.host); + + if( lwip_send(socket , message , strlen(message) , 0) < 0) { + printf("Send failed\r\n"); + download_error(targetP,REQUEST_ERROR, socket, url_str); + } + + int server_response_length = 300; + char server_reply[server_response_length + 1]; + server_reply[server_response_length] = 0; + long payload_len = 0; + long total_received_len = 0; + + int received_len = lwip_recv(socket, server_reply , sizeof server_reply - 1, 0); + if( received_len < 0 ){ + printf("recv failed\r\n"); + download_error(targetP,RECEIVE_ERROR, socket, url_str); + } + + if(!lwm2m_strncmp(server_reply, "HTTP/1.1 200 OK", 15) == 0){ + long response_code; + char *asd; + asd = server_reply + 9; + if(xatoi(&asd, &response_code) != 1) { + printf("Error reading Server response code\r\n"); + download_error(targetP,UNKNOWN_ERROR, socket, url_str); + } + printf("Server Response status:%ld\r\n", response_code); + download_error(targetP, response_code, socket, url_str); + } + printf("Server responded with 200!\r\n"); + for(int i = 15 ; i < received_len ; i++) { + if(lwm2m_strncmp(server_reply + i, "Content-Length: ", 15) == 0){ + char *asd; + asd = server_reply + i + 15; + if (xatoi(&asd, &payload_len) != 1) { + printf("Error reading Content-Length\r\n"); + download_error(targetP, UNKNOWN_ERROR, socket, url_str); + } + break; + } + } + + while(1){ + int received_len = lwip_recv(socket, server_reply , sizeof server_reply - 1, 0); + + if( received_len < 0 ){ + printf("recv failed\r\n"); + download_error(targetP, RECEIVE_ERROR, socket, url_str); + } + + + targetP->download_progress = 100 * total_received_len / payload_len; + + total_received_len += received_len; + server_reply[received_len] = '\0'; + + if(get_usb_ready()) { + usb_write(server_reply, targetP->binary_filename, received_len); + } else { + download_error(targetP, USB_ERROR, socket, url_str); + } + + if( total_received_len >= payload_len ){ + break; + } + } + + targetP->download_state = DOWNLOAD_COMPLETED; + targetP->download_progress = 100; + targetP->download_error = NO_ERROR; + lwip_close(socket); + lwm2m_free(url_str); + vTaskDelete(); + +} \ No newline at end of file diff --git a/Src/communication/wakaama_client/objects/object_target.c b/Src/communication/wakaama_client/objects/object_target.c index 9f33907..4fa73b1 100644 --- a/Src/communication/wakaama_client/objects/object_target.c +++ b/Src/communication/wakaama_client/objects/object_target.c @@ -9,13 +9,15 @@ * Supported Multiple * Name | ID | Operations | Instances | Mandatory | Type | Range | Units | Description | * -----------------|----|------------|-----------|-----------|---------|-------|-------|-------------------------------| - * target_type | 1 | R/W | No | Yes | | | | type of the programmable board| - * firmware_url | 2 | R/W | No | Yes | string | | | url to the binary | - * download_state | 3 | R | No | Yes | integer | 0-255 | | state of the download | - * firmware_version| 4 | R | No | Yes | integer | | | timestamp of the latest binary| - * flash_target | 5 | E | No | Yes | | | | programms the target | - * flash_state | 6 | R | No | Yes | integer | 0-100 | % | progress of flashing the board| - * reset_target | 7 | E | No | Yes | | | | resets the target | + * target_type | 1 | R/W | No | Yes | | | | type of the programmable board| + * firmware_url | 2 | R/W | No | Yes | string | | | url to the binary | + * download_state | 3 | R | No | Yes | integer | 0-255 | | state of the download | + * firmware_version | 4 | R | No | Yes | integer | | | timestamp of the latest binary| + * flash_target | 5 | E | No | Yes | | | | programms the target | + * flash_state | 6 | R | No | Yes | integer | 0-100 | % | progress of flashing the board| + * reset_target | 7 | E | No | Yes | | | | resets the target | + * download_error | 8 | R | No | Yes | integer | | | download error | + * download_progres | 9 | R | No | Yes | integer | 0-100 | % | progress of binary download | * */ @@ -27,6 +29,7 @@ #include #include #include "object_target.h" +#include "binary_download.h" static void prv_output_buffer(uint8_t * buffer, int length) @@ -65,27 +68,6 @@ static void prv_output_buffer(uint8_t * buffer, } } -/* - * Multiple instance objects can use userdata to store data that will be shared between the different instances. - * The lwm2m_object_t object structure - which represent every object of the liblwm2m as seen in the single instance - * object - contain a chained list called instanceList with the object specific structure target_instance_t: - */ -typedef struct _target_instance_ -{ - /* - * The first two are mandatories and represent the pointer to the next instance and the ID of this one. The rest - * is the instance scope user data (uint8_t target in this case) - */ - struct _target_instance_ * next; // matches lwm2m_list_t::next - uint16_t shortID; // matches lwm2m_list_t::id - - uint8_t flash_state; - uint32_t * target_type; - char * firmware_url; - uint8_t download_state; - uint32_t firmware_version; -} target_instance_t; - static uint8_t target_read(uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, @@ -99,7 +81,7 @@ static uint8_t target_read(uint16_t instanceId, if (*numDataP == 0) { - *dataArrayP = lwm2m_data_new(4); + *dataArrayP = lwm2m_data_new(7); if (*dataArrayP == NULL) return COAP_500_INTERNAL_SERVER_ERROR; *numDataP = 4; (*dataArrayP)[0].id = 1; @@ -107,6 +89,8 @@ static uint8_t target_read(uint16_t instanceId, (*dataArrayP)[2].id = 3; (*dataArrayP)[3].id = 4; (*dataArrayP)[4].id = 6; + (*dataArrayP)[5].id = 8; + (*dataArrayP)[6].id = 9; } for (i = 0 ; i < *numDataP ; i++) @@ -132,6 +116,12 @@ static uint8_t target_read(uint16_t instanceId, break; case 7: return COAP_405_METHOD_NOT_ALLOWED; + case 8: + lwm2m_data_encode_int(targetP->download_error, *dataArrayP + i); + break; + case 9: + lwm2m_data_encode_int(targetP->download_progress, *dataArrayP + i); + break; default: return COAP_404_NOT_FOUND; } @@ -150,9 +140,9 @@ static uint8_t target_discover(uint16_t instanceId, // is the server asking for the full object ? if (*numDataP == 0) { - *dataArrayP = lwm2m_data_new(6); + *dataArrayP = lwm2m_data_new(9); if (*dataArrayP == NULL) return COAP_500_INTERNAL_SERVER_ERROR; - *numDataP = 4; + *numDataP = 8; (*dataArrayP)[0].id = 1; (*dataArrayP)[1].id = 2; (*dataArrayP)[2].id = 3; @@ -160,6 +150,8 @@ static uint8_t target_discover(uint16_t instanceId, (*dataArrayP)[4].id = 5; (*dataArrayP)[5].id = 6; (*dataArrayP)[6].id = 7; + (*dataArrayP)[7].id = 8; + (*dataArrayP)[8].id = 9; } else { @@ -174,6 +166,8 @@ static uint8_t target_discover(uint16_t instanceId, case 5: case 6: case 7: + case 8: + case 9: break; default: return COAP_404_NOT_FOUND; @@ -213,16 +207,23 @@ static uint8_t target_write(uint16_t instanceId, break;*/ case 2: { + if (targetP->download_state == DOWNLOAD_IN_PROGRESS) { + return COAP_412_PRECONDITION_FAILED; + } if (!dataArray[i].type == LWM2M_TYPE_STRING && !dataArray[i].type == LWM2M_TYPE_OPAQUE) { return COAP_400_BAD_REQUEST; } if (targetP->firmware_url != NULL) { lwm2m_free(targetP->firmware_url); } + dataArray[i].value.asBuffer.buffer[dataArray[i].value.asBuffer.length] = '\0'; targetP->firmware_url = lwm2m_strdup((char*)dataArray[i].value.asBuffer.buffer); targetP->firmware_version = lwm2m_gettime(); targetP->download_state = DOWNLOAD_IN_PROGRESS; - // TODO: Start Downloading and add callback to set downloadCOMPLETED + sprintf(targetP->binary_filename, "%d", targetP->firmware_version); + targetP->download_progress = 0; + + xTaskCreate(startDownload, NULL, 2000, targetP, 2, NULL); } break; case 3: @@ -235,6 +236,10 @@ static uint8_t target_write(uint16_t instanceId, return COAP_405_METHOD_NOT_ALLOWED; case 7: return COAP_405_METHOD_NOT_ALLOWED; + case 8: + return COAP_405_METHOD_NOT_ALLOWED; + case 9: + return COAP_405_METHOD_NOT_ALLOWED; default: return COAP_404_NOT_FOUND; } @@ -270,6 +275,7 @@ static uint8_t target_create(uint16_t instanceId, memset(targetP, 0, sizeof(target_instance_t)); targetP->shortID = instanceId; + targetP->binary_filename = lwm2m_malloc(25); objectP->instanceList = LWM2M_LIST_ADD(objectP->instanceList, targetP); result = target_write(instanceId, numData, dataArray, objectP); @@ -335,6 +341,8 @@ static uint8_t target_exec(uint16_t instanceId, fprintf(stdout, "-----------------\r\n\r\n"); // TODO: RESET TARGET return COAP_204_CHANGED; + case 8: + return COAP_405_METHOD_NOT_ALLOWED; default: return COAP_404_NOT_FOUND; } @@ -364,6 +372,9 @@ lwm2m_object_t * get_target_object(void) targetP->download_state = NO_DOWNLOAD_DATA; targetP->firmware_version = 0; targetP->flash_state = 0; + targetP->download_progress = 0; + targetP->download_error = NO_ERROR; + targetP->binary_filename = lwm2m_malloc(25); targetObj->instanceList = LWM2M_LIST_ADD(targetObj->instanceList, targetP); /* diff --git a/Src/communication/yuarel.c b/Src/communication/yuarel.c new file mode 100644 index 0000000..981dde9 --- /dev/null +++ b/Src/communication/yuarel.c @@ -0,0 +1,294 @@ +/** + * Copyright (C) 2016,2017 Jack Engqvist Johansson + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include +#include +#include +#include "yuarel.h" + +/** + * Parse a non null terminated string into an integer. + * + * str: the string containing the number. + * len: Number of characters to parse. + */ +static inline int +natoi(const char *str, size_t len) +{ + int i, r = 0; + for (i = 0; i < len; i++) { + r *= 10; + r += str[i] - '0'; + } + + return r; +} + +/** + * Check if a URL is relative (no scheme and hostname). + * + * url: the string containing the URL to check. + * + * Returns 1 if relative, otherwise 0. + */ +static inline int +is_relative(const char *url) +{ + return (*url == '/') ? 1 : 0; +} + +/** + * Parse the scheme of a URL by inserting a null terminator after the scheme. + * + * str: the string containing the URL to parse. Will be modified. + * + * Returns a pointer to the hostname on success, otherwise NULL. + */ +static inline char * +parse_scheme(char *str) +{ + char *s; + + /* If not found or first in string, return error */ + s = strchr(str, ':'); + if (s == NULL || s == str) { + return str; + } + + /* If not followed by two slashes, return error */ + if (s[1] == '\0' || s[1] != '/' || s[2] == '\0' || s[2] != '/') { + return NULL; + } + + *s = '\0'; // Replace ':' with NULL + + return s + 3; +} + +/** + * Find a character in a string, replace it with '\0' and return the next + * character in the string. + * + * str: the string to search in. + * find: the character to search for. + * + * Returns a pointer to the character after the one to search for. If not + * found, NULL is returned. + */ +static inline char * +find_and_terminate(char *str, char find) +{ + str = strchr(str, find); + if (NULL == str) { + return NULL; + } + + *str = '\0'; + return str + 1; +} + +/* Yes, the following functions could be implemented as preprocessor macros + instead of inline functions, but I think that this approach will be more + clean in this case. */ +static inline char * +find_fragment(char *str) +{ + return find_and_terminate(str, '#'); +} + +static inline char * +find_query(char *str) +{ + return find_and_terminate(str, '?'); +} + +static inline char * +find_path(char *str) +{ + return find_and_terminate(str, '/'); +} + +/** + * Parse a URL string to a struct. + * + * url: pointer to the struct where to store the parsed URL parts. + * u: the string containing the URL to be parsed. + * + * Returns 0 on success, otherwise -1. + */ +int +yuarel_parse(struct yuarel *url, char *u) +{ + if (NULL == url || NULL == u) { + return -1; + } + + memset(url, 0, sizeof (struct yuarel)); + + /* (Fragment) */ + url->fragment = find_fragment(u); + + /* (Query) */ + url->query = find_query(u); + + /* Relative URL? Parse scheme and hostname */ + if (!is_relative(u)) { + /* Scheme */ + url->scheme = u; + u = parse_scheme(u); + if (u == NULL) { + return -1; + } + + /* Host */ + if ('\0' == *u) { + return -1; + } + url->host = u; + + /* (Path) */ + url->path = find_path(u); + + /* (Credentials) */ + u = strchr(url->host, '@'); + if (NULL != u) { + /* Missing credentials? */ + if (u == url->host) { + return -1; + } + + url->username = url->host; + url->host = u + 1; + *u = '\0'; + + u = strchr(url->username, ':'); + if (NULL == u) { + return -1; + } + + url->password = u + 1; + *u = '\0'; + } + + /* Missing hostname? */ + if ('\0' == *url->host) { + return -1; + } + + /* (Port) */ + u = strchr(url->host, ':'); + if (NULL != u && (NULL == url->path || u < url->path)) { + *(u++) = '\0'; + if ('\0' == *u) { + return -1; + } + + if (url->path) { + url->port = natoi(u, url->path - u - 1); + } else { + url->port = atoi(u); + } + } + + /* Missing hostname? */ + if ('\0' == *url->host) { + return -1; + } + } else { + /* (Path) */ + url->path = find_path(u); + } + + return 0; +} + +/** + * Split a path into several strings. + * + * No data is copied, the slashed are used as null terminators and then + * pointers to each path part will be stored in **parts. Double slashes will be + * treated as one. + * + * path: the path to split. + * parts: a pointer to an array of (char *) where to store the result. + * max_parts: max number of parts to parse. + */ +int +yuarel_split_path(char *path, char **parts, int max_parts) +{ + int i = 0; + + if (NULL == path || '\0' == *path) { + return -1; + } + + do { + /* Forward to after slashes */ + while (*path == '/') path++; + + if ('\0' == *path) { + break; + } + + parts[i++] = path; + + path = strchr(path, '/'); + if (NULL == path) { + break; + } + + *(path++) = '\0'; + } while (i < max_parts); + + return i; +} + +int +yuarel_parse_query(char *query, char delimiter, struct yuarel_param *params, int max_params) +{ + int i = 0; + + if (NULL == query || '\0' == *query) { + return -1; + } + + params[i++].key = query; + while (i < max_params && NULL != (query = strchr(query, delimiter))) { + *query = '\0'; + params[i].key = ++query; + params[i].val = NULL; + + /* Go back and split previous param */ + if (i > 0) { + if ((params[i - 1].val = strchr(params[i - 1].key, '=')) != NULL) { + *(params[i - 1].val)++ = '\0'; + } + } + i++; + } + + /* Go back and split last param */ + if ((params[i - 1].val = strchr(params[i - 1].key, '=')) != NULL) { + *(params[i - 1].val)++ = '\0'; + } + + return i; +} diff --git a/Src/fatfs.c b/Src/fatfs.c index 3704266..a389bef 100644 --- a/Src/fatfs.c +++ b/Src/fatfs.c @@ -1,155 +1,157 @@ -/** - ****************************************************************************** - * @file fatfs.c - * @brief Code for fatfs applications - ****************************************************************************** - * This notice applies to any and all portions of this file - * that are not between comment pairs USER CODE BEGIN and - * USER CODE END. Other portions of this file, whether - * inserted by the user or by software development tools - * are owned by their respective copyright owners. - * - * Copyright (c) 2018 STMicroelectronics International N.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -#include "fatfs.h" - -uint8_t retUSBH; /* Return value for USBH */ -char USBHPath[4]; /* USBH logical drive path */ -FATFS USBHFatFS; /* File system object for USBH logical drive */ -FIL USBHFile; /* File object for USBH */ - -/* USER CODE BEGIN Variables */ - -/* USER CODE END Variables */ - -void MX_FATFS_Init(void) -{ - /*## FatFS: Link the USBH driver ###########################*/ - retUSBH = FATFS_LinkDriver(&USBH_Driver, USBHPath); - - /* USER CODE BEGIN Init */ - /* additional user code for init */ - /* USER CODE END Init */ -} - -/** - * @brief Gets Time from RTC - * @param None - * @retval Time in DWORD - */ -DWORD get_fattime(void) -{ - /* USER CODE BEGIN get_fattime */ - return 0; - /* USER CODE END get_fattime */ -} - -/* USER CODE BEGIN Application */ -FRESULT scan_files ( - char* path /* Start node to be scanned (***also used as work area***) */ -) -{ - printf("Scan path \"%s\"\n", path); - FRESULT res; - DIR dir; - int i; - static FILINFO fno; - - res = f_opendir(&dir, path); /* Open the directory */ - if (res == FR_OK) { - for (;;) { - res = f_readdir(&dir, &fno); /* Read a directory item */ - if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */ - if (fno.fattrib & AM_DIR) { /* It is a directory */ - /*i = strlen(path); - sprintf(&path[i], "/%s", fno.fname); - res = scan_files(path); /* Enter the directory */ - /*if (res != FR_OK) break; - path[i] = 0;*/ - } else { /* It is a file. */ - printf("%s%s\n\r", path, fno.fname); - } - } - f_closedir(&dir); - } - return res; -} - -void usb_ls() { - printf("Start ls\n"); - if (f_mount(&USBHFatFS, "", 1) == FR_OK) { - scan_files(USBHPath); - f_mount(NULL, "", 0); - } else { - f_mount(NULL, "", 0); - printf("Error mounting USB\n"); - } -} - -#define CHECK_FRESULT(result, msg, er) \ - if ((result) != FR_OK) { \ - printf("%s, error code 0x%x\n", (msg), (result)); \ - return (er); \ - } - -int usb_write(const void *bytes, size_t size) { - FRESULT result; - - - result = f_mount(&USBHFatFS, "", 1); - if (result == FR_OK) { - FIL fp; - result = f_open(&fp, "0:/temp", FA_WRITE | FA_CREATE_ALWAYS); - CHECK_FRESULT(result, "open failed", -1); - - uint written_bytes; - result = f_write(&fp, bytes, size, &written_bytes); - CHECK_FRESULT(result, "write failed", -1); - - result = f_close(&fp); - CHECK_FRESULT(result, "close failed", -1); - - f_mount(NULL, "", 0); - } else { - CHECK_FRESULT(result, "mount failed", -1); - } - -} -/* USER CODE END Application */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ +/** + ****************************************************************************** + * @file fatfs.c + * @brief Code for fatfs applications + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +#include "fatfs.h" + +uint8_t retUSBH; /* Return value for USBH */ +char USBHPath[4]; /* USBH logical drive path */ +FATFS USBHFatFS; /* File system object for USBH logical drive */ +FIL USBHFile; /* File object for USBH */ + +/* USER CODE BEGIN Variables */ + +/* USER CODE END Variables */ + +void MX_FATFS_Init(void) +{ + /*## FatFS: Link the USBH driver ###########################*/ + retUSBH = FATFS_LinkDriver(&USBH_Driver, USBHPath); + + /* USER CODE BEGIN Init */ + /* additional user code for init */ + /* USER CODE END Init */ +} + +/** + * @brief Gets Time from RTC + * @param None + * @retval Time in DWORD + */ +DWORD get_fattime(void) +{ + /* USER CODE BEGIN get_fattime */ + return 0; + /* USER CODE END get_fattime */ +} + +/* USER CODE BEGIN Application */ +FRESULT scan_files ( + char* path /* Start node to be scanned (***also used as work area***) */ +) +{ + printf("Scan path \"%s\"\n", path); + FRESULT res; + DIR dir; + int i; + static FILINFO fno; + + res = f_opendir(&dir, path); /* Open the directory */ + if (res == FR_OK) { + for (;;) { + res = f_readdir(&dir, &fno); /* Read a directory item */ + if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */ + if (fno.fattrib & AM_DIR) { /* It is a directory */ + /*i = strlen(path); + sprintf(&path[i], "/%s", fno.fname); + res = scan_files(path); /* Enter the directory */ + /*if (res != FR_OK) break; + path[i] = 0;*/ + } else { /* It is a file. */ + printf("%s%s\n\r", path, fno.fname); + } + } + f_closedir(&dir); + } + return res; +} + +void usb_ls() { + printf("Start ls\n"); + if (f_mount(&USBHFatFS, "", 1) == FR_OK) { + scan_files(USBHPath); + f_mount(NULL, "", 0); + } else { + f_mount(NULL, "", 0); + printf("Error mounting USB\n"); + } +} + +#define CHECK_FRESULT(result, msg, er) \ + if ((result) != FR_OK) { \ + printf("%s, error code 0x%x\n", (msg), (result)); \ + return (er); \ + } + +int usb_write(const void *bytes, const char *filename, size_t size) { + FRESULT result; + + result = f_mount(&USBHFatFS, "", 1); + if (result == FR_OK) { + FIL fp; + char *path = pvPortMalloc(sizeof filename + 4); + sprintf(path, "0:/%s", filename); + result = f_open(&fp, path, FA_WRITE | FA_OPEN_APPEND); + vPortFree(path); + CHECK_FRESULT(result, "open failed", -1); + + uint written_bytes; + result = f_write(&fp, bytes, size, &written_bytes); + CHECK_FRESULT(result, "write failed", -1); + + result = f_close(&fp); + CHECK_FRESULT(result, "close failed", -1); + + f_mount(NULL, "", 0); + } else { + CHECK_FRESULT(result, "mount failed", -1); + } + +} +/* USER CODE END Application */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/Src/main.c b/Src/main.c index 3cae9cb..0f0bb61 100644 --- a/Src/main.c +++ b/Src/main.c @@ -1,451 +1,453 @@ - -/** - ****************************************************************************** - * @file : main.c - * @brief : Main program body - ****************************************************************************** - * This notice applies to any and all portions of this file - * that are not between comment pairs USER CODE BEGIN and - * USER CODE END. Other portions of this file, whether - * inserted by the user or by software development tools - * are owned by their respective copyright owners. - * - * Copyright (c) 2018 STMicroelectronics International N.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted, provided that the following conditions are met: - * - * 1. Redistribution of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of other - * contributors to this software may be used to endorse or promote products - * derived from this software without specific written permission. - * 4. This software, including modifications and/or derivative works of this - * software, must execute solely and exclusively on microcontroller or - * microprocessor devices manufactured by or for STMicroelectronics. - * 5. Redistribution and use of this software other than as permitted under - * this license is void and will automatically terminate your rights under - * this license. - * - * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY - * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT - * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ -/* Includes ------------------------------------------------------------------*/ -#include "main.h" -#include "stm32f4xx_hal.h" -#include "cmsis_os.h" -#include "fatfs.h" -#include "lwip.h" -#include "usb_host.h" - -/* USER CODE BEGIN Includes */ -#include "debug_leds.h" -#include "wakaama.h" -/* USER CODE END Includes */ - -/* Private variables ---------------------------------------------------------*/ -UART_HandleTypeDef huart3; - -osThreadId defaultTaskHandle; - -/* USER CODE BEGIN PV */ -/* Private variables ---------------------------------------------------------*/ - -/* USER CODE END PV */ - -/* Private function prototypes -----------------------------------------------*/ -void SystemClock_Config(void); -static void MX_GPIO_Init(void); -static void MX_USART3_UART_Init(void); -void StartDefaultTask(void const * argument); - -/* USER CODE BEGIN PFP */ -/* Private function prototypes -----------------------------------------------*/ - -/* USER CODE END PFP */ - -/* USER CODE BEGIN 0 */ - -/* USER CODE END 0 */ - -/** - * @brief The application entry point. - * - * @retval None - */ -int main(void) -{ - /* USER CODE BEGIN 1 */ - - /* USER CODE END 1 */ - - /* MCU Configuration----------------------------------------------------------*/ - - /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ - HAL_Init(); - - /* USER CODE BEGIN Init */ - - /* USER CODE END Init */ - - /* Configure the system clock */ - SystemClock_Config(); - - /* USER CODE BEGIN SysInit */ - - /* USER CODE END SysInit */ - - /* Initialize all configured peripherals */ - MX_GPIO_Init(); - MX_USART3_UART_Init(); - /* USER CODE BEGIN 2 */ - - /* USER CODE END 2 */ - - /* USER CODE BEGIN RTOS_MUTEX */ - /* add mutexes, ... */ - /* USER CODE END RTOS_MUTEX */ - - /* USER CODE BEGIN RTOS_SEMAPHORES */ - /* add semaphores, ... */ - /* USER CODE END RTOS_SEMAPHORES */ - - /* USER CODE BEGIN RTOS_TIMERS */ - /* start timers, add new ones, ... */ - /* USER CODE END RTOS_TIMERS */ - - /* Create the thread(s) */ - /* definition and creation of defaultTask */ - osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 1024); - defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL); - - /* USER CODE BEGIN RTOS_THREADS */ - /* add threads, ... */ - /* USER CODE END RTOS_THREADS */ - - /* USER CODE BEGIN RTOS_QUEUES */ - /* add queues, ... */ - /* USER CODE END RTOS_QUEUES */ - - - /* Start scheduler */ - osKernelStart(); - - /* We should never get here as control is now taken by the scheduler */ - - /* Infinite loop */ - /* USER CODE BEGIN WHILE */ - while (1) - { - - /* USER CODE END WHILE */ - - /* USER CODE BEGIN 3 */ - - } - /* USER CODE END 3 */ - -} - -/** - * @brief System Clock Configuration - * @retval None - */ -void SystemClock_Config(void) -{ - - RCC_OscInitTypeDef RCC_OscInitStruct; - RCC_ClkInitTypeDef RCC_ClkInitStruct; - - /**Configure the main internal regulator output voltage - */ - __HAL_RCC_PWR_CLK_ENABLE(); - - __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3); - - /**Initializes the CPU, AHB and APB busses clocks - */ - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; - RCC_OscInitStruct.HSEState = RCC_HSE_ON; - RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; - RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; - RCC_OscInitStruct.PLL.PLLM = 4; - RCC_OscInitStruct.PLL.PLLN = 120; - RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; - RCC_OscInitStruct.PLL.PLLQ = 5; - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) - { - _Error_Handler(__FILE__, __LINE__); - } - - /**Initializes the CPU, AHB and APB busses clocks - */ - RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK - |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; - RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; - RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; - RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; - - if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) - { - _Error_Handler(__FILE__, __LINE__); - } - - /**Configure the Systick interrupt time - */ - HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); - - /**Configure the Systick - */ - HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); - - /* SysTick_IRQn interrupt configuration */ - HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0); -} - -/* USART3 init function */ -static void MX_USART3_UART_Init(void) -{ - - huart3.Instance = USART3; - huart3.Init.BaudRate = 115200; - huart3.Init.WordLength = UART_WORDLENGTH_8B; - huart3.Init.StopBits = UART_STOPBITS_1; - huart3.Init.Parity = UART_PARITY_NONE; - huart3.Init.Mode = UART_MODE_TX_RX; - huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE; - huart3.Init.OverSampling = UART_OVERSAMPLING_16; - if (HAL_UART_Init(&huart3) != HAL_OK) - { - _Error_Handler(__FILE__, __LINE__); - } - -} - -/** Configure pins as - * Analog - * Input - * Output - * EVENT_OUT - * EXTI -*/ -static void MX_GPIO_Init(void) -{ - - GPIO_InitTypeDef GPIO_InitStruct; - - /* GPIO Ports Clock Enable */ - __HAL_RCC_GPIOH_CLK_ENABLE(); - __HAL_RCC_GPIOC_CLK_ENABLE(); - __HAL_RCC_GPIOA_CLK_ENABLE(); - __HAL_RCC_GPIOB_CLK_ENABLE(); - __HAL_RCC_GPIOD_CLK_ENABLE(); - __HAL_RCC_GPIOG_CLK_ENABLE(); - - /*Configure GPIO pin Output Level */ - HAL_GPIO_WritePin(GPIOB, LED_G_Pin|LED_R_Pin|LED_B_Pin, GPIO_PIN_RESET); - - /*Configure GPIO pin Output Level */ - HAL_GPIO_WritePin(USB_GPIO_OUT_GPIO_Port, USB_GPIO_OUT_Pin, GPIO_PIN_RESET); - - /*Configure GPIO pin Output Level */ - HAL_GPIO_WritePin(GPIOC, JTAG_TRST_Pin|JTAG_TDO_Pin|JTAG_TMS_Pin|JTAG_TCLK_Pin, GPIO_PIN_RESET); - - /*Configure GPIO pins : LED_G_Pin LED_R_Pin LED_B_Pin */ - GPIO_InitStruct.Pin = LED_G_Pin|LED_R_Pin|LED_B_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; - GPIO_InitStruct.Pull = GPIO_NOPULL; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; - HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); - - /*Configure GPIO pin : USB_GPIO_OUT_Pin */ - GPIO_InitStruct.Pin = USB_GPIO_OUT_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; - GPIO_InitStruct.Pull = GPIO_NOPULL; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; - HAL_GPIO_Init(USB_GPIO_OUT_GPIO_Port, &GPIO_InitStruct); - - /*Configure GPIO pin : USB_GPIO_IN_Pin */ - GPIO_InitStruct.Pin = USB_GPIO_IN_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_INPUT; - GPIO_InitStruct.Pull = GPIO_NOPULL; - HAL_GPIO_Init(USB_GPIO_IN_GPIO_Port, &GPIO_InitStruct); - - /*Configure GPIO pins : JTAG_TRST_Pin JTAG_TDO_Pin JTAG_TMS_Pin JTAG_TCLK_Pin */ - GPIO_InitStruct.Pin = JTAG_TRST_Pin|JTAG_TDO_Pin|JTAG_TMS_Pin|JTAG_TCLK_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; - GPIO_InitStruct.Pull = GPIO_PULLUP; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; - HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); - - /*Configure GPIO pin : JTAG_TDI_Pin */ - GPIO_InitStruct.Pin = JTAG_TDI_Pin; - GPIO_InitStruct.Mode = GPIO_MODE_INPUT; - GPIO_InitStruct.Pull = GPIO_PULLUP; - HAL_GPIO_Init(JTAG_TDI_GPIO_Port, &GPIO_InitStruct); - -} - -/* USER CODE BEGIN 4 */ - -int __io_putchar(int ch) -{ - uint8_t c[1]; - c[1] = '\0'; - c[0] = ch & 0x00FF; - if(c[0] == '\n') { - __io_putchar('\r'); - } - HAL_UART_Transmit(&huart3, &*c, 1, 10); - return ch; -} - -/* USER CODE END 4 */ - -/* USER CODE BEGIN Header_StartDefaultTask */ -/** - * @brief Function implementing the defaultTask thread. - * @param argument: Not used - * @retval None - */ -/* USER CODE END Header_StartDefaultTask */ -void StartDefaultTask(void const * argument) -{ - /* init code for LWIP */ - MX_LWIP_Init(); - - /* init code for USB_HOST */ - MX_USB_HOST_Init(); - - /* init code for FATFS */ - MX_FATFS_Init(); - - /* USER CODE BEGIN 5 */ - printf("\n\n\n-----------------------START-------------------------\n\n"); - osDelay(3000); // wait for DHCP initialisation - -// Initialize Wakaama LWM2M Client - lwip_socket_init(); - int socket = createUDPSocket(LOCAL_PORT, AF_INET); - if(socket != -1){ - printf("Start wakaama task\r\n"); - int res = xTaskCreate(taskWakaama, "wakaama", 3000, (void *) socket, 2, NULL); - if (res != pdPASS) { - printf("\r\nerror creating taskWakaama: %d\n", res); - } - } else { - printf("Error creating socket: %d", socket); - } - - int x = 0; - osDelay(500); - HAL_GPIO_WritePin(USB_GPIO_OUT_GPIO_Port, USB_GPIO_OUT_Pin, GPIO_PIN_SET); - BlinkBlue(); - char usrInput[2]; - /* Infinite loop */ - debug_init(&huart3); - for(;;) - { - osDelay(5); - printf("in loop %d\n\r", x); - x++; - printf("$ "); - fflush(stdout); - get_line(usrInput, 2); - printf("%s\n", usrInput); - switch(usrInput[0]) { - case 'l': - if (get_usb_ready()) { - usb_ls(); - } - break; - case 'w': - if (get_usb_ready()) { - usb_write("asd", 3); - } - break; - } - } - /* USER CODE END 5 */ -} - -/** - * @brief Period elapsed callback in non blocking mode - * @note This function is called when TIM6 interrupt took place, inside - * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment - * a global variable "uwTick" used as application time base. - * @param htim : TIM handle - * @retval None - */ -void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) -{ - /* USER CODE BEGIN Callback 0 */ - - /* USER CODE END Callback 0 */ - if (htim->Instance == TIM6) { - HAL_IncTick(); - } - /* USER CODE BEGIN Callback 1 */ - - /* USER CODE END Callback 1 */ -} - -/** - * @brief This function is executed in case of error occurrence. - * @param file: The file name as string. - * @param line: The line in file as a number. - * @retval None - */ -void _Error_Handler(char *file, int line) -{ - /* USER CODE BEGIN Error_Handler_Debug */ - /* User can add his own implementation to report the HAL error return state */ - while(1) - { - } - /* USER CODE END Error_Handler_Debug */ -} - -#ifdef USE_FULL_ASSERT -/** - * @brief Reports the name of the source file and the source line number - * where the assert_param error has occurred. - * @param file: pointer to the source file name - * @param line: assert_param error line source number - * @retval None - */ -void assert_failed(uint8_t* file, uint32_t line) -{ - /* USER CODE BEGIN 6 */ - /* User can add his own implementation to report the file name and line number, - tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ - /* USER CODE END 6 */ -} -#endif /* USE_FULL_ASSERT */ - -/** - * @} - */ - -/** - * @} - */ - -/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + +/** + ****************************************************************************** + * @file : main.c + * @brief : Main program body + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, + * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "main.h" +#include "stm32f4xx_hal.h" +#include "cmsis_os.h" +#include "fatfs.h" +#include "lwip.h" +#include "usb_host.h" + +/* USER CODE BEGIN Includes */ +#include "debug_leds.h" +#include "wakaama.h" +#include "binary_download.h" +/* USER CODE END Includes */ + +/* Private variables ---------------------------------------------------------*/ +UART_HandleTypeDef huart3; + +osThreadId defaultTaskHandle; + +/* USER CODE BEGIN PV */ +/* Private variables ---------------------------------------------------------*/ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +void SystemClock_Config(void); +static void MX_GPIO_Init(void); +static void MX_USART3_UART_Init(void); +void StartDefaultTask(void const * argument); + +/* USER CODE BEGIN PFP */ +/* Private function prototypes -----------------------------------------------*/ + +/* USER CODE END PFP */ + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/** + * @brief The application entry point. + * + * @retval None + */ +int main(void) +{ + /* USER CODE BEGIN 1 */ + + /* USER CODE END 1 */ + + /* MCU Configuration----------------------------------------------------------*/ + + /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ + HAL_Init(); + + /* USER CODE BEGIN Init */ + + /* USER CODE END Init */ + + /* Configure the system clock */ + SystemClock_Config(); + + /* USER CODE BEGIN SysInit */ + + /* USER CODE END SysInit */ + + /* Initialize all configured peripherals */ + MX_GPIO_Init(); + MX_USART3_UART_Init(); + /* USER CODE BEGIN 2 */ + + /* USER CODE END 2 */ + + /* USER CODE BEGIN RTOS_MUTEX */ + /* add mutexes, ... */ + /* USER CODE END RTOS_MUTEX */ + + /* USER CODE BEGIN RTOS_SEMAPHORES */ + /* add semaphores, ... */ + /* USER CODE END RTOS_SEMAPHORES */ + + /* USER CODE BEGIN RTOS_TIMERS */ + /* start timers, add new ones, ... */ + /* USER CODE END RTOS_TIMERS */ + + /* Create the thread(s) */ + /* definition and creation of defaultTask */ + osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 1024); + defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL); + + /* USER CODE BEGIN RTOS_THREADS */ + /* add threads, ... */ + /* USER CODE END RTOS_THREADS */ + + /* USER CODE BEGIN RTOS_QUEUES */ + /* add queues, ... */ + /* USER CODE END RTOS_QUEUES */ + + + /* Start scheduler */ + osKernelStart(); + + /* We should never get here as control is now taken by the scheduler */ + + /* Infinite loop */ + /* USER CODE BEGIN WHILE */ + while (1) + { + + /* USER CODE END WHILE */ + + /* USER CODE BEGIN 3 */ + + } + /* USER CODE END 3 */ + +} + +/** + * @brief System Clock Configuration + * @retval None + */ +void SystemClock_Config(void) +{ + + RCC_OscInitTypeDef RCC_OscInitStruct; + RCC_ClkInitTypeDef RCC_ClkInitStruct; + + /**Configure the main internal regulator output voltage + */ + __HAL_RCC_PWR_CLK_ENABLE(); + + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3); + + /**Initializes the CPU, AHB and APB busses clocks + */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PLLM = 4; + RCC_OscInitStruct.PLL.PLLN = 120; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; + RCC_OscInitStruct.PLL.PLLQ = 5; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + _Error_Handler(__FILE__, __LINE__); + } + + /**Initializes the CPU, AHB and APB busses clocks + */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK + |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; + + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) + { + _Error_Handler(__FILE__, __LINE__); + } + + /**Configure the Systick interrupt time + */ + HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); + + /**Configure the Systick + */ + HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); + + /* SysTick_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0); +} + +/* USART3 init function */ +static void MX_USART3_UART_Init(void) +{ + + huart3.Instance = USART3; + huart3.Init.BaudRate = 115200; + huart3.Init.WordLength = UART_WORDLENGTH_8B; + huart3.Init.StopBits = UART_STOPBITS_1; + huart3.Init.Parity = UART_PARITY_NONE; + huart3.Init.Mode = UART_MODE_TX_RX; + huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE; + huart3.Init.OverSampling = UART_OVERSAMPLING_16; + if (HAL_UART_Init(&huart3) != HAL_OK) + { + _Error_Handler(__FILE__, __LINE__); + } + +} + +/** Configure pins as + * Analog + * Input + * Output + * EVENT_OUT + * EXTI +*/ +static void MX_GPIO_Init(void) +{ + + GPIO_InitTypeDef GPIO_InitStruct; + + /* GPIO Ports Clock Enable */ + __HAL_RCC_GPIOH_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOD_CLK_ENABLE(); + __HAL_RCC_GPIOG_CLK_ENABLE(); + + /*Configure GPIO pin Output Level */ + HAL_GPIO_WritePin(GPIOB, LED_G_Pin|LED_R_Pin|LED_B_Pin, GPIO_PIN_RESET); + + /*Configure GPIO pin Output Level */ + HAL_GPIO_WritePin(USB_GPIO_OUT_GPIO_Port, USB_GPIO_OUT_Pin, GPIO_PIN_RESET); + + /*Configure GPIO pin Output Level */ + HAL_GPIO_WritePin(GPIOC, JTAG_TRST_Pin|JTAG_TDO_Pin|JTAG_TMS_Pin|JTAG_TCLK_Pin, GPIO_PIN_RESET); + + /*Configure GPIO pins : LED_G_Pin LED_R_Pin LED_B_Pin */ + GPIO_InitStruct.Pin = LED_G_Pin|LED_R_Pin|LED_B_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /*Configure GPIO pin : USB_GPIO_OUT_Pin */ + GPIO_InitStruct.Pin = USB_GPIO_OUT_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + HAL_GPIO_Init(USB_GPIO_OUT_GPIO_Port, &GPIO_InitStruct); + + /*Configure GPIO pin : USB_GPIO_IN_Pin */ + GPIO_InitStruct.Pin = USB_GPIO_IN_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(USB_GPIO_IN_GPIO_Port, &GPIO_InitStruct); + + /*Configure GPIO pins : JTAG_TRST_Pin JTAG_TDO_Pin JTAG_TMS_Pin JTAG_TCLK_Pin */ + GPIO_InitStruct.Pin = JTAG_TRST_Pin|JTAG_TDO_Pin|JTAG_TMS_Pin|JTAG_TCLK_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /*Configure GPIO pin : JTAG_TDI_Pin */ + GPIO_InitStruct.Pin = JTAG_TDI_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_PULLUP; + HAL_GPIO_Init(JTAG_TDI_GPIO_Port, &GPIO_InitStruct); + +} + +/* USER CODE BEGIN 4 */ + +int __io_putchar(int ch) +{ + uint8_t c[1]; + c[1] = '\0'; + c[0] = ch & 0x00FF; + if(c[0] == '\n') { + __io_putchar('\r'); + } + HAL_UART_Transmit(&huart3, &*c, 1, 10); + return ch; +} + +/* USER CODE END 4 */ + +/* USER CODE BEGIN Header_StartDefaultTask */ +/** + * @brief Function implementing the defaultTask thread. + * @param argument: Not used + * @retval None + */ +/* USER CODE END Header_StartDefaultTask */ +void StartDefaultTask(void const * argument) +{ + /* init code for LWIP */ + MX_LWIP_Init(); + + /* init code for USB_HOST */ + MX_USB_HOST_Init(); + + /* init code for FATFS */ + MX_FATFS_Init(); + + /* USER CODE BEGIN 5 */ + printf("\n\n\n-----------------------START-------------------------\n\n"); + osDelay(3000); // wait for DHCP initialisation + +// Initialize Wakaama LWM2M Client + lwip_socket_init(); + + int socket = createUDPSocket(LOCAL_PORT, AF_INET); + if(socket != -1){ + printf("Start wakaama task\r\n"); + int res = xTaskCreate(taskWakaama, "wakaama", 3000, (void *) socket, 2, NULL); + if (res != pdPASS) { + printf("\r\nerror creating taskWakaama: %d\n", res); + } + } else { + printf("Error creating socket: %d", socket); + } + + int x = 0; + osDelay(500); + HAL_GPIO_WritePin(USB_GPIO_OUT_GPIO_Port, USB_GPIO_OUT_Pin, GPIO_PIN_SET); + BlinkBlue(); + char usrInput[2]; + /* Infinite loop */ + debug_init(&huart3); + for(;;) + { + osDelay(5); + printf("in loop %d\n\r", x); + x++; + printf("$ "); + fflush(stdout); + get_line(usrInput, 2); + printf("%s\n", usrInput); + switch(usrInput[0]) { + case 'l': + if (get_usb_ready()) { + usb_ls(); + } + break; + case 'w': + if (get_usb_ready()) { + usb_write("asd", "temp", 3); + } + break; + } + } + /* USER CODE END 5 */ +} + +/** + * @brief Period elapsed callback in non blocking mode + * @note This function is called when TIM6 interrupt took place, inside + * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment + * a global variable "uwTick" used as application time base. + * @param htim : TIM handle + * @retval None + */ +void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) +{ + /* USER CODE BEGIN Callback 0 */ + + /* USER CODE END Callback 0 */ + if (htim->Instance == TIM6) { + HAL_IncTick(); + } + /* USER CODE BEGIN Callback 1 */ + + /* USER CODE END Callback 1 */ +} + +/** + * @brief This function is executed in case of error occurrence. + * @param file: The file name as string. + * @param line: The line in file as a number. + * @retval None + */ +void _Error_Handler(char *file, int line) +{ + /* USER CODE BEGIN Error_Handler_Debug */ + /* User can add his own implementation to report the HAL error return state */ + while(1) + { + } + /* USER CODE END Error_Handler_Debug */ +} + +#ifdef USE_FULL_ASSERT +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t* file, uint32_t line) +{ + /* USER CODE BEGIN 6 */ + /* User can add his own implementation to report the file name and line number, + tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + /* USER CODE END 6 */ +} +#endif /* USE_FULL_ASSERT */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/config/communication_config.h b/config/communication_config.h index ba2dca9..39150ca 100644 --- a/config/communication_config.h +++ b/config/communication_config.h @@ -5,6 +5,7 @@ #define DEVICE_NAME "Remote Programmer" #define SERVER_URI "coap://192.168.2.1:5683" +#define SERVER_IP "192.168.2.1" #define LWM2M_SERVER_PORT 5683 #define LOCAL_PORT 5683 #define MAX_PACKET_SIZE 1024