From 31ea039d17ef7d4502ec376882d84ca48287bc46 Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Fri, 2 Jun 2023 14:59:00 +0200 Subject: [PATCH 01/24] Add dynamic/static option for transport init (#361) * Add dynamic/static option for transport init Signed-off-by: Cervenka Dusan * Add forgotten getRpmsgEndpoint function Signed-off-by: Cervenka Dusan * Update erpc_setup_rpmsg_lite_remote.cpp - typo correction in erpc_transport_rpmsg_lite_remote_init --------- Signed-off-by: Cervenka Dusan Co-authored-by: Michal Princ --- erpc_c/setup/erpc_mbf_setup.h | 42 ++- erpc_c/setup/erpc_setup_dspi_master.cpp | 43 ++- erpc_c/setup/erpc_setup_dspi_slave.cpp | 43 ++- erpc_c/setup/erpc_setup_i2c_slave.cpp | 42 ++- erpc_c/setup/erpc_setup_mbf_dynamic.cpp | 37 ++- erpc_c/setup/erpc_setup_mbf_rpmsg.cpp | 38 ++- erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp | 38 ++- erpc_c/setup/erpc_setup_mbf_static.cpp | 37 ++- erpc_c/setup/erpc_setup_mu.cpp | 43 ++- erpc_c/setup/erpc_setup_rpmsg_linux.cpp | 53 ++- erpc_c/setup/erpc_setup_rpmsg_lite_master.cpp | 43 ++- erpc_c/setup/erpc_setup_rpmsg_lite_remote.cpp | 44 ++- .../erpc_setup_rpmsg_lite_rtos_master.cpp | 43 ++- .../erpc_setup_rpmsg_lite_rtos_remote.cpp | 44 ++- .../erpc_setup_rpmsg_tty_rtos_remote.cpp | 43 ++- erpc_c/setup/erpc_setup_serial.cpp | 42 ++- erpc_c/setup/erpc_setup_spi_master.cpp | 43 ++- erpc_c/setup/erpc_setup_spi_slave.cpp | 43 ++- erpc_c/setup/erpc_setup_spidev_master.cpp | 43 ++- erpc_c/setup/erpc_setup_tcp.cpp | 50 ++- erpc_c/setup/erpc_setup_uart_cmsis.cpp | 42 ++- erpc_c/setup/erpc_setup_usb_cdc.cpp | 49 ++- erpc_c/setup/erpc_transport_setup.h | 303 ++++++++++++------ .../transports/erpc_rpmsg_linux_transport.hpp | 7 + 24 files changed, 1052 insertions(+), 203 deletions(-) diff --git a/erpc_c/setup/erpc_mbf_setup.h b/erpc_c/setup/erpc_mbf_setup.h index 6cd79b3c..f760914a 100644 --- a/erpc_c/setup/erpc_mbf_setup.h +++ b/erpc_c/setup/erpc_mbf_setup.h @@ -37,14 +37,30 @@ extern "C" { //@{ /*! - * @brief Create MessageBuffer factory which is using static allocated buffers. + * @brief Create MessageBuffer factory which is using dynamic allocated buffers. */ -erpc_mbf_t erpc_mbf_static_init(void); +erpc_mbf_t erpc_mbf_dynamic_init(void); /*! - * @brief Create MessageBuffer factory which is using dynamic allocated buffers. + * @brief Deinit MessageBuffer factory. + * + * @param[in] mbf MessageBuffer factory which was initialized in init function. */ -erpc_mbf_t erpc_mbf_dynamic_init(void); +void erpc_mbf_dynamic_deinit(erpc_mbf_t mbf); + +/*! + * @brief Create MessageBuffer factory which is using RPMSG LITE TTY buffers. + * + * Has to be used with RPMSG lite TTY transport. + */ +erpc_mbf_t erpc_mbf_rpmsg_tty_init(erpc_transport_t transport); + +/*! + * @brief Deinit MessageBuffer factory. + * + * @param[in] mbf MessageBuffer factory which was initialized in init function. + */ +void erpc_mbf_rpmsg_tty_deinit(erpc_mbf_t mbf); /*! * @brief Create MessageBuffer factory which is using RPMSG LITE zero copy buffers. @@ -54,11 +70,23 @@ erpc_mbf_t erpc_mbf_dynamic_init(void); erpc_mbf_t erpc_mbf_rpmsg_init(erpc_transport_t transport); /*! - * @brief Create MessageBuffer factory which is using RPMSG LITE TTY buffers. + * @brief Deinit MessageBuffer factory. * - * Has to be used with RPMSG lite TTY transport. + * @param[in] mbf MessageBuffer factory which was initialized in init function. */ -erpc_mbf_t erpc_mbf_rpmsg_tty_init(erpc_transport_t transport); +void erpc_mbf_rpmsg_deinit(erpc_mbf_t mbf); + +/*! + * @brief Create MessageBuffer factory which is using static allocated buffers. + */ +erpc_mbf_t erpc_mbf_static_init(void); + +/*! + * @brief Deinit MessageBuffer factory. + * + * @param[in] mbf MessageBuffer factory which was initialized in init function. + */ +void erpc_mbf_static_deinit(erpc_mbf_t mbf); //@} diff --git a/erpc_c/setup/erpc_setup_dspi_master.cpp b/erpc_c/setup/erpc_setup_dspi_master.cpp index 8361b15d..b83f7af7 100644 --- a/erpc_c/setup/erpc_setup_dspi_master.cpp +++ b/erpc_c/setup/erpc_setup_dspi_master.cpp @@ -17,7 +17,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(DspiMasterTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(DspiMasterTransport, s_dspiTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -25,7 +25,42 @@ ERPC_MANUALLY_CONSTRUCTED(DspiMasterTransport, s_transport); erpc_transport_t erpc_transport_dspi_master_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz) { - s_transport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); - (void)s_transport->init(); - return reinterpret_cast(s_transport.get()); + DspiMasterTransport *dspiTransport; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_dspiTransport.isUsed()) + { + dspiTransport = NULL; + } + else + { + s_dspiTransport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); + dspiTransport = s_dspiTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + dspiTransport = new DspiMasterTransport(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); +#else +#error "Unknown eRPC allocation policy!" +#endif + + if (dspiTransport != NULL) + { + (void)dspiTransport->init(); + } + + return reinterpret_cast(dspiTransport); +} + +void erpc_transport_dspi_master_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_dspiTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + DspiMasterTransport *dspiTransport = reinterpret_cast(transport); + + delete dspiTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_dspi_slave.cpp b/erpc_c/setup/erpc_setup_dspi_slave.cpp index 016d1a72..02a165a1 100644 --- a/erpc_c/setup/erpc_setup_dspi_slave.cpp +++ b/erpc_c/setup/erpc_setup_dspi_slave.cpp @@ -17,7 +17,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(DspiSlaveTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(DspiSlaveTransport, s_dspiTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -25,7 +25,42 @@ ERPC_MANUALLY_CONSTRUCTED(DspiSlaveTransport, s_transport); erpc_transport_t erpc_transport_dspi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz) { - s_transport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); - (void)s_transport->init(); - return reinterpret_cast(s_transport.get()); + DspiSlaveTransport *dspiTransport; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_dspiTransport.isUsed()) + { + dspiTransport = NULL; + } + else + { + s_dspiTransport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); + dspiTransport = s_dspiTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + dspiTransport = new DspiSlaveTransport(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); +#else +#error "Unknown eRPC allocation policy!" +#endif + + if (dspiTransport != NULL) + { + (void)dspiTransport->init(); + } + + return reinterpret_cast(dspiTransport); +} + +void erpc_transport_dspi_slave_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_dspiTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + DspiSlaveTransport *dspiTransport = reinterpret_cast(transport); + + delete dspiTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_i2c_slave.cpp b/erpc_c/setup/erpc_setup_i2c_slave.cpp index 1181639f..9e3678b7 100644 --- a/erpc_c/setup/erpc_setup_i2c_slave.cpp +++ b/erpc_c/setup/erpc_setup_i2c_slave.cpp @@ -16,7 +16,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -static ManuallyConstructed s_transport; +ERPC_MANUALLY_CONSTRUCTED_STATIC(I2cSlaveTransport, s_i2cTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -24,7 +24,41 @@ static ManuallyConstructed s_transport; erpc_transport_t erpc_transport_i2c_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz) { - s_transport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); - (void)s_transport->init(); - return reinterpret_cast(s_transport.get()); + I2cSlaveTransport *i2cTransport; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_i2cTransport.isUsed()) + { + i2cTransport = NULL; + } + else + { + s_i2cTransport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); + i2cTransport = s_i2cTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + i2cTransport = new I2cSlaveTransport(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); +#else +#error "Unknown eRPC allocation policy!" +#endif + + if (i2cTransport != NULL) + { + (void)i2cTransport->init(); + } + + return reinterpret_cast(i2cTransport); +} +void erpc_transport_i2c_slave_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_i2cTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + I2cSlaveTransport *i2cTransport = reinterpret_cast(transport); + + delete i2cTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_mbf_dynamic.cpp b/erpc_c/setup/erpc_setup_mbf_dynamic.cpp index d9273c26..7ff6366e 100644 --- a/erpc_c/setup/erpc_setup_mbf_dynamic.cpp +++ b/erpc_c/setup/erpc_setup_mbf_dynamic.cpp @@ -47,10 +47,41 @@ class DynamicMessageBufferFactory : public MessageBufferFactory // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(DynamicMessageBufferFactory, s_msgFactory); +ERPC_MANUALLY_CONSTRUCTED_STATIC(DynamicMessageBufferFactory, s_msgFactory); erpc_mbf_t erpc_mbf_dynamic_init(void) { - s_msgFactory.construct(); - return reinterpret_cast(s_msgFactory.get()); + DynamicMessageBufferFactory *msgFactory; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_msgFactory.isUsed()) + { + msgFactory = NULL; + } + else + { + s_msgFactory.construct(); + msgFactory = s_msgFactory.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + msgFactory = new DynamicMessageBufferFactory(); +#else +#error "Unknown eRPC allocation policy!" +#endif + + return reinterpret_cast(msgFactory); +} + +void erpc_mbf_dynamic_deinit(erpc_mbf_t mbf) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)mbf; + s_msgFactory.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(mbf != NULL); + + DynamicMessageBufferFactory *msgFactory = reinterpret_cast(mbf); + + delete msgFactory; +#endif } diff --git a/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp b/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp index 2c44746a..ccf03eea 100644 --- a/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp +++ b/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp @@ -105,10 +105,42 @@ class RPMsgMessageBufferFactory : public MessageBufferFactory // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(RPMsgMessageBufferFactory, s_msgFactory); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgMessageBufferFactory, s_msgFactory); erpc_mbf_t erpc_mbf_rpmsg_init(erpc_transport_t transport) { - s_msgFactory.construct(reinterpret_cast(transport)->get_rpmsg_lite_instance()); - return reinterpret_cast(s_msgFactory.get()); + RPMsgMessageBufferFactory *msgFactory; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_msgFactory.isUsed()) + { + msgFactory = NULL; + } + else + { + s_msgFactory.construct(reinterpret_cast(transport)->get_rpmsg_lite_instance()); + msgFactory = s_msgFactory.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + msgFactory = + new RPMsgMessageBufferFactory(reinterpret_cast(transport)->get_rpmsg_lite_instance()); +#else +#error "Unknown eRPC allocation policy!" +#endif + + return reinterpret_cast(msgFactory); +} + +void erpc_mbf_rpmsg_deinit(erpc_mbf_t mbf) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)mbf; + s_msgFactory.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(mbf != NULL); + + RPMsgMessageBufferFactory *msgFactory = reinterpret_cast(mbf); + + delete msgFactory; +#endif } diff --git a/erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp b/erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp index 6c043b3f..d6a6cd3a 100644 --- a/erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp +++ b/erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp @@ -110,10 +110,42 @@ class RPMsgTTYMessageBufferFactory : public MessageBufferFactory // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(RPMsgTTYMessageBufferFactory, s_msgFactory); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgTTYMessageBufferFactory, s_msgFactory); erpc_mbf_t erpc_mbf_rpmsg_tty_init(erpc_transport_t transport) { - s_msgFactory.construct(reinterpret_cast(transport)->get_rpmsg_lite_instance()); - return reinterpret_cast(s_msgFactory.get()); + RPMsgTTYMessageBufferFactory *msgFactory; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_msgFactory.isUsed()) + { + msgFactory = NULL; + } + else + { + s_msgFactory.construct(reinterpret_cast(transport)->get_rpmsg_lite_instance()); + msgFactory = s_msgFactory.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + msgFactory = + new RPMsgTTYMessageBufferFactory(reinterpret_cast(transport)->get_rpmsg_lite_instance()); +#else +#error "Unknown eRPC allocation policy!" +#endif + + return reinterpret_cast(msgFactory); +} + +void erpc_mbf_rpmsg_tty_deinit(erpc_mbf_t mbf) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)mbf; + s_msgFactory.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(mbf != NULL); + + RPMsgTTYMessageBufferFactory *msgFactory = reinterpret_cast(mbf); + + delete msgFactory; +#endif } diff --git a/erpc_c/setup/erpc_setup_mbf_static.cpp b/erpc_c/setup/erpc_setup_mbf_static.cpp index 6f5abbd1..c4293ae5 100644 --- a/erpc_c/setup/erpc_setup_mbf_static.cpp +++ b/erpc_c/setup/erpc_setup_mbf_static.cpp @@ -124,10 +124,41 @@ class StaticMessageBufferFactory : public MessageBufferFactory // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(StaticMessageBufferFactory, s_msgFactory); +ERPC_MANUALLY_CONSTRUCTED_STATIC(StaticMessageBufferFactory, s_msgFactory); erpc_mbf_t erpc_mbf_static_init(void) { - s_msgFactory.construct(); - return reinterpret_cast(s_msgFactory.get()); + StaticMessageBufferFactory *msgFactory; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_msgFactory.isUsed()) + { + msgFactory = NULL; + } + else + { + s_msgFactory.construct(); + msgFactory = s_msgFactory.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + msgFactory = new StaticMessageBufferFactory(); +#else +#error "Unknown eRPC allocation policy!" +#endif + + return reinterpret_cast(msgFactory); +} + +void erpc_mbf_static_deinit(erpc_mbf_t mbf) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)mbf; + s_msgFactory.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(mbf != NULL); + + StaticMessageBufferFactory *msgFactory = reinterpret_cast(mbf); + + delete msgFactory; +#endif } diff --git a/erpc_c/setup/erpc_setup_mu.cpp b/erpc_c/setup/erpc_setup_mu.cpp index 8b5b1b5f..4875643f 100644 --- a/erpc_c/setup/erpc_setup_mu.cpp +++ b/erpc_c/setup/erpc_setup_mu.cpp @@ -16,7 +16,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(MUTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(MUTransport, s_muTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -24,7 +24,42 @@ ERPC_MANUALLY_CONSTRUCTED(MUTransport, s_transport); erpc_transport_t erpc_transport_mu_init(void *baseAddr) { - s_transport.construct(); - (void)s_transport->init(reinterpret_cast(baseAddr)); - return reinterpret_cast(s_transport.get()); + MUTransport *muTransport; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_muTransport.isUsed()) + { + muTransport = NULL; + } + else + { + s_muTransport.construct(); + muTransport = s_muTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + muTransport = new MUTransport(); +#else +#error "Unknown eRPC allocation policy!" +#endif + + if (muTransport != NULL) + { + (void)muTransport->init(reinterpret_cast(baseAddr)); + } + + return reinterpret_cast(muTransport); +} + +void erpc_transport_mu_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_muTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + MUTransport *muTransport = reinterpret_cast(transport); + + delete muTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_rpmsg_linux.cpp b/erpc_c/setup/erpc_setup_rpmsg_linux.cpp index 2fc6cdd5..1ce70c48 100644 --- a/erpc_c/setup/erpc_setup_rpmsg_linux.cpp +++ b/erpc_c/setup/erpc_setup_rpmsg_linux.cpp @@ -13,8 +13,8 @@ using namespace erpc; -ERPC_MANUALLY_CONSTRUCTED(RPMsgLinuxTransport, s_transport); -ERPC_MANUALLY_CONSTRUCTED(RPMsgEndpoint, s_endpoint); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgLinuxTransport, s_rpmsgTransport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgEndpoint, s_endpoint); erpc_transport_t erpc_transport_rpmsg_linux_init(int16_t local_addr, int8_t type, int16_t remote_addr) { @@ -22,6 +22,7 @@ erpc_transport_t erpc_transport_rpmsg_linux_init(int16_t local_addr, int8_t type int16_t _local_addr; int8_t _type; int16_t _remote_addr; + RPMsgLinuxTransport *rpmsgTransport; if (local_addr == -1) { @@ -50,23 +51,57 @@ erpc_transport_t erpc_transport_rpmsg_linux_init(int16_t local_addr, int8_t type _remote_addr = remote_addr; } - s_endpoint.construct(_local_addr, _type, _remote_addr); - s_transport.construct(s_endpoint.get(), _remote_addr); - - if (s_transport->init() == kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_endpoint.isUsed() || s_rpmsgTransport.isUsed()) + { + rpmsgTransport = NULL; + } + else + { + s_endpoint.construct(_local_addr, _type, _remote_addr); + s_rpmsgTransport.construct(s_endpoint.get(), _remote_addr); + rpmsgTransport = s_rpmsgTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + RPMsgEndpoint *endpoint = new RPMsgEndpoint(_local_addr, _type, _remote_addr); + if (endpoint == NULL) { - transport = reinterpret_cast(s_transport.get()); + rpmsgTransport = NULL; } else { - transport = NULL; + rpmsgTransport = new RPMsgLinuxTransport(endpoint, _remote_addr); + } +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(rpmsgTransport); + + if (rpmsgTransport != NULL) + { + if (rpmsgTransport->init() != kErpcStatus_Success) + { + erpc_transport_rpmsg_linux_deinit(transport); + transport = NULL; + } } return transport; } -void erpc_transport_rpmsg_linux_deinit(void) +void erpc_transport_rpmsg_linux_deinit(erpc_transport_t transport) { +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; s_endpoint.destroy(); s_transport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + RPMsgLinuxTransport *rpmsgTransport = reinterpret_cast(transport); + + delete rpmsgTransport->getRpmsgEndpoint(); + delete rpmsgTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_rpmsg_lite_master.cpp b/erpc_c/setup/erpc_setup_rpmsg_lite_master.cpp index 42632d72..75275726 100644 --- a/erpc_c/setup/erpc_setup_rpmsg_lite_master.cpp +++ b/erpc_c/setup/erpc_setup_rpmsg_lite_master.cpp @@ -33,7 +33,7 @@ char rpmsg_lite_base[SH_MEM_TOTAL_SIZE] __attribute__((section(".noinit.$rpmsg_s #error "RPMsg: Please provide your definition of rpmsg_lite_base[]!" #endif -ERPC_MANUALLY_CONSTRUCTED(RPMsgTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgTransport, s_rpmsgTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -42,16 +42,49 @@ ERPC_MANUALLY_CONSTRUCTED(RPMsgTransport, s_transport); erpc_transport_t erpc_transport_rpmsg_lite_master_init(uint32_t src_addr, uint32_t dst_addr, uint32_t rpmsg_link_id) { erpc_transport_t transport; + RPMsgTransport *rpmsgTransport; - s_transport.construct(); - if (s_transport->init(src_addr, dst_addr, rpmsg_lite_base, SH_MEM_TOTAL_SIZE, rpmsg_link_id) == kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_rpmsgTransport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + rpmsgTransport = NULL; } else { - transport = NULL; + s_rpmsgTransport.construct(); + rpmsgTransport = s_rpmsgTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + rpmsgTransport = new RPMsgTransport(); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(rpmsgTransport); + + if (rpmsgTransport != NULL) + { + if (rpmsgTransport->init(src_addr, dst_addr, rpmsg_lite_base, SH_MEM_TOTAL_SIZE, rpmsg_link_id) != + kErpcStatus_Success) + { + erpc_transport_rpmsg_lite_master_deinit(transport); + transport = NULL; + } } return transport; } + +void erpc_transport_rpmsg_lite_master_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_rpmsgTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + RPMsgTransport *rpmsgTransport = reinterpret_cast(transport); + + delete rpmsgTransport; +#endif +} diff --git a/erpc_c/setup/erpc_setup_rpmsg_lite_remote.cpp b/erpc_c/setup/erpc_setup_rpmsg_lite_remote.cpp index d6a07d9a..b5ec2e0a 100644 --- a/erpc_c/setup/erpc_setup_rpmsg_lite_remote.cpp +++ b/erpc_c/setup/erpc_setup_rpmsg_lite_remote.cpp @@ -18,7 +18,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(RPMsgTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgTransport, s_rpmsgTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -29,17 +29,49 @@ erpc_transport_t erpc_transport_rpmsg_lite_remote_init(uint32_t src_addr, uint32 char *nameservice_name) { erpc_transport_t transport; + RPMsgTransport *rpmsgTransport; - s_transport.construct(); - if (s_transport->init(src_addr, dst_addr, start_address, rpmsg_link_id, ready, nameservice_name) == - kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_rpmsgTransport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + rpmsgTransport = NULL; } else { - transport = NULL; + s_rpmsgTransport.construct(); + rpmsgTransport = s_rpmsgTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + rpmsgTransport = new RPMsgTransport(); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(rpmsgTransport); + + if (rpmsgTransport != NULL) + { + if (rpmsgTransport->init(src_addr, dst_addr, start_address, rpmsg_link_id, ready, nameservice_name) != + kErpcStatus_Success) + { + erpc_transport_rpmsg_lite_remote_deinit(transport); + transport = NULL; + } } return transport; } + +void erpc_transport_rpmsg_lite_remote_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_rpmsgTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + RPMsgTransport *rpmsgTransport = reinterpret_cast(transport); + + delete rpmsgTransport; +#endif +} diff --git a/erpc_c/setup/erpc_setup_rpmsg_lite_rtos_master.cpp b/erpc_c/setup/erpc_setup_rpmsg_lite_rtos_master.cpp index 89695d91..e38f1b8a 100644 --- a/erpc_c/setup/erpc_setup_rpmsg_lite_rtos_master.cpp +++ b/erpc_c/setup/erpc_setup_rpmsg_lite_rtos_master.cpp @@ -32,7 +32,7 @@ char rpmsg_lite_base[SH_MEM_TOTAL_SIZE] __attribute__((section(".noinit.$rpmsg_s #error "RPMsg: Please provide your definition of rpmsg_lite_base[]!" #endif -ERPC_MANUALLY_CONSTRUCTED(RPMsgRTOSTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgRTOSTransport, s_rpmsgTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -42,16 +42,49 @@ erpc_transport_t erpc_transport_rpmsg_lite_rtos_master_init(uint32_t src_addr, u uint32_t rpmsg_link_id) { erpc_transport_t transport; + RPMsgRTOSTransport *rpmsgTransport; - s_transport.construct(); - if (s_transport->init(src_addr, dst_addr, rpmsg_lite_base, SH_MEM_TOTAL_SIZE, rpmsg_link_id) == kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_rpmsgTransport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + rpmsgTransport = NULL; } else { - transport = NULL; + s_rpmsgTransport.construct(); + rpmsgTransport = s_rpmsgTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + rpmsgTransport = new RPMsgRTOSTransport(); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(rpmsgTransport); + + if (rpmsgTransport != NULL) + { + if (rpmsgTransport->init(src_addr, dst_addr, rpmsg_lite_base, SH_MEM_TOTAL_SIZE, rpmsg_link_id) != + kErpcStatus_Success) + { + erpc_transport_rpmsg_lite_rtos_master_deinit(transport); + transport = NULL; + } } return transport; } + +void erpc_transport_rpmsg_lite_rtos_master_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_rpmsgTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + RPMsgRTOSTransport *rpmsgTransport = reinterpret_cast(transport); + + delete rpmsgTransport; +#endif +} diff --git a/erpc_c/setup/erpc_setup_rpmsg_lite_rtos_remote.cpp b/erpc_c/setup/erpc_setup_rpmsg_lite_rtos_remote.cpp index 6ea4fefd..544d50f5 100644 --- a/erpc_c/setup/erpc_setup_rpmsg_lite_rtos_remote.cpp +++ b/erpc_c/setup/erpc_setup_rpmsg_lite_rtos_remote.cpp @@ -18,7 +18,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(RPMsgRTOSTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgRTOSTransport, s_rpmsgTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -29,17 +29,49 @@ erpc_transport_t erpc_transport_rpmsg_lite_rtos_remote_init(uint32_t src_addr, u char *nameservice_name) { erpc_transport_t transport; + RPMsgRTOSTransport *rpmsgTransport; - s_transport.construct(); - if (s_transport->init(src_addr, dst_addr, start_address, rpmsg_link_id, ready, nameservice_name) == - kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_rpmsgTransport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + rpmsgTransport = NULL; } else { - transport = NULL; + s_rpmsgTransport.construct(); + rpmsgTransport = s_rpmsgTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + rpmsgTransport = new RPMsgRTOSTransport(); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(rpmsgTransport); + + if (rpmsgTransport != NULL) + { + if (rpmsgTransport->init(src_addr, dst_addr, start_address, rpmsg_link_id, ready, nameservice_name) != + kErpcStatus_Success) + { + erpc_transport_rpmsg_lite_rtos_remote_deinit(transport); + transport = NULL; + } } return transport; } + +void erpc_transport_rpmsg_lite_rtos_remote_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_rpmsgTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + RPMsgRTOSTransport *rpmsgTransport = reinterpret_cast(transport); + + delete rpmsgTransport; +#endif +} diff --git a/erpc_c/setup/erpc_setup_rpmsg_tty_rtos_remote.cpp b/erpc_c/setup/erpc_setup_rpmsg_tty_rtos_remote.cpp index 60214efd..f4ffbb1b 100644 --- a/erpc_c/setup/erpc_setup_rpmsg_tty_rtos_remote.cpp +++ b/erpc_c/setup/erpc_setup_rpmsg_tty_rtos_remote.cpp @@ -18,7 +18,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(RPMsgTTYRTOSTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgTTYRTOSTransport, s_rpmsgTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -29,22 +29,49 @@ erpc_transport_t erpc_transport_rpmsg_lite_tty_rtos_remote_init(uint32_t src_add rpmsg_ready_cb ready, char *nameservice_name) { erpc_transport_t transport; + RPMsgTTYRTOSTransport *rpmsgTransport; - s_transport.construct(); - if (s_transport->init(src_addr, dst_addr, start_address, rpmsg_link_id, ready, nameservice_name) == - kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_rpmsgTransport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + rpmsgTransport = NULL; } else { - transport = NULL; + s_rpmsgTransport.construct(); + rpmsgTransport = s_rpmsgTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + rpmsgTransport = new RPMsgTTYRTOSTransport(); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(rpmsgTransport); + + if (rpmsgTransport != NULL) + { + if (rpmsgTransport->init(src_addr, dst_addr, start_address, rpmsg_link_id, ready, nameservice_name) != + kErpcStatus_Success) + { + erpc_transport_rpmsg_lite_tty_rtos_remote_deinit(transport); + transport = NULL; + } } return transport; } -void erpc_transport_rpmsg_lite_tty_rtos_deinit(void) +void erpc_transport_rpmsg_lite_tty_rtos_remote_deinit(erpc_transport_t transport) { - s_transport.destroy(); +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_rpmsgTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + RPMsgTTYRTOSTransport *rpmsgTransport = reinterpret_cast(transport); + + delete rpmsgTransport +#endif } diff --git a/erpc_c/setup/erpc_setup_serial.cpp b/erpc_c/setup/erpc_setup_serial.cpp index ff0690d6..5c62385b 100644 --- a/erpc_c/setup/erpc_setup_serial.cpp +++ b/erpc_c/setup/erpc_setup_serial.cpp @@ -18,7 +18,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(SerialTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(SerialTransport, s_serialTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -27,18 +27,50 @@ ERPC_MANUALLY_CONSTRUCTED(SerialTransport, s_transport); erpc_transport_t erpc_transport_serial_init(const char *portName, long baudRate) { erpc_transport_t transport; + SerialTransport *serialTransport; const uint8_t vtime = 0; const uint8_t vmin = 1; - s_transport.construct(portName, baudRate); - if (s_transport->init(vtime, vmin) == kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_serialTransport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + serialTransport = NULL; } else { - transport = NULL; + s_serialTransport.construct(portName, baudRate); + serialTransport = s_serialTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + serialTransport = new SerialTransport(portName, baudRate); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(serialTransport); + + if (serialTransport != NULL) + { + if (serialTransport->init(vtime, vmin) != kErpcStatus_Success) + { + erpc_transport_serial_deinit(transport); + transport = NULL; + } } return transport; } + +void erpc_transport_serial_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_serialTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + SerialTransport *serialTransport = reinterpret_cast(transport); + + delete serialTransport; +#endif +} diff --git a/erpc_c/setup/erpc_setup_spi_master.cpp b/erpc_c/setup/erpc_setup_spi_master.cpp index eeaa4723..7dcbfd0c 100644 --- a/erpc_c/setup/erpc_setup_spi_master.cpp +++ b/erpc_c/setup/erpc_setup_spi_master.cpp @@ -17,7 +17,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(SpiMasterTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(SpiMasterTransport, s_spiTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -25,7 +25,42 @@ ERPC_MANUALLY_CONSTRUCTED(SpiMasterTransport, s_transport); erpc_transport_t erpc_transport_spi_master_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz) { - s_transport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); - (void)s_transport->init(); - return reinterpret_cast(s_transport.get()); + SpiMasterTransport *spiTransport; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_spiTransport.isUsed()) + { + spiTransport = NULL; + } + else + { + s_spiTransport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); + spiTransport = s_spiTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + spiTransport = new SpiMasterTransport(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); +#else +#error "Unknown eRPC allocation policy!" +#endif + + if (spiTransport != NULL) + { + (void)spiTransport->init(); + } + + return reinterpret_cast(spiTransport); +} + +void erpc_transport_spi_master_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_spiTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + SpiMasterTransport *spiTransport = reinterpret_cast(transport); + + delete spiTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_spi_slave.cpp b/erpc_c/setup/erpc_setup_spi_slave.cpp index 8d569b3f..ba8daf8e 100644 --- a/erpc_c/setup/erpc_setup_spi_slave.cpp +++ b/erpc_c/setup/erpc_setup_spi_slave.cpp @@ -17,7 +17,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(SpiSlaveTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(SpiSlaveTransport, s_spiTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -25,7 +25,42 @@ ERPC_MANUALLY_CONSTRUCTED(SpiSlaveTransport, s_transport); erpc_transport_t erpc_transport_spi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz) { - s_transport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); - (void)s_transport->init(); - return reinterpret_cast(s_transport.get()); + SpiSlaveTransport *spiTransport; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_spiTransport.isUsed()) + { + spiTransport = NULL; + } + else + { + s_spiTransport.construct(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); + spiTransport = s_spiTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + spiTransport = new SpiSlaveTransport(reinterpret_cast(baseAddr), baudRate, srcClock_Hz); +#else +#error "Unknown eRPC allocation policy!" +#endif + + if (spiTransport != NULL) + { + (void)spiTransport->init(); + } + + return reinterpret_cast(spiTransport); +} + +void erpc_transport_spi_slave_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_spiTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + SpiSlaveTransport *spiTransport = reinterpret_cast(transport); + + delete spiTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_spidev_master.cpp b/erpc_c/setup/erpc_setup_spidev_master.cpp index bd1eef4e..92b94f79 100644 --- a/erpc_c/setup/erpc_setup_spidev_master.cpp +++ b/erpc_c/setup/erpc_setup_spidev_master.cpp @@ -16,7 +16,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(SpidevMasterTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(SpidevMasterTransport, s_spidevTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -24,7 +24,42 @@ ERPC_MANUALLY_CONSTRUCTED(SpidevMasterTransport, s_transport); erpc_transport_t erpc_transport_spidev_master_init(const char *spidev, uint32_t speed_Hz) { - s_transport.construct(spidev, speed_Hz); - (void)s_transport->init(); - return reinterpret_cast(s_transport.get()); + SpidevMasterTransport *spidevTransport; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_spidevTransport.isUsed()) + { + spidevTransport = NULL; + } + else + { + s_spidevTransport.construct(spidev, speed_Hz); + spidevTransport = s_spidevTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + spidevTransport = new SpidevMasterTransport(spidev, speed_Hz); +#else +#error "Unknown eRPC allocation policy!" +#endif + + if (spidevTransport != NULL) + { + (void)spidevTransport->init(); + } + + return reinterpret_cast(spidevTransport); +} + +void erpc_transport_spidev_master_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_spidevTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + SpidevMasterTransport *spidevTransport = reinterpret_cast(transport); + + delete spidevTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_tcp.cpp b/erpc_c/setup/erpc_setup_tcp.cpp index ebf21209..793354b6 100644 --- a/erpc_c/setup/erpc_setup_tcp.cpp +++ b/erpc_c/setup/erpc_setup_tcp.cpp @@ -17,7 +17,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(TCPTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(TCPTransport, s_tcpTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -26,21 +26,57 @@ ERPC_MANUALLY_CONSTRUCTED(TCPTransport, s_transport); erpc_transport_t erpc_transport_tcp_init(const char *host, uint16_t port, bool isServer) { erpc_transport_t transport; + TCPTransport *tcpTransport; - s_transport.construct(host, port, isServer); - if (kErpcStatus_Success == s_transport->open()) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_tcpTransport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + tcpTransport = NULL; } else { - transport = NULL; + s_tcpTransport.construct(host, port, isServer); + tcpTransport = s_tcpTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + tcpTransport = new TCPTransport(host, port, isServer); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(tcpTransport); + + if (tcpTransport != NULL) + { + if (tcpTransport->open() != kErpcStatus_Success) + { + erpc_transport_tcp_deinit(transport); + transport = NULL; + } } return transport; } -void erpc_transport_tcp_close(void) +void erpc_transport_tcp_close(erpc_transport_t transport) { - s_transport.get()->close(true); + erpc_assert(transport != NULL); + + TCPTransport *tcpTransport = reinterpret_cast(transport); + + tcpTransport->close(true); +} + +void erpc_transport_tcp_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_tcpTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + TCPTransport *tcpTransport = reinterpret_cast(transport); + + delete tcpTransport; +#endif } diff --git a/erpc_c/setup/erpc_setup_uart_cmsis.cpp b/erpc_c/setup/erpc_setup_uart_cmsis.cpp index 615601f3..4c1115fa 100644 --- a/erpc_c/setup/erpc_setup_uart_cmsis.cpp +++ b/erpc_c/setup/erpc_setup_uart_cmsis.cpp @@ -18,7 +18,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(UartTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(UartTransport, s_uartTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -27,16 +27,48 @@ ERPC_MANUALLY_CONSTRUCTED(UartTransport, s_transport); erpc_transport_t erpc_transport_cmsis_uart_init(void *uartDrv) { erpc_transport_t transport; + UartTransport *uartTransport; - s_transport.construct(reinterpret_cast(uartDrv)); - if (s_transport->init() == kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_uartTransport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + uartTransport = NULL; } else { - transport = NULL; + s_uartTransport.construct(reinterpret_cast(uartDrv)); + uartTransport = s_uartTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + uartTransport = new UartTransport(reinterpret_cast(uartDrv)); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(uartTransport); + + if (uartTransport != NULL) + { + if (uartTransport->init() != kErpcStatus_Success) + { + erpc_transport_cmsis_uart_deinit(transport); + transport = NULL; + } } return transport; } + +void erpc_transport_cmsis_uart_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_uartTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + UartTransport *uartTransport = reinterpret_cast(transport); + + delete uartTransport; +#endif +} diff --git a/erpc_c/setup/erpc_setup_usb_cdc.cpp b/erpc_c/setup/erpc_setup_usb_cdc.cpp index 46f26d67..4cb9d678 100644 --- a/erpc_c/setup/erpc_setup_usb_cdc.cpp +++ b/erpc_c/setup/erpc_setup_usb_cdc.cpp @@ -17,7 +17,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(UsbCdcTransport, s_usb_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(UsbCdcTransport, s_usbTransport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -27,19 +27,52 @@ erpc_transport_t erpc_transport_usb_cdc_init(void *serialHandle, void *serialCon uint8_t *usbRingBuffer, uint32_t usbRingBufferLength) { erpc_transport_t transport; + UsbCdcTransport *usbTransport; - s_usb_transport.construct( - reinterpret_cast(serialHandle), reinterpret_cast(serialConfig), - reinterpret_cast(usbCdcConfig), reinterpret_cast(usbRingBuffer), - reinterpret_cast(usbRingBufferLength)); - if (s_usb_transport->init() == kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_usbTransport.isUsed()) { - transport = reinterpret_cast(s_usb_transport.get()); + usbTransport = NULL; } else { - transport = NULL; + s_usbTransport.construct( + reinterpret_cast(serialHandle), reinterpret_cast(serialConfig), + reinterpret_cast(usbCdcConfig), usbRingBuffer, usbRingBufferLength); + usbTransport = s_usbTransport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + usbTransport = new UsbCdcTransport( + reinterpret_cast(serialHandle), reinterpret_cast(serialConfig), + reinterpret_cast(usbCdcConfig), usbRingBuffer, usbRingBufferLength); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(usbTransport); + + if (usbTransport != NULL) + { + if (usbTransport->init() != kErpcStatus_Success) + { + erpc_transport_usb_cdc_deinit(transport); + transport = NULL; + } } return transport; } + +void erpc_transport_usb_cdc_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_usbTransport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + UsbCdcTransport *usbTransport = reinterpret_cast(transport); + + delete usbTransport; +#endif +} diff --git a/erpc_c/setup/erpc_transport_setup.h b/erpc_c/setup/erpc_transport_setup.h index eaa8b0ce..89061283 100644 --- a/erpc_c/setup/erpc_transport_setup.h +++ b/erpc_c/setup/erpc_transport_setup.h @@ -40,128 +40,129 @@ extern "C" { //! @name Transport setup //@{ -//! @name CMSIS UART transport setup +//! @name DSPI transport setup //@{ /*! - * @brief Create a CMSIS UART transport. + * @brief Create a DSPI master transport. * - * Create a CMSIS UART transport instance, to be used on both the server - * and the client side. + * Create DSPI master transport instance, to be used at master core. * - * @param[in] uartDrv CMSIS USART driver structure address (Driver Control Block). + * @param[in] baseAddr Base address of DSPI peripheral used in this transport layer. + * @param[in] baudRate DSPI baud rate. + * @param[in] srcClock_Hz DSPI source clock in Hz. * * @return Return NULL or erpc_transport_t instance pointer. */ -erpc_transport_t erpc_transport_cmsis_uart_init(void *uartDrv); -//@} +erpc_transport_t erpc_transport_dspi_master_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); -//! @name Host PC serial port transport setup -//@{ +/*! + * @brief Deinitialize DSPI master transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_dspi_master_deinit(erpc_transport_t transport); /*! - * @brief Create a host PC serial port transport. + * @brief Create a DSPI slave transport. * - * Create a host PC serial port transport instance. + * Create DSPI slave transport instance, to be used at slave core. * - * @param[in] portName Port name. - * @param[in] baudRate Baud rate. + * @param[in] baseAddr Base address of DSPI peripheral used in this transport layer. + * @param[in] baudRate DSPI baud rate. + * @param[in] srcClock_Hz DSPI source clock in Hz. * * @return Return NULL or erpc_transport_t instance pointer. */ -erpc_transport_t erpc_transport_serial_init(const char *portName, long baudRate); +erpc_transport_t erpc_transport_dspi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize DSPI slave transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_dspi_slave_deinit(erpc_transport_t transport); + //@} -//! @name SPI transport setup +//! @name I2C transport setup //@{ /*! - * @brief Create a SPI master transport. + * @brief Create an I2C slave transport. * - * Create SPI master transport instance, to be used at master core. + * Create I2C slave transport instance, to be used at slave core. * - * @param[in] baseAddr Base address of SPI peripheral used in this transport layer. + * @param[in] baseAddr Base address of I2C peripheral used in this transport layer. * @param[in] baudRate SPI baud rate. - * @param[in] srcClock_Hz SPI source clock in Hz. + * @param[in] srcClock_Hz I2C source clock in Hz. * * @return Return NULL or erpc_transport_t instance pointer. */ -erpc_transport_t erpc_transport_spi_master_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); +erpc_transport_t erpc_transport_i2c_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); /*! - * @brief Create a SPI slave transport. - * - * Create SPI slave transport instance, to be used at slave core. - * - * @param[in] baseAddr Base address of SPI peripheral used in this transport layer. - * @param[in] baudRate SPI baud rate. - * @param[in] srcClock_Hz SPI source clock in Hz. + * @brief Deinitialize I2C slave transport. * - * @return Return NULL or erpc_transport_t instance pointer. + * @param[in] transport Transport which was initialized with init function. */ -erpc_transport_t erpc_transport_spi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); +void erpc_transport_i2c_slave_deinit(erpc_transport_t transport); + //@} -//! @name DSPI transport setup +//! @name MU transport setup //@{ /*! - * @brief Create a DSPI master transport. + * @brief Create an MU transport. * - * Create DSPI master transport instance, to be used at master core. + * Create Messaging Unit (MU) transport instance, to be used on both the server + * and the client side. Base address of the MU peripheral needs to be passed. * - * @param[in] baseAddr Base address of DSPI peripheral used in this transport layer. - * @param[in] baudRate DSPI baud rate. - * @param[in] srcClock_Hz DSPI source clock in Hz. + * @param[in] baseAddr Base address of MU peripheral. * * @return Return NULL or erpc_transport_t instance pointer. */ -erpc_transport_t erpc_transport_dspi_master_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); +erpc_transport_t erpc_transport_mu_init(void *baseAddr); /*! - * @brief Create a DSPI slave transport. - * - * Create DSPI slave transport instance, to be used at slave core. - * - * @param[in] baseAddr Base address of DSPI peripheral used in this transport layer. - * @param[in] baudRate DSPI baud rate. - * @param[in] srcClock_Hz DSPI source clock in Hz. + * @brief Deinitialize MU transport. * - * @return Return NULL or erpc_transport_t instance pointer. + * @param[in] transport Transport which was initialized with init function. */ -erpc_transport_t erpc_transport_dspi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); +void erpc_transport_mu_deinit(erpc_transport_t transport); + //@} -//! @name SPIdev transport setup +//! @name Linux RPMSG endpoint setup //@{ /*! - * @brief Create a SPIdev transport. + * @brief Create an Linux RPMSG endpoint transport. * - * Create SPIdev master transport instance, to be used at master core. + * This function is using RPMSG endpoints based on this implementation: + * github.com/NXPmicro/rpmsg-sysfs/tree/0aa1817545a765c200b1b2f9b6680a420dcf9171 . * - * @param[in] spidev SPI device name. - * @param[in] speed_Hz SPI clock speed in Hz. + * When local/remote address is set to '-1', then default addresses will be used. + * When type is set to '0', then Datagram model will be used, else Stream. + * + * @param[in] local_addr Local endpoint address. + * @param[in] type Datagram (0) or Stream (1). + * @param[in] remote_addr Remote endpoint address. * * @return Return NULL or erpc_transport_t instance pointer. */ -erpc_transport_t erpc_transport_spidev_master_init(const char *spidev, uint32_t speed_Hz); -//@} - -//! @name MU transport setup -//@{ +erpc_transport_t erpc_transport_rpmsg_linux_init(int16_t local_addr, int8_t type, int16_t remote_addr); /*! - * @brief Create an MU transport. - * - * Create Messaging Unit (MU) transport instance, to be used on both the server - * and the client side. Base address of the MU peripheral needs to be passed. + * @brief Deinitialize an Linux RPMSG endpoint transport. * - * @param[in] baseAddr Base address of MU peripheral. + * This function deinitialize the Linux RPMSG endpoint transport. * - * @return Return NULL or erpc_transport_t instance pointer. + * @param[in] transport Transport which was returned from init function. */ -erpc_transport_t erpc_transport_mu_init(void *baseAddr); +void erpc_transport_rpmsg_linux_deinit(erpc_transport_t transport); + //@} //! @name RPMsg-Lite transport setup @@ -181,6 +182,13 @@ erpc_transport_t erpc_transport_mu_init(void *baseAddr); */ erpc_transport_t erpc_transport_rpmsg_lite_master_init(uint32_t src_addr, uint32_t dst_addr, uint32_t rpmsg_link_id); +/*! + * @brief Deinitialize RPMsg-Lite transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_rpmsg_lite_master_deinit(erpc_transport_t transport); + /*! * @brief Create an RPMsg-Lite transport. * @@ -204,6 +212,13 @@ erpc_transport_t erpc_transport_rpmsg_lite_remote_init(uint32_t src_addr, uint32 uint32_t rpmsg_link_id, rpmsg_ready_cb ready, char *nameservice_name); +/*! + * @brief Deinitialize RPMsg-Lite transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_rpmsg_lite_remote_deinit(erpc_transport_t transport); + /*! * @brief Create an RPMsg-Lite RTOS transport. * @@ -219,6 +234,13 @@ erpc_transport_t erpc_transport_rpmsg_lite_remote_init(uint32_t src_addr, uint32 erpc_transport_t erpc_transport_rpmsg_lite_rtos_master_init(uint32_t src_addr, uint32_t dst_addr, uint32_t rpmsg_link_id); +/*! + * @brief Deinitialize RPMsg-Lite RTOS transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_rpmsg_lite_rtos_master_deinit(erpc_transport_t transport); + /*! * @brief Create an RPMsg-Lite RTOS transport. * @@ -241,6 +263,13 @@ erpc_transport_t erpc_transport_rpmsg_lite_rtos_remote_init(uint32_t src_addr, u uint32_t rpmsg_link_id, rpmsg_ready_cb ready, char *nameservice_name); +/*! + * @brief Deinitialize RPMsg-Lite RTOS transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_rpmsg_lite_rtos_remote_deinit(erpc_transport_t transport); + /*! * @brief Create an RPMsg-Lite TTY transport. * @@ -267,37 +296,104 @@ erpc_transport_t erpc_transport_rpmsg_lite_tty_rtos_remote_init(uint32_t src_add /*! * @brief Deinitialize an RPMSG lite tty rtos transport. * - * This function deinitializes the RPMSG lite tty rtos transport. + * This function deinitialize the RPMSG lite tty rtos transport. + * + * @param[in] transport Transport which was returned from init function. */ -void erpc_transport_rpmsg_lite_tty_rtos_deinit(void); +void erpc_transport_rpmsg_lite_tty_rtos_remote_deinit(erpc_transport_t transport); //@} -//! @name Linux RPMSG endpoint setup +//! @name Host PC serial port transport setup //@{ /*! - * @brief Create an Linux RPMSG endpoint transport. + * @brief Create a host PC serial port transport. * - * This function is using RPMSG endpoints based on this implementation: - * github.com/nxp-mcuxpresso/rpmsg-sysfs/tree/0aa1817545a765c200b1b2f9b6680a420dcf9171 . + * Create a host PC serial port transport instance. * - * When local/remote address is set to '-1', then default addresses will be used. - * When type is set to '0', then Datagram model will be used, else Stream. + * @param[in] portName Port name. + * @param[in] baudRate Baud rate. * - * @param[in] local_addr Local endpoint address. - * @param[in] type Datagram (0) or Stream (1). - * @param[in] remote_addr Remote endpoint address. + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_serial_init(const char *portName, long baudRate); + +/*! + * @brief Deinitialize a host PC serial port transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_serial_deinit(erpc_transport_t transport); + +//@} + +//! @name SPI transport setup +//@{ + +/*! + * @brief Create a SPI master transport. + * + * Create SPI master transport instance, to be used at master core. + * + * @param[in] baseAddr Base address of SPI peripheral used in this transport layer. + * @param[in] baudRate SPI baud rate. + * @param[in] srcClock_Hz SPI source clock in Hz. * * @return Return NULL or erpc_transport_t instance pointer. */ -erpc_transport_t erpc_transport_rpmsg_linux_init(int16_t local_addr, int8_t type, int16_t remote_addr); +erpc_transport_t erpc_transport_spi_master_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); /*! - * @brief Deinitialize an Linux RPMSG endpoint transport. + * @brief Deinitialize SPI master transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_spi_master_deinit(erpc_transport_t transport); + +/*! + * @brief Create a SPI slave transport. + * + * Create SPI slave transport instance, to be used at slave core. + * + * @param[in] baseAddr Base address of SPI peripheral used in this transport layer. + * @param[in] baudRate SPI baud rate. + * @param[in] srcClock_Hz SPI source clock in Hz. * - * This function deinitializes the Linux RPMSG endpoint transport. + * @return Return NULL or erpc_transport_t instance pointer. */ -void erpc_transport_rpmsg_linux_deinit(void); +erpc_transport_t erpc_transport_spi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); + +/*! + * @brief Deinitialize SPI slave transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_spi_slave_deinit(erpc_transport_t transport); + +//@} + +//! @name SPIdev transport setup +//@{ + +/*! + * @brief Create a SPIdev transport. + * + * Create SPIdev master transport instance, to be used at master core. + * + * @param[in] spidev SPI device name. + * @param[in] speed_Hz SPI clock speed in Hz. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_spidev_master_init(const char *spidev, uint32_t speed_Hz); + +/*! + * @brief Deinitialize SPIdev transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_spidev_master_deinit(erpc_transport_t transport); + //@} //! @name TCP transport setup @@ -327,9 +423,41 @@ erpc_transport_t erpc_transport_tcp_init(const char *host, uint16_t port, bool i * socket or select() shoudl be used * For client, close server connection * - * @return Return TRUE if listen/connection successful + * @param[in] transport Transport which was returned from init function. + */ +void erpc_transport_tcp_close(erpc_transport_t transport); + +/*! + * @brief Deinitialize TCP transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_tcp_deinit(erpc_transport_t transport); + +//@} + +//! @name CMSIS UART transport setup +//@{ + +/*! + * @brief Create a CMSIS UART transport. + * + * Create a CMSIS UART transport instance, to be used on both the server + * and the client side. + * + * @param[in] uartDrv CMSIS USART driver structure address (Driver Control Block). + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_cmsis_uart_init(void *uartDrv); + +/*! + * @brief Deinitialize CMSIS UART transport. + * + * @param[in] transport Transport which was initialized with init function. */ -void erpc_transport_tcp_close(void); +void erpc_transport_cmsis_uart_deinit(erpc_transport_t transport); + //@} //! @name USB CDC transport setup @@ -354,23 +482,14 @@ void erpc_transport_tcp_close(void); */ erpc_transport_t erpc_transport_usb_cdc_init(void *serialHandle, void *serialConfig, void *usbCdcConfig, uint8_t *usbRingBuffer, uint32_t usbRingBufferLength); -//@} - -//! @name I2C transport setup -//@{ /*! - * @brief Create an I2C slave transport. - * - * Create I2C slave transport instance, to be used at slave core. + * @brief Deinitialize USB CDC transport. * - * @param[in] baseAddr Base address of I2C peripheral used in this transport layer. - * @param[in] baudRate SPI baud rate. - * @param[in] srcClock_Hz I2C source clock in Hz. - * - * @return Return NULL or erpc_transport_t instance pointer. + * @param[in] transport Transport which was initialized with init function. */ -erpc_transport_t erpc_transport_i2c_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); +void erpc_transport_usb_cdc_deinit(erpc_transport_t transport); + //@} //@} diff --git a/erpc_c/transports/erpc_rpmsg_linux_transport.hpp b/erpc_c/transports/erpc_rpmsg_linux_transport.hpp index 968780d7..f849e951 100644 --- a/erpc_c/transports/erpc_rpmsg_linux_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_linux_transport.hpp @@ -33,6 +33,13 @@ class RPMsgLinuxTransport : public Transport virtual ~RPMsgLinuxTransport(void); + /*! + * @brief This function returns rpmsg endpoint object. + * + * @return RPMsgEndpoint * Rpmsg endpoint. + */ + RPMsgEndpoint *getRpmsgEndpoint(void){ return m_endPoint; } + /*! * @brief This function initializes Linux environment for sending and receiving messages. * From 781fb03abdb9089f430715e77ddb2be1cdfe2d1a Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Fri, 2 Jun 2023 15:02:09 +0200 Subject: [PATCH 02/24] Fix spidev init (#363) * Fix spidev init Signed-off-by: Cervenka Dusan * Fix receive error value for spidev Signed-off-by: Cervenka Dusan --------- Signed-off-by: Cervenka Dusan --- erpc_c/transports/erpc_spidev_master_transport.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/erpc_c/transports/erpc_spidev_master_transport.cpp b/erpc_c/transports/erpc_spidev_master_transport.cpp index 577634c4..972b10d9 100644 --- a/erpc_c/transports/erpc_spidev_master_transport.cpp +++ b/erpc_c/transports/erpc_spidev_master_transport.cpp @@ -108,7 +108,7 @@ SpidevMasterTransport::~SpidevMasterTransport(void) erpc_status_t SpidevMasterTransport::init(void) { - erpc_status_t status; + erpc_status_t status = kErpcStatus_Success; /* Initialize the SPI device */ /* Open SPI device file descriptor */ @@ -217,7 +217,7 @@ erpc_status_t SpidevMasterTransport::underlyingReceive(uint8_t *data, uint32_t s if (ERPC_SPIDEV_STATUS_SUCCESS != spidev_transfer(m_spidevHandle, NULL, data, size)) { - status = kErpcStatus_SendFailed; + status = kErpcStatus_ReceiveFailed; } return status; From adc90c51622419b1ee137355a5a48ae793ec7ff3 Mon Sep 17 00:00:00 2001 From: amgross Date: Thu, 10 Aug 2023 14:23:49 +0300 Subject: [PATCH 03/24] Fix typo in assert --- erpc_c/setup/erpc_server_setup.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erpc_c/setup/erpc_server_setup.cpp b/erpc_c/setup/erpc_server_setup.cpp index 2fd5580e..aff5e6ab 100644 --- a/erpc_c/setup/erpc_server_setup.cpp +++ b/erpc_c/setup/erpc_server_setup.cpp @@ -200,7 +200,7 @@ void erpc_client_add_pre_cb_action(erpc_server_t server, pre_post_action_cb preC void erpc_client_add_post_cb_action(erpc_server_t server, pre_post_action_cb postCB) { - erpc_assert(server) != NULL; + erpc_assert(server != NULL); SimpleServer *simpleServer = reinterpret_cast(server); From 87b1667afa1aafc9cc1ee1f4bac822fc0a35f2da Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Wed, 6 Sep 2023 16:32:21 +0200 Subject: [PATCH 04/24] Change mac build target from deprecated to new (#376) Signed-off-by: Cervenka Dusan --- .circleci/config.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index d37ef48a..7f1ec49b 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -24,8 +24,8 @@ jobs: # path: ./Release/Linux/erpcgen/erpcgen build-mac-gcc: macos: - xcode: 12.5.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases - resource_class: medium + xcode: 14.3.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases + resource_class: macos.m1.medium.gen1 steps: - checkout - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh @@ -34,8 +34,8 @@ jobs: path: ./Release/Darwin/erpcgen/erpcgen build-mac-clang: macos: - xcode: 12.5.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases - resource_class: medium + xcode: 14.3.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases + resource_class: macos.m1.medium.gen1 steps: - checkout - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh clang From f7417eeb28f2565a95efde78e6c127976a7f05ae Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Wed, 6 Sep 2023 16:36:53 +0200 Subject: [PATCH 05/24] Change mac build target from deprecated to temporary (#377) Signed-off-by: Cervenka Dusan Co-authored-by: Michal Princ --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 7f1ec49b..287f2d5d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -25,7 +25,7 @@ jobs: build-mac-gcc: macos: xcode: 14.3.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases - resource_class: macos.m1.medium.gen1 + resource_class: macos.x86.medium.gen2 steps: - checkout - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh @@ -35,7 +35,7 @@ jobs: build-mac-clang: macos: xcode: 14.3.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases - resource_class: macos.m1.medium.gen1 + resource_class: macos.x86.medium.gen2 steps: - checkout - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh clang From f335f8749050d5124d8be39425a6e8d79d77ca33 Mon Sep 17 00:00:00 2001 From: "Michal Princ (nxa17570)" Date: Thu, 7 Sep 2023 10:09:38 +0200 Subject: [PATCH 06/24] Revert "Change mac build target from deprecated to new (#376)" This reverts commit 87b1667afa1aafc9cc1ee1f4bac822fc0a35f2da. # Conflicts: # .circleci/config.yml --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 287f2d5d..01a78cee 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -24,7 +24,7 @@ jobs: # path: ./Release/Linux/erpcgen/erpcgen build-mac-gcc: macos: - xcode: 14.3.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases + xcode: 12.5.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases resource_class: macos.x86.medium.gen2 steps: - checkout @@ -34,7 +34,7 @@ jobs: path: ./Release/Darwin/erpcgen/erpcgen build-mac-clang: macos: - xcode: 14.3.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases + xcode: 12.5.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases resource_class: macos.x86.medium.gen2 steps: - checkout From f6d90116fd444de03dccfb0dd28686f971d4079d Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Tue, 19 Sep 2023 08:05:31 +0200 Subject: [PATCH 07/24] Move enums to enum classes (#379) * Move enums to enum classes Signed-off-by: Cervenka Dusan * Fixed python typo Signed-off-by: Cervenka Dusan --------- Signed-off-by: Cervenka Dusan --- erpc_c/infra/erpc_basic_codec.cpp | 4 +- erpc_c/infra/erpc_basic_codec.hpp | 2 +- erpc_c/infra/erpc_client_manager.cpp | 2 +- erpc_c/infra/erpc_client_manager.h | 4 +- erpc_c/infra/erpc_codec.hpp | 4 +- erpc_c/infra/erpc_server.cpp | 2 +- erpc_c/infra/erpc_simple_server.cpp | 4 +- erpc_c/infra/erpc_transport_arbitrator.cpp | 4 +- erpc_c/setup/erpc_arbitrated_client_setup.h | 3 +- .../transports/erpc_rpmsg_lite_transport.hpp | 2 +- erpcgen/src/CGenerator.cpp | 294 +++++++++-------- erpcgen/src/CGenerator.hpp | 6 +- erpcgen/src/Generator.cpp | 28 +- erpcgen/src/Generator.hpp | 2 +- erpcgen/src/InterfaceDefinition.cpp | 30 +- erpcgen/src/InterfaceDefinition.hpp | 2 +- erpcgen/src/Logging.cpp | 14 +- erpcgen/src/Logging.hpp | 10 +- erpcgen/src/PythonGenerator.cpp | 78 ++--- erpcgen/src/PythonGenerator.hpp | 4 +- erpcgen/src/SearchPath.hpp | 5 +- erpcgen/src/SymbolScanner.cpp | 25 +- erpcgen/src/UniqueIdChecker.cpp | 8 +- erpcgen/src/cpptemplate/cpptempl.cpp | 310 +++++++++--------- erpcgen/src/cpptemplate/cpptempl.hpp | 2 +- erpcgen/src/erpcgen.cpp | 40 +-- erpcgen/src/options.cpp | 93 +++--- erpcgen/src/options.hpp | 6 +- .../src/templates/c_client_source.template | 2 +- .../src/templates/c_server_source.template | 2 +- erpcgen/src/types/AliasType.hpp | 4 +- erpcgen/src/types/Annotation.hpp | 4 +- erpcgen/src/types/ArrayType.hpp | 2 +- erpcgen/src/types/BuiltinType.hpp | 28 +- erpcgen/src/types/ConstType.hpp | 2 +- erpcgen/src/types/DataType.hpp | 26 +- erpcgen/src/types/EnumMember.hpp | 4 +- erpcgen/src/types/EnumType.hpp | 4 +- erpcgen/src/types/Function.hpp | 4 +- erpcgen/src/types/FunctionType.hpp | 2 +- erpcgen/src/types/Group.hpp | 6 +- erpcgen/src/types/Interface.hpp | 2 +- erpcgen/src/types/ListType.hpp | 2 +- erpcgen/src/types/Program.hpp | 2 +- erpcgen/src/types/StructMember.hpp | 20 +- erpcgen/src/types/StructType.hpp | 4 +- erpcgen/src/types/Symbol.hpp | 18 +- erpcgen/src/types/Type.cpp | 14 +- erpcgen/src/types/UnionCase.hpp | 6 +- erpcgen/src/types/UnionType.hpp | 4 +- erpcgen/src/types/VoidType.hpp | 2 +- erpcsniffer/src/Sniffer.cpp | 66 ++-- erpcsniffer/src/Sniffer.hpp | 2 +- erpcsniffer/src/erpcsniffer.cpp | 38 +-- test/common/retarget_cpp_streamed_io.c | 2 +- test/common/unit_test_serial_client.cpp | 2 +- test/common/unit_test_serial_server.cpp | 2 +- .../unit_test_tcp_arbitrator_client.cpp | 2 +- .../unit_test_tcp_arbitrator_server.cpp | 2 +- test/common/unit_test_tcp_client.cpp | 2 +- test/common/unit_test_tcp_server.cpp | 2 +- test/test_lists/test_lists_client_impl.cpp | 4 +- test/test_shared/test_shared_client_impl.cpp | 4 +- 63 files changed, 652 insertions(+), 628 deletions(-) diff --git a/erpc_c/infra/erpc_basic_codec.cpp b/erpc_c/infra/erpc_basic_codec.cpp index a1ee9ccc..4c3adaa1 100644 --- a/erpc_c/infra/erpc_basic_codec.cpp +++ b/erpc_c/infra/erpc_basic_codec.cpp @@ -158,7 +158,7 @@ void BasicCodec::startWriteUnion(int32_t discriminator) void BasicCodec::writeNullFlag(bool isNull) { - write(static_cast(isNull ? kIsNull : kNotNull)); + write(static_cast(isNull ? null_flag_t::kIsNull : null_flag_t::kNotNull)); } void BasicCodec::writeCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr callback) @@ -392,7 +392,7 @@ void BasicCodec::readNullFlag(bool &isNull) read(flag); if (isStatusOk()) { - isNull = (flag == (uint8_t)kIsNull); + isNull = (flag == static_cast(null_flag_t::kIsNull)); } } diff --git a/erpc_c/infra/erpc_basic_codec.hpp b/erpc_c/infra/erpc_basic_codec.hpp index 581f6c7c..204b9a9e 100644 --- a/erpc_c/infra/erpc_basic_codec.hpp +++ b/erpc_c/infra/erpc_basic_codec.hpp @@ -27,7 +27,7 @@ namespace erpc { /*! * @brief Values of the uint8 flag prefixing nullable values. */ -enum _null_flag +enum class null_flag_t { kNotNull = 0, kIsNull diff --git a/erpc_c/infra/erpc_client_manager.cpp b/erpc_c/infra/erpc_client_manager.cpp index c13a6c05..34e62ad9 100644 --- a/erpc_c/infra/erpc_client_manager.cpp +++ b/erpc_c/infra/erpc_client_manager.cpp @@ -175,7 +175,7 @@ void ClientManager::verifyReply(RequestContext &request) if (request.getCodec()->isStatusOk() == true) { // Verify that this is a reply to the request we just sent. - if ((msgType != kReplyMessage) || (sequence != request.getSequence())) + if ((msgType != message_type_t::kReplyMessage) || (sequence != request.getSequence())) { request.getCodec()->updateStatus(kErpcStatus_ExpectedReply); } diff --git a/erpc_c/infra/erpc_client_manager.h b/erpc_c/infra/erpc_client_manager.h index 8544fb99..1a1dd801 100644 --- a/erpc_c/infra/erpc_client_manager.h +++ b/erpc_c/infra/erpc_client_manager.h @@ -130,8 +130,8 @@ class ClientManager : public ClientServerCommon #endif protected: - uint32_t m_sequence; //!< Sequence number. - client_error_handler_t m_errorHandler; //!< Pointer to function error handler. + uint32_t m_sequence; //!< Sequence number. + client_error_handler_t m_errorHandler; //!< Pointer to function error handler. #if ERPC_NESTED_CALLS Server *m_server; //!< Server used for nested calls. Thread::thread_id_t m_serverThreadId; //!< Thread in which server run function is called. diff --git a/erpc_c/infra/erpc_codec.hpp b/erpc_c/infra/erpc_codec.hpp index 02ac7395..14356fcd 100644 --- a/erpc_c/infra/erpc_codec.hpp +++ b/erpc_c/infra/erpc_codec.hpp @@ -32,13 +32,13 @@ namespace erpc { /*! * @brief Types of messages that can be encoded. */ -typedef enum _message_type +enum class message_type_t { kInvocationMessage = 0, kOnewayMessage, kReplyMessage, kNotificationMessage -} message_type_t; +}; typedef void *funPtr; // Pointer to functions typedef funPtr *arrayOfFunPtr; // Pointer to array of functions diff --git a/erpc_c/infra/erpc_server.cpp b/erpc_c/infra/erpc_server.cpp index 3dd19d15..2fe306bb 100644 --- a/erpc_c/infra/erpc_server.cpp +++ b/erpc_c/infra/erpc_server.cpp @@ -75,7 +75,7 @@ erpc_status_t Server::processMessage(Codec *codec, message_type_t msgType, uint3 erpc_status_t err = kErpcStatus_Success; Service *service; - if ((msgType != kInvocationMessage) && (msgType != kOnewayMessage)) + if ((msgType != message_type_t::kInvocationMessage) && (msgType != message_type_t::kOnewayMessage)) { err = kErpcStatus_InvalidArgument; } diff --git a/erpc_c/infra/erpc_simple_server.cpp b/erpc_c/infra/erpc_simple_server.cpp index ac97e9cc..3ac59c37 100644 --- a/erpc_c/infra/erpc_simple_server.cpp +++ b/erpc_c/infra/erpc_simple_server.cpp @@ -123,7 +123,7 @@ erpc_status_t SimpleServer::runInternalEnd(Codec *codec, message_type_t msgType, if (err == kErpcStatus_Success) { - if (msgType != kOnewayMessage) + if (msgType != message_type_t::kOnewayMessage) { #if ERPC_MESSAGE_LOGGING err = logMessage(codec->getBuffer()); @@ -183,7 +183,7 @@ erpc_status_t SimpleServer::run(RequestContext &request) break; } - if (msgType == kReplyMessage) + if (msgType == message_type_t::kReplyMessage) { if (sequence == request.getSequence()) { diff --git a/erpc_c/infra/erpc_transport_arbitrator.cpp b/erpc_c/infra/erpc_transport_arbitrator.cpp index bb748723..453fa341 100644 --- a/erpc_c/infra/erpc_transport_arbitrator.cpp +++ b/erpc_c/infra/erpc_transport_arbitrator.cpp @@ -107,13 +107,13 @@ erpc_status_t TransportArbitrator::receive(MessageBuffer *message) } // If this message is an invocation, return it to the calling server. - if ((msgType == kInvocationMessage) || (msgType == kOnewayMessage)) + if ((msgType == message_type_t::kInvocationMessage) || (msgType == message_type_t::kOnewayMessage)) { break; } // Just ignore messages we don't know what to do with. - if (msgType != kReplyMessage) + if (msgType != message_type_t::kReplyMessage) { continue; } diff --git a/erpc_c/setup/erpc_arbitrated_client_setup.h b/erpc_c/setup/erpc_arbitrated_client_setup.h index d8ed7bf7..d8775d60 100644 --- a/erpc_c/setup/erpc_arbitrated_client_setup.h +++ b/erpc_c/setup/erpc_arbitrated_client_setup.h @@ -66,7 +66,8 @@ extern "C" { * * @return erpc_client_t Pointer to client structure. */ -erpc_client_t erpc_arbitrated_client_init(erpc_transport_t transport, erpc_mbf_t message_buffer_factory, erpc_transport_t *arbitrator); +erpc_client_t erpc_arbitrated_client_init(erpc_transport_t transport, erpc_mbf_t message_buffer_factory, + erpc_transport_t *arbitrator); /*! * @brief This function sets error handler function. diff --git a/erpc_c/transports/erpc_rpmsg_lite_transport.hpp b/erpc_c/transports/erpc_rpmsg_lite_transport.hpp index 8ac958ff..ab4cb3c6 100644 --- a/erpc_c/transports/erpc_rpmsg_lite_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_lite_transport.hpp @@ -132,7 +132,7 @@ class RPMsgTransport : public RPMsgBaseTransport * * @return True if exist received message, else false. */ - virtual bool hasMessage(void) { return ((0UL < m_messageQueue.size()) ? true: false); } + virtual bool hasMessage(void) { return ((0UL < m_messageQueue.size()) ? true : false); } protected: /*! diff --git a/erpcgen/src/CGenerator.cpp b/erpcgen/src/CGenerator.cpp index b3fe5808..71dd8960 100644 --- a/erpcgen/src/CGenerator.cpp +++ b/erpcgen/src/CGenerator.cpp @@ -45,7 +45,7 @@ static uint8_t listCounter = 0; // Code //////////////////////////////////////////////////////////////////////////////// CGenerator::CGenerator(InterfaceDefinition *def) -: Generator(def, kC) +: Generator(def, generator_type_t::kC) { /* Set copyright rules. */ if (m_def->hasProgramSymbol()) @@ -166,19 +166,19 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da switch (dataType->getDataType()) { - case DataType::kAliasType: { + case DataType::data_type_t::kAliasType: { AliasType *aliasType = dynamic_cast(dataType); assert(aliasType); aliasType->setElementType(findChildDataType(dataTypes, aliasType->getElementType())); break; } - case DataType::kArrayType: { + case DataType::data_type_t::kArrayType: { ArrayType *arrayType = dynamic_cast(dataType); assert(arrayType); arrayType->setElementType(findChildDataType(dataTypes, arrayType->getElementType())); break; } - case DataType::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: { if (dataType->isBinary()) { // check if binary data type was replaced with structure wrapper @@ -209,7 +209,7 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da dataTypes.insert(dataType); break; } - case DataType::kFunctionType: { + case DataType::data_type_t::kFunctionType: { FunctionType *funcType = dynamic_cast(dataType); assert(funcType); @@ -232,7 +232,7 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da } break; } - case DataType::kListType: { + case DataType::data_type_t::kListType: { // The only child node of a list node is the element type. ListType *listType = dynamic_cast(dataType); DataType *trueContainerDataType = listType->getTrueContainerDataType(); @@ -324,7 +324,7 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da break; } } - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { StructType *structType = dynamic_cast(dataType); assert(structType); @@ -349,7 +349,7 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da } break; } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { // Keil need extra pragma option when unions are used. m_templateData["usedUnionType"] = true; UnionType *currentUnion = dynamic_cast(dataType); @@ -373,7 +373,7 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da void CGenerator::transformAliases() { - for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::kAliasType)) + for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kAliasType)) { AliasType *aliasType = dynamic_cast(it); assert(aliasType); @@ -434,10 +434,10 @@ void CGenerator::generate() m_templateData["usedUnionType"] = false; /* Set directions constants*/ - m_templateData["InDirection"] = getDirection(kInDirection); - m_templateData["OutDirection"] = getDirection(kOutDirection); - m_templateData["InoutDirection"] = getDirection(kInoutDirection); - m_templateData["ReturnDirection"] = getDirection(kReturn); + m_templateData["InDirection"] = getDirection(param_direction_t::kInDirection); + m_templateData["OutDirection"] = getDirection(param_direction_t::kOutDirection); + m_templateData["InoutDirection"] = getDirection(param_direction_t::kInoutDirection); + m_templateData["ReturnDirection"] = getDirection(param_direction_t::kReturn); parseSubtemplates(); @@ -448,21 +448,21 @@ void CGenerator::generate() } // check if structure/function parameters annotations are valid. - for (Symbol *symbol : getDataTypesFromSymbolScope(m_globals, DataType::kFunctionType)) + for (Symbol *symbol : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kFunctionType)) { FunctionType *functionType = dynamic_cast(symbol); assert(functionType); scanStructForAnnotations(&functionType->getParameters(), true); } - for (Symbol *symbol : getDataTypesFromSymbolScope(m_globals, DataType::kStructType)) + for (Symbol *symbol : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kStructType)) { StructType *structType = dynamic_cast(symbol); assert(structType); scanStructForAnnotations(structType, false); } - for (Symbol *symbol : m_globals->getSymbolsOfType(Symbol::kInterfaceSymbol)) + for (Symbol *symbol : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kInterfaceSymbol)) { Interface *interface = dynamic_cast(symbol); assert(interface); @@ -523,7 +523,7 @@ void CGenerator::makeConstTemplateData() { Log::info("Constant globals:\n"); data_list consts; - for (auto it : m_globals->getSymbolsOfType(Symbol::kConstSymbol)) + for (auto it : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kConstSymbol)) { ConstType *constVar = dynamic_cast(it); assert(constVar); @@ -605,7 +605,7 @@ void CGenerator::makeEnumsTemplateData() Log::info("Enums:\n"); data_list enums; int n = 0; - for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::kEnumType)) + for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kEnumType)) { EnumType *enumType = dynamic_cast(it); assert(enumType); @@ -661,11 +661,11 @@ void CGenerator::makeAliasesTemplateData() int n = 0; // All existing type declarations - datatype_vector_t aliasTypeVector = getDataTypesFromSymbolScope(m_globals, DataType::kAliasType); + datatype_vector_t aliasTypeVector = getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kAliasType); /* type definitions of structures */ int i = 0; - for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::kStructType)) + for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kStructType)) { StructType *structType = dynamic_cast(it); assert(structType); @@ -677,7 +677,7 @@ void CGenerator::makeAliasesTemplateData() } /* type definitions of non-encapsulated unions */ - for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::kUnionType)) + for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kUnionType)) { UnionType *unionType = dynamic_cast(it); assert(unionType); @@ -690,7 +690,7 @@ void CGenerator::makeAliasesTemplateData() /* type definitions of functions and table of functions */ data_list functions; - for (auto functionTypeSymbol : getDataTypesFromSymbolScope(m_globals, DataType::kFunctionType)) + for (auto functionTypeSymbol : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kFunctionType)) { FunctionType *functionType = dynamic_cast(functionTypeSymbol); assert(functionType); @@ -812,7 +812,7 @@ void CGenerator::makeAliasesTemplateData() aliasInfo["unnamedName"] = getOutputName(aliasType); switch (elementDataType->getDataType()) { - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { StructType *structType = dynamic_cast(elementDataType); assert(structType); aliasInfo["unnamed"] = getStructDefinitionTemplateData( @@ -820,7 +820,7 @@ void CGenerator::makeAliasesTemplateData() aliasInfo["unnamedType"] = "struct"; break; } - case DataType::kEnumType: { + case DataType::data_type_t::kEnumType: { EnumType *enumType = dynamic_cast(elementDataType); assert(enumType); aliasInfo["unnamed"] = getEnumTemplateData(enumType); @@ -840,7 +840,7 @@ void CGenerator::makeAliasesTemplateData() AliasType *CGenerator::getAliasType(DataType *dataType) { - for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::kAliasType)) + for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kAliasType)) { AliasType *aliasType = dynamic_cast(it); assert(aliasType); @@ -926,7 +926,7 @@ data_map CGenerator::makeGroupSymbolsTemplateData(Group *group) for (Symbol *symbol : group->getSymbols()) { data_map info; - const set<_param_direction> dirs = group->getSymbolDirections(symbol); + const set dirs = group->getSymbolDirections(symbol); if (dirs.size()) { if (symbol->isDatatypeSymbol()) @@ -1370,8 +1370,8 @@ bool CGenerator::isServerNullParam(StructMember *param) bool CGenerator::isPointerParam(StructMember *param) { DataType *paramTrueDataType = param->getDataType()->getTrueDataType(); - return (isServerNullParam(param) || - ((paramTrueDataType->isScalar() || paramTrueDataType->isEnum()) && param->getDirection() != kInDirection)); + return (isServerNullParam(param) || ((paramTrueDataType->isScalar() || paramTrueDataType->isEnum()) && + param->getDirection() != param_direction_t::kInDirection)); } bool CGenerator::isNullableParam(StructMember *param) @@ -1436,7 +1436,7 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) returnInfo["lengthName"] = ""; returnInfo["nullVariable"] = ""; - returnInfo["direction"] = getDirection(kReturn); + returnInfo["direction"] = getDirection(param_direction_t::kReturn); returnInfo["coderCall"] = getEncodeDecodeCall(result, group, dataType, nullptr, false, structMember, needTempVariableI32, true); returnInfo["shared"] = isShared; @@ -1498,7 +1498,7 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) // Directions in which list/union is serializing reference if (referencedFrom->getDirection() == param->getDirection()) { - paramInfo["serializedDirection"] = getDirection(kInoutDirection); + paramInfo["serializedDirection"] = getDirection(param_direction_t::kInoutDirection); } else { @@ -1569,7 +1569,7 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) { StructMember *symbolStructMember = dynamic_cast(symbol); assert(symbolStructMember); - if (symbolStructMember->getDirection() != kInDirection) + if (symbolStructMember->getDirection() != param_direction_t::kInDirection) { throw semantic_error( format_string("line %d, ref %d: The parameter named by a max_length annotation must be " @@ -1613,11 +1613,12 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) setSymbolDataToSide(param, group->getSymbolDirections(param), paramsToClient, paramsToServer, paramInfo); - if (needTempVariableI32 && param->getDirection() != kInDirection) + if (needTempVariableI32 && param->getDirection() != param_direction_t::kInDirection) { info["needTempVariableClientI32"] = true; } - if (needTempVariableI32 && (param->getDirection() == kInDirection || param->getDirection() == kInoutDirection)) + if (needTempVariableI32 && (param->getDirection() == param_direction_t::kInDirection || + param->getDirection() == param_direction_t::kInoutDirection)) { info["needTempVariableServerI32"] = true; } @@ -1742,10 +1743,10 @@ data_map CGenerator::getFunctionTypeTemplateData(Group *group, FunctionType *fn) return info; } -void CGenerator::setSymbolDataToSide(const Symbol *symbolType, const set<_param_direction> &directions, +void CGenerator::setSymbolDataToSide(const Symbol *symbolType, const set &directions, data_list &toClient, data_list &toServer, data_map &dataMap) { - _direction direction = kIn; + direction_t direction = direction_t::kIn; if (symbolType->isDatatypeSymbol()) { const DataType *dataType = dynamic_cast(symbolType); @@ -1753,26 +1754,26 @@ void CGenerator::setSymbolDataToSide(const Symbol *symbolType, const set<_param_ if (dataType->isStruct() || dataType->isFunction() || dataType->isUnion()) { - bool in = directions.count(kInDirection); - bool out = directions.count(kOutDirection); - bool inOut = directions.count(kInoutDirection); - bool ret = directions.count(kReturn); + bool in = directions.count(param_direction_t::kInDirection); + bool out = directions.count(param_direction_t::kOutDirection); + bool inOut = directions.count(param_direction_t::kInoutDirection); + bool ret = directions.count(param_direction_t::kReturn); Log::info("Symbol %s has directions: in:%d, out:%d, inOut:%d, ret:%d\n", symbolType->getName().c_str(), in, out, inOut, ret); if (inOut || (in && (ret || out))) { - direction = kInOut; + direction = direction_t::kInOut; } else if (ret || out) { - direction = kOut; + direction = direction_t::kOut; } else if (!in && !out && !ret && !inOut) { // ToDo: shared pointer. - direction = kNone; + direction = direction_t::kNone; } } else @@ -1787,13 +1788,13 @@ void CGenerator::setSymbolDataToSide(const Symbol *symbolType, const set<_param_ assert(structMember); switch (structMember->getDirection()) { - case kOutDirection: - case kInoutDirection: { - direction = kInOut; + case param_direction_t::kOutDirection: + case param_direction_t::kInoutDirection: { + direction = direction_t::kInOut; break; } - case kInDirection: { - direction = kIn; + case param_direction_t::kInDirection: { + direction = direction_t::kIn; break; } default: { @@ -1809,20 +1810,20 @@ void CGenerator::setSymbolDataToSide(const Symbol *symbolType, const set<_param_ switch (direction) { - case kIn: { + case direction_t::kIn: { toServer.push_back(dataMap); break; } - case kOut: { + case direction_t::kOut: { toClient.push_back(dataMap); break; } - case kInOut: { + case direction_t::kInOut: { toServer.push_back(dataMap); toClient.push_back(dataMap); break; } - case kNone: // ToDo: shared pointer + case direction_t::kNone: // ToDo: shared pointer { break; } @@ -1835,7 +1836,7 @@ data_map CGenerator::getTypeInfo(DataType *t, bool isFunction) { (void)isFunction; data_map info; - info["isNotVoid"] = make_data(t->getDataType() != DataType::kVoidType); + info["isNotVoid"] = make_data(t->getDataType() != DataType::data_type_t::kVoidType); return info; } @@ -1861,7 +1862,7 @@ string CGenerator::getErrorReturnValue(FunctionBase *fn) { BuiltinType *builtinType = dynamic_cast(dataType); assert(builtinType); - if (builtinType->getBuiltinType() == BuiltinType::kBoolType) + if (builtinType->getBuiltinType() == BuiltinType::builtin_type_t::kBoolType) { IntegerValue *integerValue = dynamic_cast(returnVal); assert(integerValue); @@ -1878,19 +1879,19 @@ string CGenerator::getErrorReturnValue(FunctionBase *fn) assert(builtinType); switch (builtinType->getBuiltinType()) { - case BuiltinType::kBoolType: { + case BuiltinType::builtin_type_t::kBoolType: { return "false"; } - case BuiltinType::kUInt8Type: { + case BuiltinType::builtin_type_t::kUInt8Type: { return "0xFFU"; } - case BuiltinType::kUInt16Type: { + case BuiltinType::builtin_type_t::kUInt16Type: { return "0xFFFFU"; } - case BuiltinType::kUInt32Type: { + case BuiltinType::builtin_type_t::kUInt32Type: { return "0xFFFFFFFFU"; } - case BuiltinType::kUInt64Type: { + case BuiltinType::builtin_type_t::kUInt64Type: { return "0xFFFFFFFFFFFFFFFFU"; } default: { @@ -1930,14 +1931,15 @@ string CGenerator::getFunctionServerCall(Function *fn, FunctionType *functionTyp DataType *trueDataType = it->getDataType()->getTrueDataType(); /* Builtin types and function types. */ - if (((trueDataType->isScalar()) || trueDataType->isEnum()) && it->getDirection() != kInDirection && - findAnnotation(it, NULLABLE_ANNOTATION)) + if (((trueDataType->isScalar()) || trueDataType->isEnum()) && + it->getDirection() != param_direction_t::kInDirection && findAnnotation(it, NULLABLE_ANNOTATION)) { // On server side is created new variable for handle null : "_" + name proto += "_"; } - else if ((it->getDirection() != kInDirection) && (((trueDataType->isScalar()) || trueDataType->isEnum()) || - (findAnnotation(it, SHARED_ANNOTATION)))) + else if ((it->getDirection() != param_direction_t::kInDirection) && + (((trueDataType->isScalar()) || trueDataType->isEnum()) || + (findAnnotation(it, SHARED_ANNOTATION)))) { proto += "&"; @@ -2009,9 +2011,9 @@ string CGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const st /* Add '*' to data types. */ if (((trueDataType->isBuiltin() || trueDataType->isEnum()) && - (it->getDirection() != kInDirection && !trueDataType->isString())) || - (trueDataType->isFunction() && - (it->getDirection() == kOutDirection || it->getDirection() == kInoutDirection))) + (it->getDirection() != param_direction_t::kInDirection && !trueDataType->isString())) || + (trueDataType->isFunction() && (it->getDirection() == param_direction_t::kOutDirection || + it->getDirection() == param_direction_t::kInoutDirection))) { paramSignature = "* " + paramSignature; } @@ -2031,7 +2033,7 @@ string CGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const st if ((dataType->isString() || dataType->isFunction() || trueDataType->isStruct() || trueDataType->isList() || trueDataType->isArray() || trueDataType->isBinary() || trueDataType->isUnion()) && - it->getDirection() == kInDirection) + it->getDirection() == param_direction_t::kInDirection) { bool pass = true; if (trueDataType->isArray()) @@ -2071,10 +2073,11 @@ string CGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const st // Todo: Need check if members are/aren't shared. if (group != nullptr) { - const set<_param_direction> directions = group->getSymbolDirections(structType); + const set directions = group->getSymbolDirections(structType); if (!findAnnotation(it, SHARED_ANNOTATION) && - (directions.count(kInoutDirection) && - (directions.count(kOutDirection) || directions.count(kReturn)))) + (directions.count(param_direction_t::kInoutDirection) && + (directions.count(param_direction_t::kOutDirection) || + directions.count(param_direction_t::kReturn)))) { throw syntax_error( format_string("line %d: structs, lists, and binary cannot be used as both " @@ -2132,7 +2135,7 @@ string CGenerator::getTypenameName(DataType *t, const string &name) string returnName; switch (t->getDataType()) { - case DataType::kArrayType: { + case DataType::data_type_t::kArrayType: { // Array type requires the array element count to come after the variable/member name. returnName = name; ArrayType *a = dynamic_cast(t); @@ -2142,7 +2145,7 @@ string CGenerator::getTypenameName(DataType *t, const string &name) returnName = getTypenameName(a->getElementType(), returnName); break; } - case DataType::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: { assert(nullptr != dynamic_cast(t)); returnName = getBuiltinTypename(dynamic_cast(t)); if (!(t->isString() && name != "" && name[0] == '*')) @@ -2152,14 +2155,14 @@ string CGenerator::getTypenameName(DataType *t, const string &name) returnName += name; break; } - case DataType::kListType: { + case DataType::data_type_t::kListType: { const ListType *a = dynamic_cast(t); assert(a); returnName = "* " + name; returnName = getTypenameName(a->getElementType(), returnName); break; } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { UnionType *unionType = dynamic_cast(t); assert(unionType); if (unionType->isNonEncapsulatedUnion()) @@ -2175,15 +2178,15 @@ string CGenerator::getTypenameName(DataType *t, const string &name) } break; } - case DataType::kVoidType: { + case DataType::data_type_t::kVoidType: { returnName = "void"; returnName += returnSpaceWhenNotEmpty(name) + name; break; } - case DataType::kAliasType: - case DataType::kEnumType: - case DataType::kFunctionType: - case DataType::kStructType: { + case DataType::data_type_t::kAliasType: + case DataType::data_type_t::kEnumType: + case DataType::data_type_t::kFunctionType: + case DataType::data_type_t::kStructType: { returnName = getOutputName(t); returnName += returnSpaceWhenNotEmpty(name) + name; break; @@ -2199,33 +2202,33 @@ string CGenerator::getBuiltinTypename(const BuiltinType *t) { switch (t->getBuiltinType()) { - case BuiltinType::kBoolType: + case BuiltinType::builtin_type_t::kBoolType: return "bool"; - case BuiltinType::kInt8Type: + case BuiltinType::builtin_type_t::kInt8Type: return "int8_t"; - case BuiltinType::kInt16Type: + case BuiltinType::builtin_type_t::kInt16Type: return "int16_t"; - case BuiltinType::kInt32Type: + case BuiltinType::builtin_type_t::kInt32Type: return "int32_t"; - case BuiltinType::kInt64Type: + case BuiltinType::builtin_type_t::kInt64Type: return "int64_t"; - case BuiltinType::kUInt8Type: + case BuiltinType::builtin_type_t::kUInt8Type: return "uint8_t"; - case BuiltinType::kUInt16Type: + case BuiltinType::builtin_type_t::kUInt16Type: return "uint16_t"; - case BuiltinType::kUInt32Type: + case BuiltinType::builtin_type_t::kUInt32Type: return "uint32_t"; - case BuiltinType::kUInt64Type: + case BuiltinType::builtin_type_t::kUInt64Type: return "uint64_t"; - case BuiltinType::kFloatType: + case BuiltinType::builtin_type_t::kFloatType: return "float"; - case BuiltinType::kDoubleType: + case BuiltinType::builtin_type_t::kDoubleType: return "double"; - case BuiltinType::kStringType: + case BuiltinType::builtin_type_t::kStringType: return "char *"; - case BuiltinType::kUStringType: + case BuiltinType::builtin_type_t::kUStringType: return "unsigned char*"; - case BuiltinType::kBinaryType: + case BuiltinType::builtin_type_t::kBinaryType: return "uint8_t *"; default: throw internal_error("unknown builtin type"); @@ -2241,10 +2244,11 @@ void CGenerator::getEncodeDecodeBuiltin(Group *group, BuiltinType *t, data_map & if (t->isString()) { templateData["checkStringNull"] = false; - templateData["withoutAlloc"] = ((structMember->getDirection() == kInoutDirection) || - (structType && group->getSymbolDirections(structType).count(kInoutDirection))) ? - true : - false; + templateData["withoutAlloc"] = + ((structMember->getDirection() == param_direction_t::kInoutDirection) || + (structType && group->getSymbolDirections(structType).count(param_direction_t::kInoutDirection))) ? + true : + false; if (!isFunctionParam) { templateData["stringAllocSize"] = getOutputName(structMember) + "_len"; @@ -2262,7 +2266,8 @@ void CGenerator::getEncodeDecodeBuiltin(Group *group, BuiltinType *t, data_map & templateData["checkStringNull"] = true; templateData["stringLocalName"] = getOutputName(structMember); templateData["stringAllocSize"] = getAnnStringValue(structMember, MAX_LENGTH_ANNOTATION); - if (structMember->getDirection() == kInoutDirection || structMember->getDirection() == kOutDirection) + if ((structMember->getDirection() == param_direction_t::kInoutDirection) || + (structMember->getDirection() == param_direction_t::kOutDirection)) { templateData["withoutAlloc"] = true; } @@ -2317,10 +2322,11 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT (structType && findAnnotation(structType, SHARED_ANNOTATION))) { templateData["funcParam"] = (structType) ? true : false; - templateData["InoutOutDirection"] = (structMember && (structMember->getDirection() == kOutDirection || - structMember->getDirection() == kInoutDirection)) ? - true : - false; + templateData["InoutOutDirection"] = + (structMember && (structMember->getDirection() == param_direction_t::kOutDirection || + structMember->getDirection() == param_direction_t::kInoutDirection)) ? + true : + false; templateData["encode"] = m_templateData["encodeSharedType"]; templateData["decode"] = m_templateData["decodeSharedType"]; templateData["name"] = name; @@ -2386,7 +2392,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT if (t->isScalar() || t->isEnum()) { templateData["pointerScalarTypes"] = false; - if (!inDataContainer && structMember && structMember->getDirection() != kInDirection) + if (!inDataContainer && structMember && structMember->getDirection() != param_direction_t::kInDirection) { DataType *trueDataType = t->getTrueDataType(); if (trueDataType->isScalar() || trueDataType->isEnum()) @@ -2398,13 +2404,13 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT switch (t->getDataType()) { - case DataType::kAliasType: { + case DataType::data_type_t::kAliasType: { AliasType *aliasType = dynamic_cast(t); assert(aliasType); return getEncodeDecodeCall(name, group, aliasType->getElementType(), structType, inDataContainer, structMember, needTempVariable, isFunctionParam); } - case DataType::kArrayType: { + case DataType::data_type_t::kArrayType: { static uint8_t arrayCounter; ArrayType *arrayType = dynamic_cast(t); assert(arrayType); @@ -2417,7 +2423,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT // To improve code serialization/deserialization for scalar types when BasicCodec is used. templateData["builtinTypeName"] = - ((m_def->getCodecType() != InterfaceDefinition::kBasicCodec) || trueElementType->isBool()) ? + ((m_def->getCodecType() != InterfaceDefinition::codec_t::kBasicCodec) || trueElementType->isBool()) ? "" : getScalarTypename(elementType); @@ -2437,12 +2443,12 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT --arrayCounter; break; } - case DataType::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: { getEncodeDecodeBuiltin(group, dynamic_cast(t), templateData, structType, structMember, isFunctionParam); break; } - case DataType::kEnumType: { + case DataType::data_type_t::kEnumType: { needTempVariable = true; templateData["decode"] = m_templateData["decodeEnumType"]; templateData["encode"] = m_templateData["encodeEnumType"]; @@ -2457,7 +2463,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT } break; } - case DataType::kFunctionType: { + case DataType::data_type_t::kFunctionType: { FunctionType *funType = dynamic_cast(t); assert(funType); const FunctionType::c_function_list_t &callbacks = funType->getCallbackFuns(); @@ -2482,14 +2488,15 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT templateData["decode"] = m_templateData["decodeFunctionType"]; break; } - case DataType::kListType: { + case DataType::data_type_t::kListType: { ListType *listType = dynamic_cast(t); assert(listType); DataType *elementType = listType->getElementType(); DataType *trueElementType = elementType->getTrueDataType(); - bool isInOut = ((structMember->getDirection() == kInoutDirection) || - (!isFunctionParam && group->getSymbolDirections(structType).count(kInoutDirection))); + bool isInOut = ((structMember->getDirection() == param_direction_t::kInoutDirection) || + (!isFunctionParam && + group->getSymbolDirections(structType).count(param_direction_t::kInoutDirection))); bool isTopDataType = (isFunctionParam && structMember->getDataType()->getTrueDataType() == t); @@ -2504,7 +2511,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT // To improve code serialization/deserialization for scalar types when BasicCodec is used. templateData["builtinTypeName"] = - ((m_def->getCodecType() != InterfaceDefinition::kBasicCodec) || trueElementType->isBool()) ? + ((m_def->getCodecType() != InterfaceDefinition::codec_t::kBasicCodec) || trueElementType->isBool()) ? "" : getScalarTypename(elementType); @@ -2562,7 +2569,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT { StructMember *lengthVariable = dynamic_cast(symbol); assert(lengthVariable); - if (lengthVariable->getDirection() != kInDirection) + if (lengthVariable->getDirection() != param_direction_t::kInDirection) { templateData["pointerScalarTypes"] = true; } @@ -2626,7 +2633,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT structMember, needTempVariable, isFunctionParam); break; } - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { // needDealloc(templateData, t, structType, structMember); string typeName = getOutputName(t); if (typeName != "") @@ -2646,7 +2653,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT } break; } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { UnionType *unionType = dynamic_cast(t); assert(unionType); @@ -2673,7 +2680,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT templateData["discrimPtr"] = false; if (isFunctionParam) { - if (structMember->getDirection() != kInDirection) + if (structMember->getDirection() != param_direction_t::kInDirection) { templateData["discrimPtr"] = true; } @@ -2793,9 +2800,10 @@ string CGenerator::getExtraDirectionPointer(StructMember *structMember) { DataType *dataType = structMember->getDataType(); DataType *trueDataType = dataType->getTrueDataType(); - _param_direction structMemberDir = structMember->getDirection(); + param_direction_t structMemberDir = structMember->getDirection(); string result; - if (structMemberDir == kOutDirection) // between out and inout can be differences in future. Maybe not. + if (structMemberDir == + param_direction_t::kOutDirection) // between out and inout can be differences in future. Maybe not. { if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isList() && !trueDataType->isArray()) @@ -2807,7 +2815,7 @@ string CGenerator::getExtraDirectionPointer(StructMember *structMember) result += "*"; } } - else if (structMemberDir == kInoutDirection) + else if (structMemberDir == param_direction_t::kInoutDirection) { if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isList() && !trueDataType->isArray()) @@ -2848,10 +2856,10 @@ data_map CGenerator::firstAllocOnServerWhenIsNeed(const string &name, StructMemb { DataType *dataType = structMember->getDataType(); DataType *trueDataType = dataType->getTrueDataType(); - _param_direction structMemberDir = structMember->getDirection(); + param_direction_t structMemberDir = structMember->getDirection(); if (!findAnnotation(structMember, SHARED_ANNOTATION)) { - if (structMemberDir == kInoutDirection) + if (structMemberDir == param_direction_t::kInoutDirection) { if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isList() && !trueDataType->isArray()) @@ -2859,14 +2867,14 @@ data_map CGenerator::firstAllocOnServerWhenIsNeed(const string &name, StructMemb return allocateCall(name, structMember); } } - else if (structMemberDir == kInDirection) + else if (structMemberDir == param_direction_t::kInDirection) { if (trueDataType->isStruct() || trueDataType->isUnion()) { return allocateCall(name, structMember); } } - else if (structMember->getDirection() == kOutDirection) + else if (structMember->getDirection() == param_direction_t::kOutDirection) { if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isArray()) { @@ -2898,27 +2906,27 @@ bool CGenerator::isNeedCallFree(DataType *dataType) DataType *trueDataType = dataType->getTrueDataType(); switch (trueDataType->getDataType()) { - case DataType::kArrayType: { + case DataType::data_type_t::kArrayType: { ArrayType *arrayType = dynamic_cast(trueDataType); assert(arrayType); return isNeedCallFree(arrayType->getElementType()); } - case DataType::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: { BuiltinType *builtinType = dynamic_cast(trueDataType); assert(builtinType); return builtinType->isString() || builtinType->isBinary(); } - case DataType::kListType: { + case DataType::data_type_t::kListType: { return true; } - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { StructType *structType = dynamic_cast(trueDataType); assert(structType); set loopDetection; return structType->containListMember() || structType->containStringMember() || containsByrefParamToFree(structType, loopDetection); } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { UnionType *unionType = dynamic_cast(trueDataType); assert(unionType); for (auto unionCase : unionType->getCases()) @@ -2956,7 +2964,7 @@ void CGenerator::setCallingFreeFunctions(Symbol *symbol, data_map &info, bool re if (!returnType) { if (trueDataType->isStruct() || trueDataType->isUnion() || - (trueDataType->isFunction() && ((structMember->getDirection() == kOutDirection)))) + (trueDataType->isFunction() && ((structMember->getDirection() == param_direction_t::kOutDirection)))) { string name = getOutputName(structMember, false); firstFreeingCall1["firstFreeingCall"] = m_templateData["freeData"]; @@ -3053,12 +3061,12 @@ bool CGenerator::containsString(DataType *dataType) DataType *trueDataType = dataType->getTrueContainerDataType(); switch (trueDataType->getDataType()) { - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { StructType *s = dynamic_cast(trueDataType); assert(s); return s->containStringMember(); } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { UnionType *u = dynamic_cast(trueDataType); assert(u); for (UnionCase *unionCase : u->getUniqueCases()) @@ -3096,12 +3104,12 @@ bool CGenerator::containsList(DataType *dataType) DataType *trueDataType = dataType->getTrueContainerDataType(); switch (trueDataType->getDataType()) { - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { StructType *s = dynamic_cast(trueDataType); assert(s); return s->containListMember(); } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { UnionType *u = dynamic_cast(trueDataType); assert(u); for (UnionCase *unionCase : u->getUniqueCases()) @@ -3269,7 +3277,7 @@ bool CGenerator::setDiscriminatorTemp(UnionType *unionType, StructType *structTy } BuiltinType *disBuiltin = dynamic_cast(disType->getTrueDataType()); - if (disBuiltin && disBuiltin->getBuiltinType() == BuiltinType::kInt32Type) + if (disBuiltin && disBuiltin->getBuiltinType() == BuiltinType::builtin_type_t::kInt32Type) { templateData["castDiscriminator"] = false; } @@ -3311,17 +3319,17 @@ string CGenerator::getScalarTypename(DataType *dataType) } } -string CGenerator::getDirection(_param_direction direction) +string CGenerator::getDirection(param_direction_t direction) { switch (direction) { - case kInDirection: + case param_direction_t::kInDirection: return "kInDirection"; - case kOutDirection: + case param_direction_t::kOutDirection: return "kOutDirection"; - case kInoutDirection: + case param_direction_t::kInoutDirection: return "kInoutDirection"; - case kReturn: + case param_direction_t::kReturn: return "kReturn"; default: throw semantic_error("Unsupported direction type"); @@ -3498,7 +3506,8 @@ void CGenerator::scanStructForAnnotations(StructType *currentStructType, bool is lengthAnn->getLocation().m_firstLine, structMember->getLocation().m_firstLine)); } // Verify using max_length annotation when referenced variable is out. - else if (isFunction && structMemberRef && structMemberRef->getDirection() == kOutDirection && + else if (isFunction && structMemberRef && + structMemberRef->getDirection() == param_direction_t::kOutDirection && !findAnnotation(structMember, MAX_LENGTH_ANNOTATION)) { throw semantic_error( @@ -3507,8 +3516,9 @@ void CGenerator::scanStructForAnnotations(StructType *currentStructType, bool is lengthAnn->getLocation().m_firstLine, structMember->getLocation().m_firstLine)); } // Verify using max_length annotation when referenced variable is inout. - else if (isFunction && structMemberRef && structMember->getDirection() == kInoutDirection && - structMemberRef->getDirection() == kInoutDirection && + else if (isFunction && structMemberRef && + structMember->getDirection() == param_direction_t::kInoutDirection && + structMemberRef->getDirection() == param_direction_t::kInoutDirection && !findAnnotation(structMember, MAX_LENGTH_ANNOTATION)) { throw semantic_error( diff --git a/erpcgen/src/CGenerator.hpp b/erpcgen/src/CGenerator.hpp index 844ae6bc..23003ebc 100644 --- a/erpcgen/src/CGenerator.hpp +++ b/erpcgen/src/CGenerator.hpp @@ -51,7 +51,7 @@ class CGenerator : public Generator virtual void generate() override; private: - enum _direction + enum class direction_t { kIn, kOut, @@ -577,7 +577,7 @@ class CGenerator : public Generator * @param[in,out] toServer List of data types designed for server direction. * @param[in] dataMap Map with information about structure or function parameter. */ - void setSymbolDataToSide(const Symbol *symbolType, const std::set<_param_direction> &directions, + void setSymbolDataToSide(const Symbol *symbolType, const std::set &directions, cpptempl::data_list &toClient, cpptempl::data_list &toServer, cpptempl::data_map &dataMap); /*! @@ -726,7 +726,7 @@ class CGenerator : public Generator * * @return String representation for given direction. */ - std::string getDirection(_param_direction direction); + std::string getDirection(param_direction_t direction); /*! * @brief This function returns information if function parameter on server side need be initialized to NULL. diff --git a/erpcgen/src/Generator.cpp b/erpcgen/src/Generator.cpp index fcb06611..86e1c082 100644 --- a/erpcgen/src/Generator.cpp +++ b/erpcgen/src/Generator.cpp @@ -108,7 +108,7 @@ Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) data_list groupNames; Group *defaultGroup = new Group(""); - for (auto it : m_globals->getSymbolsOfType(Symbol::kInterfaceSymbol)) + for (auto it : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kInterfaceSymbol)) { Interface *iface = dynamic_cast(it); assert(iface); @@ -156,7 +156,7 @@ Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) // set codec information switch (m_def->getCodecType()) { - case InterfaceDefinition::kBasicCodec: { + case InterfaceDefinition::codec_t::kBasicCodec: { m_templateData["codecClass"] = "BasicCodec"; m_templateData["codecHeader"] = "erpc_basic_codec.hpp"; break; @@ -311,7 +311,7 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat switch (dataType->getDataType()) { - case DataType::kAliasType: { + case DataType::data_type_t::kAliasType: { AliasType *aliasType = dynamic_cast(dataType); if (aliasType != nullptr) { @@ -319,7 +319,7 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - case DataType::kArrayType: { + case DataType::data_type_t::kArrayType: { ArrayType *arrayType = dynamic_cast(dataType); if (arrayType != nullptr) { @@ -327,7 +327,7 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - case DataType::kListType: { + case DataType::data_type_t::kListType: { ListType *listType = dynamic_cast(dataType); if (listType != nullptr) { @@ -335,7 +335,7 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { StructType *structType = dynamic_cast(dataType); if (structType != nullptr) { @@ -346,7 +346,7 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { // Keil need extra pragma option when unions are used. m_templateData["usedUnionType"] = true; UnionType *unionType = dynamic_cast(dataType); @@ -386,7 +386,7 @@ void Generator::findGroupDataTypes() { for (DataType *dataType : dataTypes) { - group->addDirToSymbolsMap(dataType, kReturn); + group->addDirToSymbolsMap(dataType, param_direction_t::kReturn); } } @@ -474,7 +474,7 @@ void Generator::generateGroupOutputFiles(Group *group) m_templateData["group"] = group->getTemplate(); // Log template data. - if (Log::getLogger()->getFilterLevel() >= Logger::kDebug2) + if (Log::getLogger()->getFilterLevel() >= Logger::log_level_t::kDebug2) { dump_data(m_templateData); } @@ -579,13 +579,13 @@ string Generator::getOutputName(Symbol *symbol, bool check) Annotation::program_lang_t Generator::getAnnotationLang() { - if (m_generatorType == kC) + if (m_generatorType == generator_type_t::kC) { - return Annotation::kC; + return Annotation::program_lang_t::kC; } - else if (m_generatorType == kPython) + else if (m_generatorType == generator_type_t::kPython) { - return Annotation::kPython; + return Annotation::program_lang_t::kPython; } throw internal_error("Unsupported generator type specified for annotation."); @@ -630,7 +630,7 @@ Generator::datatype_vector_t Generator::getDataTypesFromSymbolScope(SymbolScope { datatype_vector_t vector; - for (Symbol *symbol : scope->getSymbolsOfType(Symbol::kTypenameSymbol)) + for (Symbol *symbol : scope->getSymbolsOfType(Symbol::symbol_type_t::kTypenameSymbol)) { DataType *dataType = dynamic_cast(symbol); if (dataType->getDataType() == datatype) diff --git a/erpcgen/src/Generator.hpp b/erpcgen/src/Generator.hpp index 4d6c18db..64167de9 100644 --- a/erpcgen/src/Generator.hpp +++ b/erpcgen/src/Generator.hpp @@ -45,7 +45,7 @@ namespace erpcgen { class Generator { public: - enum generator_type_t + enum class generator_type_t { kC, kPython diff --git a/erpcgen/src/InterfaceDefinition.cpp b/erpcgen/src/InterfaceDefinition.cpp index 7d1e268a..88b74c13 100644 --- a/erpcgen/src/InterfaceDefinition.cpp +++ b/erpcgen/src/InterfaceDefinition.cpp @@ -33,7 +33,7 @@ InterfaceDefinition::InterfaceDefinition() , m_program(nullptr) , m_programName("") , m_outputFilename("") -, m_codec(kNotSpecified) +, m_codec(codec_t::kNotSpecified) , m_idlCrc16(0) { init(); @@ -73,20 +73,20 @@ void InterfaceDefinition::parse(const char *inputFile) void InterfaceDefinition::createBuiltinTypes() { - m_globals.addSymbol(new BuiltinType("bool", BuiltinType::_builtin_type::kBoolType)); - m_globals.addSymbol(new BuiltinType("int8", BuiltinType::_builtin_type::kInt8Type)); - m_globals.addSymbol(new BuiltinType("int16", BuiltinType::_builtin_type::kInt16Type)); - m_globals.addSymbol(new BuiltinType("int32", BuiltinType::_builtin_type::kInt32Type)); - m_globals.addSymbol(new BuiltinType("int64", BuiltinType::_builtin_type::kInt64Type)); - m_globals.addSymbol(new BuiltinType("uint8", BuiltinType::_builtin_type::kUInt8Type)); - m_globals.addSymbol(new BuiltinType("uint16", BuiltinType::_builtin_type::kUInt16Type)); - m_globals.addSymbol(new BuiltinType("uint32", BuiltinType::_builtin_type::kUInt32Type)); - m_globals.addSymbol(new BuiltinType("uint64", BuiltinType::_builtin_type::kUInt64Type)); - m_globals.addSymbol(new BuiltinType("float", BuiltinType::_builtin_type::kFloatType)); - m_globals.addSymbol(new BuiltinType("double", BuiltinType::_builtin_type::kDoubleType)); - m_globals.addSymbol(new BuiltinType("string", BuiltinType::_builtin_type::kStringType)); - m_globals.addSymbol(new BuiltinType("ustring", BuiltinType::_builtin_type::kUStringType)); - m_globals.addSymbol(new BuiltinType("binary", BuiltinType::_builtin_type::kBinaryType)); + m_globals.addSymbol(new BuiltinType("bool", BuiltinType::builtin_type_t::kBoolType)); + m_globals.addSymbol(new BuiltinType("int8", BuiltinType::builtin_type_t::kInt8Type)); + m_globals.addSymbol(new BuiltinType("int16", BuiltinType::builtin_type_t::kInt16Type)); + m_globals.addSymbol(new BuiltinType("int32", BuiltinType::builtin_type_t::kInt32Type)); + m_globals.addSymbol(new BuiltinType("int64", BuiltinType::builtin_type_t::kInt64Type)); + m_globals.addSymbol(new BuiltinType("uint8", BuiltinType::builtin_type_t::kUInt8Type)); + m_globals.addSymbol(new BuiltinType("uint16", BuiltinType::builtin_type_t::kUInt16Type)); + m_globals.addSymbol(new BuiltinType("uint32", BuiltinType::builtin_type_t::kUInt32Type)); + m_globals.addSymbol(new BuiltinType("uint64", BuiltinType::builtin_type_t::kUInt64Type)); + m_globals.addSymbol(new BuiltinType("float", BuiltinType::builtin_type_t::kFloatType)); + m_globals.addSymbol(new BuiltinType("double", BuiltinType::builtin_type_t::kDoubleType)); + m_globals.addSymbol(new BuiltinType("string", BuiltinType::builtin_type_t::kStringType)); + m_globals.addSymbol(new BuiltinType("ustring", BuiltinType::builtin_type_t::kUStringType)); + m_globals.addSymbol(new BuiltinType("binary", BuiltinType::builtin_type_t::kBinaryType)); } void InterfaceDefinition::setProgramInfo(const string &filename, const string &outputDir, codec_t codec) diff --git a/erpcgen/src/InterfaceDefinition.hpp b/erpcgen/src/InterfaceDefinition.hpp index d4696550..2431aace 100644 --- a/erpcgen/src/InterfaceDefinition.hpp +++ b/erpcgen/src/InterfaceDefinition.hpp @@ -31,7 +31,7 @@ namespace erpcgen { class InterfaceDefinition { public: - enum codec_t + enum class codec_t { kNotSpecified, kBasicCodec, diff --git a/erpcgen/src/Logging.cpp b/erpcgen/src/Logging.cpp index 0f4b6ed1..82f6fce8 100644 --- a/erpcgen/src/Logging.cpp +++ b/erpcgen/src/Logging.cpp @@ -120,7 +120,7 @@ void Log::urgent(const char *fmt, ...) { va_list args; va_start(args, fmt); - s_logger->log(Logger::kUrgent, fmt, args); + s_logger->log(Logger::log_level_t::kUrgent, fmt, args); va_end(args); } } @@ -131,7 +131,7 @@ void Log::error(const char *fmt, ...) { va_list args; va_start(args, fmt); - s_logger->log(Logger::kError, fmt, args); + s_logger->log(Logger::log_level_t::kError, fmt, args); va_end(args); } } @@ -142,7 +142,7 @@ void Log::warning(const char *fmt, ...) { va_list args; va_start(args, fmt); - s_logger->log(Logger::kWarning, fmt, args); + s_logger->log(Logger::log_level_t::kWarning, fmt, args); va_end(args); } } @@ -153,7 +153,7 @@ void Log::info(const char *fmt, ...) { va_list args; va_start(args, fmt); - s_logger->log(Logger::kInfo, fmt, args); + s_logger->log(Logger::log_level_t::kInfo, fmt, args); va_end(args); } } @@ -164,7 +164,7 @@ void Log::info2(const char *fmt, ...) { va_list args; va_start(args, fmt); - s_logger->log(Logger::kInfo2, fmt, args); + s_logger->log(Logger::log_level_t::kInfo2, fmt, args); va_end(args); } } @@ -175,7 +175,7 @@ void Log::debug(const char *fmt, ...) { va_list args; va_start(args, fmt); - s_logger->log(Logger::kDebug, fmt, args); + s_logger->log(Logger::log_level_t::kDebug, fmt, args); va_end(args); } } @@ -186,7 +186,7 @@ void Log::debug2(const char *fmt, ...) { va_list args; va_start(args, fmt); - s_logger->log(Logger::kDebug2, fmt, args); + s_logger->log(Logger::log_level_t::kDebug2, fmt, args); va_end(args); } } diff --git a/erpcgen/src/Logging.hpp b/erpcgen/src/Logging.hpp index fab7a45a..244d5f94 100644 --- a/erpcgen/src/Logging.hpp +++ b/erpcgen/src/Logging.hpp @@ -47,7 +47,7 @@ class Logger { public: //! \brief Logging levels. - enum log_level_t + enum class log_level_t { kUrgent = 0, //!< The lowest level, for messages that must always be logged. kError, //!< For fatal error messages. @@ -63,8 +63,8 @@ class Logger public: //! \brief Default constructor. Logger() - : m_filter(kInfo) - , m_level(kInfo) + : m_filter(log_level_t::kInfo) + , m_level(log_level_t::kInfo) { } @@ -199,7 +199,7 @@ class Log //! as managed by the Log class, and sets the new level to \a level. explicit SetOutputLevel(Logger::log_level_t level) : m_logger(Log::getLogger()) - , m_saved(Logger::kInfo) + , m_saved(Logger::log_level_t::kInfo) { assert(m_logger); m_saved = m_logger->getOutputLevel(); @@ -236,7 +236,7 @@ class StdoutLogger : public Logger { public: //! \brief Default constructor. - StdoutLogger(Logger::log_level_t stderrLevel = Logger::kWarning) + explicit StdoutLogger(Logger::log_level_t stderrLevel = Logger::log_level_t::kWarning) : m_stderrLevel(stderrLevel) { } diff --git a/erpcgen/src/PythonGenerator.cpp b/erpcgen/src/PythonGenerator.cpp index 2cb07984..d42865e5 100644 --- a/erpcgen/src/PythonGenerator.cpp +++ b/erpcgen/src/PythonGenerator.cpp @@ -38,7 +38,7 @@ extern const char *const kPyGlobalInit; //////////////////////////////////////////////////////////////////////////////// PythonGenerator::PythonGenerator(InterfaceDefinition *def) -: Generator(def, kPython) +: Generator(def, generator_type_t::kPython) , m_suffixStrip("") , m_suffixStripSize(0) { @@ -165,8 +165,8 @@ void PythonGenerator::generate() void PythonGenerator::setTemplateComments(Symbol *symbol, data_map &symbolInfo) { - symbolInfo["mlComment"] = convertComment(symbol->getMlComment(), kMultilineComment); - symbolInfo["ilComment"] = convertComment(symbol->getIlComment(), kInlineComment); + symbolInfo["mlComment"] = convertComment(symbol->getMlComment(), comment_type_t::kMultilineComment); + symbolInfo["ilComment"] = convertComment(symbol->getIlComment(), comment_type_t::kInlineComment); } data_map PythonGenerator::getFunctionTemplateData(Group *group, Function *fn) @@ -236,18 +236,18 @@ data_map PythonGenerator::getFunctionTemplateData(Group *group, Function *fn) /* Necessary for handling non-discriminated unions */ paramInfo["discriminator"] = getAnnStringValue(param, DISCRIMINATOR_ANNOTATION); - _param_direction dir = param->getDirection(); + param_direction_t dir = param->getDirection(); switch (dir) { - case kInDirection: + case param_direction_t::kInDirection: paramInfo["direction"] = "in"; inParams.push_back(paramInfo); break; - case kOutDirection: + case param_direction_t::kOutDirection: paramInfo["direction"] = "out"; outParams.push_back(paramInfo); break; - case kInoutDirection: + case param_direction_t::kInoutDirection: paramInfo["direction"] = "inout"; inParams.push_back(paramInfo); outParams.push_back(paramInfo); @@ -294,7 +294,7 @@ void PythonGenerator::makeConstTemplateData() { Log::info("Constant globals:\n"); data_list consts; - for (auto it : m_globals->getSymbolsOfType(Symbol::kConstSymbol)) + for (auto it : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kConstSymbol)) { ConstType *constVar = dynamic_cast(it); assert(constVar); @@ -330,7 +330,7 @@ void PythonGenerator::makeEnumsTemplateData() Log::info("Enums:\n"); data_list enums; int n = 0; - for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::kEnumType)) + for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kEnumType)) { EnumType *enumType = dynamic_cast(it); assert(enumType); @@ -371,7 +371,7 @@ void PythonGenerator::makeAliasesTemplateData() Log::info("Type definition:\n"); data_list aliases; int n = 0; - for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::kAliasType)) + for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kAliasType)) { AliasType *aliasType = dynamic_cast(it); assert(aliasType); @@ -428,7 +428,7 @@ data_map PythonGenerator::makeGroupSymbolsTemplateData(Group *group) switch (dataType->getDataType()) { - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { StructType *structType = dynamic_cast(symbol); if (structType == nullptr) { @@ -452,7 +452,7 @@ data_map PythonGenerator::makeGroupSymbolsTemplateData(Group *group) } break; } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { UnionType *unionType = dynamic_cast(symbol); if (unionType == nullptr) { @@ -482,7 +482,7 @@ data_map PythonGenerator::makeGroupSymbolsTemplateData(Group *group) } break; } - case DataType::kAliasType: { + case DataType::data_type_t::kAliasType: { AliasType *aliasType = dynamic_cast(symbol); if (aliasType == nullptr) break; @@ -577,7 +577,7 @@ void PythonGenerator::makeFunctionsTemplateData() /* type definitions of functions and table of functions */ Log::info("Functions:\n"); data_list functions; - for (Symbol *functionTypeSymbol : getDataTypesFromSymbolScope(m_globals, DataType::kFunctionType)) + for (Symbol *functionTypeSymbol : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kFunctionType)) { FunctionType *functionType = dynamic_cast(functionTypeSymbol); data_map functionInfo; @@ -605,11 +605,11 @@ data_map PythonGenerator::getTypeInfo(DataType *t) info["isNonEncapsulatedUnion"] = false; switch (t->getDataType()) { - case DataType::kAliasType: { + case DataType::data_type_t::kAliasType: { info = getTypeInfo(t->getTrueDataType()); break; } - case DataType::kArrayType: { + case DataType::data_type_t::kArrayType: { // Array type requires the array element count to come after the variable/member name. ArrayType *a = dynamic_cast(t); assert(a); @@ -618,16 +618,16 @@ data_map PythonGenerator::getTypeInfo(DataType *t) info["elementType"] = getTypeInfo(a->getElementType()); break; } - case DataType::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: { assert(dynamic_cast(t)); info["type"] = getBuiltinTypename(dynamic_cast(t)); break; } - case DataType::kEnumType: { + case DataType::data_type_t::kEnumType: { info["type"] = "enum"; break; } - case DataType::kFunctionType: { + case DataType::data_type_t::kFunctionType: { info["type"] = "function"; FunctionType *funType = dynamic_cast(t); assert(funType); @@ -649,18 +649,18 @@ data_map PythonGenerator::getTypeInfo(DataType *t) } break; } - case DataType::kListType: { + case DataType::data_type_t::kListType: { const ListType *a = dynamic_cast(t); assert(a); info["type"] = "list"; info["elementType"] = getTypeInfo(a->getElementType()); break; } - case DataType::kStructType: { + case DataType::data_type_t::kStructType: { info["type"] = "struct"; break; } - case DataType::kUnionType: { + case DataType::data_type_t::kUnionType: { UnionType *unionType = dynamic_cast(t); assert(unionType); info["type"] = "union"; @@ -705,7 +705,7 @@ data_map PythonGenerator::getTypeInfo(DataType *t) } else if (unionCase->getCaseName() != "") { - for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::kEnumType)) + for (auto it : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kEnumType)) { EnumType *enumType = dynamic_cast(it); assert(enumType); @@ -727,7 +727,7 @@ data_map PythonGenerator::getTypeInfo(DataType *t) } if (!caseData.has("type")) { - for (auto it : m_globals->getSymbolsOfType(DataType::kConstSymbol)) + for (auto it : m_globals->getSymbolsOfType(DataType::symbol_type_t::kConstSymbol)) { ConstType *constType = dynamic_cast(it); assert(constType); @@ -779,7 +779,7 @@ data_map PythonGenerator::getTypeInfo(DataType *t) info["cases"] = unionCases; break; } - case DataType::kVoidType: { + case DataType::data_type_t::kVoidType: { info["type"] = "void"; break; } @@ -793,31 +793,31 @@ string PythonGenerator::getBuiltinTypename(const BuiltinType *t) { switch (t->getBuiltinType()) { - case BuiltinType::kBoolType: + case BuiltinType::builtin_type_t::kBoolType: return "bool"; - case BuiltinType::kInt8Type: + case BuiltinType::builtin_type_t::kInt8Type: return "int8"; - case BuiltinType::kInt16Type: + case BuiltinType::builtin_type_t::kInt16Type: return "int16"; - case BuiltinType::kInt32Type: + case BuiltinType::builtin_type_t::kInt32Type: return "int32"; - case BuiltinType::kInt64Type: + case BuiltinType::builtin_type_t::kInt64Type: return "int64"; - case BuiltinType::kUInt8Type: + case BuiltinType::builtin_type_t::kUInt8Type: return "uint8"; - case BuiltinType::kUInt16Type: + case BuiltinType::builtin_type_t::kUInt16Type: return "uint16"; - case BuiltinType::kUInt32Type: + case BuiltinType::builtin_type_t::kUInt32Type: return "uint32"; - case BuiltinType::kUInt64Type: + case BuiltinType::builtin_type_t::kUInt64Type: return "uint64"; - case BuiltinType::kFloatType: + case BuiltinType::builtin_type_t::kFloatType: return "float"; - case BuiltinType::kDoubleType: + case BuiltinType::builtin_type_t::kDoubleType: return "double"; - case BuiltinType::kStringType: + case BuiltinType::builtin_type_t::kStringType: return "string"; - case BuiltinType::kBinaryType: + case BuiltinType::builtin_type_t::kBinaryType: return "binary"; default: throw internal_error("unknown builtin type"); @@ -838,7 +838,7 @@ string PythonGenerator::filterName(const string &name) return result; } -string PythonGenerator::convertComment(const string &comment, comment_type commentType) +string PythonGenerator::convertComment(const string &comment, comment_type_t commentType) { (void)commentType; // Longer patterns are ordered earlier than similar shorter patterns. diff --git a/erpcgen/src/PythonGenerator.hpp b/erpcgen/src/PythonGenerator.hpp index f20179c4..3e392526 100644 --- a/erpcgen/src/PythonGenerator.hpp +++ b/erpcgen/src/PythonGenerator.hpp @@ -235,7 +235,7 @@ class PythonGenerator : public Generator std::string filterName(const std::string &name); //! @brief Possible Doxygen comment styles. - enum comment_type + enum class comment_type_t { kMultilineComment, //!< Leading multi-line comment kInlineComment, //!< Trailing inline comment. @@ -249,7 +249,7 @@ class PythonGenerator : public Generator * * @return Python form of the provided comment. */ - std::string convertComment(const std::string &comment, comment_type commentType); + std::string convertComment(const std::string &comment, comment_type_t commentType); /*! * @brief Strip leading and trailing whitespace. diff --git a/erpcgen/src/SearchPath.hpp b/erpcgen/src/SearchPath.hpp index 6fde9b36..b5bd62f2 100644 --- a/erpcgen/src/SearchPath.hpp +++ b/erpcgen/src/SearchPath.hpp @@ -23,15 +23,12 @@ class PathSearcher { public: //! - enum _target_type + enum class target_type_t { kFindFile, kFindDirectory }; /*!< Type of searched item. */ - //! - typedef enum _target_type target_type_t; /*!< Type of searched item. */ - protected: //! Global search object singleton. static PathSearcher *s_searcher; diff --git a/erpcgen/src/SymbolScanner.cpp b/erpcgen/src/SymbolScanner.cpp index 94a23e7e..f5c12370 100644 --- a/erpcgen/src/SymbolScanner.cpp +++ b/erpcgen/src/SymbolScanner.cpp @@ -1165,7 +1165,7 @@ AstNode *SymbolScanner::handleFunction(AstNode *node, bottom_up) else /* function type */ { FunctionType *func = nullptr; - for (Symbol *funSymbol : m_globals->getSymbolsOfType(Symbol::kTypenameSymbol)) + for (Symbol *funSymbol : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kTypenameSymbol)) { DataType *datatype = dynamic_cast(funSymbol); assert(datatype); @@ -1201,7 +1201,7 @@ AstNode *SymbolScanner::handleParam(AstNode *node, top_down) if (m_currentInterface) { fun = m_currentInterface->getFunctions().back(); - for (Symbol *funSymbol : m_globals->getSymbolsOfType(Symbol::kTypenameSymbol)) + for (Symbol *funSymbol : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kTypenameSymbol)) { DataType *datatype = dynamic_cast(funSymbol); assert(datatype); @@ -1298,19 +1298,19 @@ AstNode *SymbolScanner::handleParam(AstNode *node, bottom_up) void SymbolScanner::setParameterDirection(StructMember *param, AstNode *directionNode) { /* Extract parameter direction: in/out/inout/out byref. */ - _param_direction param_direction; + param_direction_t param_direction; if (nullptr != directionNode) { switch (directionNode->getToken().getToken()) { case TOK_IN: - param_direction = kInDirection; + param_direction = param_direction_t::kInDirection; break; case TOK_OUT: - param_direction = kOutDirection; + param_direction = param_direction_t::kOutDirection; break; case TOK_INOUT: - param_direction = kInoutDirection; + param_direction = param_direction_t::kInoutDirection; break; default: delete param; @@ -1321,7 +1321,7 @@ void SymbolScanner::setParameterDirection(StructMember *param, AstNode *directio } else /* if no direction specified, default case is an 'in' variable */ { - param_direction = kInDirection; + param_direction = param_direction_t::kInDirection; } param->setDirection(param_direction); } @@ -1499,7 +1499,7 @@ void SymbolScanner::addAnnotations(AstNode *childNode, Symbol *symbol) { for (auto annotation : *childNode) { - Log::SetOutputLevel logLevel(Logger::kDebug); + Log::SetOutputLevel logLevel(Logger::log_level_t::kDebug); // name can be optional for struct/enum string nameOfType; @@ -1564,11 +1564,11 @@ Annotation::program_lang_t SymbolScanner::getAnnotationLang(AstNode *annotation) string lang = annotation_value->getToken().getValue()->toString(); if (lang.compare("c") == 0) { - return Annotation::kC; + return Annotation::program_lang_t::kC; } else if (lang.compare("py") == 0) { - return Annotation::kPython; + return Annotation::program_lang_t::kPython; } throw semantic_error(format_string("line %d: Unsupported programming language '%s' specified.", @@ -1576,7 +1576,7 @@ Annotation::program_lang_t SymbolScanner::getAnnotationLang(AstNode *annotation) .c_str()); } - return Annotation::kAll; + return Annotation::program_lang_t::kAll; } void SymbolScanner::checkAnnotationBeforeAdding(AstNode *annotation, Symbol *symbol) @@ -1645,7 +1645,8 @@ void SymbolScanner::scanStructForAnnotations() Symbol *disSymbol; if (unionType->isNonEncapsulatedUnion()) { - string discrimintorName = structMember->getAnnStringValue(DISCRIMINATOR_ANNOTATION, Annotation::kAll); + string discrimintorName = + structMember->getAnnStringValue(DISCRIMINATOR_ANNOTATION, Annotation::program_lang_t::kAll); if (discrimintorName.empty()) { throw syntax_error(format_string("Missing discriminator for union variable %s on line %d", diff --git a/erpcgen/src/UniqueIdChecker.cpp b/erpcgen/src/UniqueIdChecker.cpp index b9587041..48d102e6 100644 --- a/erpcgen/src/UniqueIdChecker.cpp +++ b/erpcgen/src/UniqueIdChecker.cpp @@ -28,21 +28,21 @@ using namespace std; void UniqueIdChecker::makeIdsUnique(erpcgen::InterfaceDefinition &def) { - initUsedInterfaceIds(def.getGlobals().getSymbolsOfType(Symbol::kInterfaceSymbol)); + initUsedInterfaceIds(def.getGlobals().getSymbolsOfType(Symbol::symbol_type_t::kInterfaceSymbol)); - for (auto it : def.getGlobals().getSymbolsOfType(Symbol::kInterfaceSymbol)) + for (auto it : def.getGlobals().getSymbolsOfType(Symbol::symbol_type_t::kInterfaceSymbol)) { assert(nullptr != it); Interface *interface = dynamic_cast(it); assert(interface); - if (Annotation *interfaceId = interface->findAnnotation(ID_ANNOTATION, Annotation::kAll)) + if (Annotation *interfaceId = interface->findAnnotation(ID_ANNOTATION, Annotation::program_lang_t::kAll)) { setInterfaceId(interface, interfaceId); } initUsedFunctionIds(interface); for (auto function : interface->getFunctions()) { - if (Annotation *functionId = function->findAnnotation(ID_ANNOTATION, Annotation::kAll)) + if (Annotation *functionId = function->findAnnotation(ID_ANNOTATION, Annotation::program_lang_t::kAll)) { setFunctionId(function, functionId); } diff --git a/erpcgen/src/cpptemplate/cpptempl.cpp b/erpcgen/src/cpptemplate/cpptempl.cpp index 9114f3fd..f1517927 100644 --- a/erpcgen/src/cpptemplate/cpptempl.cpp +++ b/erpcgen/src/cpptemplate/cpptempl.cpp @@ -51,7 +51,7 @@ void replaceAll(std::string &str, const std::string &from, const std::string &to namespace impl { // Types of tokens in control statements. -enum TokenType +enum class token_type_t { INVALID_TOKEN, KEY_PATH_TOKEN, @@ -94,16 +94,16 @@ enum TokenType // Represents a token in a control statement. class Token { - TokenType m_type; + token_type_t m_type; std::string m_value; public: - Token(TokenType tokenType) + Token(token_type_t tokenType) : m_type(tokenType) , m_value() { } - Token(TokenType tokenType, const std::string &value) + Token(token_type_t tokenType, const std::string &value) : m_type(tokenType) , m_value(value) { @@ -127,7 +127,7 @@ class Token } ~Token() = default; - TokenType get_type() const { return m_type; } + token_type_t get_type() const { return m_type; } const std::string &get_value() const { return m_value; } }; @@ -157,7 +157,7 @@ class TokenIterator bool is_valid() const { return m_index < size(); } const Token *get() const; const Token *next(); - const Token *match(TokenType tokenType, const char *failure_msg = nullptr); + const Token *match(token_type_t tokenType, const char *failure_msg = nullptr); void reset() { m_index = 0; } TokenIterator &operator++(); @@ -328,7 +328,7 @@ class NodeSet : public Node }; // Lexer states for statement tokenizer. -enum lexer_state_t +enum class lexer_state_t { INIT_STATE, //!< Initial state, skip whitespace, process single char tokens. KEY_PATH_STATE, //!< Scan a key path. @@ -339,7 +339,7 @@ enum lexer_state_t struct KeywordDef { - TokenType tok; + token_type_t tok; const char *keyword; }; @@ -348,12 +348,12 @@ class TemplateParser std::string m_text; node_vector &m_top_nodes; uint32_t m_current_line; - std::stack > m_node_stack; + std::stack > m_node_stack; node_ptr m_current_node; node_vector *m_current_nodes; bool m_eol_precedes; bool m_last_was_eol; - TokenType m_until; + token_type_t m_until; public: TemplateParser(const std::string &text, node_vector &nodes); @@ -365,13 +365,13 @@ class TemplateParser void parse_stmt(); void parse_comment(); - void push_node(Node *new_node, TokenType until); + void push_node(Node *new_node, token_type_t until); void check_omit_eol(size_t pos, bool force_omit); }; std::string indent(int level); inline bool is_key_path_char(char c); -TokenType get_keyword_token(const std::string &s); +token_type_t get_keyword_token(const std::string &s); void create_id_token(token_vector &tokens, const std::string &s); int append_string_escape(std::string &str, std::function peek); token_vector tokenize_statement(const std::string &text); @@ -759,7 +759,7 @@ std::string indent(int level) return result; } -Token TokenIterator::s_endToken(END_TOKEN); +Token TokenIterator::s_endToken(token_type_t::END_TOKEN); const Token *TokenIterator::get() const { @@ -782,7 +782,7 @@ const Token *TokenIterator::next() return get(); } -const Token *TokenIterator::match(TokenType tokenType, const char *failure_msg) +const Token *TokenIterator::match(token_type_t tokenType, const char *failure_msg) { const Token *result = get(); if (result->get_type() != tokenType) @@ -804,33 +804,33 @@ inline bool is_key_path_char(char c) return (isalnum(c) || c == '.' || c == '_'); } -const KeywordDef k_keywords[] = { { TRUE_TOKEN, "true" }, { FALSE_TOKEN, "false" }, { FOR_TOKEN, "for" }, - { IN_TOKEN, "in" }, { IF_TOKEN, "if" }, { ELIF_TOKEN, "elif" }, - { ELSE_TOKEN, "else" }, { DEF_TOKEN, "def" }, { SET_TOKEN, "set" }, - { ENDFOR_TOKEN, "endfor" }, { ENDIF_TOKEN, "endif" }, { ENDDEF_TOKEN, "enddef" }, - { AND_TOKEN, "and" }, { OR_TOKEN, "or" }, { NOT_TOKEN, "not" }, - { INVALID_TOKEN, NULL } }; +const KeywordDef k_keywords[] = { { token_type_t::TRUE_TOKEN, "true" }, { token_type_t::FALSE_TOKEN, "false" }, { token_type_t::FOR_TOKEN, "for" }, + { token_type_t::IN_TOKEN, "in" }, { token_type_t::IF_TOKEN, "if" }, { token_type_t::ELIF_TOKEN, "elif" }, + { token_type_t::ELSE_TOKEN, "else" }, { token_type_t::DEF_TOKEN, "def" }, { token_type_t::SET_TOKEN, "set" }, + { token_type_t::ENDFOR_TOKEN, "endfor" }, { token_type_t::ENDIF_TOKEN, "endif" }, { token_type_t::ENDDEF_TOKEN, "enddef" }, + { token_type_t::AND_TOKEN, "and" }, { token_type_t::OR_TOKEN, "or" }, { token_type_t::NOT_TOKEN, "not" }, + { token_type_t::INVALID_TOKEN, NULL } }; -TokenType get_keyword_token(const std::string &s) +token_type_t get_keyword_token(const std::string &s) { const KeywordDef *k = k_keywords; - for (; k->tok != INVALID_TOKEN; ++k) + for (; k->tok != token_type_t::INVALID_TOKEN; ++k) { if (s == k->keyword) { return k->tok; } } - return INVALID_TOKEN; + return token_type_t::INVALID_TOKEN; } void create_id_token(token_vector &tokens, const std::string &s) { - TokenType t = get_keyword_token(s); - if (t == INVALID_TOKEN) + token_type_t t = get_keyword_token(s); + if (t == token_type_t::INVALID_TOKEN) { // Create key path token. - tokens.emplace_back(KEY_PATH_TOKEN, s); + tokens.emplace_back(token_type_t::KEY_PATH_TOKEN, s); } else { @@ -886,7 +886,7 @@ int append_string_escape(std::string &str, std::function peek) token_vector tokenize_statement(const std::string &text) { token_vector tokens; - lexer_state_t state = INIT_STATE; + lexer_state_t state = lexer_state_t::INIT_STATE; unsigned i = 0; uint32_t pos = 0; char str_open_quote = 0; @@ -902,7 +902,7 @@ token_vector tokenize_statement(const std::string &text) switch (state) { - case INIT_STATE: + case lexer_state_t::INIT_STATE: // Skip any whitespace if (isspace(c)) { @@ -921,97 +921,97 @@ token_vector tokenize_statement(const std::string &text) { is_hex_literal = false; } - state = INT_LITERAL_STATE; + state = lexer_state_t::INT_LITERAL_STATE; } else if (is_key_path_char(c)) { pos = i; - state = KEY_PATH_STATE; + state = lexer_state_t::KEY_PATH_STATE; } else if (c == '(' || c == ')' || c == ',' || c == '+' || c == '*' || c == '/' || c == '%') { - tokens.emplace_back(static_cast(c)); + tokens.emplace_back(static_cast(c)); } else if (c == '\"' || c == '\'') { str_open_quote = c; literal.clear(); - state = STRING_LITERAL_STATE; + state = lexer_state_t::STRING_LITERAL_STATE; } else if (c == '=') { if (peek(1) == '=') { - tokens.emplace_back(EQ_TOKEN); + tokens.emplace_back(token_type_t::EQ_TOKEN); ++i; } else { - tokens.emplace_back(ASSIGN_TOKEN); + tokens.emplace_back(token_type_t::ASSIGN_TOKEN); } } else if (c == '>') { if (peek(1) == '=') { - tokens.emplace_back(GE_TOKEN); + tokens.emplace_back(token_type_t::GE_TOKEN); ++i; } else { - tokens.emplace_back(GT_TOKEN); + tokens.emplace_back(token_type_t::GT_TOKEN); } } else if (c == '<') { if (peek(1) == '=') { - tokens.emplace_back(LE_TOKEN); + tokens.emplace_back(token_type_t::LE_TOKEN); ++i; } else { - tokens.emplace_back(LT_TOKEN); + tokens.emplace_back(token_type_t::LT_TOKEN); } } else if (c == '!') { if (peek(1) == '=') { - tokens.emplace_back(NEQ_TOKEN); + tokens.emplace_back(token_type_t::NEQ_TOKEN); ++i; } else { - tokens.emplace_back(NOT_TOKEN); + tokens.emplace_back(token_type_t::NOT_TOKEN); } } else if (c == '&') { if (peek(1) == '&') { - tokens.emplace_back(AND_TOKEN); + tokens.emplace_back(token_type_t::AND_TOKEN); ++i; } else { - tokens.emplace_back(CONCAT_TOKEN); + tokens.emplace_back(token_type_t::CONCAT_TOKEN); } } else if (c == '|' && peek(1) == '|') { - tokens.emplace_back(OR_TOKEN); + tokens.emplace_back(token_type_t::OR_TOKEN); ++i; } else if (c == '-') { if (peek(1) == '-') { - state = COMMENT_STATE; + state = lexer_state_t::COMMENT_STATE; } else { - tokens.emplace_back(MINUS_TOKEN); + tokens.emplace_back(token_type_t::MINUS_TOKEN); } } else @@ -1023,23 +1023,23 @@ token_vector tokenize_statement(const std::string &text) } break; - case KEY_PATH_STATE: + case lexer_state_t::KEY_PATH_STATE: if (!is_key_path_char(c)) { create_id_token(tokens, text.substr(pos, i - pos)); // Reprocess this char in the initial state. - state = INIT_STATE; + state = lexer_state_t::INIT_STATE; --i; } break; - case STRING_LITERAL_STATE: + case lexer_state_t::STRING_LITERAL_STATE: if (c == str_open_quote) { // Create the string literal token and return to init state. - tokens.emplace_back(STRING_LITERAL_TOKEN, literal); - state = INIT_STATE; + tokens.emplace_back(token_type_t::STRING_LITERAL_TOKEN, literal); + state = lexer_state_t::INIT_STATE; } else if (c == '\\') { @@ -1051,40 +1051,40 @@ token_vector tokenize_statement(const std::string &text) } break; - case INT_LITERAL_STATE: + case lexer_state_t::INT_LITERAL_STATE: if (is_hex_literal ? isxdigit(c) : isdigit(c)) { literal += c; } else { - tokens.emplace_back(INT_LITERAL_TOKEN, literal); - state = INIT_STATE; + tokens.emplace_back(token_type_t::INT_LITERAL_TOKEN, literal); + state = lexer_state_t::INIT_STATE; --i; } break; - case COMMENT_STATE: + case lexer_state_t::COMMENT_STATE: if (c == '\n') { - state = INIT_STATE; + state = lexer_state_t::INIT_STATE; } break; } } // Handle a key path terminated by end of string. - if (state == KEY_PATH_STATE) + if (state == lexer_state_t::KEY_PATH_STATE) { create_id_token(tokens, text.substr(pos, i - pos)); } - else if (state == STRING_LITERAL_STATE) + else if (state == lexer_state_t::STRING_LITERAL_STATE) { throw TemplateException("unterminated string literal"); } - else if (state == INT_LITERAL_STATE) + else if (state == lexer_state_t::INT_LITERAL_STATE) { - tokens.emplace_back(INT_LITERAL_TOKEN, literal); + tokens.emplace_back(token_type_t::INT_LITERAL_TOKEN, literal); } return tokens; @@ -1217,57 +1217,57 @@ data_ptr ExprParser::get_var_value(const std::string &path, data_list ¶ms) data_ptr ExprParser::parse_factor() { - TokenType tokType = m_tok->get_type(); + token_type_t tokType = m_tok->get_type(); data_ptr result; switch (tokType) { - case NOT_TOKEN: + case token_type_t::NOT_TOKEN: m_tok.next(); result = parse_expr()->empty(); break; - case MINUS_TOKEN: + case token_type_t::MINUS_TOKEN: m_tok.next(); result = -(parse_expr()->getint()); break; - case OPEN_PAREN_TOKEN: + case token_type_t::OPEN_PAREN_TOKEN: m_tok.next(); result = parse_expr(); - m_tok.match(CLOSE_PAREN_TOKEN, "expected close paren"); + m_tok.match(token_type_t::CLOSE_PAREN_TOKEN, "expected close paren"); break; - case STRING_LITERAL_TOKEN: - result = m_tok.match(STRING_LITERAL_TOKEN)->get_value(); + case token_type_t::STRING_LITERAL_TOKEN: + result = m_tok.match(token_type_t::STRING_LITERAL_TOKEN)->get_value(); break; - case TRUE_TOKEN: + case token_type_t::TRUE_TOKEN: m_tok.next(); result = true; break; - case FALSE_TOKEN: + case token_type_t::FALSE_TOKEN: m_tok.next(); result = false; break; - case INT_LITERAL_TOKEN: { - const Token *literal = m_tok.match(INT_LITERAL_TOKEN, "expected int literal"); + case token_type_t::INT_LITERAL_TOKEN: { + const Token *literal = m_tok.match(token_type_t::INT_LITERAL_TOKEN, "expected int literal"); return new DataInt((int)std::strtol(literal->get_value().c_str(), NULL, 0)); break; } - case KEY_PATH_TOKEN: { - const Token *path = m_tok.match(KEY_PATH_TOKEN, "expected key path"); + case token_type_t::KEY_PATH_TOKEN: { + const Token *path = m_tok.match(token_type_t::KEY_PATH_TOKEN, "expected key path"); data_list params; - if (m_tok->get_type() == OPEN_PAREN_TOKEN) + if (m_tok->get_type() == token_type_t::OPEN_PAREN_TOKEN) { - m_tok.match(OPEN_PAREN_TOKEN); + m_tok.match(token_type_t::OPEN_PAREN_TOKEN); - while (m_tok->get_type() != CLOSE_PAREN_TOKEN) + while (m_tok->get_type() != token_type_t::CLOSE_PAREN_TOKEN) { params.push_back(parse_expr()); - if (m_tok->get_type() != CLOSE_PAREN_TOKEN) + if (m_tok->get_type() != token_type_t::CLOSE_PAREN_TOKEN) { - m_tok.match(COMMA_TOKEN, "expected comma"); + m_tok.match(token_type_t::COMMA_TOKEN, "expected comma"); } } - m_tok.match(CLOSE_PAREN_TOKEN, "expected close paren"); + m_tok.match(token_type_t::CLOSE_PAREN_TOKEN, "expected close paren"); } return get_var_value(path->get_value(), params); @@ -1282,8 +1282,8 @@ data_ptr ExprParser::parse_bfactor() { data_ptr ldata = parse_gfactor(); - TokenType tokType = m_tok->get_type(); - if (tokType == EQ_TOKEN || tokType == NEQ_TOKEN) + token_type_t tokType = m_tok->get_type(); + if (tokType == token_type_t::EQ_TOKEN || tokType == token_type_t::NEQ_TOKEN) { m_tok.next(); @@ -1293,10 +1293,10 @@ data_ptr ExprParser::parse_bfactor() std::string rhs = rdata->getvalue(); switch (tokType) { - case EQ_TOKEN: + case token_type_t::EQ_TOKEN: ldata = (lhs == rhs); break; - case NEQ_TOKEN: + case token_type_t::NEQ_TOKEN: ldata = (lhs != rhs); break; default: @@ -1310,8 +1310,8 @@ data_ptr ExprParser::parse_gfactor() { data_ptr ldata = parse_afactor(); - TokenType tokType = m_tok->get_type(); - if (tokType == GT_TOKEN || tokType == GE_TOKEN || tokType == LT_TOKEN || tokType == LE_TOKEN) + token_type_t tokType = m_tok->get_type(); + if (tokType == token_type_t::GT_TOKEN || tokType == token_type_t::GE_TOKEN || tokType == token_type_t::LT_TOKEN || tokType == token_type_t::LE_TOKEN) { m_tok.next(); @@ -1326,16 +1326,16 @@ data_ptr ExprParser::parse_gfactor() int r = ri->getint(); switch (tokType) { - case GT_TOKEN: + case token_type_t::GT_TOKEN: ldata = (l > r); break; - case GE_TOKEN: + case token_type_t::GE_TOKEN: ldata = (l >= r); break; - case LT_TOKEN: + case token_type_t::LT_TOKEN: ldata = (l < r); break; - case LE_TOKEN: + case token_type_t::LE_TOKEN: ldata = (l <= r); break; default: @@ -1348,16 +1348,16 @@ data_ptr ExprParser::parse_gfactor() std::string rhs = rdata->getvalue(); switch (tokType) { - case GT_TOKEN: + case token_type_t::GT_TOKEN: ldata = (lhs > rhs); break; - case GE_TOKEN: + case token_type_t::GE_TOKEN: ldata = (lhs >= rhs); break; - case LT_TOKEN: + case token_type_t::LT_TOKEN: ldata = (lhs < rhs); break; - case LE_TOKEN: + case token_type_t::LE_TOKEN: ldata = (lhs <= rhs); break; default: @@ -1372,8 +1372,8 @@ data_ptr ExprParser::parse_afactor() { data_ptr ldata = parse_mfactor(); - TokenType tokType = m_tok->get_type(); - if (tokType == PLUS_TOKEN || tokType == MINUS_TOKEN || tokType == CONCAT_TOKEN) + token_type_t tokType = m_tok->get_type(); + if (tokType == token_type_t::PLUS_TOKEN || tokType == token_type_t::MINUS_TOKEN || tokType == token_type_t::CONCAT_TOKEN) { m_tok.next(); @@ -1381,13 +1381,13 @@ data_ptr ExprParser::parse_afactor() switch (tokType) { - case CONCAT_TOKEN: + case token_type_t::CONCAT_TOKEN: ldata = ldata->getvalue() + rdata->getvalue(); break; - case PLUS_TOKEN: + case token_type_t::PLUS_TOKEN: ldata = ldata->getint() + rdata->getint(); break; - case MINUS_TOKEN: + case token_type_t::MINUS_TOKEN: ldata = ldata->getint() - rdata->getint(); break; default: @@ -1401,8 +1401,8 @@ data_ptr ExprParser::parse_mfactor() { data_ptr ldata = parse_factor(); - TokenType tokType = m_tok->get_type(); - if (tokType == TIMES_TOKEN || tokType == DIVIDE_TOKEN || tokType == MOD_TOKEN) + token_type_t tokType = m_tok->get_type(); + if (tokType == token_type_t::TIMES_TOKEN || tokType == token_type_t::DIVIDE_TOKEN || tokType == token_type_t::MOD_TOKEN) { m_tok.next(); @@ -1410,10 +1410,10 @@ data_ptr ExprParser::parse_mfactor() switch (tokType) { - case TIMES_TOKEN: + case token_type_t::TIMES_TOKEN: ldata = ldata->getint() * rdata->getint(); break; - case DIVIDE_TOKEN: + case token_type_t::DIVIDE_TOKEN: if (rdata->getint() == 0) { ldata = 0; @@ -1423,7 +1423,7 @@ data_ptr ExprParser::parse_mfactor() ldata = ldata->getint() / rdata->getint(); } break; - case MOD_TOKEN: + case token_type_t::MOD_TOKEN: if (rdata->getint() == 0) { ldata = 0; @@ -1444,9 +1444,9 @@ data_ptr ExprParser::parse_bterm() { data_ptr ldata = parse_bfactor(); - while (m_tok->get_type() == AND_TOKEN) + while (m_tok->get_type() == token_type_t::AND_TOKEN) { - m_tok.match(AND_TOKEN); + m_tok.match(token_type_t::AND_TOKEN); data_ptr rdata = parse_bfactor(); @@ -1459,9 +1459,9 @@ data_ptr ExprParser::parse_oterm() { data_ptr ldata = parse_bterm(); - while (m_tok->get_type() == OR_TOKEN) + while (m_tok->get_type() == token_type_t::OR_TOKEN) { - m_tok.match(OR_TOKEN); + m_tok.match(token_type_t::OR_TOKEN); data_ptr rdata = parse_bterm(); @@ -1478,11 +1478,11 @@ data_ptr ExprParser::parse_expr() { data_ptr ldata = parse_oterm(); - if (m_tok->get_type() == IF_TOKEN) + if (m_tok->get_type() == token_type_t::IF_TOKEN) { - m_tok.match(IF_TOKEN); + m_tok.match(token_type_t::IF_TOKEN); data_ptr predicate = parse_oterm(); - m_tok.match(ELSE_TOKEN); + m_tok.match(token_type_t::ELSE_TOKEN); data_ptr rdata = parse_oterm(); if (predicate->empty()) @@ -1607,21 +1607,21 @@ NodeFor::NodeFor(const token_vector &tokens, bool is_top, uint32_t line) , m_has_predicate(false) { TokenIterator tok(tokens); - tok.match(FOR_TOKEN, "expected 'for'"); - m_val = tok.match(KEY_PATH_TOKEN, "expected key path")->get_value(); - tok.match(IN_TOKEN, "expected 'in'"); - m_key = tok.match(KEY_PATH_TOKEN, "expected key path")->get_value(); - if (tok->get_type() != END_TOKEN) - { - tok.match(IF_TOKEN, "expected 'if'"); - while (tok->get_type() != END_TOKEN) + tok.match(token_type_t::FOR_TOKEN, "expected 'for'"); + m_val = tok.match(token_type_t::KEY_PATH_TOKEN, "expected key path")->get_value(); + tok.match(token_type_t::IN_TOKEN, "expected 'in'"); + m_key = tok.match(token_type_t::KEY_PATH_TOKEN, "expected key path")->get_value(); + if (tok->get_type() != token_type_t::END_TOKEN) + { + tok.match(token_type_t::IF_TOKEN, "expected 'if'"); + while (tok->get_type() != token_type_t::END_TOKEN) { m_predicate_tokens.push_back(*tok.get()); ++tok; } m_has_predicate = true; } - tok.match(END_TOKEN, "expected end of statement"); + tok.match(token_type_t::END_TOKEN, "expected end of statement"); } NodeType NodeFor::gettype() @@ -1704,11 +1704,11 @@ NodeIf::NodeIf(const token_vector &expr, uint32_t line) , m_else_if(nullptr) , m_if_type(NODE_TYPE_IF) { - if (expr[0].get_type() == ELIF_TOKEN) + if (expr[0].get_type() == token_type_t::ELIF_TOKEN) { m_if_type = NODE_TYPE_ELIF; } - else if (expr[0].get_type() == ELSE_TOKEN) + else if (expr[0].get_type() == token_type_t::ELSE_TOKEN) { m_if_type = NODE_TYPE_ELSE; } @@ -1746,21 +1746,21 @@ bool NodeIf::is_true(data_map &data) TokenIterator it(m_expr); if (m_if_type == NODE_TYPE_IF) { - it.match(IF_TOKEN, "expected 'if' keyword"); + it.match(token_type_t::IF_TOKEN, "expected 'if' keyword"); } else if (m_if_type == NODE_TYPE_ELIF) { - it.match(ELIF_TOKEN, "expected 'elif' keyword"); + it.match(token_type_t::ELIF_TOKEN, "expected 'elif' keyword"); } else if (m_if_type == NODE_TYPE_ELSE) { - it.match(ELSE_TOKEN, "expected 'else' keyword"); - it.match(END_TOKEN, "expected end of statement"); + it.match(token_type_t::ELSE_TOKEN, "expected 'else' keyword"); + it.match(token_type_t::END_TOKEN, "expected end of statement"); return true; } ExprParser parser(it, data); data_ptr d = parser.parse_expr(); - it.match(END_TOKEN, "expected end of statement"); + it.match(token_type_t::END_TOKEN, "expected end of statement"); return !d->empty(); } @@ -1781,26 +1781,26 @@ NodeDef::NodeDef(const token_vector &expr, uint32_t line) : NodeParent(line) { TokenIterator tok(expr); - tok.match(DEF_TOKEN, "expected 'def'"); + tok.match(token_type_t::DEF_TOKEN, "expected 'def'"); - m_name = tok.match(KEY_PATH_TOKEN, "expected key path")->get_value(); + m_name = tok.match(token_type_t::KEY_PATH_TOKEN, "expected key path")->get_value(); - if (tok->get_type() == OPEN_PAREN_TOKEN) + if (tok->get_type() == token_type_t::OPEN_PAREN_TOKEN) { - tok.match(OPEN_PAREN_TOKEN); + tok.match(token_type_t::OPEN_PAREN_TOKEN); - while (tok->get_type() != CLOSE_PAREN_TOKEN) + while (tok->get_type() != token_type_t::CLOSE_PAREN_TOKEN) { - m_params.push_back(tok.match(KEY_PATH_TOKEN, "expected key path")->get_value()); + m_params.push_back(tok.match(token_type_t::KEY_PATH_TOKEN, "expected key path")->get_value()); - if (tok->get_type() != CLOSE_PAREN_TOKEN) + if (tok->get_type() != token_type_t::CLOSE_PAREN_TOKEN) { - tok.match(COMMA_TOKEN, "expected comma"); + tok.match(token_type_t::COMMA_TOKEN, "expected comma"); } } - tok.match(CLOSE_PAREN_TOKEN, "expected close paren"); + tok.match(token_type_t::CLOSE_PAREN_TOKEN, "expected close paren"); } - tok.match(END_TOKEN, "expected end of statement"); + tok.match(token_type_t::END_TOKEN, "expected end of statement"); } NodeType NodeDef::gettype() @@ -1832,12 +1832,12 @@ void NodeSet::gettext(std::ostream &stream, data_map &data) { (void)stream; TokenIterator tok(m_expr); - tok.match(SET_TOKEN, "expected 'set'"); - std::string path = tok.match(KEY_PATH_TOKEN, "expected key path")->get_value(); - tok.match(ASSIGN_TOKEN); + tok.match(token_type_t::SET_TOKEN, "expected 'set'"); + std::string path = tok.match(token_type_t::KEY_PATH_TOKEN, "expected key path")->get_value(); + tok.match(token_type_t::ASSIGN_TOKEN); ExprParser parser(tok, data); data_ptr value = parser.parse_expr(); - tok.match(END_TOKEN, "expected end of statement"); + tok.match(token_type_t::END_TOKEN, "expected end of statement"); // Follow the key path, creating the key if missing. data_ptr &target = data.parse_path(path, true); @@ -1863,7 +1863,7 @@ TemplateParser::TemplateParser(const std::string &text, node_vector &nodes) , m_current_nodes(&m_top_nodes) , m_eol_precedes(true) , m_last_was_eol(true) -, m_until(INVALID_TOKEN) +, m_until(token_type_t::INVALID_TOKEN) { } @@ -1974,7 +1974,7 @@ void TemplateParser::parse_var() m_last_was_eol = false; } -void TemplateParser::push_node(Node *new_node, TokenType until) +void TemplateParser::push_node(Node *new_node, token_type_t until) { m_node_stack.push(std::make_pair(m_current_node, m_until)); m_current_node = node_ptr(new_node); @@ -2003,21 +2003,21 @@ void TemplateParser::parse_stmt() token_vector stmt_tokens = tokenize_statement(stmt_text); if (!stmt_tokens.empty()) { - TokenType first_token_type = stmt_tokens[0].get_type(); + token_type_t first_token_type = stmt_tokens[0].get_type(); // Create control statement nodes. switch (first_token_type) { - case FOR_TOKEN: - push_node(new NodeFor(stmt_tokens, m_node_stack.empty(), m_current_line), ENDFOR_TOKEN); + case token_type_t::FOR_TOKEN: + push_node(new NodeFor(stmt_tokens, m_node_stack.empty(), m_current_line), token_type_t::ENDFOR_TOKEN); break; - case IF_TOKEN: - push_node(new NodeIf(stmt_tokens, m_current_line), ENDIF_TOKEN); + case token_type_t::IF_TOKEN: + push_node(new NodeIf(stmt_tokens, m_current_line), token_type_t::ENDIF_TOKEN); break; - case ELIF_TOKEN: - case ELSE_TOKEN: { + case token_type_t::ELIF_TOKEN: + case token_type_t::ELSE_TOKEN: { auto current_if = dynamic_cast(m_current_node.get()); if (!current_if) { @@ -2035,17 +2035,17 @@ void TemplateParser::parse_stmt() break; } - case DEF_TOKEN: - push_node(new NodeDef(stmt_tokens, m_current_line), ENDDEF_TOKEN); + case token_type_t::DEF_TOKEN: + push_node(new NodeDef(stmt_tokens, m_current_line), token_type_t::ENDDEF_TOKEN); break; - case SET_TOKEN: + case token_type_t::SET_TOKEN: m_current_nodes->push_back(node_ptr(new NodeSet(stmt_tokens, m_current_line))); break; - case ENDFOR_TOKEN: - case ENDIF_TOKEN: - case ENDDEF_TOKEN: + case token_type_t::ENDFOR_TOKEN: + case token_type_t::ENDIF_TOKEN: + case token_type_t::ENDDEF_TOKEN: if (m_until == first_token_type) { assert(!m_node_stack.empty()); @@ -2061,7 +2061,7 @@ void TemplateParser::parse_stmt() { m_current_node.reset(); m_current_nodes = &m_top_nodes; - m_until = INVALID_TOKEN; + m_until = token_type_t::INVALID_TOKEN; } } else diff --git a/erpcgen/src/cpptemplate/cpptempl.hpp b/erpcgen/src/cpptemplate/cpptempl.hpp index 1527eed2..cf71a499 100644 --- a/erpcgen/src/cpptemplate/cpptempl.hpp +++ b/erpcgen/src/cpptemplate/cpptempl.hpp @@ -45,10 +45,10 @@ #include #include #include +#include #include #include #include -#include namespace cpptempl { diff --git a/erpcgen/src/erpcgen.cpp b/erpcgen/src/erpcgen.cpp index 0e2d180b..af7b132b 100644 --- a/erpcgen/src/erpcgen.cpp +++ b/erpcgen/src/erpcgen.cpp @@ -86,7 +86,7 @@ Available codecs (use with --c option):\n\ class erpcgenTool { protected: - enum verbose_type_t + enum class verbose_type_t { kWarning, kInfo, @@ -94,7 +94,7 @@ class erpcgenTool kExtraDebug }; /*!< Types of verbose outputs from erpcgen application. */ - enum languages_t + enum class languages_t { kCLanguage, kPythonLanguage, @@ -125,15 +125,15 @@ class erpcgenTool : m_argc(argc) , m_argv(argv) , m_logger(0) - , m_verboseType(kWarning) + , m_verboseType(verbose_type_t::kWarning) , m_outputFilePath(NULL) , m_ErpcFile(NULL) - , m_outputLanguage(kCLanguage) - , m_codec(InterfaceDefinition::kNotSpecified) + , m_outputLanguage(languages_t::kCLanguage) + , m_codec(InterfaceDefinition::codec_t::kNotSpecified) { // create logger instance m_logger = new StdoutLogger(); - m_logger->setFilterLevel(Logger::kWarning); + m_logger->setFilterLevel(Logger::log_level_t::kWarning); Log::setLogger(m_logger); } @@ -183,7 +183,7 @@ class erpcgenTool break; case 'v': - if (m_verboseType != kExtraDebug) + if (m_verboseType != verbose_type_t::kExtraDebug) { m_verboseType = (verbose_type_t)(((int)m_verboseType) + 1); } @@ -197,11 +197,11 @@ class erpcgenTool string lang = optarg; if (lang == "c") { - m_outputLanguage = kCLanguage; + m_outputLanguage = languages_t::kCLanguage; } else if (lang == "py") { - m_outputLanguage = kPythonLanguage; + m_outputLanguage = languages_t::kPythonLanguage; } else { @@ -215,7 +215,7 @@ class erpcgenTool string codec = optarg; if (codec.compare("basic") == 0) { - m_codec = InterfaceDefinition::kBasicCodec; + m_codec = InterfaceDefinition::codec_t::kBasicCodec; } else { @@ -312,10 +312,10 @@ class erpcgenTool switch (m_outputLanguage) { - case kCLanguage: + case languages_t::kCLanguage: CGenerator(&def).generate(); break; - case kPythonLanguage: + case languages_t::kPythonLanguage: PythonGenerator(&def).generate(); break; } @@ -356,17 +356,17 @@ class erpcgenTool // if the user has selected quiet mode, it overrides verbose switch (m_verboseType) { - case kWarning: - Log::getLogger()->setFilterLevel(Logger::kWarning); + case verbose_type_t::kWarning: + Log::getLogger()->setFilterLevel(Logger::log_level_t::kWarning); break; - case kInfo: - Log::getLogger()->setFilterLevel(Logger::kInfo); + case verbose_type_t::kInfo: + Log::getLogger()->setFilterLevel(Logger::log_level_t::kInfo); break; - case kDebug: - Log::getLogger()->setFilterLevel(Logger::kDebug); + case verbose_type_t::kDebug: + Log::getLogger()->setFilterLevel(Logger::log_level_t::kDebug); break; - case kExtraDebug: - Log::getLogger()->setFilterLevel(Logger::kDebug2); + case verbose_type_t::kExtraDebug: + Log::getLogger()->setFilterLevel(Logger::log_level_t::kDebug2); break; } } diff --git a/erpcgen/src/options.cpp b/erpcgen/src/options.cpp index 07c231ec..5edea150 100644 --- a/erpcgen/src/options.cpp +++ b/erpcgen/src/options.cpp @@ -330,18 +330,18 @@ inline static int isEndOpts(const char *token) inline static int isOption(unsigned flags, const char *arg) { return ((arg != nullptr) && ((*arg != '\0') || (arg[1] != '\0')) && - ((*arg == '-') || ((flags & Options::PLUS) && (*arg == '+')))); + ((*arg == '-') || ((flags & static_cast(Options::OptCtrl::PLUS)) && (*arg == '+')))); } // See if we should be parsing only options or if we also need to // parse positional arguments inline static int isOptsOnly(unsigned flags) { - return (flags & Options::PARSE_POS) ? 0 : 1; + return (flags & static_cast(Options::OptCtrl::PARSE_POS)) ? 0 : 1; } // return values for a keyword matching function -enum kwdmatch_t +enum class kwdmatch_t { NO_MATCH, PARTIAL_MATCH, @@ -381,21 +381,21 @@ static kwdmatch_t kwdmatch(const char *src, const char *attempt, int len = 0) int i; if (src == attempt) - return EXACT_MATCH; + return kwdmatch_t::EXACT_MATCH; if ((src == NULL) || (attempt == NULL)) - return NO_MATCH; + return kwdmatch_t::NO_MATCH; if ((!*src) && (!*attempt)) - return EXACT_MATCH; + return kwdmatch_t::EXACT_MATCH; if ((!*src) || (!*attempt)) - return NO_MATCH; + return kwdmatch_t::NO_MATCH; for (i = 0; ((i < len) || (len == 0)) && (attempt[i]) && (attempt[i] != ' '); i++) { if (TOLOWER(src[i]) != TOLOWER(attempt[i])) - return NO_MATCH; + return kwdmatch_t::NO_MATCH; } - return (src[i]) ? PARTIAL_MATCH : EXACT_MATCH; + return (src[i]) ? kwdmatch_t::PARTIAL_MATCH : kwdmatch_t::EXACT_MATCH; } // **************************************************************** OptionSpec @@ -572,11 +572,13 @@ unsigned OptionSpec::Format(char *buf, unsigned optctrls) const value_len = sizeof(default_value) - 1; } - if ((optctrls & Options::SHORT_ONLY) && ((!isNullOpt(optchar)) || (optctrls & Options::NOGUESSING))) + if ((optctrls & static_cast(Options::OptCtrl::SHORT_ONLY)) && + ((!isNullOpt(optchar)) || (optctrls & static_cast(Options::OptCtrl::NOGUESSING)))) { longopt = NULLSTR; } - if ((optctrls & Options::LONG_ONLY) && (longopt || (optctrls & Options::NOGUESSING))) + if ((optctrls & static_cast(Options::OptCtrl::LONG_ONLY)) && + (longopt || (optctrls & static_cast(Options::OptCtrl::NOGUESSING)))) { optchar = '\0'; } @@ -602,7 +604,8 @@ unsigned OptionSpec::Format(char *buf, unsigned optctrls) const if (longopt) { *(p++) = '-'; - if (!(optctrls & (Options::LONG_ONLY | Options::SHORT_ONLY))) + if (!(optctrls & + (static_cast(Options::OptCtrl::LONG_ONLY) | static_cast(Options::OptCtrl::SHORT_ONLY)))) { *(p++) = '-'; } @@ -644,7 +647,7 @@ unsigned OptionSpec::Format(char *buf, unsigned optctrls) const Options::Options(const char *arg_name, const char *const optv[]) : explicit_end(0) -, optctrls(DEFAULT) +, optctrls(static_cast(OptCtrl::DEFAULT)) , optvec(optv) , nextchar(NULLSTR) , listopt(NULLSTR) @@ -785,11 +788,11 @@ const char *Options::match_longopt(const char *opt, int len, int &ambiguous) con if (longopt == NULL) continue; result = kwdmatch(longopt, opt, len); - if (result == EXACT_MATCH) + if (result == kwdmatch_t::EXACT_MATCH) { return optspec; } - else if (result == PARTIAL_MATCH) + else if (result == kwdmatch_t::PARTIAL_MATCH) { if (matched) { @@ -827,7 +830,7 @@ const char *Options::match_longopt(const char *opt, int len, int &ambiguous) con // ^SIDE-EFFECTS: // - iter is advanced when an argument completely parsed // - optarg is modified to point to any option argument -// - if Options::QUIET is not set, error messages are printed on cerr +// - if Options::OptCtrl::QUIET is not set, error messages are printed on cerr // // ^RETURN-VALUE: // 'c' if the -c option was matched (optarg points to its argument) @@ -842,21 +845,22 @@ int Options::parse_opt(OptIter &iter, const char *&optarg) listopt = NULLSTR; // reset the list pointer if ((optvec == NULL) || (!*optvec)) - return Options::ENDOPTS; + return static_cast(Options::OptRC::ENDOPTS); // Try to match a known option - OptionSpec optspec = match_opt(*(nextchar++), (optctrls & Options::ANYCASE)); + OptionSpec optspec = match_opt(*(nextchar++), (optctrls & static_cast(Options::OptCtrl::ANYCASE))); // Check for an unknown option if (optspec.isNULL()) { // See if this was a long-option in disguise - if (!(optctrls & Options::NOGUESSING)) + if (!(optctrls & static_cast(Options::OptCtrl::NOGUESSING))) { unsigned save_ctrls = optctrls; const char *save_nextchar = nextchar; nextchar -= 1; - optctrls |= (Options::QUIET | Options::NOGUESSING); + optctrls |= + (static_cast(Options::OptCtrl::QUIET) | static_cast(Options::OptCtrl::NOGUESSING)); int optchar = parse_longopt(iter, optarg); optctrls = save_ctrls; if (optchar > 0) @@ -868,12 +872,12 @@ int Options::parse_opt(OptIter &iter, const char *&optarg) nextchar = save_nextchar; } } - if (!(optctrls & Options::QUIET)) + if (!(optctrls & static_cast(Options::OptCtrl::QUIET))) { cerr << cmdname << ": unknown option -" << *(nextchar - 1) << "." << endl; } optarg = (nextchar - 1); // record the bad option in optarg - return Options::BADCHAR; + return static_cast(Options::OptRC::BADCHAR); } // If no argument is taken, then leave now @@ -906,7 +910,7 @@ int Options::parse_opt(OptIter &iter, const char *&optarg) // No argument given - if its required, thats an error optarg = NULLSTR; - if (optspec.isValRequired() && !(optctrls & Options::QUIET)) + if (optspec.isValRequired() && !(optctrls & static_cast(Options::OptCtrl::QUIET))) { cerr << cmdname << ": argument required for -" << optspec.OptChar() << " option." << endl; } @@ -934,7 +938,7 @@ int Options::parse_opt(OptIter &iter, const char *&optarg) // ^SIDE-EFFECTS: // - iter is advanced when an argument completely parsed // - optarg is modified to point to any option argument -// - if Options::QUIET is not set, error messages are printed on cerr +// - if Options::OptCtrl::QUIET is not set, error messages are printed on cerr // // ^RETURN-VALUE: // 'c' if the the long-option corresponding to the -c option was matched @@ -952,7 +956,7 @@ int Options::parse_longopt(OptIter &iter, const char *&optarg) listopt = NULLSTR; // reset the list-spec if ((optvec == NULL) || (!*optvec)) - return Options::ENDOPTS; + return static_cast(Options::OptRC::ENDOPTS); // if a value is supplied in this argv element, get it now const char *val = strpbrk(nextchar, ":="); @@ -969,11 +973,12 @@ int Options::parse_longopt(OptIter &iter, const char *&optarg) if (optspec.isNULL()) { // See if this was a short-option in disguise - if ((!ambiguous) && (!(optctrls & Options::NOGUESSING))) + if ((!ambiguous) && (!(optctrls & static_cast(Options::OptCtrl::NOGUESSING)))) { unsigned save_ctrls = optctrls; const char *save_nextchar = nextchar; - optctrls |= (Options::QUIET | Options::NOGUESSING); + optctrls |= + (static_cast(Options::OptCtrl::QUIET) | static_cast(Options::OptCtrl::NOGUESSING)); int optchar = parse_opt(iter, optarg); optctrls = save_ctrls; if (optchar > 0) @@ -985,22 +990,25 @@ int Options::parse_longopt(OptIter &iter, const char *&optarg) nextchar = save_nextchar; } } - if (!(optctrls & Options::QUIET)) + if (!(optctrls & static_cast(Options::OptCtrl::QUIET))) { cerr << cmdname << ": " << ((ambiguous) ? "ambiguous" : "unknown") << " option " - << ((optctrls & Options::LONG_ONLY) ? "-" : "--") << nextchar << "." << endl; + << ((optctrls & static_cast(Options::OptCtrl::LONG_ONLY)) ? "-" : "--") << nextchar << "." + << endl; } optarg = nextchar; // record the bad option in optarg nextchar = NULLSTR; // we've exhausted this argument - return (ambiguous) ? Options::AMBIGUOUS : Options::BADKWD; + return (ambiguous) ? static_cast(Options::OptRC::AMBIGUOUS) : + static_cast(Options::OptRC::BADKWD); } // If no argument is taken, then leave now if (optspec.isNoArg()) { - if ((val) && !(optctrls & Options::QUIET)) + if ((val) && !(optctrls & static_cast(Options::OptCtrl::QUIET))) { - cerr << cmdname << ": option " << ((optctrls & Options::LONG_ONLY) ? "-" : "--") << optspec.LongOpt() + cerr << cmdname << ": option " + << ((optctrls & static_cast(Options::OptCtrl::LONG_ONLY)) ? "-" : "--") << optspec.LongOpt() << " does NOT take an argument." << endl; } optarg = val; // record the unexpected argument @@ -1032,7 +1040,7 @@ int Options::parse_longopt(OptIter &iter, const char *&optarg) // No argument given - if its required, thats an error optarg = NULLSTR; - if (optspec.isValRequired() && !(optctrls & Options::QUIET)) + if (optspec.isValRequired() && !(optctrls & static_cast(Options::OptCtrl::QUIET))) { const char *longopt = optspec.LongOpt(); const char *spc = ::strchr(longopt, ' '); @@ -1045,7 +1053,8 @@ int Options::parse_longopt(OptIter &iter, const char *&optarg) { longopt_len = (int)::strlen(longopt); } - cerr << cmdname << ": argument required for " << ((optctrls & Options::LONG_ONLY) ? "-" : "--"); + cerr << cmdname << ": argument required for " + << ((optctrls & static_cast(Options::OptCtrl::LONG_ONLY)) ? "-" : "--"); cerr.write(longopt, longopt_len) << " option." << endl; } nextchar = NULLSTR; // we exhausted the rest of this arg @@ -1165,7 +1174,7 @@ void Options::usage(ostream &os, const char *positionals) const // ^SIDE-EFFECTS: // - iter is advanced when an argument is completely parsed // - optarg is modified to point to any option argument -// - if Options::QUIET is not set, error messages are printed on cerr +// - if Options::OptCtrl::QUIET is not set, error messages are printed on cerr // // ^RETURN-VALUE: // 0 if all options have been parsed. @@ -1203,7 +1212,7 @@ int Options::operator()(OptIter &iter, const char *&optarg) if (arg == NULL) { listopt = NULLSTR; - return Options::ENDOPTS; + return static_cast(Options::OptRC::ENDOPTS); } else if ((!explicit_end) && isEndOpts(arg)) { @@ -1211,7 +1220,7 @@ int Options::operator()(OptIter &iter, const char *&optarg) listopt = NULLSTR; explicit_end = 1; if (parse_opts_only) - return Options::ENDOPTS; + return static_cast(Options::OptRC::ENDOPTS); get_next_arg = 1; // make sure we look at the next argument. } } while (get_next_arg); @@ -1221,27 +1230,27 @@ int Options::operator()(OptIter &iter, const char *&optarg) { if (parse_opts_only) { - return Options::ENDOPTS; + return static_cast(Options::OptRC::ENDOPTS); } else { optarg = arg; // set optarg to the positional argument iter.next(); // advance iterator to the next argument - return Options::POSITIONAL; + return static_cast(Options::OptRC::POSITIONAL); } } iter.next(); // pass the argument that arg already points to // See if we have a long option ... - if (!(optctrls & Options::SHORT_ONLY)) + if (!(optctrls & static_cast(Options::OptCtrl::SHORT_ONLY))) { if ((*arg == '-') && (arg[1] == '-')) { nextchar = arg + 2; return parse_longopt(iter, optarg); } - else if ((optctrls & Options::PLUS) && (*arg == '+')) + else if ((optctrls & static_cast(Options::OptCtrl::PLUS)) && (*arg == '+')) { nextchar = arg + 1; return parse_longopt(iter, optarg); @@ -1250,7 +1259,7 @@ int Options::operator()(OptIter &iter, const char *&optarg) if (*arg == '-') { nextchar = arg + 1; - if (optctrls & Options::LONG_ONLY) + if (optctrls & static_cast(Options::OptCtrl::LONG_ONLY)) { return parse_longopt(iter, optarg); } diff --git a/erpcgen/src/options.hpp b/erpcgen/src/options.hpp index 371daca8..0518c29f 100644 --- a/erpcgen/src/options.hpp +++ b/erpcgen/src/options.hpp @@ -383,7 +383,7 @@ class Options int parse_longopt(OptIter &iter, const char *&optarg); public: - enum OptCtrl + enum class OptCtrl { DEFAULT = 0x00, //!< Default setting ANYCASE = 0x01, //!< Ignore case when matching short-options @@ -410,7 +410,7 @@ class Options //! Error return values for operator() //! - enum OptRC + enum class OptRC { ENDOPTS = 0, BADCHAR = -1, @@ -464,7 +464,7 @@ class Options //! the positonal argument (and "iter" is advanced to the next argument //! in the iterator). //! - //! Unless Options::QUIET is used, missing option-arguments and + //! Unless Options::OptCtrl::QUIET is used, missing option-arguments and //! invalid options (and the like) will automatically cause error //! messages to be issued to cerr. int operator()(OptIter &iter, const char *&optarg); diff --git a/erpcgen/src/templates/c_client_source.template b/erpcgen/src/templates/c_client_source.template index 41f4a8fd..7d1c8ac6 100644 --- a/erpcgen/src/templates/c_client_source.template +++ b/erpcgen/src/templates/c_client_source.template @@ -86,7 +86,7 @@ extern ClientManager *g_client; else { {% endif -- generateErrorChecks %} -{$clientIndent} codec->startWriteMessage({% if not fn.isReturnValue %}kOnewayMessage{% else %}kInvocationMessage{% endif %}, {$serverIDName}, {$functionIDName}, request.getSequence()); +{$clientIndent} codec->startWriteMessage({% if not fn.isReturnValue %}message_type_t::kOnewayMessage{% else %}message_type_t::kInvocationMessage{% endif %}, {$serverIDName}, {$functionIDName}, request.getSequence()); {% if fn.isSendValue %} {% for param in fn.parameters if (param.serializedDirection == "" || param.serializedDirection == OutDirection || param.referencedName != "") %} diff --git a/erpcgen/src/templates/c_server_source.template b/erpcgen/src/templates/c_server_source.template index 0f1e526f..bad5bfe9 100644 --- a/erpcgen/src/templates/c_server_source.template +++ b/erpcgen/src/templates/c_server_source.template @@ -139,7 +139,7 @@ ERPC_MANUALLY_CONSTRUCTED_STATIC({$iface.serviceClassName}, s_{$iface.serviceCla {$serverIndent} codec->reset(); {$serverIndent} // Build response message. -{$serverIndent} codec->startWriteMessage(kReplyMessage, {$serverIDName}, {$functionIDName}, sequence); +{$serverIndent} codec->startWriteMessage(message_type_t::kReplyMessage, {$serverIDName}, {$functionIDName}, sequence); {% for param in fn.parametersToClient if (param.serializedDirection == "" || param.serializedDirection == InDirection || param.referencedName != "") %} {% if param.isNullable %} diff --git a/erpcgen/src/types/AliasType.hpp b/erpcgen/src/types/AliasType.hpp index 6fc99285..b08cffbe 100644 --- a/erpcgen/src/types/AliasType.hpp +++ b/erpcgen/src/types/AliasType.hpp @@ -35,7 +35,7 @@ class AliasType : public DataType * @param[in] elementType Given data type. */ AliasType(const std::string &name, DataType *elementType) - : DataType(name, kAliasType) + : DataType(name, data_type_t::kAliasType) , m_elementType(elementType) { } @@ -49,7 +49,7 @@ class AliasType : public DataType * @param[in] elementType Given data type. */ AliasType(const Token &tok, DataType *elementType) - : DataType(tok, kAliasType) + : DataType(tok, data_type_t::kAliasType) , m_elementType(elementType) { } diff --git a/erpcgen/src/types/Annotation.hpp b/erpcgen/src/types/Annotation.hpp index 029b232f..6d83154e 100644 --- a/erpcgen/src/types/Annotation.hpp +++ b/erpcgen/src/types/Annotation.hpp @@ -28,7 +28,7 @@ namespace erpcgen { class Annotation { public: - enum program_lang_t + enum class program_lang_t { kAll, kC, @@ -63,7 +63,7 @@ class Annotation : m_name(token.getStringValue()) , m_value(nullptr) , m_location(token.getLocation()) - , m_lang(kAll) + , m_lang(program_lang_t::kAll) { } diff --git a/erpcgen/src/types/ArrayType.hpp b/erpcgen/src/types/ArrayType.hpp index 13d105c4..2db48edd 100644 --- a/erpcgen/src/types/ArrayType.hpp +++ b/erpcgen/src/types/ArrayType.hpp @@ -35,7 +35,7 @@ class ArrayType : public DataType * @param[in] elementCount Given count. */ ArrayType(DataType *elementType, uint32_t elementCount) - : DataType("(array)", kArrayType) + : DataType("(array)", data_type_t::kArrayType) , m_elementType(elementType) , m_elementCount(elementCount) { diff --git a/erpcgen/src/types/BuiltinType.hpp b/erpcgen/src/types/BuiltinType.hpp index 003c04ce..0cdecad5 100644 --- a/erpcgen/src/types/BuiltinType.hpp +++ b/erpcgen/src/types/BuiltinType.hpp @@ -29,7 +29,7 @@ class BuiltinType : public DataType /*! * @brief Atomic builtin types. */ - enum _builtin_type + enum class builtin_type_t { kBoolType, kInt8Type, @@ -55,8 +55,8 @@ class BuiltinType : public DataType * @param[in] name Given name. * @param[in] builtinType Given builtin type. */ - BuiltinType(const std::string &name, _builtin_type builtinType) - : DataType(name, kBuiltinType) + BuiltinType(const std::string &name, builtin_type_t builtinType) + : DataType(name, data_type_t::kBuiltinType) , m_builtinType(builtinType) { } @@ -66,7 +66,7 @@ class BuiltinType : public DataType * * @return Builtin type of current object. */ - _builtin_type getBuiltinType() const { return m_builtinType; } + builtin_type_t getBuiltinType() const { return m_builtinType; } /*! * @brief This function return "true" value for identify scalar type. @@ -82,7 +82,10 @@ class BuiltinType : public DataType * @retval true When builtin type is int. * @retval false When builtin type isn't int. */ - virtual bool isInt() const override { return ((kInt8Type <= m_builtinType) && (m_builtinType <= kUInt64Type)); } + virtual bool isInt() const override + { + return ((builtin_type_t::kInt8Type <= m_builtinType) && (m_builtinType <= builtin_type_t::kUInt64Type)); + } /*! * @brief This function return "true" value for identify float type. @@ -90,7 +93,10 @@ class BuiltinType : public DataType * @retval true When builtin type is float. * @retval false When builtin type isn't float. */ - virtual bool isFloat() const override { return ((m_builtinType == kFloatType) || (m_builtinType == kDoubleType)); } + virtual bool isFloat() const override + { + return ((m_builtinType == builtin_type_t::kFloatType) || (m_builtinType == builtin_type_t::kDoubleType)); + } /*! * @brief This function return "true" value for identify bool type. @@ -98,7 +104,7 @@ class BuiltinType : public DataType * @retval true When builtin type is bool. * @retval false When builtin type isn't bool. */ - virtual bool isBool() const override { return m_builtinType == kBoolType; } + virtual bool isBool() const override { return m_builtinType == builtin_type_t::kBoolType; } /*! * @brief This function return true/false value for identify string type. @@ -108,7 +114,7 @@ class BuiltinType : public DataType */ virtual bool isString() const override { - return ((m_builtinType == kStringType) || (m_builtinType == kUStringType)); + return ((m_builtinType == builtin_type_t::kStringType) || (m_builtinType == builtin_type_t::kUStringType)); } /*! @@ -117,7 +123,7 @@ class BuiltinType : public DataType * @retval true When builtin type is ustring. * @retval false When builtin type isn't ustring. */ - virtual bool isUString() const override { return m_builtinType == kUStringType; } + virtual bool isUString() const override { return m_builtinType == builtin_type_t::kUStringType; } /*! * @brief This function return true/false value for identify binary type. @@ -125,10 +131,10 @@ class BuiltinType : public DataType * @retval true When builtin type is binary. * @retval false When builtin type isn't binary. */ - virtual bool isBinary() const override { return m_builtinType == kBinaryType; } + virtual bool isBinary() const override { return m_builtinType == builtin_type_t::kBinaryType; } protected: - _builtin_type m_builtinType; /*!< Builtin type of current object. */ + builtin_type_t m_builtinType; /*!< Builtin type of current object. */ }; } // namespace erpcgen diff --git a/erpcgen/src/types/ConstType.hpp b/erpcgen/src/types/ConstType.hpp index 7b1988fa..6a845231 100644 --- a/erpcgen/src/types/ConstType.hpp +++ b/erpcgen/src/types/ConstType.hpp @@ -37,7 +37,7 @@ class ConstType : public Symbol * @param[in] value Given value. */ ConstType(const Token &tok, DataType *dataType, Value *value) - : Symbol(kConstSymbol, tok) + : Symbol(symbol_type_t::kConstSymbol, tok) , m_dataType(dataType) , m_value(value) { diff --git a/erpcgen/src/types/DataType.hpp b/erpcgen/src/types/DataType.hpp index 9cdfd55b..daed4c24 100644 --- a/erpcgen/src/types/DataType.hpp +++ b/erpcgen/src/types/DataType.hpp @@ -29,7 +29,7 @@ class DataType : public Symbol /*! * @brief Supported data types. */ - enum data_type_t + enum class data_type_t { kAliasType, kArrayType, @@ -50,7 +50,7 @@ class DataType : public Symbol * @param[in] dataType Given data type. */ explicit DataType(data_type_t dataType) - : Symbol(kTypenameSymbol) + : Symbol(symbol_type_t::kTypenameSymbol) , m_dataType(dataType) { } @@ -64,7 +64,7 @@ class DataType : public Symbol * @param[in] name Given name for symbol. */ DataType(const std::string &name, data_type_t dataType) - : Symbol(kTypenameSymbol, name) + : Symbol(symbol_type_t::kTypenameSymbol, name) , m_dataType(dataType) { } @@ -78,7 +78,7 @@ class DataType : public Symbol * @param[in] symbolType Given symbol type for symbol. */ DataType(const Token &tok, data_type_t dataType) - : Symbol(kTypenameSymbol, tok) + : Symbol(symbol_type_t::kTypenameSymbol, tok) , m_dataType(dataType) { } @@ -115,7 +115,7 @@ class DataType : public Symbol * @retval true When data type is AliasType. * @retval false When data type isn't AliasType. */ - bool isAlias() const { return (m_dataType == kAliasType); } + bool isAlias() const { return (m_dataType == data_type_t::kAliasType); } /*! * @brief This function is testing data type. @@ -123,7 +123,7 @@ class DataType : public Symbol * @retval true When data type is ArrayType. * @retval false When data type isn't ArrayType. */ - bool isArray() const { return (m_dataType == kArrayType); } + bool isArray() const { return (m_dataType == data_type_t::kArrayType); } /*! * @brief This function return "false" value as default for identify binary type. @@ -145,7 +145,7 @@ class DataType : public Symbol * @retval true When data type is BuiltinType. * @retval false When data type isn't BuiltinType. */ - bool isBuiltin() const { return (m_dataType == kBuiltinType); } + bool isBuiltin() const { return (m_dataType == data_type_t::kBuiltinType); } /*! * @brief This function is testing data type. @@ -153,7 +153,7 @@ class DataType : public Symbol * @retval true When data type is EnumTyp. * @retval false When data type isn't EnumTyp. */ - bool isEnum() const { return (m_dataType == kEnumType); } + bool isEnum() const { return (m_dataType == data_type_t::kEnumType); } /*! * @brief This function is testing data type. @@ -161,7 +161,7 @@ class DataType : public Symbol * @retval true When data type is FunctionType. * @retval false When data type isn't FunctionType. */ - bool isFunction() const { return (m_dataType == kFunctionType); } + bool isFunction() const { return (m_dataType == data_type_t::kFunctionType); } /*! * @brief This function is testing data type. @@ -169,7 +169,7 @@ class DataType : public Symbol * @retval true When data type is ListType. * @retval false When data type isn't ListType. */ - bool isList() const { return (m_dataType == kListType); } + bool isList() const { return (m_dataType == data_type_t::kListType); } /*! * @brief This function return "false" value as default for identify scalar builtin type. @@ -212,7 +212,7 @@ class DataType : public Symbol * @retval true When data type is StructType. * @retval false When data type isn't StructType. */ - bool isStruct() const { return (m_dataType == kStructType); } + bool isStruct() const { return (m_dataType == data_type_t::kStructType); } /*! * @brief This function is testing data type. @@ -220,7 +220,7 @@ class DataType : public Symbol * @retval true When data type is UnionType. * @retval false When data type isn't UnionType. */ - bool isUnion() const { return (m_dataType == kUnionType); } + bool isUnion() const { return (m_dataType == data_type_t::kUnionType); } /*! * @brief This function is testing data type. @@ -228,7 +228,7 @@ class DataType : public Symbol * @retval true When data type is VoidType. * @retval false When data type isn't VoidType. */ - bool isVoid() const { return (m_dataType == kVoidType); } + bool isVoid() const { return (m_dataType == data_type_t::kVoidType); } protected: data_type_t m_dataType; /*!< Data type of current object */ diff --git a/erpcgen/src/types/EnumMember.hpp b/erpcgen/src/types/EnumMember.hpp index ea8b0715..f0562ca4 100644 --- a/erpcgen/src/types/EnumMember.hpp +++ b/erpcgen/src/types/EnumMember.hpp @@ -35,7 +35,7 @@ class EnumMember : public Symbol * @param[in] value Given value. */ EnumMember(const Token &tok, uint32_t value) - : Symbol(kEnumMemberSymbol, tok) + : Symbol(symbol_type_t::kEnumMemberSymbol, tok) , m_value(value) , m_valueSet(true) { @@ -49,7 +49,7 @@ class EnumMember : public Symbol * @param[in] tok Token, which contains name and location. */ explicit EnumMember(const Token &tok) - : Symbol(kEnumMemberSymbol, tok) + : Symbol(symbol_type_t::kEnumMemberSymbol, tok) , m_value(-1) , m_valueSet(false) { diff --git a/erpcgen/src/types/EnumType.hpp b/erpcgen/src/types/EnumType.hpp index 91d0c932..a28e3af5 100644 --- a/erpcgen/src/types/EnumType.hpp +++ b/erpcgen/src/types/EnumType.hpp @@ -38,7 +38,7 @@ class EnumType : public DataType * @param[in] tok Given token. */ explicit EnumType(const Token &tok) - : DataType(tok, kEnumType) + : DataType(tok, data_type_t::kEnumType) { } @@ -48,7 +48,7 @@ class EnumType : public DataType * This function set DataType with default name. */ EnumType() - : DataType("", kEnumType) + : DataType("", data_type_t::kEnumType) { } diff --git a/erpcgen/src/types/Function.hpp b/erpcgen/src/types/Function.hpp index 20262352..b72d159e 100644 --- a/erpcgen/src/types/Function.hpp +++ b/erpcgen/src/types/Function.hpp @@ -127,7 +127,7 @@ class Function : public FunctionBase, public Symbol */ Function(const Token &tok, Interface *interface) : FunctionBase() - , Symbol(kFunctionSymbol, tok) + , Symbol(symbol_type_t::kFunctionSymbol, tok) , m_uniqueId(++s_idCounter) , m_interface(interface) , m_functionType(nullptr) @@ -145,7 +145,7 @@ class Function : public FunctionBase, public Symbol */ Function(const Token &tok, Interface *interface, uint32_t uniqueId) : FunctionBase() - , Symbol(kFunctionSymbol, tok) + , Symbol(symbol_type_t::kFunctionSymbol, tok) , m_uniqueId(uniqueId) , m_interface(interface) , m_functionType(nullptr) diff --git a/erpcgen/src/types/FunctionType.hpp b/erpcgen/src/types/FunctionType.hpp index cbe0697d..15bc512b 100644 --- a/erpcgen/src/types/FunctionType.hpp +++ b/erpcgen/src/types/FunctionType.hpp @@ -42,7 +42,7 @@ class FunctionType : public FunctionBase, public DataType */ explicit FunctionType(const Token &tok) : FunctionBase() - , DataType(tok, kFunctionType) + , DataType(tok, data_type_t::kFunctionType) , m_callbackFuns() { } diff --git a/erpcgen/src/types/Group.hpp b/erpcgen/src/types/Group.hpp index ff7f51f0..bc7ae551 100644 --- a/erpcgen/src/types/Group.hpp +++ b/erpcgen/src/types/Group.hpp @@ -30,7 +30,7 @@ class Group public: typedef std::vector interface_list_t; /*!< Vector of interfaces belongs to group. */ typedef std::vector symbols_list_t; /*!< Vector of symbols belongs to group. */ - typedef std::map > + typedef std::map > symbol_directions_map_t; /*!< Map symbol with direction in which is used in current group. */ /*! @@ -70,7 +70,7 @@ class Group * @param[in] symbol Symbol for which direction should be added. * @param[in] dir Direction of the symbol. */ - void addDirToSymbolsMap(Symbol *symbol, _param_direction dir); + void addDirToSymbolsMap(Symbol *symbol, param_direction_t dir); /*! * @brief This function returns set with symbol directions. @@ -79,7 +79,7 @@ class Group * * @return Set with symbol directions. */ - const std::set<_param_direction> getSymbolDirections(Symbol *symbol) const; + const std::set getSymbolDirections(Symbol *symbol) const; /*! * @brief This function returns vector with symbols. diff --git a/erpcgen/src/types/Interface.hpp b/erpcgen/src/types/Interface.hpp index 1dea8b36..ffc400a1 100644 --- a/erpcgen/src/types/Interface.hpp +++ b/erpcgen/src/types/Interface.hpp @@ -39,7 +39,7 @@ class Interface : public Symbol * @param[in] tok Given token. */ explicit Interface(const Token &tok) - : Symbol(kInterfaceSymbol, tok) + : Symbol(symbol_type_t::kInterfaceSymbol, tok) , m_scope() , m_uniqueId(s_idCounter++) { diff --git a/erpcgen/src/types/ListType.hpp b/erpcgen/src/types/ListType.hpp index f564d7cd..cef44ec9 100644 --- a/erpcgen/src/types/ListType.hpp +++ b/erpcgen/src/types/ListType.hpp @@ -34,7 +34,7 @@ class ListType : public DataType * @param[in] elementType Given data type. */ explicit ListType(DataType *elementType) - : DataType("(list)", kListType) + : DataType("(list)", data_type_t::kListType) , m_elementType(elementType) , m_lengthVariableName("") { diff --git a/erpcgen/src/types/Program.hpp b/erpcgen/src/types/Program.hpp index 990aed65..3d0efd0d 100644 --- a/erpcgen/src/types/Program.hpp +++ b/erpcgen/src/types/Program.hpp @@ -36,7 +36,7 @@ class Program : public Symbol * @param[in] tok Given token. */ explicit Program(const Token &tok) - : Symbol(kProgramSymbol, tok) + : Symbol(symbol_type_t::kProgramSymbol, tok) { } }; diff --git a/erpcgen/src/types/StructMember.hpp b/erpcgen/src/types/StructMember.hpp index 576e74bd..f3448d57 100644 --- a/erpcgen/src/types/StructMember.hpp +++ b/erpcgen/src/types/StructMember.hpp @@ -24,7 +24,7 @@ namespace erpcgen { /*! * @brief Supported directions types. */ -enum _param_direction +enum class param_direction_t { kInDirection, kOutDirection, @@ -47,7 +47,7 @@ class StructMember : public Symbol * @param[in] dataType Given data type. */ StructMember(const std::string &name, DataType *dataType) - : Symbol(kStructMemberSymbol, name) + : Symbol(symbol_type_t::kStructMemberSymbol, name) , m_dataType(dataType) , m_paramDirection() , m_containList() @@ -65,7 +65,7 @@ class StructMember : public Symbol * @param[in] dataType Given data type. */ StructMember(const Token &tok, DataType *dataType) - : Symbol(kStructMemberSymbol, tok) + : Symbol(symbol_type_t::kStructMemberSymbol, tok) , m_dataType(dataType) , m_paramDirection() , m_containList() @@ -111,7 +111,7 @@ class StructMember : public Symbol * * @param[in] paramDirection Define direction type for parameter in functions. */ - void setDirection(_param_direction paramDirection) { m_paramDirection = paramDirection; } + void setDirection(param_direction_t paramDirection) { m_paramDirection = paramDirection; } /*! * @brief This function returns routing for parameter. @@ -120,7 +120,7 @@ class StructMember : public Symbol * * @return Returns routing type for parameter in functions. */ - _param_direction getDirection() const { return m_paramDirection; } + param_direction_t getDirection() const { return m_paramDirection; } /*! * @brief This function set information about if member contains list data type. @@ -165,11 +165,11 @@ class StructMember : public Symbol void setByref(bool byref) { m_byref = byref; } protected: - DataType *m_dataType; /*!< Struct member data type. */ - _param_direction m_paramDirection; /*!< Direction in which is member used. */ - bool m_containList; /*!< True when member contains list type */ - bool m_containString; /*!< True when member contains string type */ - bool m_byref; /*!< True when member is byref type */ + DataType *m_dataType; /*!< Struct member data type. */ + param_direction_t m_paramDirection; /*!< Direction in which is member used. */ + bool m_containList; /*!< True when member contains list type */ + bool m_containString; /*!< True when member contains string type */ + bool m_byref; /*!< True when member is byref type */ }; } // namespace erpcgen diff --git a/erpcgen/src/types/StructType.hpp b/erpcgen/src/types/StructType.hpp index 76b8d36e..7514ed40 100644 --- a/erpcgen/src/types/StructType.hpp +++ b/erpcgen/src/types/StructType.hpp @@ -39,7 +39,7 @@ class StructType : public DataType * @param[in] name Given name. */ explicit StructType(const std::string &name) - : DataType(name, kStructType) + : DataType(name, data_type_t::kStructType) { } @@ -51,7 +51,7 @@ class StructType : public DataType * @param[in] tok Given token. */ explicit StructType(const Token &tok) - : DataType(tok, kStructType) + : DataType(tok, data_type_t::kStructType) { } diff --git a/erpcgen/src/types/Symbol.hpp b/erpcgen/src/types/Symbol.hpp index 6f854713..654ed0e6 100644 --- a/erpcgen/src/types/Symbol.hpp +++ b/erpcgen/src/types/Symbol.hpp @@ -31,7 +31,7 @@ class Symbol /*! * @brief Supported symbol types. */ - enum symbol_type_t + enum class symbol_type_t { kConstSymbol, kEnumMemberSymbol, @@ -128,7 +128,7 @@ class Symbol * @retval true When symbol is ConstSymbol. * @retval false When symbol isn't ConstSymbol. */ - bool isConstSymbol() const { return (m_symbolType == kConstSymbol); } + bool isConstSymbol() const { return (m_symbolType == symbol_type_t::kConstSymbol); } /*! * @brief This function is testing symbol type. @@ -136,7 +136,7 @@ class Symbol * @retval true When symbol is EnumMemberSymbol. * @retval false When symbol isn't EnumMemberSymbol. */ - bool isEnumMemberSymbol() const { return (m_symbolType == kEnumMemberSymbol); } + bool isEnumMemberSymbol() const { return (m_symbolType == symbol_type_t::kEnumMemberSymbol); } /*! * @brief This function is testing symbol type. @@ -144,7 +144,7 @@ class Symbol * @retval true When symbol is FunctionSymbol. * @retval false When symbol isn't FunctionSymbol. */ - bool isFunctionSymbol() const { return (m_symbolType == kFunctionSymbol); } + bool isFunctionSymbol() const { return (m_symbolType == symbol_type_t::kFunctionSymbol); } /*! * @brief This function is testing symbol type. @@ -152,7 +152,7 @@ class Symbol * @retval true When symbol is InterfaceSymbol. * @retval false When symbol isn't InterfaceSymbol. */ - bool isInterfaceSymbol() const { return (m_symbolType == kInterfaceSymbol); } + bool isInterfaceSymbol() const { return (m_symbolType == symbol_type_t::kInterfaceSymbol); } /*! * @brief This function is testing symbol type. @@ -160,7 +160,7 @@ class Symbol * @retval true When symbol is ProgramSymbol. * @retval false When symbol isn't ProgramSymbol. */ - bool isProgramSymbol() const { return (m_symbolType == kProgramSymbol); } + bool isProgramSymbol() const { return (m_symbolType == symbol_type_t::kProgramSymbol); } /*! * @brief This function is testing symbol type. @@ -168,7 +168,7 @@ class Symbol * @retval true When symbol is StructMemberSymbol. * @retval false When symbol isn't StructMemberSymbol. */ - bool isStructMemberSymbol() const { return (m_symbolType == kStructMemberSymbol); } + bool isStructMemberSymbol() const { return (m_symbolType == symbol_type_t::kStructMemberSymbol); } /*! * @brief This function is testing symbol type. @@ -176,7 +176,7 @@ class Symbol * @retval true When symbol is TypenameSymbol. * @retval false When symbol isn't TypenameSymbol. */ - bool isDatatypeSymbol() const { return (m_symbolType == kTypenameSymbol); } + bool isDatatypeSymbol() const { return (m_symbolType == symbol_type_t::kTypenameSymbol); } /*! * @brief This function is testing symbol type. @@ -184,7 +184,7 @@ class Symbol * @retval true When symbol is UnionCaseMemberSymbol. * @retval false When symbol isn't UnionCaseMemberSymbol. */ - bool isUnionCaseSymbol() const { return (m_symbolType == kUnionCaseMemberSymbol); } + bool isUnionCaseSymbol() const { return (m_symbolType == symbol_type_t::kUnionCaseMemberSymbol); } /*! * @brief This function returns location for symbol. diff --git a/erpcgen/src/types/Type.cpp b/erpcgen/src/types/Type.cpp index cceb07f7..0b89d67e 100644 --- a/erpcgen/src/types/Type.cpp +++ b/erpcgen/src/types/Type.cpp @@ -99,7 +99,7 @@ vector Symbol::getAnnotations(const string &name, Annotation::prog for (unsigned int i = 0; i < m_annotations.size(); ++i) { if (m_annotations[i].getName() == name && - (m_annotations[i].getLang() == lang || m_annotations[i].getLang() == Annotation::kAll)) + (m_annotations[i].getLang() == lang || m_annotations[i].getLang() == Annotation::program_lang_t::kAll)) { anList.push_back(&m_annotations[i]); } @@ -398,13 +398,13 @@ void Group::addInterface(Interface *iface) m_interfaces.push_back(iface); } -void Group::addDirToSymbolsMap(Symbol *symbol, _param_direction dir) +void Group::addDirToSymbolsMap(Symbol *symbol, param_direction_t dir) { Log::info("Adding direction %d for symbol \"%s\"\n", dir, symbol->getName().c_str()); auto it = m_symbolDirections.find(symbol); if (it == m_symbolDirections.end()) { - set<_param_direction> directions; + set directions; directions.insert(dir); m_symbolDirections[symbol] = directions; @@ -424,9 +424,9 @@ void Group::setTemplate(cpptempl::data_map groupTemplate) m_template = groupTemplate; } -const set<_param_direction> Group::getSymbolDirections(Symbol *symbol) const +const set Group::getSymbolDirections(Symbol *symbol) const { - set<_param_direction> directions; + set directions; auto it = m_symbolDirections.find(symbol); if (it != m_symbolDirections.end()) { @@ -477,12 +477,12 @@ DataType *DataType::getTrueContainerDataType() DataType *trueDataType = this->getTrueDataType(); switch (trueDataType->getDataType()) { - case DataType::kListType: { + case DataType::data_type_t::kListType: { ListType *l = dynamic_cast(trueDataType); assert(l); return l->getElementType()->getTrueContainerDataType(); } - case DataType::kArrayType: { + case DataType::data_type_t::kArrayType: { ArrayType *a = dynamic_cast(trueDataType); assert(a); return a->getElementType()->getTrueContainerDataType(); diff --git a/erpcgen/src/types/UnionCase.hpp b/erpcgen/src/types/UnionCase.hpp index dd924c8b..752aebea 100644 --- a/erpcgen/src/types/UnionCase.hpp +++ b/erpcgen/src/types/UnionCase.hpp @@ -36,7 +36,7 @@ class UnionCase : public Symbol * @param[in] caseValue Given case value. */ UnionCase(const std::string &caseName, int32_t caseValue) - : Symbol(kUnionCaseMemberSymbol, caseName) + : Symbol(symbol_type_t::kUnionCaseMemberSymbol, caseName) , m_caseName(caseName) , m_caseValue(caseValue) , m_containingUnion(nullptr) @@ -52,7 +52,7 @@ class UnionCase : public Symbol * @param[in] caseValue Given case value. */ explicit UnionCase(int32_t caseValue) - : Symbol(kUnionCaseMemberSymbol) + : Symbol(symbol_type_t::kUnionCaseMemberSymbol) , m_caseName("") , m_caseValue(caseValue) , m_containingUnion(nullptr) @@ -68,7 +68,7 @@ class UnionCase : public Symbol * @param[in] caseName Given case name. */ explicit UnionCase(const std::string &caseName) - : Symbol(kUnionCaseMemberSymbol) + : Symbol(symbol_type_t::kUnionCaseMemberSymbol) , m_caseName(caseName) , m_caseValue(-1) , m_containingUnion(nullptr) diff --git a/erpcgen/src/types/UnionType.hpp b/erpcgen/src/types/UnionType.hpp index e04d99de..3362dbee 100644 --- a/erpcgen/src/types/UnionType.hpp +++ b/erpcgen/src/types/UnionType.hpp @@ -40,7 +40,7 @@ class UnionType : public DataType * @param[in] discriminatorName Discriminator name. */ UnionType(const std::string &name, const std::string &discriminatorName) - : DataType(name, kUnionType) + : DataType(name, data_type_t::kUnionType) , m_discriminator(discriminatorName) , m_members("(union)") , m_parentStruct(nullptr) @@ -57,7 +57,7 @@ class UnionType : public DataType * @param[in] discriminatorName Discriminator name. */ UnionType(const Token &tok, const std::string &discriminatorName) - : DataType(tok, kUnionType) + : DataType(tok, data_type_t::kUnionType) , m_discriminator(discriminatorName) , m_members("(union)") , m_parentStruct(nullptr) diff --git a/erpcgen/src/types/VoidType.hpp b/erpcgen/src/types/VoidType.hpp index 2ab9e5c6..6cb72b61 100644 --- a/erpcgen/src/types/VoidType.hpp +++ b/erpcgen/src/types/VoidType.hpp @@ -32,7 +32,7 @@ class VoidType : public DataType * This function set name to "(void)". */ VoidType() - : DataType("(void)", kVoidType) + : DataType("(void)", data_type_t::kVoidType) { } diff --git a/erpcsniffer/src/Sniffer.cpp b/erpcsniffer/src/Sniffer.cpp index 6f4f7834..16e25c8f 100644 --- a/erpcsniffer/src/Sniffer.cpp +++ b/erpcsniffer/src/Sniffer.cpp @@ -17,9 +17,9 @@ #include #include #include +#include #include #include -#include using namespace erpcgen; using namespace erpcsniffer; @@ -139,7 +139,7 @@ void Sniffer::openFile(ofstream &outputFileStream) erpc_status_t Sniffer::readNullFlag(StructMember *structMember, string &nullFlag) { - if (structMember && structMember->findAnnotation(NULLABLE_ANNOTATION, Annotation::kC) != nullptr) + if (structMember && structMember->findAnnotation(NULLABLE_ANNOTATION, Annotation::program_lang_t::kC) != nullptr) { bool nullF; m_codec->readNullFlag(nullF); @@ -154,7 +154,7 @@ erpc_status_t Sniffer::readNullFlag(StructMember *structMember, string &nullFlag erpc_status_t Sniffer::readSharedAddress(StructMember *structMember, string &address) { erpc_status_t err = kErpcStatus_Success; - if (structMember->findAnnotation(SHARED_ANNOTATION, Annotation::kC) != nullptr) + if (structMember->findAnnotation(SHARED_ANNOTATION, Annotation::program_lang_t::kC) != nullptr) { uintptr_t ptr; m_codec->readPtr(ptr); @@ -227,7 +227,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) assert(builtinType); switch (builtinType->getBuiltinType()) { - case BuiltinType::_builtin_type::kBoolType: { + case BuiltinType::builtin_type_t::kBoolType: { bool value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -237,7 +237,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "bool" + parsedDataInfo + ((value) ? "true" : "false"); break; } - case BuiltinType::_builtin_type::kInt8Type: { + case BuiltinType::builtin_type_t::kInt8Type: { int8_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -247,7 +247,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "int8_t" + parsedDataInfo + format_string("%d", value); break; } - case BuiltinType::_builtin_type::kInt16Type: { + case BuiltinType::builtin_type_t::kInt16Type: { int16_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -257,7 +257,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "int16_t" + parsedDataInfo + format_string("%d", value); break; } - case BuiltinType::_builtin_type::kInt32Type: { + case BuiltinType::builtin_type_t::kInt32Type: { int32_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -267,7 +267,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "int32_t" + parsedDataInfo + format_string("%d", value); break; } - case BuiltinType::_builtin_type::kInt64Type: { + case BuiltinType::builtin_type_t::kInt64Type: { int64_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -277,7 +277,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "int64_t" + parsedDataInfo + format_string("%ld", value); break; } - case BuiltinType::_builtin_type::kUInt8Type: { + case BuiltinType::builtin_type_t::kUInt8Type: { uint8_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -287,7 +287,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "uint8_t" + parsedDataInfo + format_string("%u", value); break; } - case BuiltinType::_builtin_type::kUInt16Type: { + case BuiltinType::builtin_type_t::kUInt16Type: { uint16_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -297,7 +297,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "uint16_t" + parsedDataInfo + format_string("%u", value); break; } - case BuiltinType::_builtin_type::kUInt32Type: { + case BuiltinType::builtin_type_t::kUInt32Type: { uint32_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -307,7 +307,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "uint32_t" + parsedDataInfo + format_string("%u", value); break; } - case BuiltinType::_builtin_type::kUInt64Type: { + case BuiltinType::builtin_type_t::kUInt64Type: { uint64_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -317,7 +317,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "uint64_t" + parsedDataInfo + format_string("%lu", value); break; } - case BuiltinType::_builtin_type::kFloatType: { + case BuiltinType::builtin_type_t::kFloatType: { float value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -327,7 +327,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "float" + parsedDataInfo + format_string("%f", value); break; } - case BuiltinType::_builtin_type::kDoubleType: { + case BuiltinType::builtin_type_t::kDoubleType: { double value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -337,7 +337,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "double" + parsedDataInfo + format_string("%f", value); break; } - case BuiltinType::_builtin_type::kStringType: { + case BuiltinType::builtin_type_t::kStringType: { char *value; uint32_t length; m_codec->readString(length, &value); @@ -348,7 +348,7 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "string" + parsedDataInfo + format_string("%.*s", length, value); break; } - case BuiltinType::_builtin_type::kBinaryType: { + case BuiltinType::builtin_type_t::kBinaryType: { uint8_t *value; uint32_t length; m_codec->readBinary(length, &value); @@ -544,8 +544,8 @@ erpc_status_t Sniffer::parseMemberType(StructType *structType, StructMember *str { Annotation *ann; string referencedName; - if ((ann = referenced->findAnnotation(LENGTH_ANNOTATION, Annotation::kC)) || - (ann = referenced->findAnnotation(DISCRIMINATOR_ANNOTATION, Annotation::kC))) + if ((ann = referenced->findAnnotation(LENGTH_ANNOTATION, Annotation::program_lang_t::kC)) || + (ann = referenced->findAnnotation(DISCRIMINATOR_ANNOTATION, Annotation::program_lang_t::kC))) { if (Value *val = ann->getValueObject()) { @@ -568,8 +568,8 @@ erpc_status_t Sniffer::parseMemberType(StructType *structType, StructMember *str // check if reference is null-able Annotation *ann; - if ((ann = structMember->findAnnotation(LENGTH_ANNOTATION, Annotation::kC)) || - (ann = structMember->findAnnotation(DISCRIMINATOR_ANNOTATION, Annotation::kC))) + if ((ann = structMember->findAnnotation(LENGTH_ANNOTATION, Annotation::program_lang_t::kC)) || + (ann = structMember->findAnnotation(DISCRIMINATOR_ANNOTATION, Annotation::program_lang_t::kC))) { if (Value *val = ann->getValueObject()) { @@ -643,12 +643,12 @@ string Sniffer::getDataTypeName(DataType *dataType) { switch (dataType->getDataType()) { - case DataType::kListType: { + case DataType::data_type_t::kListType: { ListType *listType = dynamic_cast(dataType); assert(listType); return "list<" + getDataTypeName(listType->getElementType()) + ">"; } - case DataType::kArrayType: { + case DataType::data_type_t::kArrayType: { string returnVal; while (dataType->isArray()) { @@ -659,7 +659,7 @@ string Sniffer::getDataTypeName(DataType *dataType) } return getDataTypeName(dataType) + returnVal; } - case DataType::kVoidType: { + case DataType::data_type_t::kVoidType: { return "void"; } default: @@ -705,7 +705,7 @@ erpc_status_t Sniffer::analyzeMessage(string &message, const char *timeDiffernce return err; } - enum msg_t + enum class msg_t { msg_request, // client serialization/server deserialization msg_answer // client deserialization/server serialization @@ -713,14 +713,14 @@ erpc_status_t Sniffer::analyzeMessage(string &message, const char *timeDiffernce // Set message type. msg_t msgType; - if (messageType == message_type_t::kInvocationMessage || messageType == message_type_t::kOnewayMessage) + if ((messageType == message_type_t::kInvocationMessage) || (messageType == message_type_t::kOnewayMessage)) { - msgType = msg_request; + msgType = msg_t::msg_request; message += "'Request'"; } else { - msgType = msg_answer; + msgType = msg_t::msg_answer; message += "'Answer'"; } @@ -731,7 +731,7 @@ erpc_status_t Sniffer::analyzeMessage(string &message, const char *timeDiffernce // Find and record interface information. if (Interface *interface = getInterface(serviceId)) { - string groupName = interface->getAnnStringValue(GROUP_ANNOTATION, Annotation::kC); + string groupName = interface->getAnnStringValue(GROUP_ANNOTATION, Annotation::program_lang_t::kC); message += format_string("Group name:%s\nInterface name:%s id:%d\n", groupName.c_str(), interface->getName().c_str(), serviceId); @@ -745,10 +745,10 @@ erpc_status_t Sniffer::analyzeMessage(string &message, const char *timeDiffernce StructType params = function->getParameters(); for (StructMember *param : params.getMembers()) { - if ((msgType == msg_request && (param->getDirection() == _param_direction::kInDirection || - param->getDirection() == _param_direction::kInoutDirection)) || - (msgType == msg_answer && (param->getDirection() == _param_direction::kOutDirection || - param->getDirection() == _param_direction::kInoutDirection))) + if ((msgType == msg_t::msg_request && (param->getDirection() == param_direction_t::kInDirection || + param->getDirection() == param_direction_t::kInoutDirection)) || + (msgType == msg_t::msg_answer && (param->getDirection() == param_direction_t::kOutDirection || + param->getDirection() == param_direction_t::kInoutDirection))) { string output; err = parseMemberType(¶ms, param, output); @@ -763,7 +763,7 @@ erpc_status_t Sniffer::analyzeMessage(string &message, const char *timeDiffernce } // Record function's return data information. - if (msgType == msg_answer) + if (msgType == msg_t::msg_answer) { StructMember *returnDataType = function->getReturnStructMemberType(); if (returnDataType) diff --git a/erpcsniffer/src/Sniffer.hpp b/erpcsniffer/src/Sniffer.hpp index b61177d9..70f914eb 100644 --- a/erpcsniffer/src/Sniffer.hpp +++ b/erpcsniffer/src/Sniffer.hpp @@ -39,7 +39,7 @@ class Sniffer Sniffer(erpc::Transport *transport, erpcgen::InterfaceDefinition *def, const char *outputFilePath, uint64_t quantity) : m_transport(transport) - , m_interfaces(def->getGlobals().getSymbolsOfType(erpcgen::Symbol::kInterfaceSymbol)) + , m_interfaces(def->getGlobals().getSymbolsOfType(erpcgen::Symbol::symbol_type_t::kInterfaceSymbol)) , m_outputFilePath(outputFilePath) , m_quantity(quantity) , m_codec(new erpc::BasicCodec()){}; diff --git a/erpcsniffer/src/erpcsniffer.cpp b/erpcsniffer/src/erpcsniffer.cpp index 043c328b..361080d8 100644 --- a/erpcsniffer/src/erpcsniffer.cpp +++ b/erpcsniffer/src/erpcsniffer.cpp @@ -94,7 +94,7 @@ Available transports (use with -t option):\n\ class erpcsnifferTool { protected: - enum verbose_type_t + enum class verbose_type_t { kWarning, kInfo, @@ -102,7 +102,7 @@ class erpcsnifferTool kExtraDebug }; /*!< Types of verbose outputs from erpcsniffer application. */ - enum transports_t + enum class transports_t { kNoneTransport, kTcpTransport, @@ -137,10 +137,10 @@ class erpcsnifferTool : m_argc(argc) , m_argv(argv) , m_logger(0) - , m_verboseType(kWarning) + , m_verboseType(verbose_type_t::kWarning) , m_outputFilePath(NULL) , m_ErpcFile(NULL) - , m_transport(kNoneTransport) + , m_transport(transports_t::kNoneTransport) , m_quantity(10) , m_baudrate(115200) , m_port(NULL) @@ -148,7 +148,7 @@ class erpcsnifferTool { // create logger instance m_logger = new StdoutLogger(); - m_logger->setFilterLevel(Logger::kWarning); + m_logger->setFilterLevel(Logger::log_level_t::kWarning); Log::setLogger(m_logger); } @@ -201,7 +201,7 @@ class erpcsnifferTool } case 'v': { - if (m_verboseType != kExtraDebug) + if (m_verboseType != verbose_type_t::kExtraDebug) { m_verboseType = (verbose_type_t)(((int)m_verboseType) + 1); } @@ -217,11 +217,11 @@ class erpcsnifferTool string transport = optarg; if (transport == "tcp") { - m_transport = kTcpTransport; + m_transport = transports_t::kTcpTransport; } else if (transport == "serial") { - m_transport = kSerialTransport; + m_transport = transports_t::kSerialTransport; } else { @@ -336,7 +336,7 @@ class erpcsnifferTool Transport *_transport; switch (m_transport) { - case kTcpTransport: { + case transports_t::kTcpTransport: { uint16_t portNumber = strtoul(m_port, NULL, 10); TCPTransport *tcpTransport = new TCPTransport(m_host, portNumber, true); if (erpc_status_t err = tcpTransport->open()) @@ -347,7 +347,7 @@ class erpcsnifferTool break; } - case kSerialTransport: { + case transports_t::kSerialTransport: { erpc_transport_t transport = erpc_transport_serial_init(m_port, m_baudrate); _transport = reinterpret_cast(transport); assert(_transport); @@ -363,7 +363,7 @@ class erpcsnifferTool if (def.hasProgramSymbol()) { Program *program = def.getProgramSymbol(); - if (program->findAnnotation(CRC_ANNOTATION, Annotation::kC) != nullptr) + if (program->findAnnotation(CRC_ANNOTATION, Annotation::program_lang_t::kC) != nullptr) { crc.setCrcStart(def.getIdlCrc16()); } @@ -408,17 +408,17 @@ class erpcsnifferTool // if the user has selected quiet mode, it overrides verbose switch (m_verboseType) { - case kWarning: - Log::getLogger()->setFilterLevel(Logger::kWarning); + case verbose_type_t::kWarning: + Log::getLogger()->setFilterLevel(Logger::log_level_t::kWarning); break; - case kInfo: - Log::getLogger()->setFilterLevel(Logger::kInfo); + case verbose_type_t::kInfo: + Log::getLogger()->setFilterLevel(Logger::log_level_t::kInfo); break; - case kDebug: - Log::getLogger()->setFilterLevel(Logger::kDebug); + case verbose_type_t::kDebug: + Log::getLogger()->setFilterLevel(Logger::log_level_t::kDebug); break; - case kExtraDebug: - Log::getLogger()->setFilterLevel(Logger::kDebug2); + case verbose_type_t::kExtraDebug: + Log::getLogger()->setFilterLevel(Logger::log_level_t::kDebug2); break; } } diff --git a/test/common/retarget_cpp_streamed_io.c b/test/common/retarget_cpp_streamed_io.c index 69f24e15..757c4b2b 100644 --- a/test/common/retarget_cpp_streamed_io.c +++ b/test/common/retarget_cpp_streamed_io.c @@ -132,7 +132,7 @@ int _sys_read(FILEHANDLE fh, unsigned char *buf, unsigned len, int mode) else // LOG_Push((uint8_t *)(&buf[pos - 1]), 1); // Echo normal char to terminal // DbgConsole_SendData((uint8_t *)(&buf[pos - 1]), 1); // Echo normal char to terminal - DbgConsole_Putchar(buf[pos-1]); // Echo normal char to terminal + DbgConsole_Putchar(buf[pos - 1]); // Echo normal char to terminal } while (buf[pos - 1] != '\r'); diff --git a/test/common/unit_test_serial_client.cpp b/test/common/unit_test_serial_client.cpp index 9fadbf77..38c37c35 100644 --- a/test/common/unit_test_serial_client.cpp +++ b/test/common/unit_test_serial_client.cpp @@ -56,7 +56,7 @@ int main(int argc, char **argv) // create logger instance StdoutLogger *m_logger = new StdoutLogger(); - m_logger->setFilterLevel(Logger::kInfo); + m_logger->setFilterLevel(Logger::log_level_t::kInfo); Log::setLogger(m_logger); Log::info("Starting ERPC client...\n"); diff --git a/test/common/unit_test_serial_server.cpp b/test/common/unit_test_serial_server.cpp index fc911cbd..0dc4f61e 100644 --- a/test/common/unit_test_serial_server.cpp +++ b/test/common/unit_test_serial_server.cpp @@ -54,7 +54,7 @@ int main(int argc, const char *argv[]) { // create logger instance StdoutLogger *m_logger = new StdoutLogger(); - m_logger->setFilterLevel(Logger::kInfo); + m_logger->setFilterLevel(Logger::log_level_t::kInfo); Log::setLogger(m_logger); Log::info("Starting ERPC server...\n"); diff --git a/test/common/unit_test_tcp_arbitrator_client.cpp b/test/common/unit_test_tcp_arbitrator_client.cpp index 549cb554..0c1330a1 100644 --- a/test/common/unit_test_tcp_arbitrator_client.cpp +++ b/test/common/unit_test_tcp_arbitrator_client.cpp @@ -108,7 +108,7 @@ int main(int argc, char **argv) // create logger instance StdoutLogger m_logger; - m_logger.setFilterLevel(Logger::kInfo); + m_logger.setFilterLevel(Logger::log_level_t::kInfo); Log::setLogger(&m_logger); Log::info("Intit ERPC first (client) app...\n"); diff --git a/test/common/unit_test_tcp_arbitrator_server.cpp b/test/common/unit_test_tcp_arbitrator_server.cpp index d32a1fc9..d196b0b4 100644 --- a/test/common/unit_test_tcp_arbitrator_server.cpp +++ b/test/common/unit_test_tcp_arbitrator_server.cpp @@ -118,7 +118,7 @@ int main(int argc, char **argv) // create logger instance StdoutLogger m_logger; - m_logger.setFilterLevel(Logger::kInfo); + m_logger.setFilterLevel(Logger::log_level_t::kInfo); Log::setLogger(&m_logger); diff --git a/test/common/unit_test_tcp_client.cpp b/test/common/unit_test_tcp_client.cpp index 132bd047..0dca069c 100644 --- a/test/common/unit_test_tcp_client.cpp +++ b/test/common/unit_test_tcp_client.cpp @@ -61,7 +61,7 @@ int main(int argc, char **argv) // create logger instance StdoutLogger *m_logger = new StdoutLogger(); - m_logger->setFilterLevel(Logger::kInfo); + m_logger->setFilterLevel(Logger::log_level_t::kInfo); Log::setLogger(m_logger); Log::info("Starting ERPC client...\n"); diff --git a/test/common/unit_test_tcp_server.cpp b/test/common/unit_test_tcp_server.cpp index 7bef7a6d..d689d380 100644 --- a/test/common/unit_test_tcp_server.cpp +++ b/test/common/unit_test_tcp_server.cpp @@ -54,7 +54,7 @@ int main(int argc, const char *argv[]) { // create logger instance StdoutLogger *m_logger = new StdoutLogger(); - m_logger->setFilterLevel(Logger::kInfo); + m_logger->setFilterLevel(Logger::log_level_t::kInfo); Log::setLogger(m_logger); Log::info("Starting ERPC server...\n"); diff --git a/test/test_lists/test_lists_client_impl.cpp b/test/test_lists/test_lists_client_impl.cpp index 4603070d..22e44e80 100644 --- a/test/test_lists/test_lists_client_impl.cpp +++ b/test/test_lists/test_lists_client_impl.cpp @@ -52,7 +52,7 @@ TEST(test_list, sendReceiveZeroSize) received_list = sendReceivedInt32(&send_list); - EXPECT_EQ(received_list->elementsCount , 0); + EXPECT_EQ(received_list->elementsCount, 0); erpc_free(received_list->elements); erpc_free(received_list); @@ -88,7 +88,7 @@ TEST(test_list, SendReceived2Int32) list_r = list_int32_1_t_r->elements; for (uint32_t j = 0; j < list_int32_1_t_r->elementsCount; ++j) { - EXPECT_EQ((*list_r) / 2 , *list_s); + EXPECT_EQ((*list_r) / 2, *list_s); ++list_s; ++list_r; } diff --git a/test/test_shared/test_shared_client_impl.cpp b/test/test_shared/test_shared_client_impl.cpp index 87213bea..db39dfc2 100644 --- a/test/test_shared/test_shared_client_impl.cpp +++ b/test/test_shared/test_shared_client_impl.cpp @@ -17,7 +17,7 @@ TEST(test_shared, sendReceiveBaseSharedStruct) BaseSharedStruct sm = { 4, 5 }; BaseSharedStruct *_sm; _sm = sendReceiveBaseSharedStruct(&sm); - EXPECT_EQ(_sm , &sm); + EXPECT_EQ(_sm, &sm); } TEST(test_shared, inoutBaseSharedStruct) @@ -25,7 +25,7 @@ TEST(test_shared, inoutBaseSharedStruct) BaseSharedStruct sm = { 4, 5 }; BaseSharedStruct *_sm = &sm; inoutBaseSharedStruct(&_sm); - EXPECT_EQ(_sm , &sm); + EXPECT_EQ(_sm, &sm); } /*TEST(test_shared, inoutStruct1) From 9fb576381031073ba9d9d748d80e256725f23047 Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Tue, 19 Sep 2023 09:04:26 +0200 Subject: [PATCH 08/24] Fixed rpmsg tty transport to work with serial transport (#373) Ability to receive message in two buffers Signed-off-by: Cervenka Dusan --- .../erpc_rpmsg_tty_rtos_transport.cpp | 59 ++++++++++++++----- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp index 62272787..6b5c4522 100644 --- a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp +++ b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp @@ -179,7 +179,7 @@ erpc_status_t RPMsgTTYRTOSTransport::init(uint32_t src_addr, uint32_t dst_addr, ready_cb(); } - (void)rpmsg_lite_wait_for_link_up(s_rpmsg, RL_BLOCK); + static_cast(rpmsg_lite_wait_for_link_up(s_rpmsg, RL_BLOCK)); #if RL_USE_STATIC_API m_rpmsg_queue = rpmsg_queue_create(s_rpmsg, m_queue_stack, &m_queue_context); @@ -257,32 +257,63 @@ erpc_status_t RPMsgTTYRTOSTransport::receive(MessageBuffer *message) erpc_status_t status = kErpcStatus_Success; FramedTransport::Header h; char *buf = NULL; + char *buf2 = NULL; uint32_t length = 0; int32_t ret_val = rpmsg_queue_recv_nocopy(s_rpmsg, m_rpmsg_queue, &m_dst_addr, &buf, &length, RL_BLOCK); uint16_t computedCrc; erpc_assert((m_crcImpl != NULL) && ("Uninitialized Crc16 object." != NULL)); - erpc_assert(buf != NULL); if (ret_val == RL_SUCCESS) { - (void)memcpy(reinterpret_cast(&h), buf, sizeof(h)); - message->set(&(reinterpret_cast(buf))[sizeof(h)], length - sizeof(h)); - - /* Verify CRC. */ - computedCrc = m_crcImpl->computeCRC16(&(reinterpret_cast(buf))[sizeof(h)], h.m_messageSize); - if (computedCrc != h.m_crc) + erpc_assert(buf != NULL); + if (length < sizeof(h)) { - status = kErpcStatus_CrcCheckFailed; + status = kErpcStatus_ReceiveFailed; } - else + if (status == kErpcStatus_Success) { - message->setUsed(h.m_messageSize); + static_cast(memcpy(reinterpret_cast(&h), buf, sizeof(h))); + /* If header and body is sent in two packets, we need call receive again to get body part. */ + if (length == sizeof(h)) + { + ret_val = rpmsg_queue_recv_nocopy(s_rpmsg, m_rpmsg_queue, &m_dst_addr, &buf2, &length, RL_BLOCK); + if (ret_val == RL_SUCCESS) + { + erpc_assert(buf2 != NULL); + erpc_assert((length + sizeof(h)) <= ERPC_DEFAULT_BUFFER_SIZE); + static_cast(memcpy(&buf[sizeof(h)], buf2, length)); + } + static_cast(rpmsg_lite_release_rx_buffer(s_rpmsg, buf2)); + } + else + { + length -= sizeof(h); /* offset for MessageBuffer */ + } + buf = &buf[sizeof(h)]; /* offset for MessageBuffer */ } } - else + if (status == kErpcStatus_Success) { - status = kErpcStatus_ReceiveFailed; + if (ret_val == RL_SUCCESS) + { + message->set(reinterpret_cast(buf), length); + + /* Verify CRC. */ + computedCrc = m_crcImpl->computeCRC16(reinterpret_cast(buf), h.m_messageSize); + if (computedCrc != h.m_crc) + { + status = kErpcStatus_CrcCheckFailed; + } + else + { + message->setUsed(h.m_messageSize); + } + } + else + { + status = kErpcStatus_ReceiveFailed; + } } return status; @@ -303,7 +334,7 @@ erpc_status_t RPMsgTTYRTOSTransport::send(MessageBuffer *message) h.m_crc = m_crcImpl->computeCRC16(buf, used); h.m_messageSize = used; - (void)memcpy(&buf[-sizeof(h)], (uint8_t *)&h, sizeof(h)); + static_cast(memcpy(&buf[-sizeof(h)], (uint8_t *)&h, sizeof(h))); ret_val = rpmsg_lite_send_nocopy(s_rpmsg, m_rpmsg_ept, m_dst_addr, &buf[-sizeof(h)], used + sizeof(h)); if (ret_val == RL_SUCCESS) From 78569aca632fd9750d89f3c54f4377df328b34b3 Mon Sep 17 00:00:00 2001 From: thewon86 Date: Tue, 19 Sep 2023 21:31:50 +0800 Subject: [PATCH 09/24] Feature/winsock2 support (#365) * Feature/winsock2 support * Adding mingw to testing tcp apps. Signed-off-by: Dusan Cervenka * Update run_unit_tests.py Remove redundant print cmd * Hide shell errors for mingw Signed-off-by: Cervenka Dusan * Adding delay between running tests Looks like server on mac target is not ready when client is executed Signed-off-by: Cervenka Dusan * Change pragma for g_client for mingw Signed-off-by: Cervenka Dusan --------- Signed-off-by: Dusan Cervenka Signed-off-by: Cervenka Dusan Co-authored-by: Dusan Cervenka Co-authored-by: Cervenka Dusan --- .circleci/config.yml | 3 +- erpc_c/Makefile | 6 +- erpc_c/port/erpc_config_internal.h | 3 +- erpc_c/port/erpc_port_stdlib.cpp | 2 + erpc_c/setup/erpc_arbitrated_client_setup.cpp | 5 + erpc_c/setup/erpc_client_setup.cpp | 5 + erpc_c/transports/erpc_tcp_transport.cpp | 131 +++++++++++++++++- erpc_c/transports/erpc_tcp_transport.hpp | 8 ++ .../src/templates/c_common_functions.template | 8 ++ mk/common.mk | 23 +-- mk/flags.mk | 10 +- mk/targets.mk | 4 +- test/common/gtest/gtest.cpp | 2 + test/mk/erpc_src.mk | 6 +- test/mk/test.mk | 3 + test/mk/unit_test.mk | 14 +- test/run_unit_tests.py | 11 +- 17 files changed, 210 insertions(+), 34 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 01a78cee..7f1a2e7e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -49,7 +49,8 @@ jobs: steps: - checkout - run: powershell.exe .\install_dependencies.ps1 - - run: powershell.exe .\mingw64\bin\mingw32-make erpcgen + - run: .\mingw64\bin\mingw32-make all + - run: .\mingw64\opt\bin\python3.exe .\test\run_unit_tests.py -m"..\\..\\mingw64\\bin\\mingw32-make" # - store_artifacts: # path: ./Release/MINGW64/erpcgen/erpcgen.exe build-windows-VS: diff --git a/erpc_c/Makefile b/erpc_c/Makefile index 9ad45d15..0637a6dc 100644 --- a/erpc_c/Makefile +++ b/erpc_c/Makefile @@ -63,7 +63,6 @@ SOURCES += $(ERPC_C_ROOT)/infra/erpc_arbitrated_client_manager.cpp \ $(ERPC_C_ROOT)/infra/erpc_pre_post_action.cpp \ $(ERPC_C_ROOT)/port/erpc_port_stdlib.cpp \ $(ERPC_C_ROOT)/port/erpc_threading_pthreads.cpp \ - $(ERPC_C_ROOT)/port/erpc_serial.cpp \ $(ERPC_C_ROOT)/setup/erpc_arbitrated_client_setup.cpp \ $(ERPC_C_ROOT)/setup/erpc_client_setup.cpp \ $(ERPC_C_ROOT)/setup/erpc_setup_mbf_dynamic.cpp \ @@ -72,8 +71,11 @@ SOURCES += $(ERPC_C_ROOT)/infra/erpc_arbitrated_client_manager.cpp \ $(ERPC_C_ROOT)/setup/erpc_setup_serial.cpp \ $(ERPC_C_ROOT)/setup/erpc_setup_tcp.cpp \ $(ERPC_C_ROOT)/transports/erpc_inter_thread_buffer_transport.cpp \ - $(ERPC_C_ROOT)/transports/erpc_serial_transport.cpp \ $(ERPC_C_ROOT)/transports/erpc_tcp_transport.cpp +ifeq "$(is_mingw)" "" + SOURCES += $(ERPC_C_ROOT)/transports/erpc_serial_transport.cpp \ + $(ERPC_C_ROOT)/port/erpc_serial.cpp +endif HEADERS += $(ERPC_C_ROOT)/config/erpc_config.h \ $(ERPC_C_ROOT)/infra/erpc_arbitrated_client_manager.hpp \ diff --git a/erpc_c/port/erpc_config_internal.h b/erpc_c/port/erpc_config_internal.h index 482de9ea..f5209c65 100644 --- a/erpc_c/port/erpc_config_internal.h +++ b/erpc_c/port/erpc_config_internal.h @@ -22,7 +22,8 @@ #if !defined(ERPC_HAS_POSIX) // Detect Linux, BSD, Cygwin, and Mac OS X. #if defined(__linux__) || defined(__GNU__) || defined(__FreeBSD__) || defined(__NetBSD__) || \ - defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__) || defined(__MACH__) + defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__) || defined(__MACH__) || \ + defined(__MINGW32__) #define ERPC_HAS_POSIX (1) #else #define ERPC_HAS_POSIX (0) diff --git a/erpc_c/port/erpc_port_stdlib.cpp b/erpc_c/port/erpc_port_stdlib.cpp index 2413ed44..19d9ed70 100644 --- a/erpc_c/port/erpc_port_stdlib.cpp +++ b/erpc_c/port/erpc_port_stdlib.cpp @@ -15,6 +15,7 @@ using namespace std; +#if !defined(__MINGW32__) void *operator new(size_t count) THROW_BADALLOC { void *p = erpc_malloc(count); @@ -62,6 +63,7 @@ void operator delete[](void *ptr, std::size_t count) THROW NOEXCEPT (void)count; erpc_free(ptr); } +#endif void *erpc_malloc(size_t size) { diff --git a/erpc_c/setup/erpc_arbitrated_client_setup.cpp b/erpc_c/setup/erpc_arbitrated_client_setup.cpp index 7057c041..a37a73ec 100644 --- a/erpc_c/setup/erpc_arbitrated_client_setup.cpp +++ b/erpc_c/setup/erpc_arbitrated_client_setup.cpp @@ -31,8 +31,13 @@ using namespace erpc; // global client variables ERPC_MANUALLY_CONSTRUCTED_STATIC(ArbitratedClientManager, s_client); +#if defined(__MINGW32__) +__declspec( selectany ) +#endif ClientManager *g_client; +#if !defined(__MINGW32__) #pragma weak g_client +#endif ERPC_MANUALLY_CONSTRUCTED_STATIC(BasicCodecFactory, s_codecFactory); ERPC_MANUALLY_CONSTRUCTED_STATIC(TransportArbitrator, s_arbitrator); diff --git a/erpc_c/setup/erpc_client_setup.cpp b/erpc_c/setup/erpc_client_setup.cpp index 52abbd03..36631c8a 100644 --- a/erpc_c/setup/erpc_client_setup.cpp +++ b/erpc_c/setup/erpc_client_setup.cpp @@ -29,8 +29,13 @@ using namespace erpc; // global client variables ERPC_MANUALLY_CONSTRUCTED_STATIC(ClientManager, s_client); +#if defined(__MINGW32__) +__declspec( selectany ) +#endif ClientManager *g_client; +#if !defined(__MINGW32__) #pragma weak g_client +#endif ERPC_MANUALLY_CONSTRUCTED_STATIC(BasicCodecFactory, s_codecFactory); ERPC_MANUALLY_CONSTRUCTED_STATIC(Crc16, s_crc16); diff --git a/erpc_c/transports/erpc_tcp_transport.cpp b/erpc_c/transports/erpc_tcp_transport.cpp index 59fac360..5709cbf8 100644 --- a/erpc_c/transports/erpc_tcp_transport.cpp +++ b/erpc_c/transports/erpc_tcp_transport.cpp @@ -13,24 +13,34 @@ #include extern "C" { +// Set this to 1 to enable debug logging. +// TODO fix issue with the transport not working on Linux if debug logging is disabled. +//#define TCP_TRANSPORT_DEBUG_LOG (1) + +#if TCP_TRANSPORT_DEBUG_LOG #if ERPC_HAS_POSIX +#if defined(__MINGW32__) +#error Missing implementation for mingw. +#endif #include #endif +#endif #include +#if defined(__MINGW32__) +#include +#include +#else #include #include -#include #include +#endif +#include #include #include } using namespace erpc; -// Set this to 1 to enable debug logging. -// TODO fix issue with the transport not working on Linux if debug logging is disabled. -//#define TCP_TRANSPORT_DEBUG_LOG (1) - #if TCP_TRANSPORT_DEBUG_LOG #define TCP_DEBUG_PRINT(_fmt_, ...) printf(_fmt_, ##__VA_ARGS__) #define TCP_DEBUG_ERR(_msg_) err(errno, _msg_) @@ -39,6 +49,12 @@ using namespace erpc; #define TCP_DEBUG_ERR(_msg_) #endif +#if defined(__MINGW32__) +#ifndef AI_NUMERICSERV +#define AI_NUMERICSERV 0x00000008 // Servicename must be a numeric port number +#endif +#endif + //////////////////////////////////////////////////////////////////////////////// // Code //////////////////////////////////////////////////////////////////////////////// @@ -47,20 +63,36 @@ TCPTransport::TCPTransport(bool isServer) : m_isServer(isServer) , m_host(NULL) , m_port(0) +#if defined(__MINGW32__) +, m_socket(INVALID_SOCKET) +#else , m_socket(-1) +#endif , m_serverThread(serverThreadStub) , m_runServer(true) { +#if defined(__MINGW32__) + WSADATA ws; + WSAStartup(MAKEWORD(2, 2), &ws); +#endif } TCPTransport::TCPTransport(const char *host, uint16_t port, bool isServer) : m_isServer(isServer) , m_host(host) , m_port(port) +#if defined(__MINGW32__) +, m_socket(INVALID_SOCKET) +#else , m_socket(-1) +#endif , m_serverThread(serverThreadStub) , m_runServer(true) { +#if defined(__MINGW32__) + WSADATA ws; + WSAStartup(MAKEWORD(2, 2), &ws); +#endif } TCPTransport::~TCPTransport(void) {} @@ -96,10 +128,18 @@ erpc_status_t TCPTransport::connectClient(void) char portString[8]; struct addrinfo *res0; int result, set; +#if defined(__MINGW32__) + SOCKET sock = INVALID_SOCKET; +#else int sock = -1; +#endif struct addrinfo *res; +#if defined(__MINGW32__) + if (m_socket != INVALID_SOCKET) +#else if (m_socket != -1) +#endif { TCP_DEBUG_PRINT("%s", "socket already connected\n"); } @@ -138,7 +178,11 @@ erpc_status_t TCPTransport::connectClient(void) { // Create the socket. sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); +#if defined(__MINGW32__) + if (sock == INVALID_SOCKET) +#else if (sock < 0) +#endif { continue; } @@ -146,8 +190,13 @@ erpc_status_t TCPTransport::connectClient(void) // Attempt to connect. if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) { +#if defined(__MINGW32__) + closesocket(sock); + sock = INVALID_SOCKET; +#else ::close(sock); sock = -1; +#endif continue; } @@ -159,7 +208,11 @@ erpc_status_t TCPTransport::connectClient(void) freeaddrinfo(res0); // Check if we were able to open a connection. +#if defined(__MINGW32__) + if (sock == INVALID_SOCKET) +#else if (sock < 0) +#endif { // TODO check EADDRNOTAVAIL: TCP_DEBUG_ERR("connecting failed"); @@ -170,9 +223,17 @@ erpc_status_t TCPTransport::connectClient(void) if (status == kErpcStatus_Success) { set = 1; +#if defined(__MINGW32__) + if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&set, sizeof(int)) < 0) +#else if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void *)&set, sizeof(int)) < 0) +#endif { +#if defined(__MINGW32__) + closesocket(sock); +#else ::close(sock); +#endif TCP_DEBUG_ERR("setsockopt failed"); status = kErpcStatus_Fail; } @@ -187,9 +248,17 @@ erpc_status_t TCPTransport::connectClient(void) // Disable SIGPIPE for this socket. This will cause write() to return an EPIPE statusor if the // other side has disappeared instead of our process receiving a SIGPIPE. set = 1; +#if defined(__MINGW32__) + if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (const char *)&set, sizeof(int)) < 0) +#else if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int)) < 0) +#endif { +#if defined(__MINGW32__) + closesocket(sock); +#else ::close(sock); +#endif TCP_DEBUG_ERR("setsockopt failed"); status = kErpcStatus_Fail; } @@ -199,7 +268,9 @@ erpc_status_t TCPTransport::connectClient(void) { #else // globally disable the SIGPIPE signal +#if !defined(__MINGW32__) signal(SIGPIPE, SIG_IGN); +#endif #endif // defined(SO_NOSIGPIPE) m_socket = sock; } @@ -215,11 +286,19 @@ erpc_status_t TCPTransport::close(bool stopServer) m_runServer = false; } +#if defined(__MINGW32__) + if (m_socket != INVALID_SOCKET) + { + closesocket(m_socket); + m_socket = INVALID_SOCKET; + } +#else if (m_socket != -1) { ::close(m_socket); m_socket = -1; } +#endif return kErpcStatus_Success; } @@ -230,7 +309,11 @@ erpc_status_t TCPTransport::underlyingReceive(uint8_t *data, uint32_t size) erpc_status_t status = kErpcStatus_Success; // Block until we have a valid connection. +#if defined(__MINGW32__) + while (m_socket == INVALID_SOCKET) +#else while (m_socket <= 0) +#endif { // Sleep 10 ms. Thread::sleep(10000); @@ -239,7 +322,11 @@ erpc_status_t TCPTransport::underlyingReceive(uint8_t *data, uint32_t size) // Loop until all requested data is received. while (size > 0U) { +#if defined(__MINGW32__) + length = recv(m_socket, (char *)data, size, 0); +#else length = read(m_socket, data, size); +#endif // Length will be zero if the connection is closed. if (length > 0) @@ -271,7 +358,11 @@ erpc_status_t TCPTransport::underlyingSend(const uint8_t *data, uint32_t size) erpc_status_t status = kErpcStatus_Success; ssize_t result; +#if defined(__MINGW32__) + if (m_socket == INVALID_SOCKET) +#else if (m_socket <= 0) +#endif { // we should not pretend to have a succesful Send or we create a deadlock status = kErpcStatus_ConnectionFailure; @@ -281,7 +372,11 @@ erpc_status_t TCPTransport::underlyingSend(const uint8_t *data, uint32_t size) // Loop until all data is sent. while (size > 0U) { +#if defined(__MINGW32__) + result = ::send(m_socket, (const char *)data, size, 0); +#else result = write(m_socket, data, size); +#endif if (result >= 0) { size -= result; @@ -310,7 +405,11 @@ erpc_status_t TCPTransport::underlyingSend(const uint8_t *data, uint32_t size) void TCPTransport::serverThread(void) { int yes = 1; +#if defined(__MINGW32__) + SOCKET serverSocket; +#else int serverSocket; +#endif int result; struct sockaddr incomingAddress; socklen_t incomingAddressLength; @@ -322,7 +421,11 @@ void TCPTransport::serverThread(void) // Create socket. serverSocket = socket(AF_INET, SOCK_STREAM, 0); +#if defined(__MINGW32__) + if (serverSocket == INVALID_SOCKET) +#else if (serverSocket < 0) +#endif { TCP_DEBUG_ERR("failed to create server socket"); } @@ -335,7 +438,11 @@ void TCPTransport::serverThread(void) serverAddress.sin_port = htons(m_port); // Turn on reuse address option. - result = setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); +#if defined(__MINGW32__) + result = setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes, sizeof(yes)); +#else + result = setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (const void *)&yes, sizeof(yes)); +#endif if (result < 0) { TCP_DEBUG_ERR("setsockopt failed"); @@ -373,13 +480,21 @@ void TCPTransport::serverThread(void) incomingAddressLength = sizeof(struct sockaddr); // we should use select() otherwise we can't end the server properly incomingSocket = accept(serverSocket, &incomingAddress, &incomingAddressLength); +#if defined(__MINGW32__) + if (incomingSocket != INVALID_SOCKET) +#else if (incomingSocket > 0) +#endif { // Successfully accepted a connection. m_socket = incomingSocket; // should be inherited from accept() socket but it's not always ... yes = 1; +#if defined(__MINGW32__) + setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, (const char *)&yes, sizeof(yes)); +#else setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, (void *)&yes, sizeof(yes)); +#endif } else { @@ -387,7 +502,11 @@ void TCPTransport::serverThread(void) } } } +#if defined(__MINGW32__) + closesocket(serverSocket); +#else ::close(serverSocket); +#endif } } diff --git a/erpc_c/transports/erpc_tcp_transport.hpp b/erpc_c/transports/erpc_tcp_transport.hpp index 4d7ed579..8bb74d4f 100644 --- a/erpc_c/transports/erpc_tcp_transport.hpp +++ b/erpc_c/transports/erpc_tcp_transport.hpp @@ -9,6 +9,10 @@ #ifndef _EMBEDDED_RPC__TCP_TRANSPORT_H_ #define _EMBEDDED_RPC__TCP_TRANSPORT_H_ +#if defined(__MINGW32__) +#include +#endif + #include "erpc_framed_transport.hpp" #include "erpc_threading.h" @@ -85,7 +89,11 @@ class TCPTransport : public FramedTransport bool m_isServer; /*!< If true then server is using transport, else client. */ const char *m_host; /*!< Specify the host name or IP address of the computer. */ uint16_t m_port; /*!< Specify the listening port number. */ +#if defined(__MINGW32__) + SOCKET m_socket; /*!< Socket number. */ +#else int m_socket; /*!< Socket number. */ +#endif Thread m_serverThread; /*!< Pointer to server thread. */ bool m_runServer; /*!< Thread is executed while this is true. */ diff --git a/erpcgen/src/templates/c_common_functions.template b/erpcgen/src/templates/c_common_functions.template index 712d3f8d..ee3c79fd 100644 --- a/erpcgen/src/templates/c_common_functions.template +++ b/erpcgen/src/templates/c_common_functions.template @@ -27,7 +27,11 @@ {% if empty(crc16) == false %} // for mdk/keil do not forgett add "--muldefweak" for linker extern const uint32_t erpc_generated_crc; +#if defined(__MINGW32__) +__declspec( selectany ) +#else #pragma weak erpc_generated_crc +#endif extern const uint32_t erpc_generated_crc = {$crc16}; {% endif -- empty(crc16) == false %} {% enddef --checkCrc %} @@ -38,7 +42,11 @@ extern const uint32_t erpc_generated_crc = {$crc16}; // Constant variable definitions {% for c in consts %} +#if defined(__MINGW32__) +__declspec( selectany ) +#else #pragma weak {$c.name} +#endif extern const {$c.typeAndName} = {$c.value}; {% endfor -- consts %} {% endif %} diff --git a/mk/common.mk b/mk/common.mk index aeb20dab..91de62a0 100644 --- a/mk/common.mk +++ b/mk/common.mk @@ -54,20 +54,13 @@ space := $(empty) $(empty) #------------------------------------------------------------------------------- # Get the OS name. Known values are "Linux", "CYGWIN_NT-5.1", and "Darwin". -os_name := $(shell uname -s) - -# Set to 1 if running on mingw. -ifeq "$(os_name)" "" +ifeq "$(and $(findstring Windows,$(OS)),1)" "1" os_name := $(shell powershell [System.Environment]::OSVersion.Version) ifneq "$(os_name)" "" - is_mingw := 1 + os_name := "MINGW" endif else - # Set to 1 if running on Darwin. - is_darwin := $(and $(findstring Darwin,$(os_name)),1) - - # Set to 1 if running on cygwin. - is_cygwin := $(and $(findstring CYGWIN,$(os_name)),1) + os_name := $(shell uname -s) # Set to 1 if running on redhat. is_redhat := $(shell if [ -f /etc/redhat-release ]; then echo 1 ; fi) @@ -75,6 +68,16 @@ else # Set to 1 if running on Linux. is_linux := $(and $(findstring Linux,$(os_name)),1) + # Set to 1 if running on Darwin. + is_darwin := $(and $(findstring Darwin,$(os_name)),1) +endif + +# Set to 1 if running on cygwin. +is_cygwin := $(and $(findstring CYGWIN,$(os_name)),1) + +# Set to 1 if running on Windows under Mingw. +is_mingw := $(and $(findstring MINGW,$(os_name)),1) +ifeq "$(is_mingw)" "" is_mingw := $(and $(findstring MSYS_NT,$(os_name)),1) endif diff --git a/mk/flags.mk b/mk/flags.mk index c22d9d55..8c282c0a 100644 --- a/mk/flags.mk +++ b/mk/flags.mk @@ -68,10 +68,6 @@ else CXXFLAGS += -g3 -O0 -DDEBUG -DYYDEBUG=1 endif -ifneq "$(is_mingw)" "1" - LIBRARIES += -lc -endif - ifneq "$(is_cygwin)" "1" LIBRARIES += -lstdc++ endif @@ -81,3 +77,9 @@ ifeq "$(is_linux)" "1" endif LIBRARIES += -lm + +ifeq "$(is_mingw)" "1" + LIBRARIES += -pthread -lws2_32 +else + LIBRARIES += -lc +endif diff --git a/mk/targets.mk b/mk/targets.mk index 1c603143..41074493 100644 --- a/mk/targets.mk +++ b/mk/targets.mk @@ -122,8 +122,8 @@ $(MAKE_TARGET): $(OBJECTS_ALL) @$(call printmessage,link,Linking, $(APP_NAME)) $(at)$(LD) $(LDFLAGS) \ $(OBJECTS_ALL) \ - $(LIBRARIES) \ - -o $@ + -o $@ \ + $(LIBRARIES) @echo "Output binary:" ; echo " $(APP_NAME)" endif diff --git a/test/common/gtest/gtest.cpp b/test/common/gtest/gtest.cpp index e2626e9a..4a7fc663 100644 --- a/test/common/gtest/gtest.cpp +++ b/test/common/gtest/gtest.cpp @@ -7044,9 +7044,11 @@ GTEST_DEFINE_string_( namespace internal { +# if !GTEST_OS_WINDOWS // Valid only for fast death tests. Indicates the code is running in the // child process of a fast style death test. static bool g_in_fast_death_test_child = false; +# endif // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as diff --git a/test/mk/erpc_src.mk b/test/mk/erpc_src.mk index d27e8f43..ace22ad9 100644 --- a/test/mk/erpc_src.mk +++ b/test/mk/erpc_src.mk @@ -46,6 +46,8 @@ SOURCES += $(UT_COMMON_SRC)/addOne.cpp \ $(ERPC_C_ROOT)/infra/erpc_transport_arbitrator.cpp \ $(ERPC_C_ROOT)/port/erpc_port_stdlib.cpp \ $(ERPC_C_ROOT)/port/erpc_threading_pthreads.cpp \ - $(ERPC_C_ROOT)/port/erpc_serial.cpp \ - $(ERPC_C_ROOT)/transports/erpc_serial_transport.cpp \ $(ERPC_C_ROOT)/transports/erpc_tcp_transport.cpp +ifeq "$(is_mingw)" "" + SOURCES += $(ERPC_C_ROOT)/transports/erpc_serial_transport.cpp \ + $(ERPC_C_ROOT)/port/erpc_serial.cpp +endif diff --git a/test/mk/test.mk b/test/mk/test.mk index 4ab0ab21..8853482b 100644 --- a/test/mk/test.mk +++ b/test/mk/test.mk @@ -106,6 +106,9 @@ $(ERPC_OUT_DIR)/$(ERPC_NAME)/$(APP_TYPE).py: $(IDL_FILE) # Add libtest.a to build. LIBRARIES += -ltest LDFLAGS += -L$(OUTPUT_ROOT)/$(DEBUG_OR_RELEASE)/$(os_name)/test/lib +ifeq "$(is_mingw)" "1" + LIBRARIES += -lws2_32 +endif else ERPC_C_ROOT = $(ERPC_ROOT)/erpc_c diff --git a/test/mk/unit_test.mk b/test/mk/unit_test.mk index 7c80b813..0d7ce17a 100644 --- a/test/mk/unit_test.mk +++ b/test/mk/unit_test.mk @@ -30,6 +30,14 @@ UT_OUTPUT_DIR = $(OUTPUT_ROOT)/test/$(TEST_NAME) TCP_CLIENT_PATH = $(UT_OUTPUT_DIR)/$(os_name)/tcp/gcc/$(CLIENT_NAME)/$(DEBUG_OR_RELEASE)/$(CLIENT_NAME)_tcp_test TCP_SERVER_PATH = $(UT_OUTPUT_DIR)/$(os_name)/tcp/gcc/$(SERVER_NAME)/$(DEBUG_OR_RELEASE)/$(SERVER_NAME)_tcp_test +test_server_serial = test_server_serial +test_client_serial = test_client_serial +clean_serial = clean_serial +ifeq "$(is_mingw)" "1" + test_server_serial = + test_client_serial = + clean_serial = +endif .PHONY: all all: test_lib test_client test_server @@ -50,7 +58,7 @@ test-serial: test_lib test_client_serial test_server_serial fresh: clean all .PHONY: test_client -test_client: test_client_tcp test_client_serial +test_client: test_client_tcp $(test_client_serial) .PHONY: test_client_tcp test_client_tcp: erpcgen @@ -67,7 +75,7 @@ else endif .PHONY: test_server -test_server: test_server_tcp test_server_serial +test_server: test_server_tcp $(test_server_serial) .PHONY: test_server_tcp test_server_tcp: erpcgen @@ -105,7 +113,7 @@ run-erpcgen-common: erpcgen #cleans only output directories related to this unit test .PHONY: clean clean_serial clean_tcp -clean: clean_serial clean_tcp +clean: $(clean_serial) clean_tcp clean_tcp: @echo Cleaning $(TEST_NAME)_tcp... diff --git a/test/run_unit_tests.py b/test/run_unit_tests.py index 34a703a7..229a4883 100644 --- a/test/run_unit_tests.py +++ b/test/run_unit_tests.py @@ -12,10 +12,11 @@ # then run # $./run_unit_tests.py [tcp] # to run this script with optional transport layer argument -from subprocess import call +import subprocess import re import os import sys +import time #define output text colour class class bcolors: @@ -36,6 +37,7 @@ def isTestDir(dir): testServerCommand = "run-tcp-server" transportLayer = "tcp" target = "release" +make = "make" # Process command line options # Check for 2 or more arguments because argv[0] is the script name @@ -52,6 +54,8 @@ def isTestDir(dir): target = "debug" elif arg == "-r": target = "release" + elif "-m" in arg: + make = arg[2:] else: print("Invalid argument/s. Options are: tcp, -r, -d\n") sys.exit(1) @@ -72,8 +76,9 @@ def isTestDir(dir): print(bcolors.BLUE + "\nRunning " + bcolors.ORANGE + dir + bcolors.BLUE +" unit tests with " + bcolors.ORANGE + transportLayer + bcolors.BLUE + " transport layer." + bcolors.ENDC) os.chdir(dir) - call(["make", build, testServerCommand]) - testsExitStatus += call(["make", build, testClientCommand]) + subprocess.Popen([make, build, testServerCommand]) + time.sleep(0.1) + testsExitStatus += subprocess.call([make, build, testClientCommand]) os.chdir('..') # For completeness, change back to erpc/ directory From 3b4746d0718457c9b376bb1ddba9bb9d2f01dc46 Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Wed, 11 Oct 2023 09:32:09 +0200 Subject: [PATCH 10/24] A bit nicer CI config (#383) Signed-off-by: Cervenka Dusan --- .circleci/config.yml | 42 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 7f1a2e7e..d714b6b7 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,45 +3,69 @@ version: 2.1 orbs: win: circleci/windows@5.0 # The Windows orb gives you everything you need to start using the +commands: + install_dependencies: + parameters: + compiler: + default: "" + type: string + steps: + - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh <> + run_tests: + parameters: + compiler: + default: "" + type: string + steps: + - run: chmod u+x run_tests.sh && ./run_tests.sh <> + jobs: build-linux-gcc: machine: image: ubuntu-2204:2022.04.2 #https://circleci.com/developer/machine/image/ubuntu-2204 pick LTS steps: - checkout - - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh - - run: chmod u+x run_tests.sh && ./run_tests.sh + - install_dependencies + - run_tests - store_artifacts: path: ./Release/Linux/erpcgen/erpcgen + build-linux-clang: machine: image: ubuntu-2204:2022.04.2 #https://circleci.com/developer/machine/image/ubuntu-2204 pick LTS steps: - checkout - - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh clang - - run: chmod u+x run_tests.sh && ./run_tests.sh clang + - install_dependencies: + compiler: "clang" + - run_tests: + compiler: "clang" # - store_artifacts: # path: ./Release/Linux/erpcgen/erpcgen + build-mac-gcc: macos: xcode: 12.5.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases resource_class: macos.x86.medium.gen2 steps: - checkout - - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh - - run: chmod u+x run_tests.sh && ./run_tests.sh + - install_dependencies + - run_tests - store_artifacts: path: ./Release/Darwin/erpcgen/erpcgen + build-mac-clang: macos: xcode: 12.5.1 # https://circleci.com/docs/using-macos/#supported-xcode-versions https://en.wikipedia.org/wiki/MacOS_version_history#Releases resource_class: macos.x86.medium.gen2 steps: - checkout - - run: chmod u+x install_dependencies.sh && ./install_dependencies.sh clang - - run: chmod u+x run_tests.sh && ./run_tests.sh clang + - install_dependencies: + compiler: "clang" + - run_tests: + compiler: "clang" # - store_artifacts: # path: ./Release/Darwin/erpcgen/erpcgen + build-windows-mingw: executor: name: win/default @@ -53,6 +77,7 @@ jobs: - run: .\mingw64\opt\bin\python3.exe .\test\run_unit_tests.py -m"..\\..\\mingw64\\bin\\mingw32-make" # - store_artifacts: # path: ./Release/MINGW64/erpcgen/erpcgen.exe + build-windows-VS: executor: name: win/default @@ -66,6 +91,7 @@ jobs: - run: powershell.exe "& 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\MSBuild.exe' .\erpcgen\VisualStudio_v14\erpcgen.sln /property:Configuration=Release" - store_artifacts: path: ./erpcgen/VisualStudio_v14/Release/erpcgen.exe + workflows: build-workflow: jobs: From 7f98fda93b09974487f9ed5d2ce4dd833b45664f Mon Sep 17 00:00:00 2001 From: "Michal Princ (nxa17570)" Date: Thu, 12 Oct 2023 13:55:11 +0200 Subject: [PATCH 11/24] Update README.md to reference main branch instead of removed master --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40cd0260..52bab81c 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ To install the Python infrastructure for eRPC see instructions in the [erpc_pyth ## Code providing -Repository on Github contains two main branches. __Master__ and __develop__. Code is developed on __develop__ branch. Release version is created via merging __develop__ branch into __master__ branch. +Repository on Github contains two main branches: __main__ and __develop__. Code is developed on __develop__ branch. Release version is created via merging __develop__ branch into __main__ branch. --- Copyright 2014-2016 Freescale Semiconductor, Inc. From 8616dbe4edeb83675ca047c5c66f51c65a4b2cec Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Tue, 17 Oct 2023 16:37:06 +0200 Subject: [PATCH 12/24] Feature/support multiple clients (#271) * Implementing better C++ eRPC support Signed-off-by: Cervenka Dusan * Moving C interface related function declarations into interface header file. Signed-off-by: Cervenka Dusan * Move C generated code into it's own files. Signed-off-by: Cervenka Dusan * Many C++ minor fixes Signed-off-by: Cervenka Dusan * C support multiple clients Signed-off-by: Cervenka Dusan * Tests can be built. Signed-off-by: Cervenka Dusan * Fixed infinity loops in tests (c++ vs c scope) Signed-off-by: Cervenka Dusan * test_callbacks works Signed-off-by: Cervenka Dusan * test_arbitrator is working now Signed-off-by: Cervenka Dusan * Many minor code improvements. Signed-off-by: Cervenka Dusan * Namespace can be defined by user. Default erpcshim Signed-off-by: Cervenka Dusan * Putting function declaration under interface. Signed-off-by: Cervenka Dusan * Refactored code Signed-off-by: Cervenka Dusan * Fixed yml tests. Signed-off-by: Cervenka Dusan * Added c++ enum classes Signed-off-by: Cervenka Dusan * Change based on PR review Signed-off-by: Cervenka Dusan * Revert "Added c++ enum classes" This reverts commit d5acf06b5d93aa7d4fdb87feb132813cc2531c25. Signed-off-by: Cervenka Dusan * Fixes based on Michal observations Signed-off-by: Cervenka Dusan * Fix wrong name in server function call Signed-off-by: Cervenka Dusan --------- Signed-off-by: Cervenka Dusan Co-authored-by: Michal Princ --- .clang-format | 2 +- erpc_c/Makefile | 2 + .../infra/erpc_arbitrated_client_manager.hpp | 2 +- erpc_c/infra/erpc_basic_codec.cpp | 59 -- erpc_c/infra/erpc_basic_codec.hpp | 34 -- erpc_c/infra/erpc_client_manager.h | 2 + erpc_c/infra/erpc_client_server_common.hpp | 13 +- erpc_c/infra/erpc_codec.hpp | 36 +- erpc_c/infra/erpc_framed_transport.hpp | 2 +- erpc_c/infra/erpc_manually_constructed.hpp | 2 +- erpc_c/infra/erpc_message_buffer.hpp | 6 +- erpc_c/infra/erpc_static_queue.hpp | 1 + erpc_c/infra/erpc_transport_arbitrator.hpp | 6 +- erpc_c/infra/erpc_utils.cpp | 26 + erpc_c/infra/erpc_utils.hpp | 17 + erpc_c/port/erpc_serial.cpp | 2 +- erpc_c/setup/erpc_transport_setup.h | 1 - .../transports/erpc_dspi_slave_transport.cpp | 3 +- .../transports/erpc_i2c_slave_transport.cpp | 3 +- .../transports/erpc_i2c_slave_transport.hpp | 2 +- erpc_c/transports/erpc_mu_transport.hpp | 3 +- .../transports/erpc_rpmsg_linux_transport.hpp | 2 +- .../transports/erpc_rpmsg_lite_transport.hpp | 2 +- .../erpc_rpmsg_tty_rtos_transport.hpp | 2 +- .../transports/erpc_spi_master_transport.cpp | 3 +- .../transports/erpc_spi_master_transport.hpp | 3 +- .../transports/erpc_spi_slave_transport.cpp | 3 +- .../transports/erpc_spi_slave_transport.hpp | 2 +- erpc_c/transports/erpc_usb_cdc_transport.hpp | 2 +- erpcgen/Makefile | 22 +- erpcgen/VisualStudio_v14/.gitignore | 11 +- erpcgen/VisualStudio_v14/erpcgen.vcxproj | 39 +- .../VisualStudio_v14/erpcgen.vcxproj.filters | 31 +- erpcgen/src/CGenerator.cpp | 531 ++++++++++-------- erpcgen/src/CGenerator.hpp | 98 +++- erpcgen/src/Generator.cpp | 125 ++++- erpcgen/src/Generator.hpp | 49 +- erpcgen/src/PythonGenerator.cpp | 65 +-- erpcgen/src/PythonGenerator.hpp | 31 +- erpcgen/src/SymbolScanner.cpp | 287 ++++++---- erpcgen/src/SymbolScanner.hpp | 2 +- erpcgen/src/UniqueIdChecker.cpp | 2 +- erpcgen/src/UniqueIdChecker.hpp | 6 +- erpcgen/src/annotations.h | 6 +- erpcgen/src/erpcgen.cpp | 24 +- erpcgen/src/erpcgen_lexer.l | 2 + erpcgen/src/erpcgen_parser.y | 62 +- .../src/templates/c_client_header.template | 70 +++ .../src/templates/c_client_source.template | 239 +++----- .../src/templates/c_common_header.template | 59 +- .../src/templates/c_server_header.template | 83 +-- .../src/templates/c_server_source.template | 292 +++------- .../src/templates/cpp_client_header.template | 36 ++ .../src/templates/cpp_client_source.template | 198 +++++++ ...{c_coders.template => cpp_coders.template} | 20 +- ...template => cpp_common_functions.template} | 41 +- .../templates/cpp_interface_header.template | 60 ++ .../templates/cpp_interface_source.template | 57 ++ .../src/templates/cpp_server_header.template | 46 ++ .../src/templates/cpp_server_source.template | 253 +++++++++ erpcgen/src/types/Function.hpp | 35 +- erpcgen/src/types/FunctionType.hpp | 5 +- erpcgen/src/types/Group.hpp | 1 + erpcgen/src/types/Interface.hpp | 31 +- erpcgen/src/types/Type.cpp | 8 + erpcgen/test/conftest.py | 139 ++++- erpcgen/test/test_builtin_types.yml | 6 +- erpcgen/test/test_comments.yml | 10 +- erpcgen/test/test_enum.yml | 12 +- erpcgen/test/test_error_checks_c.yml | 24 +- erpcgen/test/test_error_return_c.yml | 4 +- erpcgen/test/test_expressions.yml | 2 +- erpcgen/test/test_extern_c.yml | 4 +- erpcgen/test/test_forward_declaration_c.yml | 43 +- erpcgen/test/test_import.yml | 8 +- erpcgen/test/test_include.yml | 21 +- .../test/test_includes/test_includes_union.h | 7 +- erpcgen/test/test_name_c.yml | 15 +- erpcgen/test/test_nullable_c.yml | 19 +- erpcgen/test/test_redundant_definitions.yml | 36 +- erpcgen/test/test_scope_c.yml | 8 +- erpcgen/test/test_service_c.yml | 16 +- erpcgen/test/test_struct.yml | 10 +- erpcgen/test/test_types_header.yml | 33 -- erpcgen/test/test_union_c.yml | 17 +- erpcsniffer/src/Sniffer.cpp | 2 +- erpcsniffer/src/erpcsniffer.cpp | 12 +- run_tests.sh | 3 +- test/common/gtestListener.hpp | 8 +- test/common/myAlloc.hpp | 12 +- test/common/unit_test_arbitrator_app0.cpp | 13 +- test/common/unit_test_arbitrator_app1.cpp | 7 +- test/common/unit_test_client.cpp | 17 +- test/common/unit_test_serial_client.cpp | 13 +- test/common/unit_test_serial_server.cpp | 56 +- test/common/unit_test_server.cpp | 17 +- .../unit_test_tcp_arbitrator_client.cpp | 11 +- .../unit_test_tcp_arbitrator_server.cpp | 8 +- test/common/unit_test_tcp_client.cpp | 13 +- test/common/unit_test_tcp_server.cpp | 56 +- test/common/unit_test_wrapped.h | 7 + test/mk/erpc_src.mk | 1 + test/mk/test.mk | 18 +- test/mk/unit_test.mk | 4 +- test/run_unit_tests.py | 42 +- test/test_annotations/external.h | 2 + .../test_annotations_client_impl.cpp | 8 +- .../test_annotations_server_impl.cpp | 42 +- test/test_arbitrator/client.mk | 9 +- test/test_arbitrator/server.mk | 8 + test/test_arbitrator/test_arbitrator.erpc | 1 + .../test_arbitrator_client_impl.cpp | 43 +- .../test_arbitrator_server_impl.cpp | 64 ++- test/test_arrays/test_arrays_client_impl.cpp | 8 +- test/test_arrays/test_arrays_server_impl.cpp | 192 ++++++- test/test_binary/test_binary_client_impl.cpp | 8 +- test/test_binary/test_binary_server_impl.cpp | 30 +- .../test_builtin/test_builtin_client_impl.cpp | 8 +- .../test_builtin/test_builtin_server_impl.cpp | 104 +++- test/test_callbacks/callbacks1.h | 11 - test/test_callbacks/callbacks2.h | 9 - test/test_callbacks/client.mk | 44 ++ test/test_callbacks/server.mk | 44 ++ test/test_callbacks/test_callbacks.erpc | 17 +- .../test_callbacks_client_impl.cpp | 9 +- .../test_callbacks_server_impl.cpp | 132 ++++- test/test_const/test_const_client_impl.cpp | 5 +- test/test_const/test_const_server_impl.cpp | 10 +- test/test_enums/test_enums_client_impl.cpp | 8 +- test/test_enums/test_enums_server_impl.cpp | 61 +- test/test_lists/test_lists_client_impl.cpp | 8 +- test/test_lists/test_lists_server_impl.cpp | 121 +++- test/test_shared/test_shared_client_impl.cpp | 8 +- test/test_shared/test_shared_server_impl.cpp | 30 +- test/test_struct/test_struct_client_impl.cpp | 9 +- test/test_struct/test_struct_server_impl.cpp | 144 ++++- .../test_typedef/test_typedef_client_impl.cpp | 8 +- .../test_typedef/test_typedef_server_impl.cpp | 68 ++- test/test_unions/test_unions_client_impl.cpp | 8 +- test/test_unions/test_unions_server_impl.cpp | 52 +- 140 files changed, 3658 insertions(+), 1599 deletions(-) create mode 100644 erpc_c/infra/erpc_utils.cpp create mode 100644 erpc_c/infra/erpc_utils.hpp create mode 100644 erpcgen/src/templates/c_client_header.template create mode 100644 erpcgen/src/templates/cpp_client_header.template create mode 100644 erpcgen/src/templates/cpp_client_source.template rename erpcgen/src/templates/{c_coders.template => cpp_coders.template} (92%) rename erpcgen/src/templates/{c_common_functions.template => cpp_common_functions.template} (95%) create mode 100644 erpcgen/src/templates/cpp_interface_header.template create mode 100644 erpcgen/src/templates/cpp_interface_source.template create mode 100644 erpcgen/src/templates/cpp_server_header.template create mode 100644 erpcgen/src/templates/cpp_server_source.template delete mode 100644 erpcgen/test/test_types_header.yml delete mode 100644 test/test_callbacks/callbacks1.h delete mode 100644 test/test_callbacks/callbacks2.h create mode 100644 test/test_callbacks/client.mk create mode 100644 test/test_callbacks/server.mk diff --git a/.clang-format b/.clang-format index eeed4bea..c2333882 100644 --- a/.clang-format +++ b/.clang-format @@ -63,7 +63,7 @@ BraceWrapping: AfterUnion: true BeforeCatch: true BeforeElse: true -#IncludeBlocks: "Preserve" # for future version of clang +IncludeBlocks: "Preserve" # for future version of clang IncludeCategories: - Regex: "^<" # system includes Priority: 10 diff --git a/erpc_c/Makefile b/erpc_c/Makefile index 0637a6dc..71957b44 100644 --- a/erpc_c/Makefile +++ b/erpc_c/Makefile @@ -60,6 +60,7 @@ SOURCES += $(ERPC_C_ROOT)/infra/erpc_arbitrated_client_manager.cpp \ $(ERPC_C_ROOT)/infra/erpc_server.cpp \ $(ERPC_C_ROOT)/infra/erpc_simple_server.cpp \ $(ERPC_C_ROOT)/infra/erpc_transport_arbitrator.cpp \ + $(ERPC_C_ROOT)/infra/erpc_utils.cpp \ $(ERPC_C_ROOT)/infra/erpc_pre_post_action.cpp \ $(ERPC_C_ROOT)/port/erpc_port_stdlib.cpp \ $(ERPC_C_ROOT)/port/erpc_threading_pthreads.cpp \ @@ -93,6 +94,7 @@ HEADERS += $(ERPC_C_ROOT)/config/erpc_config.h \ $(ERPC_C_ROOT)/infra/erpc_static_queue.hpp \ $(ERPC_C_ROOT)/infra/erpc_transport_arbitrator.hpp \ $(ERPC_C_ROOT)/infra/erpc_transport.hpp \ + $(ERPC_C_ROOT)/infra/erpc_utils.hpp \ $(ERPC_C_ROOT)/infra/erpc_client_server_common.hpp \ $(ERPC_C_ROOT)/infra/erpc_pre_post_action.h \ $(ERPC_C_ROOT)/port/erpc_setup_extensions.h \ diff --git a/erpc_c/infra/erpc_arbitrated_client_manager.hpp b/erpc_c/infra/erpc_arbitrated_client_manager.hpp index fa2e45a1..33b65ab7 100644 --- a/erpc_c/infra/erpc_arbitrated_client_manager.hpp +++ b/erpc_c/infra/erpc_arbitrated_client_manager.hpp @@ -63,7 +63,7 @@ class ArbitratedClientManager : public ClientManager * * @return TransportArbitrator * Transport arbitrator instance. */ - TransportArbitrator *getArbitrator(void) { return m_arbitrator; }; + TransportArbitrator * getArbitrator(void) { return m_arbitrator; }; protected: TransportArbitrator *m_arbitrator; //!< Optional transport arbitrator. May be NULL. diff --git a/erpc_c/infra/erpc_basic_codec.cpp b/erpc_c/infra/erpc_basic_codec.cpp index 4c3adaa1..7fc54407 100644 --- a/erpc_c/infra/erpc_basic_codec.cpp +++ b/erpc_c/infra/erpc_basic_codec.cpp @@ -161,37 +161,6 @@ void BasicCodec::writeNullFlag(bool isNull) write(static_cast(isNull ? null_flag_t::kIsNull : null_flag_t::kNotNull)); } -void BasicCodec::writeCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr callback) -{ - uint8_t i; - - erpc_assert(callbacksCount > 1U); - - // callbacks = callbacks table - for (i = 0; i < callbacksCount; i++) - { - if (callbacks[i] == callback) - { - write(i); - break; - } - if ((i + 1U) == callbacksCount) - { - updateStatus(kErpcStatus_UnknownCallback); - } - } -} - -void BasicCodec::writeCallback(funPtr callback1, funPtr callback2) -{ - // callbacks = callback directly - // When declared only one callback function no serialization is needed. - if (callback1 != callback2) - { - updateStatus(kErpcStatus_UnknownCallback); - } -} - void BasicCodec::startReadMessage(message_type_t &type, uint32_t &service, uint32_t &request, uint32_t &sequence) { uint32_t header; @@ -396,34 +365,6 @@ void BasicCodec::readNullFlag(bool &isNull) } } -void BasicCodec::readCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr *callback) -{ - uint8_t _tmp_local; - - erpc_assert(callbacksCount > 1U); - - // callbacks = callbacks table - read(_tmp_local); - if (isStatusOk()) - { - if (_tmp_local < callbacksCount) - { - *callback = callbacks[_tmp_local]; - } - else - { - *callback = NULL; - m_status = kErpcStatus_UnknownCallback; - } - } -} - -void BasicCodec::readCallback(funPtr callbacks1, funPtr *callback2) -{ - // callbacks = callback directly - *callback2 = callbacks1; -} - ERPC_MANUALLY_CONSTRUCTED_ARRAY_STATIC(BasicCodec, s_basicCodecManual, ERPC_CODEC_COUNT); Codec *BasicCodecFactory::create(void) diff --git a/erpc_c/infra/erpc_basic_codec.hpp b/erpc_c/infra/erpc_basic_codec.hpp index 204b9a9e..c39a0c64 100644 --- a/erpc_c/infra/erpc_basic_codec.hpp +++ b/erpc_c/infra/erpc_basic_codec.hpp @@ -189,23 +189,6 @@ class BasicCodec : public Codec * @param[in] isNull Null flag to send. */ virtual void writeNullFlag(bool isNull) override; - - /*! - * @brief Writes an order ID of callback function. - * - * @param[in] callbacks Pointer to array of callbacks. - * @param[in] callbacksCount Size of array of callbacks. - * @param[in] callback Callback which ID should be serialized. - */ - virtual void writeCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr callback) override; - - /*! - * @brief Writes an order ID of callback function. - * - * @param[in] callback1 Pointer to existing callback. - * @param[out] callback2 Callback which ID should be serialized. - */ - virtual void writeCallback(funPtr callback1, funPtr callback2) override; //@} //! @name Decoding @@ -350,23 +333,6 @@ class BasicCodec : public Codec * @param[in] isNull Null flag to read. */ virtual void readNullFlag(bool &isNull) override; - - /*! - * @brief Read an callback function id and return address of callback function. - * - * @param[in] callbacks Pointer to array of callbacks. - * @param[in] callbacksCount Size of array of callbacks. - * @param[out] callback Callback which is deserialized. Null in case of error. - */ - virtual void readCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr *callback) override; - - /*! - * @brief Read an callback function id and return address of callback function. - * - * @param[in] callback1 Pointer to existing callback. - * @param[out] callback2 Callback which is deserialized. - */ - virtual void readCallback(funPtr callbacks1, funPtr *callback2) override; //@} }; diff --git a/erpc_c/infra/erpc_client_manager.h b/erpc_c/infra/erpc_client_manager.h index 1a1dd801..2a301642 100644 --- a/erpc_c/infra/erpc_client_manager.h +++ b/erpc_c/infra/erpc_client_manager.h @@ -25,6 +25,8 @@ */ extern "C" { +#else +#include "erpc_common.h" #endif typedef void (*client_error_handler_t)(erpc_status_t err, diff --git a/erpc_c/infra/erpc_client_server_common.hpp b/erpc_c/infra/erpc_client_server_common.hpp index 0c172461..68ee2a94 100644 --- a/erpc_c/infra/erpc_client_server_common.hpp +++ b/erpc_c/infra/erpc_client_server_common.hpp @@ -10,8 +10,8 @@ #ifndef _EMBEDDED_RPC__CLIENTSERVERCOMMON_H_ #define _EMBEDDED_RPC__CLIENTSERVERCOMMON_H_ -#include "erpc_config_internal.h" #include "erpc_codec.hpp" +#include "erpc_config_internal.h" #if ERPC_MESSAGE_LOGGING #include "erpc_message_loggers.hpp" #endif @@ -66,7 +66,7 @@ class ClientServerCommon #endif #if ERPC_MESSAGE_LOGGING #ifdef ERPC_OTHER_INHERITANCE - , + , #else #define ERPC_OTHER_INHERITANCE 1 : @@ -75,7 +75,7 @@ class ClientServerCommon #endif #if ERPC_PRE_POST_ACTION #ifdef ERPC_OTHER_INHERITANCE - , + , #else #define ERPC_OTHER_INHERITANCE 1 : @@ -83,12 +83,15 @@ class ClientServerCommon PrePostAction() #endif #ifdef ERPC_OTHER_INHERITANCE - , + , #else #define ERPC_OTHER_INHERITANCE 1 : #endif - m_messageFactory(NULL), m_codecFactory(NULL), m_transport(NULL){}; + m_messageFactory(NULL) + , m_codecFactory(NULL) + , m_transport(NULL) + {}; /*! * @brief ClientServerCommon destructor diff --git a/erpc_c/infra/erpc_codec.hpp b/erpc_c/infra/erpc_codec.hpp index 14356fcd..c436f38b 100644 --- a/erpc_c/infra/erpc_codec.hpp +++ b/erpc_c/infra/erpc_codec.hpp @@ -15,8 +15,8 @@ #include "erpc_message_buffer.hpp" #include "erpc_transport.hpp" +#include #include -#include /*! * @addtogroup infra_codec @@ -257,23 +257,6 @@ class Codec * @param[in] isNull Null flag to send. */ virtual void writeNullFlag(bool isNull) = 0; - - /*! - * @brief Writes an order ID of callback function. - * - * @param[in] callbacks Pointer to array of callbacks. - * @param[in] callbacksCount Size of array of callbacks. - * @param[in] callback Callback which ID should be serialized. - */ - virtual void writeCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr callback) = 0; - - /*! - * @brief Writes an order ID of callback function. - * - * @param[in] callback1 Pointer to existing callback. - * @param[out] callback2 Callback which ID should be serialized. - */ - virtual void writeCallback(funPtr callback1, funPtr callback2) = 0; //@} //! @name Decoding @@ -410,23 +393,6 @@ class Codec */ virtual void readNullFlag(bool &isNull) = 0; - /*! - * @brief Read an callback function id and return address of callback function. - * - * @param[in] callbacks Pointer to array of callbacks. - * @param[in] callbacksCount Size of array of callbacks. - * @param[out] callback Callback which is deserialized. Null in case of error. - */ - virtual void readCallback(arrayOfFunPtr callbacks, uint8_t callbacksCount, funPtr *callback) = 0; - - /*! - * @brief Read an callback function id and return address of callback function. - * - * @param[in] callback1 Pointer to existing callback. - * @param[out] callback2 Callback which is deserialized. - */ - virtual void readCallback(funPtr callbacks1, funPtr *callback2) = 0; - protected: MessageBuffer m_buffer; /*!< Message buffer object */ MessageBuffer::Cursor m_cursor; /*!< Copy data to message buffers. */ diff --git a/erpc_c/infra/erpc_framed_transport.hpp b/erpc_c/infra/erpc_framed_transport.hpp index dac35770..580b0ab8 100644 --- a/erpc_c/infra/erpc_framed_transport.hpp +++ b/erpc_c/infra/erpc_framed_transport.hpp @@ -114,7 +114,7 @@ class FramedTransport : public Transport * * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. */ - virtual Crc16 *getCrc16() override; + virtual Crc16 *getCrc16(void) override; protected: Crc16 *m_crcImpl; /*!< CRC object. */ diff --git a/erpc_c/infra/erpc_manually_constructed.hpp b/erpc_c/infra/erpc_manually_constructed.hpp index 119c4a02..de4f9f7e 100644 --- a/erpc_c/infra/erpc_manually_constructed.hpp +++ b/erpc_c/infra/erpc_manually_constructed.hpp @@ -161,7 +161,7 @@ class ManuallyConstructed * @brief Returns information if object is free or is used. * * @return true Object is constructed and used. - * @return false Object wasn't constructer or it is destructed and free. + * @return false Object wasn't constructed or it was destructed already. */ bool isUsed(void) { return m_isConstructed; } diff --git a/erpc_c/infra/erpc_message_buffer.hpp b/erpc_c/infra/erpc_message_buffer.hpp index bfd67edd..d815ca74 100644 --- a/erpc_c/infra/erpc_message_buffer.hpp +++ b/erpc_c/infra/erpc_message_buffer.hpp @@ -308,9 +308,9 @@ class MessageBuffer Cursor &operator+=(uint16_t n); /*! - * @brief Substract operator return local buffer. + * @brief Subtract operator return local buffer. * - * @param[in] n Substracting with n. + * @param[in] n Subtracting with n. * * @return Current cursor instance. */ @@ -324,7 +324,7 @@ class MessageBuffer Cursor &operator++(void); /*! - * @brief Substract -1 operator. + * @brief Subtract -1 operator. * * @return Current cursor instance. */ diff --git a/erpc_c/infra/erpc_static_queue.hpp b/erpc_c/infra/erpc_static_queue.hpp index 2bedfeba..d1996fbb 100644 --- a/erpc_c/infra/erpc_static_queue.hpp +++ b/erpc_c/infra/erpc_static_queue.hpp @@ -11,6 +11,7 @@ #define __embedded_rpc__static_queue__ #include +#include /*! * @addtogroup infra_utility diff --git a/erpc_c/infra/erpc_transport_arbitrator.hpp b/erpc_c/infra/erpc_transport_arbitrator.hpp index 34bad73b..891ed7a3 100644 --- a/erpc_c/infra/erpc_transport_arbitrator.hpp +++ b/erpc_c/infra/erpc_transport_arbitrator.hpp @@ -65,7 +65,7 @@ class TransportArbitrator : public Transport * * @return Transport * Returns shared client/server transport. */ - Transport *getSharedTransport(void) { return m_sharedTransport; } + Transport * getSharedTransport(void) { return m_sharedTransport; } /*! * @brief This function set codec. @@ -79,7 +79,7 @@ class TransportArbitrator : public Transport * * @return Codec * Pointer to codec used within transport. */ - Codec *getCodec(void) { return m_codec; } + Codec * getCodec(void) { return m_codec; } /*! * @brief Prototype for receiving message. @@ -140,7 +140,7 @@ class TransportArbitrator : public Transport * * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. */ - virtual Crc16 *getCrc16(void) override; + virtual Crc16 * getCrc16(void) override; /*! * @brief Check if the underlying shared transport has a message diff --git a/erpc_c/infra/erpc_utils.cpp b/erpc_c/infra/erpc_utils.cpp new file mode 100644 index 00000000..f59acbb6 --- /dev/null +++ b/erpc_c/infra/erpc_utils.cpp @@ -0,0 +1,26 @@ +/* + * Copyright 2023 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_utils.hpp" + +bool erpc::findIndexOfFunction(const arrayOfFunctionPtr_t sourceArrayOfFunctionPtr, uint16_t sourceArrayLength, + const functionPtr_t functionPtr, uint16_t &retVal) +{ + uint32_t index; + bool find = false; + for (index = 0; index < sourceArrayLength; index++) + { + if (sourceArrayOfFunctionPtr[index] == functionPtr) + { + retVal = index; + find = true; + break; + } + } + return find; +} diff --git a/erpc_c/infra/erpc_utils.hpp b/erpc_c/infra/erpc_utils.hpp new file mode 100644 index 00000000..9b2f97d5 --- /dev/null +++ b/erpc_c/infra/erpc_utils.hpp @@ -0,0 +1,17 @@ +/* + * Copyright 2023 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +namespace erpc { +typedef void *functionPtr_t; +typedef functionPtr_t *arrayOfFunctionPtr_t; + +bool findIndexOfFunction(const arrayOfFunctionPtr_t sourceArrayOfFunctionPtr, uint16_t sourceArrayLength, + const functionPtr_t functionPtr, uint16_t &retVal); +} diff --git a/erpc_c/port/erpc_serial.cpp b/erpc_c/port/erpc_serial.cpp index 9f94799d..2423ca8e 100644 --- a/erpc_c/port/erpc_serial.cpp +++ b/erpc_c/port/erpc_serial.cpp @@ -135,7 +135,7 @@ int serial_setup(int fd, speed_t speed) #ifdef __APPLE__ return ioctl(fd, IOSSIOSPEED, &speed); -#endif //#ifdef __APPLE__ +#endif // #ifdef __APPLE__ #endif // _WIN32 return 0; diff --git a/erpc_c/setup/erpc_transport_setup.h b/erpc_c/setup/erpc_transport_setup.h index bf36bda6..d72db62f 100644 --- a/erpc_c/setup/erpc_transport_setup.h +++ b/erpc_c/setup/erpc_transport_setup.h @@ -151,7 +151,6 @@ void erpc_transport_lpi2c_slave_deinit(erpc_transport_t transport); */ erpc_transport_t erpc_transport_lpspi_slave_init(void *baseAddr, uint32_t baudRate, uint32_t srcClock_Hz); - /*! * @brief Deinitialize LPSPI slave transport. * diff --git a/erpc_c/transports/erpc_dspi_slave_transport.cpp b/erpc_c/transports/erpc_dspi_slave_transport.cpp index 1c5a9487..b0f68a5b 100644 --- a/erpc_c/transports/erpc_dspi_slave_transport.cpp +++ b/erpc_c/transports/erpc_dspi_slave_transport.cpp @@ -8,9 +8,10 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "erpc_dspi_slave_transport.hpp" + #include #include -#include "erpc_dspi_slave_transport.hpp" extern "C" { #include "board.h" diff --git a/erpc_c/transports/erpc_i2c_slave_transport.cpp b/erpc_c/transports/erpc_i2c_slave_transport.cpp index 991f864f..7fa3b52a 100644 --- a/erpc_c/transports/erpc_i2c_slave_transport.cpp +++ b/erpc_c/transports/erpc_i2c_slave_transport.cpp @@ -6,9 +6,10 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "erpc_i2c_slave_transport.hpp" + #include #include -#include "erpc_i2c_slave_transport.hpp" extern "C" { #include "board.h" diff --git a/erpc_c/transports/erpc_i2c_slave_transport.hpp b/erpc_c/transports/erpc_i2c_slave_transport.hpp index bd10280a..425b2807 100644 --- a/erpc_c/transports/erpc_i2c_slave_transport.hpp +++ b/erpc_c/transports/erpc_i2c_slave_transport.hpp @@ -9,8 +9,8 @@ #ifndef _EMBEDDED_RPC__I2C_SLAVE_TRANSPORT_H_ #define _EMBEDDED_RPC__I2C_SLAVE_TRANSPORT_H_ -#include #include "erpc_config_internal.h" +#include #if ERPC_THREADS #include "erpc_threading.h" #endif diff --git a/erpc_c/transports/erpc_mu_transport.hpp b/erpc_c/transports/erpc_mu_transport.hpp index b2c38afe..16a819e1 100644 --- a/erpc_c/transports/erpc_mu_transport.hpp +++ b/erpc_c/transports/erpc_mu_transport.hpp @@ -48,7 +48,8 @@ extern "C" { #define MU_REG_COUNT (MU_RR_COUNT) /*!< Count of MU tx/rx registers to be used by this transport layer */ #endif /* ERPC_TRANSPORT_MU_USE_MCMGR */ -#if (defined(MIMXRT1187_cm7_SERIES) || defined(MIMXRT1187_cm33_SERIES) || defined(MIMXRT1189_cm7_SERIES) || defined(MIMXRT1189_cm33_SERIES)) +#if (defined(MIMXRT1187_cm7_SERIES) || defined(MIMXRT1187_cm33_SERIES) || defined(MIMXRT1189_cm7_SERIES) || \ + defined(MIMXRT1189_cm33_SERIES)) #define MU_TX_SHIFT (1UL << (MU_REG_COUNT - 1U)) #define MU_RX_SHIFT (1UL << (MU_REG_COUNT - 1U)) #define MU_RX_INTR_MASK (MU_RX_INTR(MU_RX_SHIFT)) diff --git a/erpc_c/transports/erpc_rpmsg_linux_transport.hpp b/erpc_c/transports/erpc_rpmsg_linux_transport.hpp index f849e951..ce13725c 100644 --- a/erpc_c/transports/erpc_rpmsg_linux_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_linux_transport.hpp @@ -38,7 +38,7 @@ class RPMsgLinuxTransport : public Transport * * @return RPMsgEndpoint * Rpmsg endpoint. */ - RPMsgEndpoint *getRpmsgEndpoint(void){ return m_endPoint; } + RPMsgEndpoint *getRpmsgEndpoint(void) { return m_endPoint; } /*! * @brief This function initializes Linux environment for sending and receiving messages. diff --git a/erpc_c/transports/erpc_rpmsg_lite_transport.hpp b/erpc_c/transports/erpc_rpmsg_lite_transport.hpp index ab4cb3c6..6537eae6 100644 --- a/erpc_c/transports/erpc_rpmsg_lite_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_lite_transport.hpp @@ -10,8 +10,8 @@ #ifndef _EMBEDDED_RPC__RPMSG_LITE_TRANSPORT_H_ #define _EMBEDDED_RPC__RPMSG_LITE_TRANSPORT_H_ -#include "erpc_crc16.hpp" #include "erpc_config_internal.h" +#include "erpc_crc16.hpp" #include "erpc_message_buffer.hpp" #include "erpc_rpmsg_lite_base_transport.hpp" #include "erpc_static_queue.hpp" diff --git a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.hpp b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.hpp index a1baf11b..30d3ee02 100644 --- a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.hpp @@ -129,7 +129,7 @@ class RPMsgTTYRTOSTransport : public RPMsgBaseTransport * * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. */ - virtual Crc16 *getCrc16(void); + virtual Crc16 * getCrc16(void) override; protected: uint32_t m_dst_addr; /*!< Destination address used by rpmsg. */ diff --git a/erpc_c/transports/erpc_spi_master_transport.cpp b/erpc_c/transports/erpc_spi_master_transport.cpp index da4f36ee..20a216de 100644 --- a/erpc_c/transports/erpc_spi_master_transport.cpp +++ b/erpc_c/transports/erpc_spi_master_transport.cpp @@ -8,9 +8,10 @@ * SPDX-License-Identifier: BSD-3-Clause */ -#include #include "erpc_spi_master_transport.hpp" +#include + extern "C" { #include "board.h" #include "fsl_gpio.h" diff --git a/erpc_c/transports/erpc_spi_master_transport.hpp b/erpc_c/transports/erpc_spi_master_transport.hpp index 8614b623..e90e27a2 100644 --- a/erpc_c/transports/erpc_spi_master_transport.hpp +++ b/erpc_c/transports/erpc_spi_master_transport.hpp @@ -10,9 +10,10 @@ #ifndef _EMBEDDED_RPC__SPI_MASTER_TRANSPORT_H_ #define _EMBEDDED_RPC__SPI_MASTER_TRANSPORT_H_ +#include "erpc_framed_transport.hpp" + #include #include -#include "erpc_framed_transport.hpp" extern "C" { #include "fsl_spi.h" diff --git a/erpc_c/transports/erpc_spi_slave_transport.cpp b/erpc_c/transports/erpc_spi_slave_transport.cpp index dadd77de..f4d034b2 100644 --- a/erpc_c/transports/erpc_spi_slave_transport.cpp +++ b/erpc_c/transports/erpc_spi_slave_transport.cpp @@ -8,9 +8,10 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "erpc_spi_slave_transport.hpp" + #include #include -#include "erpc_spi_slave_transport.hpp" extern "C" { #include "board.h" diff --git a/erpc_c/transports/erpc_spi_slave_transport.hpp b/erpc_c/transports/erpc_spi_slave_transport.hpp index 4a6de45a..bc4e22b9 100644 --- a/erpc_c/transports/erpc_spi_slave_transport.hpp +++ b/erpc_c/transports/erpc_spi_slave_transport.hpp @@ -10,8 +10,8 @@ #ifndef _EMBEDDED_RPC__SPI_SLAVE_TRANSPORT_H_ #define _EMBEDDED_RPC__SPI_SLAVE_TRANSPORT_H_ -#include #include "erpc_config_internal.h" +#include #if ERPC_THREADS #include "erpc_threading.h" #endif diff --git a/erpc_c/transports/erpc_usb_cdc_transport.hpp b/erpc_c/transports/erpc_usb_cdc_transport.hpp index a32df59d..ee4abf69 100644 --- a/erpc_c/transports/erpc_usb_cdc_transport.hpp +++ b/erpc_c/transports/erpc_usb_cdc_transport.hpp @@ -9,8 +9,8 @@ #ifndef _EMBEDDED_RPC__USB_CDC_TRANSPORT_H_ #define _EMBEDDED_RPC__USB_CDC_TRANSPORT_H_ -#include #include "erpc_config_internal.h" +#include #if !ERPC_THREADS_IS(NONE) #include "erpc_threading.h" #endif diff --git a/erpcgen/Makefile b/erpcgen/Makefile index a6aa0b7a..9118d5c2 100644 --- a/erpcgen/Makefile +++ b/erpcgen/Makefile @@ -71,11 +71,18 @@ SOURCES += $(OBJS_ROOT)/erpcgen_parser.tab.cpp \ .SECONDARY: $(OBJS_ROOT)/erpcgen_parser.tab.cpp \ $(OBJS_ROOT)/erpcgen_lexer.cpp \ $(OBJS_ROOT)/erpcgen/src/templates/c_common_header.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_interface_header.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_interface_source.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_client_header.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_client_source.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_server_header.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_server_source.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_coders.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_common_functions.c \ + $(OBJS_ROOT)/erpcgen/src/templates/c_client_header.c \ $(OBJS_ROOT)/erpcgen/src/templates/c_client_source.c \ $(OBJS_ROOT)/erpcgen/src/templates/c_server_header.c \ $(OBJS_ROOT)/erpcgen/src/templates/c_server_source.c \ - $(OBJS_ROOT)/erpcgen/src/templates/c_coders.c \ - $(OBJS_ROOT)/erpcgen/src/templates/c_common_functions.c \ $(OBJS_ROOT)/erpcgen/src/templates/c_crc.c \ $(OBJS_ROOT)/erpcgen/src/templates/py_init.c \ $(OBJS_ROOT)/erpcgen/src/templates/py_common.c \ @@ -86,11 +93,18 @@ SOURCES += $(OBJS_ROOT)/erpcgen_parser.tab.cpp \ $(OBJS_ROOT)/erpcgen/src/templates/py_global_init.c SOURCES += $(OBJS_ROOT)/erpcgen/src/templates/c_common_header.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_interface_header.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_interface_source.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_client_header.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_client_source.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_server_header.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_server_source.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_coders.c \ + $(OBJS_ROOT)/erpcgen/src/templates/cpp_common_functions.c \ + $(OBJS_ROOT)/erpcgen/src/templates/c_client_header.c \ $(OBJS_ROOT)/erpcgen/src/templates/c_client_source.c \ $(OBJS_ROOT)/erpcgen/src/templates/c_server_header.c \ $(OBJS_ROOT)/erpcgen/src/templates/c_server_source.c \ - $(OBJS_ROOT)/erpcgen/src/templates/c_coders.c \ - $(OBJS_ROOT)/erpcgen/src/templates/c_common_functions.c \ $(OBJS_ROOT)/erpcgen/src/templates/c_crc.c \ $(OBJS_ROOT)/erpcgen/src/templates/py_init.c \ $(OBJS_ROOT)/erpcgen/src/templates/py_common.c \ diff --git a/erpcgen/VisualStudio_v14/.gitignore b/erpcgen/VisualStudio_v14/.gitignore index 43daf212..024f1d9a 100644 --- a/erpcgen/VisualStudio_v14/.gitignore +++ b/erpcgen/VisualStudio_v14/.gitignore @@ -4,12 +4,17 @@ erpcgen_parser.tab.cpp erpcgen_parser.tab.hpp # templates -c_client_source.cpp -c_coders.cpp +cpp_client_source.cpp +cpp_client_header.cpp +cpp_server_header.cpp +cpp_server_source.cpp +cpp_coders.cpp c_common_header.cpp +c_client_source.cpp +c_client_header.cpp c_server_header.cpp c_server_source.cpp -c_common_functions.cpp +cpp_common_functions.cpp c_defines.cpp c_crc.cpp py_client.cpp diff --git a/erpcgen/VisualStudio_v14/erpcgen.vcxproj b/erpcgen/VisualStudio_v14/erpcgen.vcxproj index df0c94cb..9d37fc2e 100644 --- a/erpcgen/VisualStudio_v14/erpcgen.vcxproj +++ b/erpcgen/VisualStudio_v14/erpcgen.vcxproj @@ -97,12 +97,19 @@ - python.exe ..\bin\txt_to_c.py --output .\c_coders.cpp ..\src\templates\c_coders.template -python.exe ..\bin\txt_to_c.py --output .\c_client_source.cpp ..\src\templates\c_client_source.template + python.exe ..\bin\txt_to_c.py --output .\cpp_coders.cpp ..\src\templates\cpp_coders.template python.exe ..\bin\txt_to_c.py --output .\c_common_header.cpp ..\src\templates\c_common_header.template +python.exe ..\bin\txt_to_c.py --output .\cpp_interface_header.cpp ..\src\templates\cpp_interface_header.template +python.exe ..\bin\txt_to_c.py --output .\cpp_interface_source.cpp ..\src\templates\cpp_interface_source.template +python.exe ..\bin\txt_to_c.py --output .\cpp_client_header.cpp ..\src\templates\cpp_client_header.template +python.exe ..\bin\txt_to_c.py --output .\cpp_client_source.cpp ..\src\templates\cpp_client_source.template +python.exe ..\bin\txt_to_c.py --output .\cpp_server_source.cpp ..\src\templates\cpp_server_source.template +python.exe ..\bin\txt_to_c.py --output .\cpp_server_header.cpp ..\src\templates\cpp_server_header.template +python.exe ..\bin\txt_to_c.py --output .\c_client_header.cpp ..\src\templates\c_client_header.template +python.exe ..\bin\txt_to_c.py --output .\c_client_source.cpp ..\src\templates\c_client_source.template python.exe ..\bin\txt_to_c.py --output .\c_server_source.cpp ..\src\templates\c_server_source.template python.exe ..\bin\txt_to_c.py --output .\c_server_header.cpp ..\src\templates\c_server_header.template -python.exe ..\bin\txt_to_c.py --output .\c_common_functions.cpp ..\src\templates\c_common_functions.template +python.exe ..\bin\txt_to_c.py --output .\cpp_common_functions.cpp ..\src\templates\cpp_common_functions.template python.exe ..\bin\txt_to_c.py --output .\c_crc.cpp ..\src\templates\c_crc.template python.exe ..\bin\txt_to_c.py --output .\py_client.cpp ..\src\templates\py_client.template python.exe ..\bin\txt_to_c.py --output .\py_coders.cpp ..\src\templates\py_coders.template @@ -137,12 +144,19 @@ python.exe ..\bin\txt_to_c.py --output .\py_global_init.cpp ..\src\templates\py_ %(AdditionalLibraryDirectories) - python.exe ..\bin\txt_to_c.py --output .\c_coders.cpp ..\src\templates\c_coders.template -python.exe ..\bin\txt_to_c.py --output .\c_client_source.cpp ..\src\templates\c_client_source.template + python.exe ..\bin\txt_to_c.py --output .\cpp_coders.cpp ..\src\templates\cpp_coders.template python.exe ..\bin\txt_to_c.py --output .\c_common_header.cpp ..\src\templates\c_common_header.template +python.exe ..\bin\txt_to_c.py --output .\cpp_interface_header.cpp ..\src\templates\cpp_interface_header.template +python.exe ..\bin\txt_to_c.py --output .\cpp_interface_source.cpp ..\src\templates\cpp_interface_source.template +python.exe ..\bin\txt_to_c.py --output .\cpp_client_header.cpp ..\src\templates\cpp_client_header.template +python.exe ..\bin\txt_to_c.py --output .\cpp_client_source.cpp ..\src\templates\cpp_client_source.template +python.exe ..\bin\txt_to_c.py --output .\cpp_server_source.cpp ..\src\templates\cpp_server_source.template +python.exe ..\bin\txt_to_c.py --output .\cpp_server_header.cpp ..\src\templates\cpp_server_header.template +python.exe ..\bin\txt_to_c.py --output .\c_client_header.cpp ..\src\templates\c_client_header.template +python.exe ..\bin\txt_to_c.py --output .\c_client_source.cpp ..\src\templates\c_client_source.template python.exe ..\bin\txt_to_c.py --output .\c_server_source.cpp ..\src\templates\c_server_source.template python.exe ..\bin\txt_to_c.py --output .\c_server_header.cpp ..\src\templates\c_server_header.template -python.exe ..\bin\txt_to_c.py --output .\c_common_functions.cpp ..\src\templates\c_common_functions.template +python.exe ..\bin\txt_to_c.py --output .\cpp_common_functions.cpp ..\src\templates\cpp_common_functions.template python.exe ..\bin\txt_to_c.py --output .\c_crc.cpp ..\src\templates\c_crc.template python.exe ..\bin\txt_to_c.py --output .\py_client.cpp ..\src\templates\py_client.template python.exe ..\bin\txt_to_c.py --output .\py_coders.cpp ..\src\templates\py_coders.template @@ -229,13 +243,20 @@ python.exe ..\bin\txt_to_c.py --output .\py_global_init.cpp ..\src\templates\py_ - - + + + + + + + + + - + 4005;4244;%(DisableSpecificWarnings) diff --git a/erpcgen/VisualStudio_v14/erpcgen.vcxproj.filters b/erpcgen/VisualStudio_v14/erpcgen.vcxproj.filters index 29c6416c..1d72bbdb 100644 --- a/erpcgen/VisualStudio_v14/erpcgen.vcxproj.filters +++ b/erpcgen/VisualStudio_v14/erpcgen.vcxproj.filters @@ -164,13 +164,34 @@ Source Files\cpptemplate - + Source Files - + Source Files - + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + Source Files @@ -254,7 +275,7 @@ Source Files - + Source Files @@ -282,4 +303,4 @@ - \ No newline at end of file + diff --git a/erpcgen/src/CGenerator.cpp b/erpcgen/src/CGenerator.cpp index 71dd8960..676dab38 100644 --- a/erpcgen/src/CGenerator.cpp +++ b/erpcgen/src/CGenerator.cpp @@ -15,6 +15,7 @@ #include "format_string.hpp" #include +#include #include #include @@ -31,11 +32,19 @@ static const char *const kIdentifierChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHI // Templates strings converted from text files by txt_to_c.py. extern const char *const kCCommonHeader; -extern const char *const kCServerHeader; +extern const char *const kCppCommonHeader; +extern const char *const kCppInterfaceHeader; +extern const char *const kCppInterfaceSource; +extern const char *const kCppClientHeader; +extern const char *const kCppClientSource; +extern const char *const kCppServerHeader; +extern const char *const kCppServerSource; +extern const char *const kCppCoders; +extern const char *const kCppCommonFunctions; +extern const char *const kCClientHeader; extern const char *const kCClientSource; +extern const char *const kCServerHeader; extern const char *const kCServerSource; -extern const char *const kCCoders; -extern const char *const kCCommonFunctions; extern const char *const kCCrc; // number which makes list temporary variables unique. @@ -70,81 +79,138 @@ CGenerator::CGenerator(InterfaceDefinition *def) void CGenerator::generateOutputFiles(const string &fileName) { - generateClientSourceFile(fileName); + generateCommonCHeaderFiles(fileName); + generateCommonCppHeaderFiles(fileName); + + generateInterfaceCppHeaderFile(fileName); + generateInterfaceCppSourceFile(fileName); + + generateClientCppHeaderFile(fileName); + generateClientCppSourceFile(fileName); + + generateServerCppHeaderFile(fileName); + generateServerCppSourceFile(fileName); - generateServerHeaderFile(fileName); - generateServerSourceFile(fileName); + generateClientCHeaderFile(fileName); + generateClientCSourceFile(fileName); - generateCommonHeaderFiles(fileName); + generateServerCHeaderFile(fileName); + generateServerCSourceFile(fileName); } -void CGenerator::generateTypesHeaderFile() +void CGenerator::generateCommonCHeaderFiles(string fileName) { - string typesHeaderFileName = m_templateData["commonTypesFile"]->getvalue(); + fileName += "_common.h"; + m_templateData["commonGuardMacro"] = generateIncludeGuardName(fileName); + m_templateData["commonCHeaderName"] = fileName; + m_templateData["cCommonHeaderFile"] = true; + generateOutputFile(fileName, "c_common_header", m_templateData, kCCommonHeader); +} - m_templateData["commonGuardMacro"] = generateIncludeGuardName(typesHeaderFileName); - m_templateData["genCommonTypesFile"] = true; - m_templateData["commonTypesFile"] = ""; +void CGenerator::generateCommonCppHeaderFiles(string fileName) +{ + fileName += "_common.hpp"; + m_templateData["commonGuardMacro"] = generateIncludeGuardName(fileName); + m_templateData["commonCppHeaderName"] = fileName; + m_templateData["cCommonHeaderFile"] = false; + generateOutputFile(fileName, "c_common_header", m_templateData, kCCommonHeader); +} - generateOutputFile(typesHeaderFileName, "c_common_header", m_templateData, kCCommonHeader); +void CGenerator::generateInterfaceCppHeaderFile(string fileName) +{ + fileName += "_interface.hpp"; + m_templateData["interfaceCppGuardMacro"] = generateIncludeGuardName(fileName); + m_templateData["interfaceCppHeaderName"] = fileName; + generateOutputFile(fileName, "cpp_interface_header", m_templateData, kCppInterfaceHeader); } -void CGenerator::generateCommonHeaderFiles(const string &fileName) +void CGenerator::generateInterfaceCppSourceFile(string fileName) { - m_templateData["commonGuardMacro"] = generateIncludeGuardName(fileName + ".h"); - m_templateData["genCommonTypesFile"] = false; + fileName += "_interface.cpp"; + m_templateData["interfaceCppSourceName"] = fileName; + generateOutputFile(fileName, "cpp_interface_source", m_templateData, kCppInterfaceSource); +} - generateOutputFile(fileName + ".h", "c_common_header", m_templateData, kCCommonHeader); +void CGenerator::generateClientCppHeaderFile(string fileName) +{ + fileName += "_client.hpp"; + m_templateData["clientCppGuardMacro"] = generateIncludeGuardName(fileName); + m_templateData["clientCppHeaderName"] = fileName; + generateOutputFile(fileName, "cpp_client_header", m_templateData, kCppClientHeader); } -void CGenerator::generateClientSourceFile(string fileName) +void CGenerator::generateClientCppSourceFile(string fileName) { - m_templateData["source"] = "client"; fileName += "_client.cpp"; - m_templateData["clientSourceName"] = fileName; + m_templateData["clientCppSourceName"] = fileName; + + generateOutputFile(fileName, "cpp_client_source", m_templateData, kCppClientSource); +} + +void CGenerator::generateServerCppHeaderFile(string fileName) +{ + fileName += "_server.hpp"; + m_templateData["serverCppGuardMacro"] = generateIncludeGuardName(fileName); + m_templateData["serverCppHeaderName"] = fileName; + generateOutputFile(fileName, "cpp_server_header", m_templateData, kCppServerHeader); +} + +void CGenerator::generateServerCppSourceFile(string fileName) +{ + fileName += "_server.cpp"; + m_templateData["serverCppSourceName"] = fileName; + + generateOutputFile(fileName, "cpp_server_source", m_templateData, kCppServerSource); +} - // TODO: temporary workaround for tests - m_templateData["unitTest"] = (fileName.compare("test_unit_test_common_client.cpp") == 0 ? false : true); +void CGenerator::generateClientCHeaderFile(string fileName) +{ + fileName = "c_" + fileName + "_client.h"; + m_templateData["clientCGuardMacro"] = generateIncludeGuardName(fileName); + m_templateData["clientCHeaderName"] = fileName; + generateOutputFile(fileName, "c_client_header", m_templateData, kCClientHeader); +} + +void CGenerator::generateClientCSourceFile(string fileName) +{ + fileName = "c_" + fileName + "_client.cpp"; + m_templateData["clientCSourceName"] = fileName; generateOutputFile(fileName, "c_client_source", m_templateData, kCClientSource); } -void CGenerator::generateServerHeaderFile(string fileName) +void CGenerator::generateServerCHeaderFile(string fileName) { - fileName += "_server.h"; - m_templateData["serverGuardMacro"] = generateIncludeGuardName(fileName); - m_templateData["serverHeaderName"] = fileName; + fileName = "c_" + fileName + "_server.h"; + m_templateData["serverCGuardMacro"] = generateIncludeGuardName(fileName); + m_templateData["serverCHeaderName"] = fileName; generateOutputFile(fileName, "c_server_header", m_templateData, kCServerHeader); } -void CGenerator::generateServerSourceFile(string fileName) +void CGenerator::generateServerCSourceFile(string fileName) { - m_templateData["source"] = "server"; - fileName += "_server.cpp"; - m_templateData["serverSourceName"] = fileName; - - // TODO: temporary workaround for tests - m_templateData["unitTest"] = (fileName.compare("test_unit_test_common_server.cpp") == 0 ? false : true); + fileName = "c_" + fileName + "_server.cpp"; + m_templateData["serverCSourceName"] = fileName; generateOutputFile(fileName, "c_server_source", m_templateData, kCServerSource); } void CGenerator::generateCrcFile() { - string filenName = "erpc_crc16.hpp"; - m_templateData["crcGuardMacro"] = generateIncludeGuardName(filenName); - m_templateData["crcHeaderName"] = filenName; - generateOutputFile(filenName, "c_crc", m_templateData, kCCrc); + string fileName = "erpc_crc16.hpp"; + m_templateData["crcGuardMacro"] = generateIncludeGuardName(fileName); + m_templateData["crcHeaderName"] = fileName; + generateOutputFile(fileName, "c_crc", m_templateData, kCCrc); } void CGenerator::parseSubtemplates() { - string templateName = "c_coders"; + string templateName = "cpp_coders"; try { - parse(kCCoders, m_templateData); - templateName = "c_common_functions"; - parse(kCCommonFunctions, m_templateData); + parse(kCppCoders, m_templateData); + templateName = "cpp_common_functions"; + parse(kCppCommonFunctions, m_templateData); } catch (TemplateException &e) { @@ -414,7 +480,7 @@ void CGenerator::generate() } /* Generate file with shim code version. */ m_templateData["versionGuardMacro"] = - generateIncludeGuardName(format_string("erpc_generated_shim_code_crc_%d", m_idlCrc16).c_str()); + generateIncludeGuardName(format_string("erpc_generated_shim_code_crc_%d", m_idlCrc16)); m_templateData["generateInfraErrorChecks"] = generateInfraErrorChecks; m_templateData["generateAllocErrorChecks"] = generateAllocErrorChecks; @@ -426,7 +492,6 @@ void CGenerator::generate() m_templateData["structs"] = empty; m_templateData["unions"] = empty; m_templateData["consts"] = empty; - m_templateData["functions"] = empty; m_templateData["nonExternalStructUnion"] = false; @@ -448,13 +513,6 @@ void CGenerator::generate() } // check if structure/function parameters annotations are valid. - for (Symbol *symbol : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kFunctionType)) - { - FunctionType *functionType = dynamic_cast(symbol); - assert(functionType); - scanStructForAnnotations(&functionType->getParameters(), true); - } - for (Symbol *symbol : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kStructType)) { StructType *structType = dynamic_cast(symbol); @@ -470,6 +528,11 @@ void CGenerator::generate() { scanStructForAnnotations(&function->getParameters(), true); } + + for (FunctionType *functionType : interface->getFunctionTypes()) + { + scanStructForAnnotations(&functionType->getParameters(), true); + } } // transform alias data types @@ -489,15 +552,20 @@ void CGenerator::generate() // for common header, only C specific makeSymbolsDeclarationTemplateData(); - // check if types header annotation is used - if (m_def->hasProgramSymbol()) - { - m_templateData["commonTypesFile"] = getAnnStringValue(program, TYPES_HEADER_ANNOTATION); - } - else + data_list interfacesFilesList; + string commonFilesFilename; + for (Group *group : m_groups) { - m_templateData["commonTypesFile"] = ""; + commonFilesFilename = getGroupCommonFileName(group); + for (auto iface : group->getInterfaces()) + { + data_map interfaceFile; + interfaceFile["interfaceName"] = iface->getName(); + interfaceFile["interfaceCommonFileName"] = commonFilesFilename; + interfacesFilesList.push_back(interfaceFile); + } } + m_templateData["interfacesFiles"] = interfacesFilesList; for (Group *group : m_groups) { @@ -506,17 +574,10 @@ void CGenerator::generate() groupTemplate["includes"] = makeGroupIncludesTemplateData(group); groupTemplate["symbolsMap"] = makeGroupSymbolsTemplateData(group); groupTemplate["interfaces"] = makeGroupInterfacesTemplateData(group); - groupTemplate["callbacks"] = makeGroupCallbacksTemplateData(group); group->setTemplate(groupTemplate); generateGroupOutputFiles(group); } - - // generate types header if used - if (!m_templateData["commonTypesFile"]->getvalue().empty()) - { - generateTypesHeaderFile(); - } } void CGenerator::makeConstTemplateData() @@ -537,7 +598,7 @@ void CGenerator::makeConstTemplateData() if (nullptr == constVarValue) { throw semantic_error( - format_string("line %d: Const pointing to null Value object.", constVar->getLastLine()).c_str()); + format_string("line %d: Const pointing to null Value object.", constVar->getLastLine())); } /* Use char[] for constants. */ @@ -558,8 +619,7 @@ void CGenerator::makeConstTemplateData() if (constVarValue->getType() != kIntegerValue) { throw semantic_error(format_string("line %d: Const enum pointing to non-integer Value object.", - constVar->getLastLine()) - .c_str()); + constVar->getLastLine())); } EnumType *constEnum = dynamic_cast(constVarType); @@ -576,9 +636,8 @@ void CGenerator::makeConstTemplateData() if (value.compare("") == 0) { value = "(" + constVarType->getName() + ") " + constVarValue->toString(); - Log::warning(format_string("Enum value '%s' is not pointing to any '%s' variable \n", - constVarValue->toString().c_str(), constVarType->getName().c_str()) - .c_str()); + Log::warning("Enum value '%s' is not pointing to any '%s' variable \n", + constVarValue->toString().c_str(), constVarType->getName().c_str()); } } else @@ -688,81 +747,6 @@ void CGenerator::makeAliasesTemplateData() } } - /* type definitions of functions and table of functions */ - data_list functions; - for (auto functionTypeSymbol : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kFunctionType)) - { - FunctionType *functionType = dynamic_cast(functionTypeSymbol); - assert(functionType); - data_map functionInfo; - - // aware of external function definitions - if (!findAnnotation(functionType, EXTERNAL_ANNOTATION)) - { - AliasType *a = new AliasType(getFunctionPrototype(nullptr, functionType), functionType); - a->setMlComment(functionType->getMlComment()); - a->setIlComment(functionType->getIlComment()); - - /* Function type definition need be inserted after all parameters types definitions. */ - DataType *callbackParamType = functionType->getReturnStructMemberType()->getDataType(); - for (StructMember *callbackParam : functionType->getParameters().getMembers()) - { - DataType *callbackParamDataType = callbackParam->getDataType(); - if (!callbackParamType || callbackParamDataType->getFirstLine() > callbackParamType->getFirstLine()) - { - callbackParamType = callbackParamDataType; - } - } - if (!callbackParamType || !callbackParamType->isAlias()) - { - /* order isn't important */ - aliasTypeVector.insert(aliasTypeVector.begin() + i++, a); - } - else - { - /* skip structure, unions and functions type definitions */ - for (unsigned int aliasTypesIt = i; aliasTypesIt < aliasTypeVector.size(); ++aliasTypesIt) - { - if (callbackParamType == aliasTypeVector[aliasTypesIt]) - { - // Add aliases in IDL declaration order. - unsigned int nextIt = aliasTypesIt + 1; - while (nextIt < aliasTypeVector.size()) - { - AliasType *nextAlias = dynamic_cast(aliasTypeVector[nextIt]); - assert(nextAlias); - if (nextAlias->getElementType()->isFunction()) - { - ++nextIt; - } - else - { - break; - } - } - - aliasTypeVector.insert(aliasTypeVector.begin() + nextIt, a); - break; - } - } - } - } - - /* Table template data. */ - data_list callbacks; - for (Function *fun : functionType->getCallbackFuns()) - { - data_map callbacksInfo; - callbacksInfo["name"] = fun->getName(); - callbacks.push_back(callbacksInfo); - } - functionInfo["callbacks"] = callbacks; - /* Function type name. */ - functionInfo["name"] = functionType->getName(); - functions.push_back(functionInfo); - } - m_templateData["functions"] = functions; - for (auto it : aliasTypeVector) { AliasType *aliasType = dynamic_cast(it); @@ -1016,43 +1000,6 @@ data_map CGenerator::makeGroupSymbolsTemplateData(Group *group) return symbolsTemplate; } -data_list CGenerator::makeGroupCallbacksTemplateData(Group *group) -{ - data_list functionTypes; - std::map functionTypeMap; - - // need go trough functions instead of group symbols. - for (Interface *interface : group->getInterfaces()) - { - for (Function *function : interface->getFunctions()) - { - FunctionType *functionType = function->getFunctionType(); - if (functionType) - { - bool isPresent = (functionTypeMap.find(functionType) != functionTypeMap.end()); - if (isPresent) - { - ++functionTypeMap[functionType]; - } - else - { - functionTypeMap[functionType] = 1; - } - } - } - } - - for (std::map::iterator it = functionTypeMap.begin(); it != functionTypeMap.end(); ++it) - { - if (it->second > 1) - { - functionTypes.push_back(getFunctionTypeTemplateData(group, it->first)); - } - } - - return functionTypes; -} - data_map CGenerator::getStructDeclarationTemplateData(StructType *structType) { data_map info; @@ -1082,8 +1029,8 @@ data_map CGenerator::getStructDeclarationTemplateData(StructType *structType) DataType *trueDataType = member->getDataType()->getTrueDataType(); // Check if member is byRef type. Add "*" for type and allocate space for data on server side. - if (member->isByref() && - (trueDataType->isStruct() || trueDataType->isUnion() || trueDataType->isScalar() || trueDataType->isEnum())) + if (member->isByref() && (trueDataType->isStruct() || trueDataType->isUnion() || trueDataType->isScalar() || + trueDataType->isEnum() || trueDataType->isFunction())) { memberName = "*" + memberName; } @@ -1157,8 +1104,7 @@ data_map CGenerator::getStructDefinitionTemplateData(Group *group, StructType *s { throw syntax_error( format_string("line %d: Struct member shall use byref option. Member is using forward declared type.", - member->getFirstLine()) - .c_str()); + member->getFirstLine())); } // Handle nullable annotation bool isNullable = @@ -1364,14 +1310,16 @@ void CGenerator::setTemplateComments(Symbol *symbol, data_map &symbolInfo) bool CGenerator::isServerNullParam(StructMember *param) { DataType *paramTrueDataType = param->getDataType()->getTrueDataType(); - return (!paramTrueDataType->isScalar() && !paramTrueDataType->isEnum() && !paramTrueDataType->isArray()); + return (!paramTrueDataType->isScalar() && !paramTrueDataType->isEnum() && !paramTrueDataType->isArray() && + !paramTrueDataType->isFunction()); } bool CGenerator::isPointerParam(StructMember *param) { DataType *paramTrueDataType = param->getDataType()->getTrueDataType(); - return (isServerNullParam(param) || ((paramTrueDataType->isScalar() || paramTrueDataType->isEnum()) && - param->getDirection() != param_direction_t::kInDirection)); + return (isServerNullParam(param) || + ((paramTrueDataType->isScalar() || paramTrueDataType->isEnum() || paramTrueDataType->isFunction()) && + param->getDirection() != param_direction_t::kInDirection)); } bool CGenerator::isNullableParam(StructMember *param) @@ -1383,6 +1331,8 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) { data_map info; Symbol *fnSymbol = dynamic_cast(fn); + data_list externalInterfacesDataList; + list externalInterfacesList; // reset list numbering. listCounter = 0; @@ -1393,6 +1343,8 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) setTemplateComments(fnSymbol, info); info["needTempVariableServerI32"] = false; info["needTempVariableClientI32"] = false; + info["needTempVariableServerU16"] = false; + info["needTempVariableClientU16"] = false; info["needNullVariableOnServer"] = false; /* Is function declared as external? */ @@ -1444,7 +1396,8 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) info["needTempVariableClientI32"] = needTempVariableI32; returnInfo["resultVariable"] = resultVariable; returnInfo["errorReturnValue"] = getErrorReturnValue(fn); - returnInfo["isNullReturnType"] = (!trueDataType->isScalar() && !trueDataType->isEnum()); + returnInfo["isNullReturnType"] = + (!trueDataType->isScalar() && !trueDataType->isEnum() && !trueDataType->isFunction()); } info["returnValue"] = returnInfo; @@ -1542,7 +1495,7 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) // Special case when scalar variables are @nullable string nullableName = getOutputName(param); paramInfo["nullableName"] = nullableName; - if (paramTrueType->isScalar() || paramTrueType->isEnum()) + if (paramTrueType->isScalar() || paramTrueType->isEnum() || paramTrueType->isFunction()) { paramInfo["nullVariable"] = getTypenameName(paramTrueType, "*_" + nullableName); } @@ -1580,12 +1533,41 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) } } + string ifaceScope = ""; + if (paramTrueType->isFunction()) + { + FunctionType *funType = dynamic_cast(paramTrueType); + if (funType->getCallbackFuns().size() > 1) + { + info["needTempVariableServerU16"] = true; + info["needTempVariableClientU16"] = true; + } + if (funType->getInterface() != fn->getInterface()) + { + ifaceScope = funType->getInterface()->getName(); + } + } + paramInfo["mallocServer"] = firstAllocOnServerWhenIsNeed(name, param); setCallingFreeFunctions(param, paramInfo, false); // Use shared memory feature instead of serializing/deserializing data. bool isShared = (isPointerParam(param) && findAnnotation(param, SHARED_ANNOTATION) != nullptr); + + string pureCName = ""; + if ((param->getDirection() != param_direction_t::kInDirection) && paramTrueType->isFunction()) + { + pureCName += "&"; + } + if (paramTrueType->isFunction()) + { + pureCName += "_"; + } + pureCName += name; + paramInfo["shared"] = isShared; + paramInfo["pureName"] = name; + paramInfo["pureNameC"] = pureCName; string encodeDecodeName; if (isShared) { @@ -1602,6 +1584,12 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) paramInfo["variable"] = getTypenameName(paramType, name); paramInfo["name"] = name; + if (ifaceScope != "") + { + externalInterfacesList.push_back(ifaceScope); + } + paramInfo["ifaceScope"] = ifaceScope; + paramInfo["isFunction"] = paramTrueType->isFunction(); Log::debug("Calling EncodeDecode param %s with paramType %s.\n", param->getName().c_str(), paramType->getName().c_str()); @@ -1632,6 +1620,11 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) paramsToFree.push_back(paramInfo); } } + externalInterfacesList.unique(); + for (auto externalInterface : externalInterfacesList) + { + externalInterfacesDataList.push_back(externalInterface); + } if (paramsToClient.size() > 0) { info["isReturnValue"] = true; @@ -1644,6 +1637,7 @@ data_map CGenerator::getFunctionBaseTemplateData(Group *group, FunctionBase *fn) info["paramsToFree"] = paramsToFree; info["parametersToClient"] = paramsToClient; info["parametersToServer"] = paramsToServer; + info["externalInterfaces"] = externalInterfacesDataList; return info; } @@ -1659,9 +1653,9 @@ data_map CGenerator::getFunctionTemplateData(Group *group, Function *fn) if (fn->getFunctionType()) { int similarFunctions = 0; - for (Interface *interface : group->getInterfaces()) + for (Interface *_interface : group->getInterfaces()) { - for (Function *function : interface->getFunctions()) + for (Function *function : _interface->getFunctions()) { if (fn->getFunctionType() == function->getFunctionType()) { @@ -1679,6 +1673,7 @@ data_map CGenerator::getFunctionTemplateData(Group *group, Function *fn) if (useCommonFunction) { std::string callbackFName = getOutputName(fn->getFunctionType()); + info["callbackFNameNoGroup"] = callbackFName; if (!group->getName().empty()) { callbackFName += "_" + group->getName(); @@ -1690,13 +1685,36 @@ data_map CGenerator::getFunctionTemplateData(Group *group, Function *fn) else { info["isCallback"] = false; - string serverProto = getFunctionServerCall(fn); - info["serverPrototype"] = serverProto; + info["serverPrototype"] = getFunctionServerCall(fn); info["serviceId"] = ""; } + string serverProtoC = getFunctionServerCall(fn, true); + info["serverPrototypeC"] = serverProtoC; string proto = getFunctionPrototype(group, fn); info["prototype"] = proto; + string protoCpp = getFunctionPrototype(group, fn, getOutputName(fn->getInterface()) + "_client", "", true); + info["prototypeCpp"] = protoCpp; + string protoInterface = getFunctionPrototype(group, fn, "", "", true); + info["prototypeInterface"] = protoInterface; + + data_list callbackParameters; + for (auto parameter : fn->getParameters().getMembers()) + { + if (parameter->getDataType()->isFunction()) + { + data_map paramData; + FunctionType *funType = dynamic_cast(parameter->getDataType()); + paramData["name"] = parameter->getName(); + paramData["type"] = funType->getName(); + paramData["interface"] = funType->getCallbackFuns()[0]->getInterface()->getName() + "_interface"; + paramData["in"] = ((parameter->getDirection() == param_direction_t::kInDirection)); + paramData["out"] = ((parameter->getDirection() == param_direction_t::kOutDirection)); + callbackParameters.push_back(paramData); + } + } + info["callbackParameters"] = callbackParameters; + info["name"] = getOutputName(fn); info["id"] = fn->getUniqueId(); @@ -1723,7 +1741,7 @@ data_map CGenerator::getFunctionTypeTemplateData(Group *group, FunctionType *fn) } } - string proto = getFunctionPrototype(group, fn, name); + string proto = getFunctionPrototype(group, fn, "", name); info = getFunctionBaseTemplateData(group, fn); info["prototype"] = proto; info["name"] = name; @@ -1733,7 +1751,7 @@ data_map CGenerator::getFunctionTypeTemplateData(Group *group, FunctionType *fn) { data_map functionInfo = getFunctionTemplateData(group, function); // set serverPrototype function with parameters of common function. - string serverProto = getFunctionServerCall(function, fn); + string serverProto = getFunctionServerCall(function, true); functionInfo["serverPrototype"] = serverProto; functionInfos.push_back(functionInfo); } @@ -1910,17 +1928,23 @@ string CGenerator::getErrorReturnValue(FunctionBase *fn) } } -string CGenerator::getFunctionServerCall(Function *fn, FunctionType *functionType) +string CGenerator::getFunctionServerCall(Function *fn, bool isCCall) { string proto = ""; - if (!fn->getReturnType()->isVoid()) + if (!isCCall) { - proto += "result = "; + if (!fn->getReturnType()->isVoid()) + { + proto += "result = "; + } + proto += "m_handler->"; } proto += getOutputName(fn); proto += "("; - auto params = (functionType) ? functionType->getParameters().getMembers() : fn->getParameters().getMembers(); + FunctionType *funcType = fn->getFunctionType(); + + auto params = (funcType) ? funcType->getParameters().getMembers() : fn->getParameters().getMembers(); if (params.size()) { @@ -1931,20 +1955,28 @@ string CGenerator::getFunctionServerCall(Function *fn, FunctionType *functionTyp DataType *trueDataType = it->getDataType()->getTrueDataType(); /* Builtin types and function types. */ - if (((trueDataType->isScalar()) || trueDataType->isEnum()) && + if (((trueDataType->isScalar()) || trueDataType->isEnum() || trueDataType->isFunction()) && it->getDirection() != param_direction_t::kInDirection && findAnnotation(it, NULLABLE_ANNOTATION)) { // On server side is created new variable for handle null : "_" + name proto += "_"; } else if ((it->getDirection() != param_direction_t::kInDirection) && - (((trueDataType->isScalar()) || trueDataType->isEnum()) || + (((trueDataType->isScalar()) || trueDataType->isEnum() || trueDataType->isFunction()) || (findAnnotation(it, SHARED_ANNOTATION)))) { - proto += "&"; + if (!isCCall) + { + proto += "&"; + } + } + std::string paramName = getOutputName(fn->getParameters().getMembers()[n]); + if ((paramName.empty()) || (funcType && funcType->getCallbackFuns().size() > 1)) + { + paramName = getOutputName(it); } - proto += getOutputName(it); + proto += paramName; if (!isLast) { @@ -1956,34 +1988,40 @@ string CGenerator::getFunctionServerCall(Function *fn, FunctionType *functionTyp return proto + ");"; } -string CGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const std::string name) +string CGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const std::string &interfaceName, + const string &name, bool insideInterfaceCall) { DataType *dataTypeReturn = fn->getReturnType(); string proto = getExtraPointerInReturn(dataTypeReturn); + string ifaceVar = interfaceName; if (proto == "*") { proto += " "; } - Symbol *symbol = dynamic_cast(fn); - assert(symbol); + if (ifaceVar != "") + { + ifaceVar += "::"; + } FunctionType *funType = dynamic_cast(fn); if (name.empty()) { + Symbol *symbol = dynamic_cast(fn); + assert(symbol); string functionName = getOutputName(symbol); if (funType) /* Need add '(*name)' for function type definition. */ { - proto += "(*" + functionName + ")"; + proto += "(" + ifaceVar + "*" + functionName + ")"; } else /* Use function name only. */ { - proto += functionName; + proto += ifaceVar + functionName; } } else { - proto += name; + proto += ifaceVar + name; } proto += "("; @@ -1992,7 +2030,7 @@ string CGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const st // add interface id and function id parameters for common callbacks shim code function if (!name.empty()) { - proto += "uint32_t serviceID, uint32_t functionID"; + proto += "ClientManager *m_clientManager, uint32_t serviceID, uint32_t functionID"; if (params.size() > 0) { proto += ", "; @@ -2011,9 +2049,8 @@ string CGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const st /* Add '*' to data types. */ if (((trueDataType->isBuiltin() || trueDataType->isEnum()) && - (it->getDirection() != param_direction_t::kInDirection && !trueDataType->isString())) || - (trueDataType->isFunction() && (it->getDirection() == param_direction_t::kOutDirection || - it->getDirection() == param_direction_t::kInoutDirection))) + ((it->getDirection() != param_direction_t::kInDirection) && !trueDataType->isString())) || + (trueDataType->isFunction() && (it->getDirection() != param_direction_t::kInDirection))) { paramSignature = "* " + paramSignature; } @@ -2087,6 +2124,18 @@ string CGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const st } } + if (insideInterfaceCall) + { + if (trueDataType->isFunction()) + { + FunctionType *funcType = dynamic_cast(trueDataType); + if (fn->getInterface() != funcType->getInterface()) + { + proto += funcType->getInterface()->getName() + "_interface::"; + } + } + } + proto += paramSignature; if (!isLast) { @@ -2290,7 +2339,7 @@ void CGenerator::getEncodeDecodeBuiltin(Group *group, BuiltinType *t, data_map & } data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataType *t, StructType *structType, - bool inDataContainer, StructMember *structMember, bool &needTempVariable, + bool inDataContainer, StructMember *structMember, bool &needTempVariableI32, bool isFunctionParam) { // prepare data for template @@ -2362,7 +2411,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT templateData["sharedType"] = "union"; if (setDiscriminatorTemp(u, structType, structMember, isFunctionParam, templateData)) { - needTempVariable = true; + needTempVariableI32 = true; } break; @@ -2376,7 +2425,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT // Check if member is byRef type. Add "*" for type and allocate space for data on server side. if (structMember && structMember->isByref() && !isFunctionParam && - (t->isStruct() || t->isUnion() || t->isScalar() || t->isEnum())) + (t->isStruct() || t->isUnion() || t->isScalar() || t->isEnum() || t->isFunction())) { templateData["freeingCall2"] = m_templateData["freeData"]; templateData["memberAllocation"] = allocateCall(name, t); @@ -2389,13 +2438,13 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT templateData["name"] = localName; - if (t->isScalar() || t->isEnum()) + if (t->isScalar() || t->isEnum() || t->isFunction()) { templateData["pointerScalarTypes"] = false; if (!inDataContainer && structMember && structMember->getDirection() != param_direction_t::kInDirection) { DataType *trueDataType = t->getTrueDataType(); - if (trueDataType->isScalar() || trueDataType->isEnum()) + if (trueDataType->isScalar() || trueDataType->isEnum() || t->isFunction()) { templateData["pointerScalarTypes"] = true; } @@ -2408,7 +2457,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT AliasType *aliasType = dynamic_cast(t); assert(aliasType); return getEncodeDecodeCall(name, group, aliasType->getElementType(), structType, inDataContainer, - structMember, needTempVariable, isFunctionParam); + structMember, needTempVariableI32, isFunctionParam); } case DataType::data_type_t::kArrayType: { static uint8_t arrayCounter; @@ -2431,7 +2480,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT templateData["forLoopCount"] = format_string("arrayCount%d", arrayCounter); templateData["protoNext"] = getEncodeDecodeCall(format_string("%s[arrayCount%d]", arrayName.c_str(), arrayCounter++), group, - elementType, structType, true, structMember, needTempVariable, isFunctionParam); + elementType, structType, true, structMember, needTempVariableI32, isFunctionParam); templateData["size"] = format_string("%dU", arrayType->getElementCount()); templateData["sizeTemp"] = format_string("%dU", arrayType->getElementCount()); templateData["isElementArrayType"] = trueElementType->isArray(); @@ -2449,7 +2498,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT break; } case DataType::data_type_t::kEnumType: { - needTempVariable = true; + needTempVariableI32 = true; templateData["decode"] = m_templateData["decodeEnumType"]; templateData["encode"] = m_templateData["encodeEnumType"]; string typeName = getOutputName(t); @@ -2468,6 +2517,8 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT assert(funType); const FunctionType::c_function_list_t &callbacks = funType->getCallbackFuns(); templateData["callbacksCount"] = callbacks.size(); + templateData["cbTypeName"] = funType->getName(); + templateData["cbParamOutName"] = name; if (callbacks.size() > 1) { templateData["callbacks"] = "_" + funType->getName(); @@ -2478,11 +2529,11 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT } else { - throw semantic_error(format_string("line %d: Function has function type parameter (callback " - "parameter), but in IDL is missing function definition, which can " - "be passed there.", - structMember->getFirstLine()) - .c_str()); + throw semantic_error( + format_string("line %d: Function has function type parameter (callback " + "parameter), but in IDL is missing function definition, which can " + "be passed there.", + structMember->getFirstLine())); } templateData["encode"] = m_templateData["encodeFunctionType"]; templateData["decode"] = m_templateData["decodeFunctionType"]; @@ -2630,7 +2681,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT templateData["size"] = size; templateData["useBinaryCoder"] = isBinaryList(listType); templateData["protoNext"] = getEncodeDecodeCall(nextName, group, elementType, structType, true, - structMember, needTempVariable, isFunctionParam); + structMember, needTempVariableI32, isFunctionParam); break; } case DataType::data_type_t::kStructType: { @@ -2661,7 +2712,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT // set discriminator name if (setDiscriminatorTemp(unionType, structType, structMember, isFunctionParam, templateData)) { - needTempVariable = true; + needTempVariableI32 = true; } /* NonEncapsulated unions as a function/structure param/member. */ @@ -2756,7 +2807,7 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT caseMembers.push_back(memberData); if (casesNeedTempVariable) { - needTempVariable = true; + needTempVariableI32 = true; } } } @@ -2806,7 +2857,7 @@ string CGenerator::getExtraDirectionPointer(StructMember *structMember) param_direction_t::kOutDirection) // between out and inout can be differences in future. Maybe not. { if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isList() && - !trueDataType->isArray()) + !trueDataType->isArray() && !trueDataType->isFunction()) { result = "*"; } @@ -2818,7 +2869,7 @@ string CGenerator::getExtraDirectionPointer(StructMember *structMember) else if (structMemberDir == param_direction_t::kInoutDirection) { if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isList() && - !trueDataType->isArray()) + !trueDataType->isArray() && !trueDataType->isFunction()) { result = "*"; } @@ -2862,7 +2913,7 @@ data_map CGenerator::firstAllocOnServerWhenIsNeed(const string &name, StructMemb if (structMemberDir == param_direction_t::kInoutDirection) { if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isList() && - !trueDataType->isArray()) + !trueDataType->isArray() && !trueDataType->isFunction()) { return allocateCall(name, structMember); } @@ -2876,7 +2927,8 @@ data_map CGenerator::firstAllocOnServerWhenIsNeed(const string &name, StructMemb } else if (structMember->getDirection() == param_direction_t::kOutDirection) { - if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isArray()) + if (!trueDataType->isBuiltin() && !trueDataType->isEnum() && !trueDataType->isArray() && + !trueDataType->isFunction()) { return allocateCall(name, structMember); } @@ -2963,8 +3015,7 @@ void CGenerator::setCallingFreeFunctions(Symbol *symbol, data_map &info, bool re { if (!returnType) { - if (trueDataType->isStruct() || trueDataType->isUnion() || - (trueDataType->isFunction() && ((structMember->getDirection() == param_direction_t::kOutDirection)))) + if (trueDataType->isStruct() || trueDataType->isUnion()) { string name = getOutputName(structMember, false); firstFreeingCall1["firstFreeingCall"] = m_templateData["freeData"]; @@ -3232,7 +3283,7 @@ void CGenerator::setNoSharedAnn(Symbol *parentSymbol, Symbol *childSymbol) bool CGenerator::setDiscriminatorTemp(UnionType *unionType, StructType *structType, StructMember *structMember, bool isFunctionParam, data_map &templateData) { - bool needTempVariable = false; + bool needTempVariableI32 = false; if (structType) { string discriminatorName; @@ -3283,7 +3334,7 @@ bool CGenerator::setDiscriminatorTemp(UnionType *unionType, StructType *structTy } else { - needTempVariable = true; + needTempVariableI32 = true; templateData["castDiscriminator"] = true; templateData["discriminatorType"] = disType->getName(); } @@ -3295,7 +3346,7 @@ bool CGenerator::setDiscriminatorTemp(UnionType *unionType, StructType *structTy templateData["dataLiteral"] = ""; templateData["castDiscriminator"] = false; } - return needTempVariable; + return needTempVariableI32; } string CGenerator::getScalarTypename(DataType *dataType) diff --git a/erpcgen/src/CGenerator.hpp b/erpcgen/src/CGenerator.hpp index 23003ebc..e6a9949f 100644 --- a/erpcgen/src/CGenerator.hpp +++ b/erpcgen/src/CGenerator.hpp @@ -62,11 +62,11 @@ class CGenerator : public Generator cpptempl::data_list m_symbolsTemplate; /*!< List of all symbol templates */ std::vector - m_listBinaryTypes; /*!< - * Contains binary types transformed to list. - * More ListType are present when @length annotation is used for binary type. - * If binary without @length is used then it is placed on first place in this vector. - */ + m_listBinaryTypes; /*!< + * Contains binary types transformed to list. + * More ListType are present when @length annotation is used for binary type. + * If binary without @length is used then it is placed on first place in this vector. + */ std::vector m_structListTypes; /*!< * Contains list types transformed to struct{list<>}. @@ -92,39 +92,88 @@ class CGenerator : public Generator void generateOutputFiles(const std::string &fileNameExtension) override; /*! - * @brief This function generate output common types header file. + * @brief This function generate header file output with common eRPC code. * - * @param[in] fileName Name for output client source file. + * @param[in] fileName Name for common eRPC header file output. + */ + void generateCommonCHeaderFiles(std::string fileName); + + /*! + * @brief This function generate header file output with common eRPC code. + * + * @param[in] fileName Name for common eRPC header file output. + */ + void generateCommonCppHeaderFiles(std::string fileName); + + /*! + * @brief This function generate output interface header file. + * + * @param[in] fileName Name for output interface header file. + */ + void generateInterfaceCppHeaderFile(std::string fileName); + + /*! + * @brief This function generate output interface source file. + * + * @param[in] fileName Name for output interface source file. + */ + void generateInterfaceCppSourceFile(std::string fileName); + + /*! + * @brief This function generate output client header file for cpp. + * + * @param[in] fileName Name for output client header file. */ - void generateTypesHeaderFile(); + void generateClientCppHeaderFile(std::string fileName); /*! - * @brief This function generate output common header file. + * @brief This function generate output client source file for cpp. * * @param[in] fileName Name for output client source file. */ - void generateCommonHeaderFiles(const std::string &fileName); + void generateClientCppSourceFile(std::string fileName); + + /*! + * @brief This function generate output server header file for cpp. + * + * @param[in] fileName Name for output server header file. + */ + void generateServerCppHeaderFile(std::string fileName); + + /*! + * @brief This function generate output server source file for cpp. + * + * @param[in] fileName Name for output server source file. + */ + void generateServerCppSourceFile(std::string fileName); + + /*! + * @brief This function generate output client header file for C. + * + * @param[in] fileName Name for output client header file. + */ + void generateClientCHeaderFile(std::string fileName); /*! - * @brief This function generate output client source file. + * @brief This function generate output client source file for C. * * @param[in] fileName Name for output client source file. */ - void generateClientSourceFile(std::string fileName); + void generateClientCSourceFile(std::string fileName); /*! - * @brief This function generate output server header file. + * @brief This function generate output server header file for C. * * @param[in] fileName Name for output server header file. */ - void generateServerHeaderFile(std::string fileName); + void generateServerCHeaderFile(std::string fileName); /*! - * @brief This function generate output server source file. + * @brief This function generate output server source file for C. * * @param[in] fileName Name for output server source file. */ - void generateServerSourceFile(std::string fileName); + void generateServerCSourceFile(std::string fileName); /*! * @brief This function generate output crc16 source file. @@ -204,7 +253,7 @@ class CGenerator : public Generator * * @return Contains interface function data. */ - cpptempl::data_map getFunctionTypeTemplateData(Group *group, FunctionType *fn); + cpptempl::data_map getFunctionTypeTemplateData(Group *group, FunctionType *fn) override; /*! * @brief This function will get symbol comments and convert to language specific ones @@ -420,21 +469,24 @@ class CGenerator : public Generator * * @param[in] group Group to which function belongs. * @param[in] fn Function for prototyping. - * @param[in] name Name used for FunctionType. + * @param[in] interfaceName Interface name used for function declaration. + * @param[in] name Name used for shared code in case of function type. + * @param[in] insideInterfaceCall interfaceClass specific. * * @return String prototype representation for given function. */ - std::string getFunctionPrototype(Group *group, FunctionBase *fn, const std::string name = ""); + std::string getFunctionPrototype(Group *group, FunctionBase *fn, const std::string &interfaceName = "", + const std::string &name = "", bool insideInterfaceCall = false) override; /*! * @brief This function return interface function representation called by server side. * * @param[in] fn Function for interface function representation. - * @param[in] functionType Inside FunctionType common shim code server call need use FunctionType parameters names. + * @param[in] isCCall C and C++ code is similar, but not same. * * @return String representation for given function. */ - std::string getFunctionServerCall(Function *fn, FunctionType *functionType = nullptr); + std::string getFunctionServerCall(Function *fn, bool isCCall = false); /*! * @brief This function return name with guard. @@ -480,13 +532,13 @@ class CGenerator : public Generator * @param[in] structType Structure holdings structure members. * @param[in] inDataContainer Is inside data container (struct, list, array). * @param[in] structMember Null for return. - * @param[out] needTempVariable Return true, when data type contains enum, function, union type. + * @param[out] needTempVariableI32 Return true, when data type contains enum, function, union type. * @param[in] isFunctionParam True for function param else false (structure member). * * @return Template data for decode or encode data type. */ cpptempl::data_map getEncodeDecodeCall(const std::string &name, Group *group, DataType *t, StructType *structType, - bool inDataContainer, StructMember *structMember, bool &needTempVariable, + bool inDataContainer, StructMember *structMember, bool &needTempVariableI32, bool isFunctionParam); /*! diff --git a/erpcgen/src/Generator.cpp b/erpcgen/src/Generator.cpp index 86e1c082..8530b4ed 100644 --- a/erpcgen/src/Generator.cpp +++ b/erpcgen/src/Generator.cpp @@ -20,6 +20,7 @@ #include #include #include +#include using namespace erpcgen; using namespace cpptempl; @@ -38,6 +39,7 @@ Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) string scopeName = "erpcShim"; string scopeNameC; string scopeNamePrefix = ""; + string namespaceVal = scopeName; m_templateData["erpcVersion"] = ERPC_VERSION; m_templateData["erpcVersionNumber"] = ERPC_VERSION_NUMBER; @@ -90,6 +92,11 @@ Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) { scopeName = getAnnStringValue(program, SCOPE_NAME_ANNOTATION); } + + if (findAnnotation(program, NAMESPACE_ANNOTATION) != nullptr) + { + namespaceVal = getAnnStringValue(program, NAMESPACE_ANNOTATION); + } } m_templateData["scopeName"] = scopeName; @@ -102,6 +109,7 @@ Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) } m_templateData["scopeNameC"] = scopeNameC; m_templateData["scopeNamePrefix"] = scopeNamePrefix; + m_templateData["namespace"] = namespaceVal; // get group annotation with vector of theirs interfaces m_groups.clear(); @@ -430,12 +438,21 @@ data_list Generator::makeGroupInterfacesTemplateData(Group *group) // TODO: for C only? ifaceInfo["serviceClassName"] = getOutputName(iface) + "_service"; + ifaceInfo["clientClassName"] = getOutputName(iface) + "_client"; + ifaceInfo["serverClassName"] = getOutputName(iface) + "_server"; + ifaceInfo["interfaceClassName"] = getOutputName(iface) + "_interface"; Log::info("%d: (%d) %s\n", n++, iface->getUniqueId(), iface->getName().c_str()); /* Has interface function declared as non-external? */ data_list functions = getFunctionsTemplateData(group, iface); ifaceInfo["functions"] = functions; + data_list callbacksInt; + data_list callbacksExt; + data_list callbacksAll; + getCallbacksTemplateData(group, iface, callbacksInt, callbacksExt, callbacksAll); + ifaceInfo["callbacksInt"] = callbacksInt; + ifaceInfo["callbacksAll"] = callbacksAll; ifaceInfo["isNonExternalInterface"] = false; for (unsigned int i = 0; i < functions.size(); ++i) { @@ -455,20 +472,29 @@ data_list Generator::makeGroupInterfacesTemplateData(Group *group) return interfaces; } -void Generator::generateGroupOutputFiles(Group *group) +string Generator::getGroupCommonFileName(Group *group) { - // generate output files only for groups with interfaces or for IDLs with no interfaces at all + string fileName = ""; if (!group->getInterfaces().empty() || (m_groups.size() == 1 && group->getName() == "")) { string groupName = group->getName(); - string fileName = stripExtension(m_def->getOutputFilename()); + fileName = stripExtension(m_def->getOutputFilename()); m_templateData["outputFilename"] = fileName; if (groupName != "") { fileName += "_" + groupName; } Log::info("File name %s\n", fileName.c_str()); - m_templateData["commonHeaderName"] = fileName; + } + return fileName; +} + +void Generator::generateGroupOutputFiles(Group *group) +{ + // generate output files only for groups with interfaces or for IDLs with no interfaces at all + if (!group->getInterfaces().empty() || (m_groups.size() == 1 && group->getName() == "")) + { + string fileName = getGroupCommonFileName(group); // group templates m_templateData["group"] = group->getTemplate(); @@ -567,10 +593,8 @@ string Generator::getOutputName(Symbol *symbol, bool check) auto it = reserverdWords.find(annName); if (it != reserverdWords.end()) { - throw semantic_error( - format_string("line %d: Wrong symbol name '%s'. Cannot use program language reserved words.", line, - annName.c_str()) - .c_str()); + throw semantic_error(format_string( + "line %d: Wrong symbol name '%s'. Cannot use program language reserved words.", line, annName.c_str())); } } @@ -641,3 +665,88 @@ Generator::datatype_vector_t Generator::getDataTypesFromSymbolScope(SymbolScope return vector; } + +void Generator::getCallbacksTemplateData(Group *group, const Interface *iface, data_list &callbackTypesInt, + data_list &callbackTypesExt, data_list &callbackTypesAll) +{ + list callbackTypes; + list interfacesNames; + list callbackTypesNames; + interfacesNames.push_back(iface->getName()); + for (auto function : iface->getFunctions()) + { + for (auto param : function->getParameters().getMembers()) + { + DataType *datatype = param->getDataType()->getTrueDataType(); + if (datatype->isFunction()) + { + FunctionType *funType = dynamic_cast(datatype); + if (funType->getInterface() != iface) + { + interfacesNames.push_back(funType->getInterface()->getName()); + } + if ((std::find(callbackTypesNames.begin(), callbackTypesNames.end(), funType->getName()) == + callbackTypesNames.end())) + { + callbackTypes.push_back(funType); + callbackTypesNames.push_back(funType->getName()); + } + } + } + } + for (auto functionType : iface->getFunctionTypes()) + { + if ((std::find(callbackTypesNames.begin(), callbackTypesNames.end(), functionType->getName()) == + callbackTypesNames.end())) + { + callbackTypes.push_back(functionType); + callbackTypesNames.push_back(functionType->getName()); + } + } + + for (auto functionType : callbackTypes) + { + data_list functionsInt; + data_list functionsExt; + data_list functionsAll; + for (auto fun : functionType->getCallbackFuns()) + { + if ((std::find(interfacesNames.begin(), interfacesNames.end(), fun->getInterface()->getName()) != + interfacesNames.end())) + { + data_map function; + function["name"] = fun->getName(); + if (fun->getInterface() == iface) + { + functionsInt.push_back(function); + } + else + { + functionsExt.push_back(function); + } + functionsAll.push_back(function); + } + } + if (!functionsAll.empty()) + { + data_map callbackType; + callbackType["name"] = functionType->getName(); + callbackType["typenameName"] = getFunctionPrototype(nullptr, functionType); + callbackType["interfaceTypenameName"] = + getFunctionPrototype(nullptr, functionType, iface->getName() + "_interface"); + if (!functionsInt.empty()) + { + callbackType["callbacks"] = functionsInt; + callbackType["callbacksData"] = getFunctionTypeTemplateData(group, functionType); + callbackTypesInt.push_back(callbackType); + } + if (!functionsExt.empty()) + { + callbackType["callbacks"] = functionsExt; + callbackTypesExt.push_back(callbackType); + } + callbackType["callbacks"] = functionsAll; + callbackTypesAll.push_back(callbackType); + } + } +} diff --git a/erpcgen/src/Generator.hpp b/erpcgen/src/Generator.hpp index 64167de9..dd9ad734 100644 --- a/erpcgen/src/Generator.hpp +++ b/erpcgen/src/Generator.hpp @@ -201,12 +201,25 @@ class Generator * * @param[in] group Pointer to a group. * @param[in] fn From this are set interface function template data. - * @param[in] fnIndex Function index. * * @return Contains interface function data. */ virtual cpptempl::data_map getFunctionTemplateData(Group *group, Function *fn) = 0; + /*! + * @brief This function returns function type (callbacks type) template data. + * + * This function returns function type (callbacks type) template data with all data, which + * are necessary for generating output code for output files. Shim code is generating + * common function for serialization/deserialization of data. + * + * @param[in] group Group to which function belongs. + * @param[in] fn From this are set function type template data. + * + * @return Contains interface function data. + */ + virtual cpptempl::data_map getFunctionTypeTemplateData(Group *group, FunctionType *fn) = 0; + /*! * @brief This function will get symbol comments and convert to language specific ones * @@ -238,6 +251,14 @@ class Generator */ virtual void generateOutputFiles(const std::string &fileNameExtension) = 0; + /** + * @brief Function return common fileName part for group generated files. + * + * @param group Pointer to a group. + * @return string Common filename part of group generated files. + */ + std::string getGroupCommonFileName(Group *group); + /*! * @brief This function generates output files for defined interfaces. * @@ -347,6 +368,20 @@ class Generator */ datatype_vector_t getDataTypesFromSymbolScope(SymbolScope *scope, DataType::data_type_t datatype); + /*! + * @brief This function return interface function prototype. + * + * @param[in] group Group to which function belongs. + * @param[in] fn Function for prototyping. + * @param[in] interfaceName Interface name used for function declaration. + * @param[in] name Name used for shared code in case of function type. + * @param[in] insideInterfaceCall interfaceClass specific. + * + * @return String prototype representation for given function. + */ + virtual std::string getFunctionPrototype(Group *group, FunctionBase *fn, const std::string &interfaceName = "", + const std::string &name = "", bool insideInterfaceCall = false) = 0; + private: /*! * @brief This function return interface functions list. @@ -359,6 +394,18 @@ class Generator * @return Contains interface functions data. */ cpptempl::data_list getFunctionsTemplateData(Group *group, Interface *iface); + + /*! + * @brief Get the Callbacks template data and dived them to the interface scope list. + * + * @param[in] group Group to which callbacks belongs. + * @param[in] iface Use callbacks belongs to this interface. + * @param[out] callbackTypesInt Template data for current interface scope callbacks + * @param[out] callbackTypesExt Template data for others interface scope callbacks + * @param[out] callbackTypesAll Template data of all callbacks. + */ + void getCallbacksTemplateData(Group *group, const Interface *iface, cpptempl::data_list &callbackTypesInt, + cpptempl::data_list &callbackTypesExt, cpptempl::data_list &callbackTypesAll); }; } // namespace erpcgen diff --git a/erpcgen/src/PythonGenerator.cpp b/erpcgen/src/PythonGenerator.cpp index d42865e5..e56dc373 100644 --- a/erpcgen/src/PythonGenerator.cpp +++ b/erpcgen/src/PythonGenerator.cpp @@ -122,6 +122,7 @@ void PythonGenerator::generate() m_templateData["structs"] = empty; m_templateData["unions"] = empty; m_templateData["consts"] = empty; + m_templateData["functions"] = empty; parseSubtemplates(); @@ -146,8 +147,6 @@ void PythonGenerator::generate() makeEnumsTemplateData(); - makeFunctionsTemplateData(); - for (Group *group : m_groups) { data_map groupTemplate; @@ -173,7 +172,7 @@ data_map PythonGenerator::getFunctionTemplateData(Group *group, Function *fn) { (void)group; data_map info; - string proto = getFunctionPrototype(fn); + string proto = getFunctionPrototype(nullptr, fn); info["name"] = getOutputName(fn); info["prototype"] = proto; @@ -266,12 +265,22 @@ data_map PythonGenerator::getFunctionTemplateData(Group *group, Function *fn) return info; } -string PythonGenerator::getFunctionPrototype(Function *fn) +string PythonGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const string &interfaceName, + const string &name, bool insideInterfaceCall) { - string proto = getOutputName(fn); + FunctionType *functionType = dynamic_cast(fn); + if (functionType) + { + return ""; /*Todo: implement*/ + } + Function *function = dynamic_cast(fn); + + assert(function); + + string proto = getOutputName(function); proto += "(self"; - auto params = fn->getParameters().getMembers(); + auto params = function->getParameters().getMembers(); if (params.size()) { for (auto it : params) @@ -572,32 +581,6 @@ void PythonGenerator::setOneStructMemberTemplateData(StructMember *member, data_ setTemplateComments(member, member_info); } -void PythonGenerator::makeFunctionsTemplateData() -{ - /* type definitions of functions and table of functions */ - Log::info("Functions:\n"); - data_list functions; - for (Symbol *functionTypeSymbol : getDataTypesFromSymbolScope(m_globals, DataType::data_type_t::kFunctionType)) - { - FunctionType *functionType = dynamic_cast(functionTypeSymbol); - data_map functionInfo; - - /* Table template data. */ - data_list callbacks; - for (Function *fun : functionType->getCallbackFuns()) - { - data_map callbacksInfo; - callbacksInfo["name"] = fun->getName(); - callbacks.push_back(callbacksInfo); - } - functionInfo["callbacks"] = callbacks; - /* Function type name. */ - functionInfo["name"] = functionType->getName(); - functions.push_back(functionInfo); - } - m_templateData["functions"] = functions; -} - data_map PythonGenerator::getTypeInfo(DataType *t) { data_map info; @@ -643,9 +626,9 @@ data_map PythonGenerator::getTypeInfo(DataType *t) } else { - throw semantic_error(format_string("Function has function type parameter (callback parameter), but in " - "IDL is missing function definition, which can be passed there.") - .c_str()); + throw semantic_error( + "Function has function type parameter (callback parameter), but in " + "IDL is missing function definition, which can be passed there."); } break; } @@ -687,7 +670,7 @@ data_map PythonGenerator::getTypeInfo(DataType *t) StructMember *discriminatorMember = dynamic_cast(discriminatorSym); if (!discriminatorMember) { - throw internal_error(format_string("union discriminator is not a struct member")); + throw internal_error("union discriminator is not a struct member"); } info["discriminatorType"] = getTypeInfo(discriminatorMember->getDataType()); } @@ -842,7 +825,7 @@ string PythonGenerator::convertComment(const string &comment, comment_type_t com { (void)commentType; // Longer patterns are ordered earlier than similar shorter patterns. - static const char *const kCommentBegins[] = { "//!<", "//!", "///<", "///", "/*!<", "/*!", "/**<", "/**", 0 }; + static const char *const kCommentBegins[] = { "//!<", "//!", "///<", "///", "/*!<", "/*!", "/**<", "/**", "/*", 0 }; static const char *const kCommentEnds[] = { "*/", 0 }; string result = stripWhitespace(comment); @@ -870,7 +853,7 @@ string PythonGenerator::convertComment(const string &comment, comment_type_t com // Check if we failed to find a matching comment begin. if (kCommentBegins[i] == 0) { - throw internal_error("unable to convert Doxygen comment"); + throw internal_error("Unable to convert Doxygen comment in:" + result); } // Search for a matching comment end to strip. There may not be a comment end. @@ -941,7 +924,7 @@ string PythonGenerator::convertComment(const string &comment, comment_type_t com return result; } -bool PythonGenerator::checkWhitspaceChar(char c) +bool PythonGenerator::checkWhitespaceChar(char c) { if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { @@ -961,7 +944,7 @@ string PythonGenerator::stripWhitespace(const string &s) { char c = result[i]; - if ((i < (int)result.size() - 1 && c == ' ' && !checkWhitspaceChar(result[i + 1])) || !checkWhitspaceChar(c)) + if ((i < (int)result.size() - 1 && c == ' ' && !checkWhitespaceChar(result[i + 1])) || !checkWhitespaceChar(c)) { break; } @@ -975,7 +958,7 @@ string PythonGenerator::stripWhitespace(const string &s) for (n = 0, i = (int)result.size() - 1; i > 0; --i, ++n) { char c = result[i]; - if (!checkWhitspaceChar(c)) + if (!checkWhitespaceChar(c)) { break; } diff --git a/erpcgen/src/PythonGenerator.hpp b/erpcgen/src/PythonGenerator.hpp index 3e392526..e31ee6a4 100644 --- a/erpcgen/src/PythonGenerator.hpp +++ b/erpcgen/src/PythonGenerator.hpp @@ -117,12 +117,25 @@ class PythonGenerator : public Generator * * @param[in] group Pointer to a group. * @param[in] fn From this are set interface function template data. - * @param[in] fnIndex Function index. * * @return Contains interface function data. */ cpptempl::data_map getFunctionTemplateData(Group *group, Function *fn) override; + /*! + * @brief This function returns function type (callbacks type) template data. + * + * This function returns function type (callbacks type) template data with all data, which + * are necessary for generating output code for output files. Shim code is generating + * common function for serialization/deserialization of data. + * + * @param[in] group Group to which function belongs. + * @param[in] fn From this are set function type template data. + * + * @return Contains interface function data. + */ + cpptempl::data_map getFunctionTypeTemplateData(Group *group, FunctionType *fn) override { return {}; }; + /*! * @brief This function will get symbol comments and convert to language specific ones * @@ -134,11 +147,16 @@ class PythonGenerator : public Generator /*! * @brief This function return interface function prototype. * + * @param[in] group Group to which function belongs. * @param[in] fn Function for prototyping. + * @param[in] interfaceName Interface name used for function declaration. + * @param[in] name Name used for shared code in case of function type. + * @param[in] insideInterfaceCall interfaceClass specific. * * @return String prototype representation for given function. */ - std::string getFunctionPrototype(Function *fn); + std::string getFunctionPrototype(Group *group, FunctionBase *fn, const std::string &interfaceName = "", + const std::string &name = "", bool insideInterfaceCall = false) override; /*! * @brief This function sets const template data. @@ -185,13 +203,6 @@ class PythonGenerator : public Generator */ void makeAliasesTemplateData(); - /*! - * @brief This function sets function type template data. - * - * This is used for registering callback functions in generated output. - */ - void makeFunctionsTemplateData(); - /*! * @brief This function sets struct member information to struct data map variable. * @@ -263,7 +274,7 @@ class PythonGenerator : public Generator * * @param[in] c Checked character. */ - bool checkWhitspaceChar(char c); + bool checkWhitespaceChar(char c); /*! * Stores reserved words for Python program language. diff --git a/erpcgen/src/SymbolScanner.cpp b/erpcgen/src/SymbolScanner.cpp index f5c12370..21c6c2ec 100644 --- a/erpcgen/src/SymbolScanner.cpp +++ b/erpcgen/src/SymbolScanner.cpp @@ -45,8 +45,7 @@ void SymbolScanner::handleRoot(AstNode *node, bottom_up) forwardTypes += format_string("type name %s: line %d", it->first.c_str(), it->second->getFirstLine()); } throw syntax_error(format_string("Missing type definitions for one or more forward type declarations: %s", - forwardTypes.c_str()) - .c_str()); + forwardTypes.c_str())); } } @@ -147,37 +146,43 @@ DataType *SymbolScanner::getDataTypeForConst(AstNode *typeNode) AstNode *SymbolScanner::handleType(AstNode *node, top_down) { - // Extract new type name. - AstNode *ident = (*node)[0]; - const Token &tok = ident->getToken(); - const string &name = tok.getStringValue(); - Log::debug("type: %s\n", name.c_str()); - - // Find existing type. - AstNode *typeNode = (*node)[1]; - DataType *dataType = nullptr; - if (!containsStructEnumDeclaration(typeNode)) + if (m_currentInterface == nullptr) { - dataType = lookupDataType(typeNode); - } + // Extract new type name. + AstNode *ident = (*node)[0]; + const Token &tok = ident->getToken(); + const string &name = tok.getStringValue(); + Log::debug("type: %s\n", name.c_str()); - AliasType *type = new AliasType(tok, dataType); + // Find existing type. + AstNode *typeNode = (*node)[1]; + DataType *dataType = nullptr; + if (!containsStructEnumDeclaration(typeNode)) + { + dataType = lookupDataType(typeNode); + } - // Get comment if exist. - addDoxygenComments(type, node->getChild(3), node->getChild(4)); + AliasType *type = new AliasType(tok, dataType); - m_currentAlias = type; + // Get comment if exist. + addDoxygenComments(type, node->getChild(3), node->getChild(4)); + + m_currentAlias = type; + } return nullptr; } AstNode *SymbolScanner::handleType(AstNode *node, bottom_up) { - if (m_currentAlias) + if (m_currentInterface == nullptr) { - addAnnotations(node->getChild(2), m_currentAlias); - addGlobalSymbol(m_currentAlias); - m_currentAlias = nullptr; + if (m_currentAlias) + { + addAnnotations(node->getChild(2), m_currentAlias); + addGlobalSymbol(m_currentAlias); + m_currentAlias = nullptr; + } } return nullptr; } @@ -637,9 +642,8 @@ AstNode *SymbolScanner::handleStruct(AstNode *node, top_down) AstNode *structNameNode = (*node)[0]; if (!structNameNode && m_currentAlias == nullptr) { - throw semantic_error( - format_string("line %d: illegal anonymous struct definition at file level", node->getToken().getFirstLine()) - .c_str()); + throw semantic_error(format_string("line %d: illegal anonymous struct definition at file level", + node->getToken().getFirstLine())); } // Create the struct symbol. @@ -661,10 +665,10 @@ AstNode *SymbolScanner::handleStruct(AstNode *node, top_down) } else { - throw syntax_error(format_string("line %d: Structure definition type name didn't match data type of " - "forward declaration from line %d.", - tok.getFirstLine(), forwardDecl->second->getFirstLine()) - .c_str()); + throw syntax_error( + format_string("line %d: Structure definition type name didn't match data type of " + "forward declaration from line %d.", + tok.getFirstLine(), forwardDecl->second->getFirstLine())); } } else @@ -817,10 +821,10 @@ AstNode *SymbolScanner::handleUnion(AstNode *node, top_down) } else { - throw syntax_error(format_string("line %d: Union definition type name didn't match data type of " - "forward declaration from line %d.", - tok->getFirstLine(), forwardDecl->second->getFirstLine()) - .c_str()); + throw syntax_error( + format_string("line %d: Union definition type name didn't match data type of " + "forward declaration from line %d.", + tok->getFirstLine(), forwardDecl->second->getFirstLine())); } } else @@ -1013,6 +1017,55 @@ AstNode *SymbolScanner::handleInterface(AstNode *node, bottom_up) { addAnnotations(node->getChild(2), m_currentInterface); + /* Check if function callbacks were not used in other interfaces*/ + for (Symbol *funSymbol : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kInterfaceSymbol)) + { + Interface *interface = dynamic_cast(funSymbol); + assert(interface); + + if (interface == m_currentInterface) + { + continue; + } + + for (Function *func : interface->getFunctions()) + { + for (StructMember *param : func->getParameters().getMembers()) + { + DataType *dataType = param->getDataType()->getTrueDataType(); + if (dataType->isFunction()) + { + FunctionType *funcType = dynamic_cast(dataType); + assert(funcType); + + if ((m_currentInterface->getName() == funcType->getInterface()->getName()) && + (m_currentInterface != funcType->getInterface())) + { + bool found = false; + for (FunctionType *funcTypeCurrent : m_currentInterface->getFunctionTypes()) + { + if (funcTypeCurrent->getName() == funcType->getName()) + { + found = true; + delete funcType->getInterface(); + delete funcType; + param->setDataType(funcTypeCurrent); + break; + } + } + if (found == false) + { + throw syntax_error( + format_string("line %d, Callback name %s doesn't exists in interface %s.\n", + funcType->getLocation().m_firstLine, funcType->getName().c_str(), + funcType->getInterface()->getName().c_str())); + } + } + } + } + } + } + // Interfaces cannot be nested, so we can just clear this. If they were nestable, we would // have to keep a stack of open interfaces. m_currentInterface = nullptr; @@ -1027,10 +1080,16 @@ AstNode *SymbolScanner::handleFunction(AstNode *node, top_down) const Token &tok = ident->getToken(); const string &name = tok.getStringValue(); Log::debug("function: %s\n", name.c_str()); + bool isFunctionType = node->getChild(4) != nullptr; // Create function symbol. FunctionBase *func; - if (m_currentInterface) /* function definition */ + if (isFunctionType) + { + func = new FunctionType(tok, m_currentInterface); + m_currentInterface->addFunctionType(dynamic_cast(func)); + } + else { if (m_currentInterface->getFunctions().size() == 0) { @@ -1042,11 +1101,6 @@ AstNode *SymbolScanner::handleFunction(AstNode *node, top_down) } m_currentInterface->addFunction(dynamic_cast(func)); } - else /* function type */ - { - func = new FunctionType(tok); - addGlobalSymbol(dynamic_cast(func)); - } m_currentStruct = &(func->getParameters()); @@ -1123,21 +1177,30 @@ AstNode *SymbolScanner::handleFunction(AstNode *node, top_down) } /* Get comment if exist. */ - addDoxygenComments(dynamic_cast(func), node->getChild(5), node->getChild(6)); + addDoxygenComments(dynamic_cast(func), node->getChild(6), node->getChild(7)); return nullptr; } AstNode *SymbolScanner::handleFunction(AstNode *node, bottom_up) { + bool isFunctionType = node->getChild(4) != nullptr; - if (m_currentInterface) /* function definition */ + if (isFunctionType) /* function type */ + { + FunctionType *func = m_currentInterface->getFunctionTypes().back(); + func->getParameters().getScope().setParent(&m_currentInterface->getScope()); + + /* Function annotations. */ + addAnnotations(node->getChild(5), func); + } + else /* function definition */ { Function *func = m_currentInterface->getFunctions().back(); func->getParameters().getScope().setParent(&m_currentInterface->getScope()); /* Function annotations. */ - addAnnotations(node->getChild(4), func); + addAnnotations(node->getChild(5), func); /* Add missing callbacks parameters. */ FunctionType *callbackFunctionType = func->getFunctionType(); @@ -1162,25 +1225,6 @@ AstNode *SymbolScanner::handleFunction(AstNode *node, bottom_up) } } } - else /* function type */ - { - FunctionType *func = nullptr; - for (Symbol *funSymbol : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kTypenameSymbol)) - { - DataType *datatype = dynamic_cast(funSymbol); - assert(datatype); - - if (datatype->isFunction()) - { - func = dynamic_cast(datatype); - } - } - assert(func); - func->getParameters().getScope().setParent(m_globals); - - /* Function annotations. */ - addAnnotations(node->getChild(4), func); - } // Handle annotations for function params scanStructForAnnotations(); @@ -1198,34 +1242,27 @@ AstNode *SymbolScanner::handleParam(AstNode *node, top_down) StructMember *callbackParam = nullptr; Function *fun = nullptr; FunctionType *funType = nullptr; - if (m_currentInterface) + bool isFunctionType = m_currentInterface->getFunctions().empty(); + if (!isFunctionType) { fun = m_currentInterface->getFunctions().back(); - for (Symbol *funSymbol : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kTypenameSymbol)) + for (FunctionType *funType : m_currentInterface->getFunctionTypes()) { - DataType *datatype = dynamic_cast(funSymbol); - assert(datatype); - - if (datatype->isFunction()) + FunctionType::c_function_list_t &callbacks = funType->getCallbackFuns(); + if (find(callbacks.begin(), callbacks.end(), fun) != callbacks.end()) { - funType = dynamic_cast(datatype); - assert(funType); - FunctionType::c_function_list_t &callbacks = funType->getCallbackFuns(); - if (find(callbacks.begin(), callbacks.end(), fun) != callbacks.end()) + if (fun->getParameters().getMembers().size() > funType->getParameters().getMembers().size()) { - if (fun->getParameters().getMembers().size() > funType->getParameters().getMembers().size()) - { - throw syntax_error(format_string("line %d: Function definition contains more parameters than " - "function type definition from %d.\n", - fun->getFirstLine(), funType->getFirstLine()) - .c_str()); - } - else - { - callbackParam = funType->getParameters().getMembers()[fun->getParameters().getMembers().size()]; - } - break; + throw syntax_error( + format_string("line %d: Function definition contains more parameters than " + "function type definition from %d.\n", + fun->getFirstLine(), funType->getFirstLine())); } + else + { + callbackParam = funType->getParameters().getMembers()[fun->getParameters().getMembers().size()]; + } + break; } } } @@ -1260,7 +1297,48 @@ AstNode *SymbolScanner::handleParam(AstNode *node, top_down) /* Extract param data type. */ AstNode *typeNode = (*node)[1]; assert(typeNode); - DataType *dataType = lookupDataType(typeNode); + DataType *dataType = nullptr; + const Token &typeToken = typeNode->getToken(); + if (typeToken.getToken() == TOK_IFACE_SCOPE) + { + /* Find if interface and function definition exist already or create temporary. */ + AstNode *iface = typeNode->getChild(0); + AstNode *type = typeNode->getChild(1); + std::string ifaceName = iface->getToken().getStringValue(); + std::string functionTypeName = type->getToken().getStringValue(); + for (Symbol *funSymbol : m_globals->getSymbolsOfType(Symbol::symbol_type_t::kInterfaceSymbol)) + { + Interface *interface = dynamic_cast(funSymbol); + assert(interface); + + if (interface->getName() == ifaceName) + { + for (FunctionType *funcType : interface->getFunctionTypes()) + { + if (funcType->getName() == functionTypeName) + { + dataType = funcType; + break; + } + } + if (dataType == nullptr) + { + throw syntax_error(format_string("line %d: Callback name %s doesn't exists.\n", + type->getToken().getFirstLine(), functionTypeName.c_str())); + } + break; + } + } + if (dataType == nullptr) + { + /* create temporary */ + dataType = new FunctionType(type->getToken(), new Interface(iface->getToken())); + } + } + else + { + dataType = lookupDataType(typeNode); + } /* Extract param name. */ if (ident) @@ -1268,7 +1346,7 @@ AstNode *SymbolScanner::handleParam(AstNode *node, top_down) Token &tok = ident->getToken(); param = new StructMember(tok, dataType); } - else if (m_currentInterface && !funType) // Functions need param names. Types of functions don't. + else if (!isFunctionType) // Functions need param names. Types of functions don't. { throw syntax_error( format_string("line %d: Missing function param name.\n", node->getToken().getFirstLine())); @@ -1368,15 +1446,25 @@ DataType *SymbolScanner::lookupDataType(const AstNode *typeNode) const Token &typeToken = typeNode->getToken(); switch (typeToken.getToken()) { - case TOK_ARRAY: + case TOK_ARRAY: { return createArrayType(typeNode); + } - case TOK_IDENT: - return lookupDataTypeByName(typeToken, m_globals); - - case TOK_LIST: + case TOK_IDENT: { + DataType *dataType = nullptr; + if (m_currentInterface != nullptr) + { + dataType = lookupDataTypeByName(typeToken, &m_currentInterface->getScope()); + } + if (dataType == nullptr) + { + dataType = lookupDataTypeByName(typeToken, m_globals); + } + return dataType; + } + case TOK_LIST: { return createListType(typeNode); - + } case TOK_UNION: { assert(nullptr != m_currentStruct); return lookupDataTypeByName(typeNode->getChild(3)->getToken(), &(m_currentStruct->getScope()), false); @@ -1414,7 +1502,7 @@ DataType *SymbolScanner::createArrayType(const AstNode *typeNode) return array; } -Value *SymbolScanner::getValueFromSymbol(Token &tok) +Value *SymbolScanner::getValueFromSymbol(const Token &tok) { if (tok.getValue() != nullptr) { @@ -1572,8 +1660,7 @@ Annotation::program_lang_t SymbolScanner::getAnnotationLang(AstNode *annotation) } throw semantic_error(format_string("line %d: Unsupported programming language '%s' specified.", - annotation->getToken().getFirstLine(), lang.c_str()) - .c_str()); + annotation->getToken().getFirstLine(), lang.c_str())); } return Annotation::program_lang_t::kAll; @@ -1751,8 +1838,7 @@ void SymbolScanner::addForwardDeclaration(DataType *dataType) { throw semantic_error(format_string("line %d: Declaring type '%s' already declared here '%d'", dataType->getFirstLine(), dataType->getName().c_str(), - symbol->getFirstLine()) - .c_str()); + symbol->getFirstLine())); } auto findDataTypeIT = m_forwardDeclarations.find(dataType->getName()); @@ -1762,8 +1848,7 @@ void SymbolScanner::addForwardDeclaration(DataType *dataType) { throw semantic_error(format_string("line %d: Declaring type '%s' already declared here '%d'", dataType->getFirstLine(), dataType->getName().c_str(), - findDataTypeIT->second->getFirstLine()) - .c_str()); + findDataTypeIT->second->getFirstLine())); } else { @@ -1782,8 +1867,7 @@ void SymbolScanner::removeForwardDeclaration(DataType *dataType) { throw semantic_error(format_string("line %d: Declaring type '%s' already declared here '%d'", dataType->getFirstLine(), dataType->getName().c_str(), - findDataTypeIT->second->getFirstLine()) - .c_str()); + findDataTypeIT->second->getFirstLine())); } m_forwardDeclarations.erase(findDataTypeIT); } @@ -1796,8 +1880,7 @@ void SymbolScanner::addGlobalSymbol(Symbol *symbol) { throw semantic_error(format_string("line %d: Declaring symbol '%s' already declared here '%d'", symbol->getFirstLine(), symbol->getName().c_str(), - findDataTypeIT->second->getFirstLine()) - .c_str()); + findDataTypeIT->second->getFirstLine())); } m_globals->addSymbol(symbol); } diff --git a/erpcgen/src/SymbolScanner.hpp b/erpcgen/src/SymbolScanner.hpp index 7a2e32a9..5b72e808 100644 --- a/erpcgen/src/SymbolScanner.hpp +++ b/erpcgen/src/SymbolScanner.hpp @@ -458,7 +458,7 @@ class SymbolScanner : public AstWalker * @exception syntax_error Thrown, when token value is null or when symbol is not defined in global symbol scope. * @exception semantic_error Thrown, when symbol type is not constant or enum member. */ - Value *getValueFromSymbol(Token &tok); + Value *getValueFromSymbol(const Token &tok); /*! * @brief This function returns the data type for a constant variable diff --git a/erpcgen/src/UniqueIdChecker.cpp b/erpcgen/src/UniqueIdChecker.cpp index 48d102e6..b06dd22e 100644 --- a/erpcgen/src/UniqueIdChecker.cpp +++ b/erpcgen/src/UniqueIdChecker.cpp @@ -26,7 +26,7 @@ using namespace std; // Code //////////////////////////////////////////////////////////////////////////////// -void UniqueIdChecker::makeIdsUnique(erpcgen::InterfaceDefinition &def) +void UniqueIdChecker::makeIdsUnique(InterfaceDefinition &def) { initUsedInterfaceIds(def.getGlobals().getSymbolsOfType(Symbol::symbol_type_t::kInterfaceSymbol)); diff --git a/erpcgen/src/UniqueIdChecker.hpp b/erpcgen/src/UniqueIdChecker.hpp index 942b680d..c9390b57 100644 --- a/erpcgen/src/UniqueIdChecker.hpp +++ b/erpcgen/src/UniqueIdChecker.hpp @@ -38,7 +38,7 @@ class UniqueIdChecker * * @param[in] def Interface definition variable. */ - void makeIdsUnique(erpcgen::InterfaceDefinition &def); + void makeIdsUnique(InterfaceDefinition &def); private: /*! @@ -46,14 +46,14 @@ class UniqueIdChecker * * @param[in] ifaces Vector of interfaces. */ - void initUsedInterfaceIds(erpcgen::SymbolScope::symbol_vector_t ifaces); + void initUsedInterfaceIds(SymbolScope::symbol_vector_t ifaces); /*! * @brief This function will go through interface functions and set initial value of id number. * * @param[in] iface Interface. */ - void initUsedFunctionIds(erpcgen::Interface *iface); + void initUsedFunctionIds(Interface *iface); /*! * @brief This helper function sets a function symbol's unique id from the specified annotation. diff --git a/erpcgen/src/annotations.h b/erpcgen/src/annotations.h index afa0cc60..c88f138f 100644 --- a/erpcgen/src/annotations.h +++ b/erpcgen/src/annotations.h @@ -40,6 +40,9 @@ //! Specify the symbol name. #define NAME_ANNOTATION "name" +//! Specify the namespace of program code. +#define NAMESPACE_ANNOTATION "namespace" + //! Turn off error checking code for allocations in generated output #define NO_ALLOC_ERRORS_ANNOTATION "no_alloc_errors" @@ -76,7 +79,4 @@ //! Shared memory area end address #define SHARED_MEMORY_END_ANNOTATION "shared_memory_end" -//! Place all types definitions (e.g. typedef, structs, etc.) into one file -#define TYPES_HEADER_ANNOTATION "types_header" - #endif /* _EMBEDDED_RPC__ANNOTATIONS_H_ */ diff --git a/erpcgen/src/erpcgen.cpp b/erpcgen/src/erpcgen.cpp index af7b132b..056a8ec6 100644 --- a/erpcgen/src/erpcgen.cpp +++ b/erpcgen/src/erpcgen.cpp @@ -98,19 +98,19 @@ class erpcgenTool { kCLanguage, kPythonLanguage, - }; /*!< Generated outputs format. */ + }; /*!< Generated outputs format. */ typedef vector string_vector_t; /*!< Vector of positional arguments. */ - int m_argc; /*!< Number of command line arguments. */ - char **m_argv; /*!< String value for each command line argument. */ - StdoutLogger *m_logger; /*!< Singleton logger instance. */ - verbose_type_t m_verboseType; /*!< Which type of log is need to set (warning, info, debug). */ - const char *m_outputFilePath; /*!< Path to the output file. */ - const char *m_ErpcFile; /*!< ERPC file. */ - string_vector_t m_positionalArgs; /*!< Positional arguments. */ - languages_t m_outputLanguage; /*!< Output language we're generating. */ - InterfaceDefinition::codec_t m_codec; /*!< Used codec type. */ + int m_argc; /*!< Number of command line arguments. */ + char **m_argv; /*!< String value for each command line argument. */ + StdoutLogger *m_logger; /*!< Singleton logger instance. */ + verbose_type_t m_verboseType; /*!< Which type of log is need to set (warning, info, debug). */ + const char *m_outputFilePath; /*!< Path to the output file. */ + const char *m_ErpcFile; /*!< ERPC file. */ + string_vector_t m_positionalArgs; /*!< Positional arguments. */ + languages_t m_outputLanguage; /*!< Output language we're generating. */ + InterfaceDefinition::codec_t m_codec; /*!< Used codec type. */ public: /*! @@ -205,7 +205,7 @@ class erpcgenTool } else { - Log::error(format_string("error: unknown language %s", lang.c_str()).c_str()); + Log::error("error: unknown language %s", lang.c_str()); return 1; } break; @@ -219,7 +219,7 @@ class erpcgenTool } else { - Log::error(format_string("error: unknown codec type %s", codec.c_str()).c_str()); + Log::error("error: unknown codec type %s", codec.c_str()); return 1; } break; diff --git a/erpcgen/src/erpcgen_lexer.l b/erpcgen/src/erpcgen_lexer.l index 1c0a1b20..9bbdd998 100644 --- a/erpcgen/src/erpcgen_lexer.l +++ b/erpcgen/src/erpcgen_lexer.l @@ -237,6 +237,8 @@ void { return TOK_VOID; } "->" { return TOK_ARROW; } +"::" { return TOK_IFACE_SCOPE; } + [@{}()\[\]<>=,;:+\-*/%^~&|] { return yytext[0]; } \"(ESC|[^\"])*\" { diff --git a/erpcgen/src/erpcgen_parser.y b/erpcgen/src/erpcgen_parser.y index 46586703..f49eb396 100644 --- a/erpcgen/src/erpcgen_parser.y +++ b/erpcgen/src/erpcgen_parser.y @@ -155,6 +155,7 @@ token_loc_t mergeLocation(const token_loc_t & l1, const token_loc_t & l2); %token TOK_ML_COMMENT "doxygen ml. comment" %token TOK_IL_COMMENT "doxygen il. comment" %token TOK_PROGRAM "program" +%token TOK_IFACE_SCOPE "::" %token END 0 "end of file" // virtual tokens used for AST @@ -210,6 +211,8 @@ token_loc_t mergeLocation(const token_loc_t & l1, const token_loc_t & l2); %type function_return_type %type function_type_base_def %type function_type_def +%type function_cb_type_def +%type function_cb_type_list %type ident %type ident_opt %type int_const_expr @@ -225,6 +228,7 @@ token_loc_t mergeLocation(const token_loc_t & l1, const token_loc_t & l2); %type program %type root_def %type simple_data_type +%type simple_data_type_scope %type string_literal %type struct_def %type struct_data_type @@ -339,11 +343,6 @@ definition_base : const_def { $$ = $interface_def; } - | - function_type_def - { - $$ = $function_type_def; - } ; import_stmt : TOK_IMPORT TOK_STRING_LITERAL @@ -451,7 +450,7 @@ interface_def : TOK_INTERFACE[iface] ident[name] '{' function_def_list_opt[f ; function_def_list_opt - : function_def_list + : function_def_list { $$ = $function_def_list; } @@ -465,7 +464,12 @@ function_def_list_opt * TOK_CHILDREN -> ( function_def* ) */ function_def_list - : function_def + : function_cb_type_list function_def + { + $function_cb_type_list->appendChild($function_def); + $$ = $function_cb_type_list; + } + | function_def { $$ = new AstNode(Token(TOK_CHILDREN)); $$->appendChild($function_def); @@ -477,13 +481,39 @@ function_def_list } ; +function_cb_type_def + : doxy_ml_comment_opt annotation_list_opt TOK_TYPE function_type_def comma_semi_opt doxy_il_comment_opt + { + $$ = $function_type_def; + $$->appendChild(new AstNode(*$TOK_TYPE)); + $$->appendChild($annotation_list_opt); + $$->appendChild($doxy_ml_comment_opt); + $$->appendChild($doxy_il_comment_opt); + } + ; + +function_cb_type_list + : function_cb_type_def + { + $$ = new AstNode(Token(TOK_CHILDREN)); + $$->appendChild($function_cb_type_def); + } + | function_cb_type_list[fun_type_list] function_cb_type_def + { + $fun_type_list->appendChild($function_cb_type_def); + $$ = $fun_type_list; + } + ; + function_def : doxy_ml_comment_opt annotation_list_opt function_type_base_def comma_semi_opt doxy_il_comment_opt { $$ = $function_type_base_def; + $$->appendChild(NULL); /* Compatibility with function type definition */ $$->appendChild($annotation_list_opt); $$->appendChild($doxy_ml_comment_opt); $$->appendChild($doxy_il_comment_opt); } + ; function_type_base_def : function_type_def @@ -592,7 +622,7 @@ param_list_in : param_def_in /* * TOK_PARAM -> ( ident simple_data_type ( TOK_CHILDREN -> TOK_ANNOTATION* ) ) */ -param_def : param_dir[dir] simple_data_type[datatype] ident_opt[name] annotation_list_opt[annotations] +param_def : param_dir[dir] simple_data_type_scope[datatype] ident_opt[name] annotation_list_opt[annotations] { $$ = new AstNode(Token(TOK_PARAM, NULL, @name)); $$->appendChild($name); @@ -603,7 +633,7 @@ param_def : param_dir[dir] simple_data_type[datatype] ident_opt[name] an } ; -param_def_in : param_dir_in[dir] simple_data_type[datatype] ident_opt[name] annotation_list_opt[annotations] +param_def_in : param_dir_in[dir] simple_data_type_scope[datatype] ident_opt[name] annotation_list_opt[annotations] { $$ = new AstNode(Token(TOK_PARAM, NULL, @name)); $$->appendChild($name); @@ -892,6 +922,19 @@ union_member } ; +simple_data_type_scope + : ident TOK_IFACE_SCOPE typename + { + $$ = new AstNode(Token(TOK_IFACE_SCOPE)); + $$->appendChild($ident); + $$->appendChild($typename); + } + | simple_data_type + { + $$ = $simple_data_type; + } + ; + simple_data_type : list_type { @@ -905,7 +948,6 @@ simple_data_type { $$ = $typename; } - ; data_type : simple_data_type diff --git a/erpcgen/src/templates/c_client_header.template b/erpcgen/src/templates/c_client_header.template new file mode 100644 index 00000000..fb83a8b2 --- /dev/null +++ b/erpcgen/src/templates/c_client_header.template @@ -0,0 +1,70 @@ +{% if mlComment != "" %} +{$mlComment} + +{% endif %} +{$commonHeader()} + +#if !defined({$clientCGuardMacro}) +#define {$clientCGuardMacro} + +#include "{$commonCHeaderName}" +#include "erpc_client_manager.h" +{% for iface in group.interfaces %} +{% for fn in iface.functions %} +{% for externalInterface in fn.externalInterfaces %} +{% for interfaceFile in interfacesFiles %} +{% if externalInterface == interfaceFile.interfaceName %} +#include "c_{$interfaceFile.interfaceCommonFileName}_client.h" +{% endif %} +{% endfor -- interfacesFiles %} +{% endfor -- externalInterface %} +{% endfor -- fn %} +{% endfor -- iface %} + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#if !defined({$getFunctionDeclarationMacroName()}) +#define {$getFunctionDeclarationMacroName()} + +{% for iface in group.interfaces %} +{% for cb in iface.callbacksInt%} +typedef {$cb.typenameName}; +{% endfor %} + +/*! @brief {$iface.name} identifiers */ +enum _{$iface.name}_ids +{ + k{$iface.name}_service_id = {$iface.id}, +{% for fn in iface.functions %} + k{$iface.name}_{$fn.name}_id = {$fn.id}, +{% endfor %} +}; + +{% endfor %} +{% for iface in group.interfaces if iface.isNonExternalInterface == true %} +{$> iface.mlComment} +//! @name {$iface.name} +//@{ +{% for fn in iface.functions if fn.isNonExternalFunction == true %} +{$> fn.mlComment} +{$fn.prototype};{$fn.ilComment}{$loop.addNewLineIfNotLast} +{% endfor -- functions %} +//@}{$iface.ilComment} + +{% endfor -- iface %} +#endif // {$getFunctionDeclarationMacroName()} + +{% for iface in group.interfaces %} +void init{$iface.clientClassName}(erpc_client_t client); + +void deinit{$iface.clientClassName}(void); + +{% endfor -- iface %} +#if defined(__cplusplus) +} +#endif + +#endif // {$clientCGuardMacro} diff --git a/erpcgen/src/templates/c_client_source.template b/erpcgen/src/templates/c_client_source.template index 7d1c8ac6..619e65cf 100644 --- a/erpcgen/src/templates/c_client_source.template +++ b/erpcgen/src/templates/c_client_source.template @@ -1,197 +1,102 @@ +{% set source = "client" >%} {% if mlComment != "" %} {$mlComment} {% endif %} {$commonHeader()} -#include "erpc_client_manager.h" -#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC -#include "erpc_port.h" -#endif -#include "{$codecHeader}" -extern "C" -{ -#include "{$commonHeaderName}.h" -{% if groupNames %} -// import callbacks declaration from other groups -{% for name in groupNames if name != group.name %} -#include "{$outputFilename}_{$name}.h" -{% endfor %} -{% endif %} -} +#include "{$clientCHeaderName}" +#include "{$clientCppHeaderName}" +#include "erpc_manually_constructed.hpp" +{% set utils = false >%} +{% for iface in group.interfaces %} +{% if (count(iface.callbacksAll) > 0) && (utils == false) %} +#include "erpc_utils.hpp" +{% set utils = true >%} +{% endif %} +{% endfor %} -{$checkVersion()} -{$>checkCrc()} using namespace erpc; using namespace std; +{$usingNamespace() >} +{% for iface in group.interfaces %} +{% if count(iface.callbacksAll) > 0 %} -extern ClientManager *g_client; -{$generateCrcVariable()} -{$> setSharedMemAddresses()} -{% if unitTest %} -{$> callbackTable(functions)} -{% endif %} -{$> constantsDefinitions(consts)} -{$> symbolHeader(group.symbolsMap.symbolsToServer, "serial", "def")} -{$> symbolSource(group.symbolsMap.symbolsToServer, "serial", "def")} -{$> symbolHeader(group.symbolsMap.symbolsToClient, "deserial", "def")} -{$> symbolSource(group.symbolsMap.symbolsToClient, "deserial", "def")} -{$> symbolHeader(group.symbolsMap.symbolsToServer, "serial", "noSharedMem")} -{$> symbolSource(group.symbolsMap.symbolsToServer, "serial", "noSharedMem")} -{$> symbolHeader(group.symbolsMap.symbolsToClient, "deserial", "noSharedMem")} -{$> symbolSource(group.symbolsMap.symbolsToClient, "deserial", "noSharedMem")} -{% def clientShimCode(fn, serverIDName, functionIDName) ------------------------- clientShimCode(fn, serverIDName, functionIDName) %} -{% set clientIndent = "" >%} -{% if generateErrorChecks %} - erpc_status_t err = kErpcStatus_Success; - -{% endif -- generateErrorChecks %} -{% if fn.isReturnValue %} -{% if fn.needTempVariableClientI32 %} - int32_t _tmp_local_i32; +{% for cb in iface.callbacksAll %} +static const {$cb.name} _{$cb.name}[{$count(cb.callbacks)}] = { {% for c in cb.callbacks %}{$c.name}{% if !loop.last %}, {% endif -- loop.last %}{% endfor -- f.callbacks %} }; +{% endfor %} {% endif %} -{% endif %} -{% if fn.returnValue.type.isNotVoid %} - {$fn.returnValue.resultVariable}{% if fn.returnValue.isNullReturnType %} = NULL{% endif %}; -{% endif -- isNotVoid %} +{% endfor %} -#if ERPC_PRE_POST_ACTION - pre_post_action_cb preCB = g_client->getPreCB(); - if (preCB) - { - preCB(); - } +{% for iface in group.interfaces %} +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC +{$iface.clientClassName} *s_{$iface.clientClassName} = nullptr; +#else +ERPC_MANUALLY_CONSTRUCTED_STATIC({$iface.clientClassName}, s_{$iface.clientClassName}); #endif +{% endfor -- iface %} +{% for iface in group.interfaces %} +{% for fn in iface.functions %} - // Get a new request. -{% if !fn.isReturnValue %} - RequestContext request = g_client->createRequest(true); -{% else %} - RequestContext request = g_client->createRequest(false); -{% endif -- isReturnValue %} - - // Encode the request. -{% if codecClass == "Codec" %} - {$codecClass} * codec = request.getCodec(); -{% else %} - {$codecClass} * codec = static_cast<{$codecClass} *>(request.getCodec()); +{$fn.prototype} +{ +{% if count(fn.callbackParameters) > 0 %} + uint16_t _fnIndex; +{% for cb in fn.callbackParameters%} + {% if cb.interface != ""%}{$cb.interface}{% else %}{$iface.interfaceClassName}{% endif %}::{$cb.type} _{$cb.name} = NULL; +{% endfor %} +{% endif%} +{% if fn.returnValue.type.isNotVoid %} + {$fn.returnValue.resultVariable}{% if fn.returnValue.isNullReturnType %} = NULL{% endif %}; {% endif %} +{% if count(fn.callbackParameters) > 0 %} +{% for cb in fn.callbackParameters if cb.in %} -{% if generateAllocErrorChecks %} -{% set clientIndent = " " >%} - if (codec == NULL) + if (findIndexOfFunction((arrayOfFunctionPtr_t)_{$cb.type}, sizeof(_{$cb.type})/sizeof({$cb.type}), (functionPtr_t){$cb.name}, _fnIndex)) { - err = kErpcStatus_MemoryError; + {% if cb.interface != ""%}{$cb.interface}{% else %}{$iface.interfaceClassName}{% endif %}::get_callbackAddress_{$cb.type}(_fnIndex, &_{$cb.name}); } - else - { -{% endif -- generateErrorChecks %} -{$clientIndent} codec->startWriteMessage({% if not fn.isReturnValue %}message_type_t::kOnewayMessage{% else %}message_type_t::kInvocationMessage{% endif %}, {$serverIDName}, {$functionIDName}, request.getSequence()); - -{% if fn.isSendValue %} -{% for param in fn.parameters if (param.serializedDirection == "" || param.serializedDirection == OutDirection || param.referencedName != "") %} -{% if param.isNullable %} -{$ addIndent(clientIndent & " ", f_paramIsNullableEncode(param))} - -{% else -- isNullable %} -{% if param.direction != OutDirection %} -{$addIndent(clientIndent & " ", param.coderCall.encode(param.coderCall))} - -{% endif -- param != OutDirection %} -{% endif -- isNullable %} -{% endfor -- fn parameters %} -{% endif -- isSendValue %} -{$clientIndent} // Send message to server -{$clientIndent} // Codec status is checked inside this function. -{$clientIndent} g_client->performRequest(request); -{% if fn.isReturnValue %} -{% for param in fn.parametersToClient if (param.serializedDirection == "" || param.serializedDirection == InDirection || param.referencedName != "") %} - -{% if param.isNullable %} -{% if ((source == "client") && (param.direction != ReturnDirection) && (empty(param.lengthName) == false)) %} -{% set lengthNameCon = ") && (" & param.lengthName & " != NULL)" >%} -{% else %} -{% set lengthNameCon = "" >%} -{% endif %} -{$clientIndent} if ({% if lengthNameCon != "" %}({% endif %}{$param.nullableName} != NULL{$lengthNameCon}) -{$clientIndent} { -{$addIndent(clientIndent & " ", param.coderCall.decode(param.coderCall))} - } -{% else -- notNullable %} -{$addIndent(clientIndent & " ", param.coderCall.decode(param.coderCall))} -{% endif -- isNullable %} -{% endfor -- fn parametersToClient %} -{% if fn.returnValue.type.isNotVoid %} - -{% if fn.returnValue.isNullable %} -{$clientIndent} bool isNull; -{$addIndent(clientIndent & " ", f_paramIsNullableDecode(fn.returnValue))} -{% else -- isNullable %} -{$> addIndent(clientIndent & " ", allocMem(fn.returnValue.firstAlloc))} -{$addIndent(clientIndent & " ", fn.returnValue.coderCall.decode(fn.returnValue.coderCall))} -{% endif -- isNullable %} -{% endif -- isNotVoid %} -{% endif -- isReturnValue %} -{% if generateErrorChecks %} - -{$clientIndent} err = codec->getStatus(); -{% endif -- generateErrorChecks %} -{% if generateAllocErrorChecks %} - } -{% endif -- generateAllocErrorChecks %} - - // Dispose of the request. - g_client->releaseRequest(request); -{% if generateErrorChecks %} - - // Invoke error handler callback function - g_client->callErrorHandler(err, {$functionIDName}); -{% endif -- generateErrorChecks %} - -#if ERPC_PRE_POST_ACTION - pre_post_action_cb postCB = g_client->getPostCB(); - if (postCB) - { - postCB(); - } -#endif +{% endfor %} -{% if generateErrorChecks && fn.returnValue.type.isNotVoid %} -{% if empty(fn.returnValue.errorReturnValue) == false && fn.returnValue.isNullReturnType == false %} +{%endif%} + {% if fn.returnValue.type.isNotVoid %}result = {% endif %}s_{$iface.clientClassName}->{$fn.name}({% for param in fn.parameters %}{% if !loop.first %}, {% endif %}{$param.pureNameC}{% endfor %}); +{% for cb in fn.callbackParameters if cb.out %} - if (err != kErpcStatus_Success) + if ({% if cb.interface != ""%}{$cb.interface}{% else %}{$iface.interfaceClassName}{% endif %}::get_callbackIdx_{$cb.type}(&_{$cb.name}, _fnIndex)) { - result = {$fn.returnValue.errorReturnValue}; + *{$cb.name}=_{$cb.type}[_fnIndex]; } -{% endif %} -{% endif -- generateErrorChecks %} +{% endfor %} +{% if fn.returnValue.type.isNotVoid %} - return{% if fn.returnValue.type.isNotVoid %} result{% endif -- isNotVoid %}; -{% enddef --------------------------------------------------------------------------------- clientShimCode(fn, serverIDName, functionIDName) %} -{% for callbackType in group.callbacks %} -// Common function for serializing and deserializing callback functions of same type. -static {$callbackType.prototype}; + return result; +{% endif %} +} +{% endfor -- fn %} +{% endfor -- iface %} +{% for iface in group.interfaces %} -{% endfor %} -{% for callbackType in group.callbacks %} -// Common function for serializing and deserializing callback functions of same type. -static {$callbackType.prototype} +void init{$iface.clientClassName}(erpc_client_t client) { -{$ clientShimCode(callbackType, "serviceID", "functionID") >} +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(s_{$iface.clientClassName} == nullptr); + s_{$iface.clientClassName} = new {$iface.clientClassName}(reinterpret_cast(client)); +#else + erpc_assert(!s_{$iface.clientClassName}.isUsed()); + s_{$iface.clientClassName}.construct(reinterpret_cast(client)); +#endif } -{% endfor %} -{% for iface in group.interfaces %} -{% for fn in iface.functions %} - -// {$iface.name} interface {$fn.name} function client shim. -{$fn.prototype} +void deinit{$iface.clientClassName}(void) { -{% if fn.isCallback %} - {% if fn.returnValue.type.isNotVoid %}return {% endif %}{$fn.callbackFName}(k{$iface.name}_service_id, k{$iface.name}_{$fn.name}_id{% for param in fn.parameters %}, {$param.name}{% endfor %}); -{% else -- fn.isCallback >%} -{$ clientShimCode(fn, "k"& iface.name & "_service_id", "k" & iface.name & "_" & fn.name & "_id") >} -{% endif -- fn.isCallback >%} +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + if (s_{$iface.clientClassName} != nullptr) + { + delete s_{$iface.clientClassName}; + s_{$iface.clientClassName} = nullptr; + } +#else + s_{$iface.clientClassName}.destroy(); +#endif } -{% endfor -- fn %} {% endfor -- iface %} diff --git a/erpcgen/src/templates/c_common_header.template b/erpcgen/src/templates/c_common_header.template index 8c093ba7..2083bbd2 100644 --- a/erpcgen/src/templates/c_common_header.template +++ b/erpcgen/src/templates/c_common_header.template @@ -13,33 +13,38 @@ #endif {% endif -- usedUnionType %} -{% if not commonTypesFile == "" %} -// Common types header file -#include "{$commonTypesFile}" -{% else %} +{% for inc in includes %} +#include "{$inc}" +{% endfor -- includes %} + +{% if cCommonHeaderFile %} +#if defined(__cplusplus) +extern "C" +{ +#endif #include #include #include +{% else %} +#include +#include +#include +{% endif %} + #include "erpc_version.h" {% if empty(crc16) == false %} #include "{$crcHeaderName}" {% endif -- empty(crc16) == false %} -{% for inc in includes %} -#include "{$inc}" -{% endfor -- includes %} {$checkVersion()} {$>checkCrc()} -{% endif -- not commonTypesFile %} -{% if commonTypesFile == "" %} + #if !defined(ERPC_TYPE_DEFINITIONS{$scopeNamePrefix}{$scopeNameC}) #define ERPC_TYPE_DEFINITIONS{$scopeNamePrefix}{$scopeNameC} {% if not empty(enums) %} // Enumerators data types declarations {% for enum in enums %} -{% if enum.name != "" %} -{% endif %} {$> enum.mlComment} {% if enum.name %}typedef {% endif --enum.name %}enum{$addIndent(" ", enum.name)} { @@ -103,38 +108,12 @@ extern const {$c.typeAndName};{$c.ilComment}{$loop.addNewLineIfNotLast} {% endif -- consts %} #endif // ERPC_TYPE_DEFINITIONS{$scopeNamePrefix}{$scopeNameC} -{% endif -- commonTypesFile %} - -{% if not genCommonTypesFile %} -{% for iface in group.interfaces %} -/*! @brief {$iface.name} identifiers */ -enum _{$iface.name}_ids -{ - k{$iface.name}_service_id = {$iface.id}, -{% for fn in iface.functions %} - k{$iface.name}_{$fn.name}_id = {$fn.id}, -{% endfor %} -}; - -{% endfor %} -#if defined(__cplusplus) -extern "C" { -#endif -{% for iface in group.interfaces if iface.isNonExternalInterface == true %} - -{$> iface.mlComment} -//! @name {$iface.name} -//@{ -{% for fn in iface.functions if fn.isNonExternalFunction == true %} -{$> fn.mlComment} -{$fn.prototype};{$fn.ilComment}{$loop.addNewLineIfNotLast} -{% endfor -- functions %} -//@}{$iface.ilComment} -{% endfor -- iface %} +{% if cCommonHeaderFile %} #if defined(__cplusplus) } #endif -{% endif -- genCommonTypesFile %} +{% else %} +{% endif %} #endif // {$commonGuardMacro} diff --git a/erpcgen/src/templates/c_server_header.template b/erpcgen/src/templates/c_server_header.template index 082ea3e9..e2a7afcb 100644 --- a/erpcgen/src/templates/c_server_header.template +++ b/erpcgen/src/templates/c_server_header.template @@ -1,51 +1,63 @@ -{% if mlComment != ""%} +{% if mlComment != "" %} {$mlComment} {% endif %} {$commonHeader()} -#if !defined({$serverGuardMacro}) -#define {$serverGuardMacro} +#if !defined({$serverCGuardMacro}) +#define {$serverCGuardMacro} -#ifdef __cplusplus -#include "erpc_server.hpp" -#include "{$codecHeader}" +#include "{$commonCHeaderName}" +{% for iface in group.interfaces %} +{% for fn in iface.functions %} +{% for externalInterface in fn.externalInterfaces %} +{% for interfaceFile in interfacesFiles %} +{% if externalInterface == interfaceFile.interfaceName %} +#include "c_{$interfaceFile.interfaceCommonFileName}_client.h" +{% endif %} +{% endfor -- interfacesFiles %} +{% endfor -- externalInterface %} +{% endfor -- fn %} +{% endfor -- iface %} + +#if defined(__cplusplus) extern "C" { -#include "{$commonHeaderName}.h" -#include -#include -} +#endif -{$checkVersion()} -{$>checkCrc()} -{% for iface in group.interfaces %} +typedef void * erpc_service_t; -/*! - * @brief Service subclass for {$iface.name}. - */ -class {$iface.serviceClassName} : public erpc::Service -{ -public: - {$iface.serviceClassName}() : Service(k{$iface.name}_service_id) {} +#if !defined({$getFunctionDeclarationMacroName()}) +#define {$getFunctionDeclarationMacroName()} - /*! @brief Call the correct server shim based on method unique ID. */ - virtual erpc_status_t handleInvocation(uint32_t methodId, uint32_t sequence, erpc::Codec * codec, erpc::MessageBufferFactory *messageFactory); +{% for iface in group.interfaces %} +{% for cb in iface.callbacksInt%} +typedef {$cb.typenameName}; +{% endfor %} -private: +/*! @brief {$iface.name} identifiers */ +enum _{$iface.name}_ids +{ + k{$iface.name}_service_id = {$iface.id}, {% for fn in iface.functions %} - /*! @brief Server shim for {$fn.name} of {$iface.name} interface. */ - erpc_status_t {$fn.name}_shim(erpc::{$codecClass} * codec, erpc::MessageBufferFactory *messageFactory, uint32_t sequence);{$loop.addNewLineIfNotLast} -{% endfor -- fn %} + k{$iface.name}_{$fn.name}_id = {$fn.id}, +{% endfor %} }; -{% endfor -- iface %} -extern "C" { -#else -#include "{$commonHeaderName}.h" -#endif // __cplusplus +{% endfor %} +{% for iface in group.interfaces if iface.isNonExternalInterface == true %} +{$> iface.mlComment} +//! @name {$iface.name} +//@{ +{% for fn in iface.functions if fn.isNonExternalFunction == true %} +{$> fn.mlComment} +{$fn.prototype};{$fn.ilComment}{$loop.addNewLineIfNotLast} +{% endfor -- functions %} +//@}{$iface.ilComment} -typedef void * erpc_service_t; +{% endfor -- iface %} + +#endif // {$getFunctionDeclarationMacroName()} {% for iface in group.interfaces %} /*! @brief Return {$iface.serviceClassName} service object. */ @@ -55,8 +67,9 @@ erpc_service_t create_{$iface.serviceClassName}(void); void destroy_{$iface.serviceClassName}(erpc_service_t service); {% endfor -- iface %} -#ifdef __cplusplus + +#if defined(__cplusplus) } -#endif // __cplusplus +#endif -#endif // {$serverGuardMacro} +#endif // {$serverCGuardMacro} diff --git a/erpcgen/src/templates/c_server_source.template b/erpcgen/src/templates/c_server_source.template index bad5bfe9..48d9d5ba 100644 --- a/erpcgen/src/templates/c_server_source.template +++ b/erpcgen/src/templates/c_server_source.template @@ -1,255 +1,88 @@ -{% if mlComment != ""%} +{% if mlComment != "" %} {$mlComment} {% endif %} {$commonHeader()} +{% set source = "server" >%} -#include "{$serverHeaderName}" -#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC #include -#include "erpc_port.h" -#endif +#include "{$serverCHeaderName}" +#include "{$serverCppHeaderName}" #include "erpc_manually_constructed.hpp" -{% if empty(group.includes) == false %} -extern "C" -{ -{% for inc in group.includes %} -#include "{$inc}" -{% endfor -- group.includes %} -} -{% endif -- empty(group.includes) %} +{% set utils = false >%} +{% for iface in group.interfaces %} +{% if (count(iface.callbacksAll) > 0) && (utils == false) %} +#include "erpc_utils.hpp" +{% set utils = true >%} +{% endif %} +{% endfor %} -{$checkVersion()} -{$>checkCrc()} using namespace erpc; using namespace std; - -#if ERPC_NESTED_CALLS_DETECTION -extern bool nestingDetection; -#endif - +{$usingNamespace() >} {% for iface in group.interfaces %} -ERPC_MANUALLY_CONSTRUCTED_STATIC({$iface.serviceClassName}, s_{$iface.serviceClassName}); - -{% endfor -- iface %} -{$generateCrcVariable()} -{$> setSharedMemAddresses()} -{% if unitTest %} -{$> callbackTable(functions)} -{% endif %} -{$> constantsDefinitions(consts)} -{$> symbolHeader(group.symbolsMap.symbolsToServer, "deserial", "def")} -{$> symbolSource(group.symbolsMap.symbolsToServer, "deserial", "def")} -{$> symbolHeader(group.symbolsMap.symbolsToClient, "serial", "def")} -{$> symbolSource(group.symbolsMap.symbolsToClient, "serial", "def")} -{$> symbolFreeSpaceHeader(group.symbolsMap.symbolsServerFree, "def")} -{$> symbolFreeSpaceSource(group.symbolsMap.symbolsServerFree, "def")} -{$> symbolHeader(group.symbolsMap.symbolsToServer, "deserial", "noSharedMem")} -{$> symbolSource(group.symbolsMap.symbolsToServer, "deserial", "noSharedMem")} -{$> symbolHeader(group.symbolsMap.symbolsToClient, "serial", "noSharedMem")} -{$> symbolSource(group.symbolsMap.symbolsToClient, "serial", "noSharedMem")} -{$> symbolFreeSpaceHeader(group.symbolsMap.symbolsServerFree, "noSharedMem")} -{$> symbolFreeSpaceSource(group.symbolsMap.symbolsServerFree, "noSharedMem")} -{% def serverShimCode(fn, serverIDName, functionIDName) ------------------------- serverShimCode(fn, serverIDName, functionIDName) %} -{% set serverIndent = "" >%} -{% if (fn.isReturnValue || fn.isSendValue) && generateErrorChecks %} - erpc_status_t err = kErpcStatus_Success; +{% if count(iface.callbacksAll) > 0 %} -{% endif -- isReturnValue || isSendValue %} -{% for param in fn.parameters %} - {$param.variable}{% if param.isNullParam %} = NULL{% endif %}; -{% if !empty(param.nullVariable) %} - {$param.nullVariable} = NULL; +{% for cb in iface.callbacksAll %} +static const {$cb.name} _{$cb.name}[{$count(cb.callbacks)}] = { {% for c in cb.callbacks %}{$c.name}{% if !loop.last %}, {% endif -- loop.last %}{% endfor -- f.callbacks %} }; +{% endfor %} {% endif %} -{% if !param.shared %} -{% if param.isNullable == false && param.direction != OutDirection %} -{$> addIndent(" ", allocMem(param.mallocServer))} -{% endif -- !param.isNullable && param.direction != OutDirection %} -{% endif -- shared %} -{% endfor -- param %} -{% if fn.needNullVariableOnServer %} - bool isNull; -{% endif -- needNullVariableOnServer %} -{% if fn.needTempVariableServerI32 %} - int32_t _tmp_local_i32; -{% endif %} -{% if fn.returnValue.type.isNotVoid %} - {$fn.returnValue.resultVariable}{% if fn.returnValue.isNullReturnType %} = NULL{% endif %}; -{% endif %} -{% if fn.isReturnValue || fn.isSendValue %} - -{% endif %} - // startReadMessage() was already called before this shim was invoked. - -{% if fn.isSendValue %} -{% for param in fn.parameters if (param.serializedDirection == "" || param.serializedDirection == OutDirection || param.referencedName != "") %} -{% if param.isNullable %} -{$addIndent(" ", f_paramIsNullableDecode(param))} - -{% else -- notNullable %} -{% if param.direction != OutDirection %} -{$addIndent(" ", param.coderCall.decode(param.coderCall))} - -{% endif -- param != OutDirection %} -{% endif -- isNullable %} -{% endfor -- parametersToServer %} -{% endif -- isSendValue %} -{% for param in fn.parametersToClient %} -{% if !param.shared %} -{% if param.isNullable == false && param.direction == OutDirection && empty(param.mallocServer) == false %} -{$> addIndent(" ", allocMem(param.mallocServer))} - -{% endif -- !param.isNullable && param.direction == OutDirection %} -{% endif -- shared %} -{% endfor -- param %} -{% if (fn.isReturnValue || fn.isSendValue) && generateErrorChecks %} -{% set serverIndent = " " >%} - err = codec->getStatus(); - if (err == kErpcStatus_Success) - { -{% endif -- generateErrorChecks %} -{$serverIndent} // Invoke the actual served function. -#if ERPC_NESTED_CALLS_DETECTION -{$serverIndent} nestingDetection = true; -#endif -{% if serverIDName == "serviceID" %} -{% for callbackFunction in callbackType.functions %} -{$serverIndent} {% if loop.first == false %}else {% endif %}if (({$serverIDName} == {$callbackFunction.serviceId}) && ({$functionIDName} == {$callbackFunction.id})) -{$serverIndent} { -{$serverIndent} {$callbackFunction.serverPrototype} -{$serverIndent} } -{% endfor -- callbackFunction in callbackType.functions %} -{% else -- serverIDName == "serviceID" %} -{$serverIndent} {$fn.serverPrototype} -{% endif --serverIDName == "serviceID" %} -#if ERPC_NESTED_CALLS_DETECTION -{$serverIndent} nestingDetection = false; -#endif -{% if fn.isReturnValue %} - -{$serverIndent} // preparing MessageBuffer for serializing data -{$serverIndent} {% if generateErrorChecks %}err = {% endif %}messageFactory->prepareServerBufferForSend(codec->getBuffer()); -{% if generateErrorChecks %} - } - - if (err == kErpcStatus_Success) - { -{% endif -- generateErrorChecks %} -{$serverIndent} // preparing codec for serializing data -{$serverIndent} codec->reset(); - -{$serverIndent} // Build response message. -{$serverIndent} codec->startWriteMessage(message_type_t::kReplyMessage, {$serverIDName}, {$functionIDName}, sequence); -{% for param in fn.parametersToClient if (param.serializedDirection == "" || param.serializedDirection == InDirection || param.referencedName != "") %} - -{% if param.isNullable %} -{$serverIndent} if ({% if source == "server" && empty(param.nullVariable) == false %}_{% endif %}{$param.name} != NULL) -{$serverIndent} { -{$addIndent(serverIndent & " ", param.coderCall.encode(param.coderCall))} -{$serverIndent} } -{% else -- isNullable %} -{$addIndent(serverIndent & " ", param.coderCall.encode(param.coderCall))} -{% endif -- isNullable %} -{% endfor -- parametersToClient %} -{% if fn.returnValue.type.isNotVoid %} - -{% if fn.returnValue.isNullable %} -{$addIndent(serverIndent & " ", f_paramIsNullableEncode(fn.returnValue))} -{% else -- isNullable %} -{$addIndent(serverIndent & " ", fn.returnValue.coderCall.encode(fn.returnValue.coderCall))} -{% endif -- isNullable %} -{% endif -- notVoid %} -{% if generateErrorChecks %} - - err = codec->getStatus(); -{% endif generateErrorChecks %} -{% endif -- isReturnValue %} -{% if (fn.isReturnValue || fn.isSendValue) && generateErrorChecks %} - } - -{% endif -- fn.isReturnValue || fn.isSendValue %} -{% for param in fn.paramsToFree %} -{$> addIndent(" ", param.coderCall.freeingCall(param.coderCall))} -{$> addIndent(" ", param.firstFreeingCall1.firstFreeingCall(param.firstFreeingCall1))} - -{% endfor -- parameters %} -{% if fn.returnValue.type.isNotVoid %} -{% set needFreeingCall = fn.returnValue.coderCall.freeingCall(fn.returnValue.coderCall) %} -{% set needFirstFreeingCall = fn.returnValue.firstFreeingCall1.firstFreeingCall(fn.returnValue.firstFreeingCall1) %} -{% if empty(needFreeingCall) == false || empty(needFirstFreeingCall) == false %} -{$> addIndent(" ", needFreeingCall)} -{$> addIndent(" ", needFirstFreeingCall)} - -{% endif -- !empty(needFreeingCall) || !empty(needFirstFreeingCall) %} -{% endif -- notVoid %} -{% if (fn.isReturnValue || fn.isSendValue) && generateErrorChecks %} - return err; -{% else %} - return codec->getStatus(); -{% endif %} -{% enddef --------------------------------------------------------------------------------- serverShimCode(fn, serverIDName, functionIDName) %} -{% for callbackType in group.callbacks %} - -// Common function for serializing and deserializing callback functions of same type. -static erpc_status_t {$callbackType.name}_shim(uint32_t serviceID, uint32_t functionID, {$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence); {% endfor %} -{% for callbackType in group.callbacks %} +{% for iface in group.interfaces %} -// Common function for serializing and deserializing callback functions of same type. -static erpc_status_t {$callbackType.name}_shim(uint32_t serviceID, uint32_t functionID, {$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence) +class {$iface.serverClassName}: public {$iface.interfaceClassName} { -{$ serverShimCode(callbackType, "serviceID", "functionID") >} -} -{% endfor %} -{% for iface in group.interfaces -- service subclass method impl %} + public: + virtual ~{$iface.serverClassName}() {}; -// Call the correct server shim based on method unique ID. -erpc_status_t {$iface.serviceClassName}::handleInvocation(uint32_t methodId, uint32_t sequence, Codec * codec, MessageBufferFactory *messageFactory) -{ - erpc_status_t erpcStatus; -{% if codecClass != "Codec" %} - {$codecClass} *_codec = static_cast<{$codecClass} *>(codec); -{% endif %} - switch (methodId) - { {% for fn in iface.functions %} - case k{$iface.name}_{$fn.name}_id: - { - erpcStatus = {$fn.name}_shim({%if codecClass == "Codec" %}codec{% else %}_codec{% endif %}, messageFactory, sequence); - break; - } -{% endfor -- fn %} - default: + {$fn.prototypeInterface} { - erpcStatus = kErpcStatus_InvalidArgument; - break; +{% if count(fn.callbackParameters) > 0 %} + uint16_t _fnIndex; +{% for cb in fn.callbackParameters%} + ::{$cb.type} _{$cb.name} = NULL; +{% endfor %} +{% endif %} +{% if fn.returnValue.type.isNotVoid %} + {$fn.returnValue.resultVariable}{% if fn.returnValue.isNullReturnType %} = NULL{% endif %}; +{% endif %} +{% if count(fn.callbackParameters) > 0 %} +{% for cb in fn.callbackParameters if cb.in %} + + if ({% if cb.interface != ""%}{$cb.interface}{% else %}{$iface.interfaceClassName}{% endif %}::get_callbackIdx_{$cb.type}(&{$cb.name}, _fnIndex)) + { + _{$cb.name}=::_{$cb.type}[_fnIndex]; + } +{% endfor %} + +{% endif%} + {% if fn.returnValue.type.isNotVoid %}result = {% endif %}::{$fn.name}({% for param in fn.parameters %}{% if !loop.first %}, {% endif %}{$param.pureNameC}{% endfor %}); +{% for cb in fn.callbackParameters if cb.out %} + + if (findIndexOfFunction((arrayOfFunctionPtr_t)::_{$cb.type}, sizeof(::_{$cb.type})/sizeof(::{$cb.type}), (functionPtr_t)_{$cb.name}, _fnIndex)) + { + {% if cb.interface != ""%}{$cb.interface}{% else %}{$iface.interfaceClassName}{% endif %}::get_callbackAddress_{$cb.type}(_fnIndex, {$cb.name}); + } +{% endfor %} +{% if fn.returnValue.type.isNotVoid %} + + return result; +{% endif %} } - } - - return erpcStatus; -} -{% for fn in iface.functions %} - -// Server shim for {$fn.name} of {$iface.name} interface. -erpc_status_t {$iface.serviceClassName}::{$fn.name}_shim({$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence) -{ -{% if fn.isCallback %} - return {$fn.callbackFName}_shim(k{$iface.name}_service_id, k{$iface.name}_{$fn.name}_id, codec, messageFactory, sequence); -{% else -- fn.isCallback >%} -{$ serverShimCode(fn, "k"& iface.name & "_service_id", "k" & iface.name & "_" & fn.name & "_id") >} -{% endif -- fn.isCallback >%} -} {% endfor -- fn %} -{% endfor -- iface %} -{% for iface in group.interfaces %} +}; + +ERPC_MANUALLY_CONSTRUCTED_STATIC({$iface.serviceClassName}, s_{$iface.serviceClassName}); +ERPC_MANUALLY_CONSTRUCTED_STATIC({$iface.serverClassName}, s_{$iface.serverClassName}); erpc_service_t create_{$iface.serviceClassName}(void) { erpc_service_t service; #if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC - service = new (nothrow) {$iface.serviceClassName}(); + service = new (nothrow) {$iface.serviceClassName}(new (nothrow){$iface.serverClassName}()); #else if (s_{$iface.serviceClassName}.isUsed()) { @@ -257,7 +90,8 @@ erpc_service_t create_{$iface.serviceClassName}(void) } else { - s_{$iface.serviceClassName}.construct(); + s_{$iface.serverClassName}.construct(); + s_{$iface.serviceClassName}.construct(s_{$iface.serverClassName}.get()); service = s_{$iface.serviceClassName}.get(); } #endif @@ -268,12 +102,16 @@ erpc_service_t create_{$iface.serviceClassName}(void) void destroy_{$iface.serviceClassName}(erpc_service_t service) { #if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC - erpc_assert(service != NULL); - delete ({$iface.serviceClassName} *)service; + if (service) + { + delete ({$iface.serverClassName} *)((({$iface.serviceClassName} *)service)->getHandler()); + delete ({$iface.serviceClassName} *)service; + } #else (void)service; erpc_assert(service == s_{$iface.serviceClassName}.get()); s_{$iface.serviceClassName}.destroy(); + s_{$iface.serverClassName}.destroy(); #endif } diff --git a/erpcgen/src/templates/cpp_client_header.template b/erpcgen/src/templates/cpp_client_header.template new file mode 100644 index 00000000..85d166bb --- /dev/null +++ b/erpcgen/src/templates/cpp_client_header.template @@ -0,0 +1,36 @@ +{% if mlComment != "" %} +{$mlComment} + +{% endif %} +{$commonHeader()} + +#if !defined({$clientCppGuardMacro}) +#define {$clientCppGuardMacro} + +#include "{$interfaceCppHeaderName}" + +#include "erpc_client_manager.h" +{$fillNamespaceBegin()>} + +{% for iface in group.interfaces %} +class {$iface.clientClassName}: public {$iface.interfaceClassName} +{ + public: + {$iface.clientClassName}(erpc::ClientManager *manager); + + virtual ~{$iface.clientClassName}(); +{% for fn in iface.functions if fn.isNonExternalFunction == true %} + +{% if fn.mlComment %} + {$fn.mlComment} +{% endif %} + virtual {$fn.prototypeInterface}; +{% endfor -- fn %} + + protected: + erpc::ClientManager *m_clientManager; +}; + +{% endfor -- iface %} +{$fillNamespaceEnd()} +#endif // {$clientCppGuardMacro} diff --git a/erpcgen/src/templates/cpp_client_source.template b/erpcgen/src/templates/cpp_client_source.template new file mode 100644 index 00000000..ddffe9e0 --- /dev/null +++ b/erpcgen/src/templates/cpp_client_source.template @@ -0,0 +1,198 @@ +{% set source = "client" >%} +{% if mlComment != "" %} +{$mlComment} + +{% endif %} +{$commonHeader()} + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC +#include "erpc_port.h" +#endif +#include "{$codecHeader}" +#include "{$clientCppHeaderName}" +#include "erpc_manually_constructed.hpp" + +{$checkVersion()} +{$>checkCrc()} +using namespace erpc; +using namespace std; +{$usingNamespace() >} +{$generateCrcVariable()} +{$> setSharedMemAddresses()} +{$> constantsDefinitions(consts)} +{$> symbolHeader(group.symbolsMap.symbolsToServer, "serial", "def")} +{$> symbolSource(group.symbolsMap.symbolsToServer, "serial", "def")} +{$> symbolHeader(group.symbolsMap.symbolsToClient, "deserial", "def")} +{$> symbolSource(group.symbolsMap.symbolsToClient, "deserial", "def")} +{$> symbolHeader(group.symbolsMap.symbolsToServer, "serial", "noSharedMem")} +{$> symbolSource(group.symbolsMap.symbolsToServer, "serial", "noSharedMem")} +{$> symbolHeader(group.symbolsMap.symbolsToClient, "deserial", "noSharedMem")} +{$> symbolSource(group.symbolsMap.symbolsToClient, "deserial", "noSharedMem")} + +{% def clientShimCode(client, fn, serverIDName, functionIDName) ------------------------- clientShimCode(fn, serverIDName, functionIDName) %} +{% set clientIndent = "" >%} +{% if generateErrorChecks %} + erpc_status_t err = kErpcStatus_Success; + +{% endif -- generateErrorChecks %} +{% if fn.isReturnValue %} +{% if fn.needTempVariableClientI32 %} + int32_t _tmp_local_i32; +{% endif %} +{% endif %} +{% if fn.needTempVariableClientU16 %} + uint16_t _tmp_local_u16; +{% endif %} +{% if fn.returnValue.type.isNotVoid %} + {$fn.returnValue.resultVariable}{% if fn.returnValue.isNullReturnType %} = NULL{% endif %}; +{% endif -- isNotVoid %} + +#if ERPC_PRE_POST_ACTION + pre_post_action_cb preCB = {$client}->getPreCB(); + if (preCB) + { + preCB(); + } +#endif + + // Get a new request. +{% if !fn.isReturnValue %} + RequestContext request = {$client}->createRequest(true); +{% else %} + RequestContext request = {$client}->createRequest(false); +{% endif -- isReturnValue %} + + // Encode the request. +{% if codecClass == "Codec" %} + {$codecClass} * codec = request.getCodec(); +{% else %} + {$codecClass} * codec = static_cast<{$codecClass} *>(request.getCodec()); +{% endif %} + +{% if generateAllocErrorChecks %} +{% set clientIndent = " " >%} + if (codec == NULL) + { + err = kErpcStatus_MemoryError; + } + else + { +{% endif -- generateErrorChecks %} +{$clientIndent} codec->startWriteMessage({% if not fn.isReturnValue %}message_type_t::kOnewayMessage{% else %}message_type_t::kInvocationMessage{% endif %}, {$serverIDName}, {$functionIDName}, request.getSequence()); + +{% if fn.isSendValue %} +{% for param in fn.parameters if (param.serializedDirection == "" || param.serializedDirection == OutDirection || param.referencedName != "") %} +{% if param.isNullable %} +{$ addIndent(clientIndent & " ", f_paramIsNullableEncode(param))} + +{% else -- isNullable %} +{% if param.direction != OutDirection %} +{$addIndent(clientIndent & " ", param.coderCall.encode(param.coderCall))} + +{% endif -- param != OutDirection %} +{% endif -- isNullable %} +{% endfor -- fn parameters %} +{% endif -- isSendValue %} +{$clientIndent} // Send message to server +{$clientIndent} // Codec status is checked inside this function. +{$clientIndent} {$client}->performRequest(request); +{% if fn.isReturnValue %} +{% for param in fn.parametersToClient if (param.serializedDirection == "" || param.serializedDirection == InDirection || param.referencedName != "") %} + +{% if param.isNullable %} +{% if ((source == "client") && (param.direction != ReturnDirection) && (empty(param.lengthName) == false)) %} +{% set lengthNameCon = ") && (" & param.lengthName & " != NULL)" >%} +{% else %} +{% set lengthNameCon = "" >%} +{% endif %} +{$clientIndent} if ({% if lengthNameCon != "" %}({% endif %}{$param.nullableName} != NULL{$lengthNameCon}) +{$clientIndent} { +{$addIndent(clientIndent & " ", param.coderCall.decode(param.coderCall))} + } +{% else -- notNullable %} +{$addIndent(clientIndent & " ", param.coderCall.decode(param.coderCall))} +{% endif -- isNullable %} +{% endfor -- fn parametersToClient %} +{% if fn.returnValue.type.isNotVoid %} + +{% if fn.returnValue.isNullable %} +{$clientIndent} bool isNull; +{$addIndent(clientIndent & " ", f_paramIsNullableDecode(fn.returnValue))} +{% else -- isNullable %} +{$> addIndent(clientIndent & " ", allocMem(fn.returnValue.firstAlloc))} +{$addIndent(clientIndent & " ", fn.returnValue.coderCall.decode(fn.returnValue.coderCall))} +{% endif -- isNullable %} +{% endif -- isNotVoid %} +{% endif -- isReturnValue %} +{% if generateErrorChecks %} + +{$clientIndent} err = codec->getStatus(); +{% endif -- generateErrorChecks %} +{% if generateAllocErrorChecks %} + } +{% endif -- generateAllocErrorChecks %} + + // Dispose of the request. + {$client}->releaseRequest(request); +{% if generateErrorChecks %} + + // Invoke error handler callback function + {$client}->callErrorHandler(err, {$functionIDName}); +{% endif -- generateErrorChecks %} + +#if ERPC_PRE_POST_ACTION + pre_post_action_cb postCB = {$client}->getPostCB(); + if (postCB) + { + postCB(); + } +#endif + +{% if generateErrorChecks && fn.returnValue.type.isNotVoid %} +{% if empty(fn.returnValue.errorReturnValue) == false && fn.returnValue.isNullReturnType == false %} + + if (err != kErpcStatus_Success) + { + result = {$fn.returnValue.errorReturnValue}; + } +{% endif %} +{% endif -- generateErrorChecks %} + + return{% if fn.returnValue.type.isNotVoid %} result{% endif -- isNotVoid %}; +{% enddef --------------------------------------------------------------------------------- clientShimCode(fn, serverIDName, functionIDName) %} +{% for iface in group.interfaces %} +{% for cb in iface.callbacksInt if (count(cb.callbacks) > 1) %} + +// Common function for serializing and deserializing callback functions of same type. +static {$cb.callbacksData.prototype}; +{% endfor %} +{% for cb in iface.callbacksInt if (count(cb.callbacks) > 1) %} + +// Common function for serializing and deserializing callback functions of same type. +static {$cb.callbacksData.prototype} +{ +{$ clientShimCode("m_clientManager", cb.callbacksData, "serviceID", "functionID") >} +} +{% endfor %} + +{$iface.clientClassName}::{$iface.clientClassName}(ClientManager *manager) +:m_clientManager(manager) +{ +} + +{$iface.clientClassName}::~{$iface.clientClassName}() +{ +} +{% for fn in iface.functions %} + +// {$iface.name} interface {$fn.name} function client shim. +{$fn.prototypeCpp} +{ +{% if fn.isCallback %} + {% if fn.returnValue.type.isNotVoid %}return {% endif %}{$fn.callbackFName}(m_clientManager, m_serviceId, {$getClassFunctionIdName(fn)}{% for param in fn.parameters %}, {$param.pureName}{% endfor %}); +{% else -- fn.isCallback >%} +{$ clientShimCode("m_clientManager", fn, "m_serviceId", getClassFunctionIdName(fn)) >} +{% endif -- fn.isCallback >%} +} +{% endfor -- fn %} +{% endfor -- iface %} diff --git a/erpcgen/src/templates/c_coders.template b/erpcgen/src/templates/cpp_coders.template similarity index 92% rename from erpcgen/src/templates/c_coders.template rename to erpcgen/src/templates/cpp_coders.template index 4bf37fa7..1dd7dacc 100644 --- a/erpcgen/src/templates/c_coders.template +++ b/erpcgen/src/templates/cpp_coders.template @@ -5,7 +5,7 @@ char * {$info.stringLocalName}_local; codec->readString({$info.stringLocalName}_len, &{$info.stringLocalName}_local); {% if info.stringAllocSize != info.stringLocalName & "_len" %} - if ({$info.stringLocalName}_len <= {$info.stringAllocSize}) + if (({$info.stringAllocSize} >= 0) && ({$info.stringLocalName}_len <= static_cast({$info.stringAllocSize}))) { {% set indent = " " >%} {% else %} @@ -209,9 +209,13 @@ switch ({% if info.dataLiteral != "" %}{$info.dataLiteral}{% endif %}{$info.disc {% def decodeFunctionType(info) %} {% if info.callbacksCount == 1 %} -codec->readCallback((funPtr)({$info.callbacks}), (funPtr *)(&{$info.name})); +{% if param.direction != InDirection %}*{% endif %}{$info.name} = &{% if param.ifaceScope != ""%}{$param.ifaceScope}{% else %}{$iface.name}{% endif %}_interface::{$info.callbacks}; {% else -- info.callbacksCount == 1 %} -codec->readCallback((arrayOfFunPtr)({$info.callbacks}), {$info.callbacksCount}, (funPtr *)(&{$info.name})); +codec->read(_tmp_local_u16); +if (!{% if param.ifaceScope != ""%}{$param.ifaceScope}{% else %}{$iface.name}{% endif %}_interface::get_callbackAddress_{$info.cbTypeName}(_tmp_local_u16, {% if param.direction == InDirection %}&{% endif %}{$info.cbParamOutName})) +{ + codec->updateStatus(kErpcStatus_UnknownCallback); +} {% endif -- info.callbacksCount == 1 %} {% enddef -------------------------- FunctionType %} @@ -257,7 +261,8 @@ codec->readData({$info.name}, {$info.sizeTemp} * sizeof({$info.builtinTypeName}) uint32_t {$info.stringLocalName}_len = strlen((const char*){$info.name}); {% if info.stringAllocSize != info.stringLocalName & "_len" %} - erpc_assert({$info.stringLocalName}_len <= {$info.stringAllocSize}); + erpc_assert({$info.stringAllocSize} >= 0); + erpc_assert({$info.stringLocalName}_len <= static_cast({$info.stringAllocSize})); {% endif %} codec->writeString({$info.stringLocalName}_len, (const char*){$info.name}); @@ -340,9 +345,12 @@ switch ({$info.dataLiteral}{$info.discriminatorName}) {% def encodeFunctionType(info) %} {% if info.callbacksCount == 1 %} -codec->writeCallback((funPtr)({$info.callbacks}), (funPtr)({$info.name})); +/* No need to serialize code for {$info.name} when only one cb exists. */ +// (void){% if param.ifaceScope != ""%}{$param.ifaceScope}{% else %}{$iface.name}{% endif %}_interface::get_callbackIdx_{$info.cbTypeName}(&{$info.name}, _tmp_local_u16); +// codec->write(_tmp_local_u16); {% else -- info.callbacksCount == 1 %} -codec->writeCallback((arrayOfFunPtr)({$info.callbacks}), {$info.callbacksCount}, (funPtr)({$info.name})); +(void){% if param.ifaceScope != ""%}{$param.ifaceScope}{% else %}{$iface.name}{% endif %}_interface::get_callbackIdx_{$info.cbTypeName}(&{$info.name}, _tmp_local_u16); +codec->write(_tmp_local_u16); {% endif -- info.callbacksCount == 1 %} {% enddef -------------------------- FunctionType %} diff --git a/erpcgen/src/templates/c_common_functions.template b/erpcgen/src/templates/cpp_common_functions.template similarity index 95% rename from erpcgen/src/templates/c_common_functions.template rename to erpcgen/src/templates/cpp_common_functions.template index ee3c79fd..5891ab3e 100644 --- a/erpcgen/src/templates/c_common_functions.template +++ b/erpcgen/src/templates/cpp_common_functions.template @@ -36,6 +36,28 @@ extern const uint32_t erpc_generated_crc = {$crc16}; {% endif -- empty(crc16) == false %} {% enddef --checkCrc %} +{# ---------------- namespace ---------------- #} +{% def fillNamespaceBegin() %} +{% if empty(namespace) == false %} + +namespace {$namespace} +{ +{% endif -- empty(crc16) == false %} +{% enddef --checkCrc %} + +{% def fillNamespaceEnd() %} +{% if empty(namespace) == false %} +} // {$namespace} + +{% endif -- empty(crc16) == false %} +{% enddef --checkCrc %} + +{% def usingNamespace() %} +{% if empty(namespace) == false %} +using namespace {$namespace}; +{% endif -- empty(crc16) == false %} +{% enddef --checkCrc %} + {# ---------------- constantsDefinitions ---------------- #} {% def constantsDefinitions(consts) %} {% if not empty(consts) %} @@ -349,17 +371,6 @@ static void free_{$union.name}_union(int32_t discriminator, {$union.name} * data } {% enddef -- unionFreeSpaceSource %} -{# ---------------- callbacksTable ---------------- #} -{% def callbackTable(functionsTypes) %} -{% if functionsTypes %} -{% for f in functionsTypes %} -{% if count(f.callbacks) > 1 %} -static const {$f.name} _{$f.name}[] = { {% for c in f.callbacks %}{$c.name}{% if !loop.last %}, {% endif -- loop.last %}{% endfor -- f.callbacks %} }; -{% endif -- f.callbacks.size() %} -{% endfor -- functionsTypes %} -{% endif -- functionsTypes %} -{% enddef ------------------------------- callbackTable %} - {# ---------------- allocMem ---------------- #} {% def allocMem(info) %} {% if empty(info) == false %} @@ -524,3 +535,11 @@ else {% if source == "server" && !empty(param.nullVariable) %}_{% endif %}{$param.nullableName} = NULL; } {% enddef ------------------------------- f_paramIsNullableDecode %} + +{% def getFunctionDeclarationMacroName() %} +ERPC_FUNCTIONS_DEFINITIONS{% if group.name %}_{% endif %}{$upper(group.name)}{%>%} +{% enddef ------------------------------- getFunctionDeclarationMacroName %} + +{% def getClassFunctionIdName(fn) %} +m_{$fn.name}Id{%>%} +{% enddef ------------------------------- getClassFunctionIdName %} diff --git a/erpcgen/src/templates/cpp_interface_header.template b/erpcgen/src/templates/cpp_interface_header.template new file mode 100644 index 00000000..27c52834 --- /dev/null +++ b/erpcgen/src/templates/cpp_interface_header.template @@ -0,0 +1,60 @@ +{% if mlComment != "" %} +{$mlComment} + +{% endif %} +{$commonHeader()} + +#if !defined({$interfaceCppGuardMacro}) +#define {$interfaceCppGuardMacro} + +#include "{$commonCppHeaderName}" +{% for iface in group.interfaces %} +{% for fn in iface.functions %} +{% for externalInterface in fn.externalInterfaces %} +{% for interfaceFile in interfacesFiles %} +{% if externalInterface == interfaceFile.interfaceName %} +#include "{$interfaceFile.interfaceCommonFileName}_interface.hpp" +{% endif %} +{% endfor -- interfacesFiles %} +{% endfor -- externalInterface %} +{% endfor -- fn %} +{% endfor -- iface %} +{$fillNamespaceBegin()} +{% for iface in group.interfaces %} + +// Abstract base class for {$iface.name} +class {$iface.interfaceClassName} +{ + public: +{%if count(iface.callbacksInt) > 0%} +{% for cb in iface.callbacksInt%} + typedef {$cb.interfaceTypenameName}; +{% endfor %} + +{%endif %} + static const uint8_t m_serviceId = {$iface.id}; +{% for fn in iface.functions %} + static const uint8_t {$getClassFunctionIdName(fn)} = {$fn.id}; +{% endfor -- fn %} + + virtual ~{$iface.interfaceClassName}(void); +{% for fn in iface.functions if fn.isNonExternalFunction == true %} + +{% if fn.mlComment %} + {$fn.mlComment} +{% endif %} + virtual {$fn.prototypeInterface} = 0; +{% endfor -- fn %} +{% for cb in iface.callbacksInt %} + + static bool get_callbackAddress_{$cb.name}(uint16_t index, {$cb.name} *callback); + static bool get_callbackIdx_{$cb.name}(const {$cb.name} *callback, uint16_t &index); +{% endfor %} +private: +{% for cb in iface.callbacksInt %} + static {$cb.name} _{$cb.name}[{$count(cb.callbacks)}]; +{% endfor %} +}; +{% endfor -- iface %} +{$fillNamespaceEnd()} +#endif // {$interfaceCppGuardMacro} diff --git a/erpcgen/src/templates/cpp_interface_source.template b/erpcgen/src/templates/cpp_interface_source.template new file mode 100644 index 00000000..86d37e07 --- /dev/null +++ b/erpcgen/src/templates/cpp_interface_source.template @@ -0,0 +1,57 @@ +{% if mlComment != "" %} +{$mlComment} + +{% endif %} +{$commonHeader()} + +#include "{$interfaceCppHeaderName}" + +{$checkVersion()} +{$>checkCrc()} + +using namespace std; +{$usingNamespace() >} + +{% for iface in group.interfaces -- service subclass method impl %} +{$iface.interfaceClassName}::~{$iface.interfaceClassName}(void) +{ +} +{% for cb in iface.callbacksInt %} +{$iface.interfaceClassName}::{$cb.name} {$iface.interfaceClassName}::_{$cb.name}[{$count(cb.callbacks)}] = { {% for c in cb.callbacks %}&{$iface.interfaceClassName}::{$c.name}{% if !loop.last %}, {% endif -- loop.last %}{% endfor -- f.callbacks %} }; +{% endfor %} +{% for cb in iface.callbacksInt %} + +bool {$iface.interfaceClassName}::get_callbackAddress_{$cb.name}(uint16_t index, {$cb.name} *callback) +{ + bool find; + + if (indexcheckCrc()} +{$fillNamespaceBegin()>} + +{% for iface in group.interfaces %} +/*! + * @brief Service subclass for {$iface.name}. + */ +class {$iface.serviceClassName} : public erpc::Service +{ +public: + {$iface.serviceClassName}({$iface.interfaceClassName} *_{$iface.interfaceClassName}); + + virtual ~{$iface.serviceClassName}(); + + /*! @brief return service interface handler. */ + {$iface.interfaceClassName}* getHandler(void); + + /*! @brief Call the correct server shim based on method unique ID. */ + virtual erpc_status_t handleInvocation(uint32_t methodId, uint32_t sequence, erpc::Codec * codec, erpc::MessageBufferFactory *messageFactory); + +private: + {$iface.interfaceClassName} *m_handler; +{% for fn in iface.functions %} + /*! @brief Server shim for {$fn.name} of {$iface.name} interface. */ + erpc_status_t {$fn.name}_shim(erpc::{$codecClass} * codec, erpc::MessageBufferFactory *messageFactory, uint32_t sequence);{$loop.addNewLineIfNotLast} +{% endfor -- fn %} +}; + +{% endfor -- iface %} +{$fillNamespaceEnd()} +#endif // {$serverCppGuardMacro} diff --git a/erpcgen/src/templates/cpp_server_source.template b/erpcgen/src/templates/cpp_server_source.template new file mode 100644 index 00000000..a7eb79e3 --- /dev/null +++ b/erpcgen/src/templates/cpp_server_source.template @@ -0,0 +1,253 @@ +{% set source = "server" >%} +{% if mlComment != ""%} +{$mlComment} + +{% endif %} +{$commonHeader()} + +#include "{$serverCppHeaderName}" +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC +#include +#include "erpc_port.h" +#endif +#include "erpc_manually_constructed.hpp" + +{$checkVersion()} +{$>checkCrc()} +using namespace erpc; +using namespace std; +{$usingNamespace() >} + +#if ERPC_NESTED_CALLS_DETECTION +extern bool nestingDetection; +#endif + +{$generateCrcVariable()} +{$> setSharedMemAddresses()} +{$> constantsDefinitions(consts)} +{$> symbolHeader(group.symbolsMap.symbolsToServer, "deserial", "def")} +{$> symbolSource(group.symbolsMap.symbolsToServer, "deserial", "def")} +{$> symbolHeader(group.symbolsMap.symbolsToClient, "serial", "def")} +{$> symbolSource(group.symbolsMap.symbolsToClient, "serial", "def")} +{$> symbolFreeSpaceHeader(group.symbolsMap.symbolsServerFree, "def")} +{$> symbolFreeSpaceSource(group.symbolsMap.symbolsServerFree, "def")} +{$> symbolHeader(group.symbolsMap.symbolsToServer, "deserial", "noSharedMem")} +{$> symbolSource(group.symbolsMap.symbolsToServer, "deserial", "noSharedMem")} +{$> symbolHeader(group.symbolsMap.symbolsToClient, "serial", "noSharedMem")} +{$> symbolSource(group.symbolsMap.symbolsToClient, "serial", "noSharedMem")} +{$> symbolFreeSpaceHeader(group.symbolsMap.symbolsServerFree, "noSharedMem")} +{$> symbolFreeSpaceSource(group.symbolsMap.symbolsServerFree, "noSharedMem")} +{% def serverShimCode(iface, handler, fn, serverIDName, functionIDName) ------------------------- serverShimCode(fn, serverIDName, functionIDName) %} +{% set serverIndent = "" >%} +{% if (fn.isReturnValue || fn.isSendValue) && generateErrorChecks %} + erpc_status_t err = kErpcStatus_Success; + +{% endif -- isReturnValue || isSendValue %} +{% for param in fn.parameters %} + {% if param.isFunction %}{% if param.ifaceScope != ""%}{$param.ifaceScope}{% else %}{$iface.name}{% endif %}_interface::{% endif %}{$param.variable}{% if param.isNullParam %} = NULL{% endif %}; +{% if !empty(param.nullVariable) %} + {$param.nullVariable} = NULL; +{% endif %} +{% if !param.shared %} +{% if param.isNullable == false && param.direction != OutDirection %} +{$> addIndent(" ", allocMem(param.mallocServer))} +{% endif -- !param.isNullable && param.direction != OutDirection %} +{% endif -- shared %} +{% endfor -- param %} +{% if fn.needNullVariableOnServer %} + bool isNull; +{% endif -- needNullVariableOnServer %} +{% if fn.needTempVariableServerI32 %} + int32_t _tmp_local_i32; +{% endif %} +{% if fn.needTempVariableServerU16 %} + uint16_t _tmp_local_u16; +{% endif %} +{% if fn.returnValue.type.isNotVoid %} + {$fn.returnValue.resultVariable}{% if fn.returnValue.isNullReturnType %} = NULL{% endif %}; +{% endif %} +{% if fn.isReturnValue || fn.isSendValue %} + +{% endif %} + // startReadMessage() was already called before this shim was invoked. + +{% if fn.isSendValue %} +{% for param in fn.parameters if (param.serializedDirection == "" || param.serializedDirection == OutDirection || param.referencedName != "") %} +{% if param.isNullable %} +{$addIndent(" ", f_paramIsNullableDecode(param))} + +{% else -- notNullable %} +{% if param.direction != OutDirection %} +{$addIndent(" ", param.coderCall.decode(param.coderCall))} + +{% endif -- param != OutDirection %} +{% endif -- isNullable %} +{% endfor -- parametersToServer %} +{% endif -- isSendValue %} +{% for param in fn.parametersToClient %} +{% if !param.shared %} +{% if param.isNullable == false && param.direction == OutDirection && empty(param.mallocServer) == false %} +{$> addIndent(" ", allocMem(param.mallocServer))} + +{% endif -- !param.isNullable && param.direction == OutDirection %} +{% endif -- shared %} +{% endfor -- param %} +{% if (fn.isReturnValue || fn.isSendValue) && generateErrorChecks %} +{% set serverIndent = " " >%} + err = codec->getStatus(); + if (err == kErpcStatus_Success) + { +{% endif -- generateErrorChecks %} +{$serverIndent} // Invoke the actual served function. +#if ERPC_NESTED_CALLS_DETECTION +{$serverIndent} nestingDetection = true; +#endif +{% if serverIDName == "serviceID" %} +{% for callbackFunction in fn.functions %} +{$serverIndent} {% if loop.first == false %}else {% endif %}if (({$serverIDName} == {$callbackFunction.serviceId}) && ({$functionIDName} == {$callbackFunction.id})) +{$serverIndent} { +{$serverIndent} m_handler->{$callbackFunction.serverPrototype} +{$serverIndent} } +{% endfor -- callbackFunction in callbackType.functions %} +{% else -- serverIDName == "serviceID" %} +{$serverIndent} {$fn.serverPrototype} +{% endif --serverIDName == "serviceID" %} +#if ERPC_NESTED_CALLS_DETECTION +{$serverIndent} nestingDetection = false; +#endif +{% if fn.isReturnValue %} + +{$serverIndent} // preparing MessageBuffer for serializing data +{$serverIndent} {% if generateErrorChecks %}err = {% endif %}messageFactory->prepareServerBufferForSend(codec->getBuffer()); +{% if generateErrorChecks %} + } + + if (err == kErpcStatus_Success) + { +{% endif -- generateErrorChecks %} +{$serverIndent} // preparing codec for serializing data +{$serverIndent} codec->reset(); + +{$serverIndent} // Build response message. +{$serverIndent} codec->startWriteMessage(message_type_t::kReplyMessage, {$serverIDName}, {$functionIDName}, sequence); +{% for param in fn.parametersToClient if (param.serializedDirection == "" || param.serializedDirection == InDirection || param.referencedName != "") %} + +{% if param.isNullable %} +{$serverIndent} if ({% if source == "server" && empty(param.nullVariable) == false %}_{% endif %}{$param.name} != NULL) +{$serverIndent} { +{$addIndent(serverIndent & " ", param.coderCall.encode(param.coderCall))} +{$serverIndent} } +{% else -- isNullable %} +{$addIndent(serverIndent & " ", param.coderCall.encode(param.coderCall))} +{% endif -- isNullable %} +{% endfor -- parametersToClient %} +{% if fn.returnValue.type.isNotVoid %} + +{% if fn.returnValue.isNullable %} +{$addIndent(serverIndent & " ", f_paramIsNullableEncode(fn.returnValue))} +{% else -- isNullable %} +{$addIndent(serverIndent & " ", fn.returnValue.coderCall.encode(fn.returnValue.coderCall))} +{% endif -- isNullable %} +{% endif -- notVoid %} +{% if generateErrorChecks %} + + err = codec->getStatus(); +{% endif generateErrorChecks %} +{% endif -- isReturnValue %} +{% if (fn.isReturnValue || fn.isSendValue) && generateErrorChecks %} + } + +{% endif -- fn.isReturnValue || fn.isSendValue %} +{% for param in fn.paramsToFree %} +{$> addIndent(" ", param.coderCall.freeingCall(param.coderCall))} +{$> addIndent(" ", param.firstFreeingCall1.firstFreeingCall(param.firstFreeingCall1))} + +{% endfor -- parameters %} +{% if fn.returnValue.type.isNotVoid %} +{% set needFreeingCall = fn.returnValue.coderCall.freeingCall(fn.returnValue.coderCall) %} +{% set needFirstFreeingCall = fn.returnValue.firstFreeingCall1.firstFreeingCall(fn.returnValue.firstFreeingCall1) %} +{% if empty(needFreeingCall) == false || empty(needFirstFreeingCall) == false %} +{$> addIndent(" ", needFreeingCall)} +{$> addIndent(" ", needFirstFreeingCall)} + +{% endif -- !empty(needFreeingCall) || !empty(needFirstFreeingCall) %} +{% endif -- notVoid %} +{% if (fn.isReturnValue || fn.isSendValue) && generateErrorChecks %} + return err; +{% else %} + return codec->getStatus(); +{% endif %} +{% enddef --------------------------------------------------------------------------------- serverShimCode(fn, serverIDName, functionIDName) %} +{% for iface in group.interfaces %} +{% for cb in iface.callbacksInt if (count(cb.callbacks) > 1) %} +// Common function for serializing and deserializing callback functions of same type. +static erpc_status_t {$iface.interfaceClassName}_{$cb.name}_shim({$iface.interfaceClassName} *m_handler, uint32_t serviceID, uint32_t functionID, {$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence); +{% endfor %} +{% endfor %} +{% for iface in group.interfaces %} +{% for cb in iface.callbacksInt if (count(cb.callbacks) > 1) %} + +// Common function for serializing and deserializing callback functions of same type. +static erpc_status_t {$iface.interfaceClassName}_{$cb.name}_shim({$iface.interfaceClassName} *m_handler, uint32_t serviceID, uint32_t functionID, {$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence) +{ +{$ serverShimCode(iface, "m_handler", cb.callbacksData, "serviceID", "functionID") >} +} +{% endfor %} +{% endfor %} +{% for iface in group.interfaces -- service subclass method impl %} + +{$iface.serviceClassName}::{$iface.serviceClassName}({$iface.interfaceClassName} *_{$iface.interfaceClassName}) + : erpc::Service({$iface.interfaceClassName}::m_serviceId) + , m_handler(_{$iface.interfaceClassName}) +{ +} + +{$iface.serviceClassName}::~{$iface.serviceClassName}() +{ +} + +// return service interface handler. +{$iface.interfaceClassName}* {$iface.serviceClassName}::getHandler(void) +{ + return m_handler; +} + +// Call the correct server shim based on method unique ID. +erpc_status_t {$iface.serviceClassName}::handleInvocation(uint32_t methodId, uint32_t sequence, Codec * codec, MessageBufferFactory *messageFactory) +{ + erpc_status_t erpcStatus; +{% if codecClass != "Codec" %} + {$codecClass} *_codec = static_cast<{$codecClass} *>(codec); +{% endif %} + switch (methodId) + { +{% for fn in iface.functions %} + case {$iface.interfaceClassName}::{$getClassFunctionIdName(fn)}: + { + erpcStatus = {$fn.name}_shim({%if codecClass == "Codec" %}codec{% else %}_codec{% endif %}, messageFactory, sequence); + break; + } + +{% endfor -- fn %} + default: + { + erpcStatus = kErpcStatus_InvalidArgument; + break; + } + } + + return erpcStatus; +} +{% for fn in iface.functions %} + +// Server shim for {$fn.name} of {$iface.name} interface. +erpc_status_t {$iface.serviceClassName}::{$fn.name}_shim({$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence) +{ +{% if fn.isCallback %} + return {$iface.interfaceClassName}_{$fn.callbackFNameNoGroup}_shim(m_handler, {$iface.interfaceClassName}::m_serviceId, {$iface.interfaceClassName}::{$getClassFunctionIdName(fn)}, codec, messageFactory, sequence); +{% else -- fn.isCallback >%} +{$ serverShimCode(iface, "m_handler", fn, iface.interfaceClassName & "::m_serviceId", iface.interfaceClassName & "::" & getClassFunctionIdName(fn)) >} +{% endif -- fn.isCallback >%} +} +{% endfor -- fn %} +{% endfor -- iface %} diff --git a/erpcgen/src/types/Function.hpp b/erpcgen/src/types/Function.hpp index b72d159e..ad4a3e11 100644 --- a/erpcgen/src/types/Function.hpp +++ b/erpcgen/src/types/Function.hpp @@ -21,6 +21,7 @@ //////////////////////////////////////////////////////////////////////////////// namespace erpcgen { +class Interface; /*! * @brief Function base declaration. @@ -33,15 +34,23 @@ class FunctionBase /*! * @brief Constructor. */ - FunctionBase() + FunctionBase(Interface *interface) : m_parameters("(fn)") , m_returnType(nullptr) , m_isOneway(false) + , m_interface(interface) { } virtual ~FunctionBase(){}; + /*! + * @brief This function returns parent Interface. + * + * @return parent Interface. + */ + Interface *getInterface() const { return m_interface; } + /*! * @brief This function returns function parameters. * @@ -105,9 +114,9 @@ class FunctionBase StructType m_parameters; /*!< Function parameters are saved as structure members. */ StructMember *m_returnType; /*!< Function return data type. */ bool m_isOneway; /*!< If false then communication is bidirectional. */ + Interface *m_interface; /*!< Parent interface. */ }; -class Interface; class FunctionType; /*! * @brief Function declaration. @@ -123,13 +132,12 @@ class Function : public FunctionBase, public Symbol * This function set symbol token to given token. * * @param[in] tok Given token. - * @param[in] m_interface Parent interface. + * @param[in] interface Parent interface. */ Function(const Token &tok, Interface *interface) - : FunctionBase() + : FunctionBase(interface) , Symbol(symbol_type_t::kFunctionSymbol, tok) , m_uniqueId(++s_idCounter) - , m_interface(interface) , m_functionType(nullptr) { } @@ -140,14 +148,13 @@ class Function : public FunctionBase, public Symbol * This function set symbol token to given token, uniqueId and idCounter to given uniqueId. * * @param[in] tok Given token. - * @param[in] m_interface Parent interface. + * @param[in] interface Parent interface. * @param[in] uniqueId Given unique function id. */ Function(const Token &tok, Interface *interface, uint32_t uniqueId) - : FunctionBase() + : FunctionBase(interface) , Symbol(symbol_type_t::kFunctionSymbol, tok) , m_uniqueId(uniqueId) - , m_interface(interface) , m_functionType(nullptr) { s_idCounter = uniqueId; @@ -167,13 +174,6 @@ class Function : public FunctionBase, public Symbol */ void setUniqueId(uint32_t newId) { m_uniqueId = newId; } - /*! - * @brief This function returns parent Interface. - * - * @return parent Interface. - */ - Interface *getInterface() const { return m_interface; } - /*! * @brief This function returns description about the interface function. * @@ -206,10 +206,9 @@ class Function : public FunctionBase, public Symbol protected: uint32_t m_uniqueId; /*!< Function unique id. */ - Interface *m_interface; /*!< Parent interface. */ - FunctionType *m_functionType; /*!< Parent interface. */ + FunctionType *m_functionType; /*!< Function type. */ - static uint32_t s_idCounter; /*!< Function id counter. Each function will increase this. */ + static uint32_t s_idCounter; /*!< Function id counter. Each function will increase this. */ }; } // namespace erpcgen diff --git a/erpcgen/src/types/FunctionType.hpp b/erpcgen/src/types/FunctionType.hpp index 15bc512b..2c944213 100644 --- a/erpcgen/src/types/FunctionType.hpp +++ b/erpcgen/src/types/FunctionType.hpp @@ -39,9 +39,10 @@ class FunctionType : public FunctionBase, public DataType * This function set symbol token to given token. * * @param[in] tok Given token. + * @param[in] m_interface Parent interface. */ - explicit FunctionType(const Token &tok) - : FunctionBase() + FunctionType(const Token &tok, Interface *interface) + : FunctionBase(interface) , DataType(tok, data_type_t::kFunctionType) , m_callbackFuns() { diff --git a/erpcgen/src/types/Group.hpp b/erpcgen/src/types/Group.hpp index bc7ae551..d2cf95a0 100644 --- a/erpcgen/src/types/Group.hpp +++ b/erpcgen/src/types/Group.hpp @@ -41,6 +41,7 @@ class Group explicit Group(const std::string &name) : m_name(name) { + m_template["name"] = name; } /*! diff --git a/erpcgen/src/types/Interface.hpp b/erpcgen/src/types/Interface.hpp index ffc400a1..c4a82a83 100644 --- a/erpcgen/src/types/Interface.hpp +++ b/erpcgen/src/types/Interface.hpp @@ -29,7 +29,8 @@ namespace erpcgen { class Interface : public Symbol { public: - typedef std::vector function_vector_t; /*!< Vector of Interface functions. */ + typedef std::vector function_vector_t; /*!< Vector of Interface functions. */ + typedef std::vector function_types_vector_t; /*!< Vector of Interface function types. */ /*! * @brief Constructor. @@ -55,6 +56,16 @@ class Interface : public Symbol */ void addFunction(Function *func); + /*! + * @brief This function will add function type to the interface. + * + * The function will add function type given by pointer func to the interface members vector m_functionTypes. + * Also this member will be added as symbol to interface symbol scope m_scope. + * + * @param[in] func Function pointer, which is added to interface members vector. + */ + void addFunctionType(FunctionType *func); + /*! * @brief This function return symbol scope. * @@ -67,7 +78,14 @@ class Interface : public Symbol * * @return Interface functions vector. */ - function_vector_t &getFunctions() { return m_functions; } + const function_vector_t &getFunctions() const { return m_functions; } + + /*! + * @brief This function return interface function types vector. + * + * @return Interface function types vector. + */ + const function_types_vector_t &getFunctionTypes() const { return m_functionTypes; } /*! * @brief This function get unique id of interface. @@ -101,11 +119,12 @@ class Interface : public Symbol virtual std::string getDescription() const override; protected: - SymbolScope m_scope; /*!< Scope which interface belongs to. */ - function_vector_t m_functions; /*!< Vector of interface functions. */ - uint32_t m_uniqueId; /*!< Interface unique id. */ + SymbolScope m_scope; /*!< Scope which interface belongs to. */ + function_vector_t m_functions; /*!< Vector of interface functions. */ + function_types_vector_t m_functionTypes; /*!< Vector of interface function types. */ + uint32_t m_uniqueId; /*!< Interface unique id. */ - static uint32_t s_idCounter; /*!< Interface id counter. Each interface will increase this. */ + static uint32_t s_idCounter; /*!< Interface id counter. Each interface will increase this. */ }; } // namespace erpcgen diff --git a/erpcgen/src/types/Type.cpp b/erpcgen/src/types/Type.cpp index 0b89d67e..b218760e 100644 --- a/erpcgen/src/types/Type.cpp +++ b/erpcgen/src/types/Type.cpp @@ -514,6 +514,14 @@ void Interface::addFunction(Function *func) m_functions.push_back(func); } +void Interface::addFunctionType(FunctionType *func) +{ + assert(func); + + m_scope.addSymbol(func); + m_functionTypes.push_back(func); +} + string Interface::getDescription() const { string fns; diff --git a/erpcgen/test/conftest.py b/erpcgen/test/conftest.py index 324dd9bf..759c3157 100644 --- a/erpcgen/test/conftest.py +++ b/erpcgen/test/conftest.py @@ -284,8 +284,8 @@ def _run(cwd, captureOutput, pytestConfig, args, compilerType): # Enable all warnings except for unused functions. defaultArgs = ["-c", "-Wall", "-Werror", "-Wno-unused-function"] defaultArgs += self._args - argsCC = [self._pathCC, "-std=gnu11"] + defaultArgs - argsCXX = [self._pathCXX, "-std=gnu++11"] + defaultArgs + argsCC = [self._pathCC, "-std=gnu17"] + defaultArgs + argsCXX = [self._pathCXX, "-std=gnu++17"] + defaultArgs incl = [] for i in self._includes: @@ -294,15 +294,24 @@ def _run(cwd, captureOutput, pytestConfig, args, compilerType): argsCXX += incl argsCC += incl + hasCSource = False + hasCppSource = False for s in self._sources: if str(s).split(".")[-1] == "cpp": argsCXX.append(str(s)) + hasCppSource = True else: argsCC.append(str(s)) + hasCSource = True - output = [_run(self._cwd, captureOutput, pytestConfig, argsCC, "C")] - output.append(_run(self._cwd, captureOutput, - pytestConfig, argsCXX, "CXX")) + output = [] + + if hasCSource: + output.append(_run(self._cwd, captureOutput, + pytestConfig, argsCC, "C")) + if hasCppSource: + output.append(_run(self._cwd, captureOutput, + pytestConfig, argsCXX, "CXX")) return output @@ -481,29 +490,58 @@ def run(self): pass -class ErpcgenCCompileTest(ErpcgenCompileTest): - # @brief Tests that generated C code will compile successfully. - # - # An objects directory is created under the test case directory. It is used to hold the - # .o files written by the compiler. A .c file with the main() function is also written to - # the objects directory. +class ErpcgenCCppCompileTest(ErpcgenCompileTest): + # @brief Compile with C and CPP main. + def __init__(self, spec: ErpcgenTestSpec, name: str, caseDir: str, outDir: str): + super(ErpcgenCCppCompileTest, self).__init__( + spec, name, caseDir, outDir) + self._caseDir = caseDir + self._out_dir = outDir + + def run(self): + ErpcgenCCompileTest(self._caseDir, self._out_dir).run() + ErpcgenCppCompileTest(self._caseDir, self._out_dir).run() + + +class ErpcgenCCppCompileTestCommon(object): MAIN_CODE = textwrap.dedent(""" int main(void) { return 0; } """) - def __init__(self, spec: ErpcgenTestSpec, name: str, caseDir: str, outDir: str): - super(ErpcgenCCompileTest, self).__init__(spec, name, caseDir, outDir) - self._objs_dir = caseDir.mkdir(OBJECTS_DIR_NAME) - self._compiler = CCompiler(self._objs_dir) + def __init__(self, outDir: str): + self._out_dir = outDir + self._objs_dir = None + self._compiler = None + + def getMainSourceCode(self): + raise ErpcgenTestException( + "Missing implementation for getting main source code") + + def getMainFilename(self): + raise ErpcgenTestException( + "Missing implementation for getting main filename") + + def getObjectsDir(self): + raise ErpcgenTestException( + "Missing implementation for getting objects dir") + + def getCompiler(self): + raise ErpcgenTestException( + "Missing implementation for getting compiler") + def run(self): # TODO run compiler tests on Windows if sys.platform == 'win32': return + self._compiler = self.getCompiler() + + self._objs_dir = self.getObjectsDir() + # Add include directories. self._compiler.add_include(erpc_dir.join("erpc_c", "port")) self._compiler.add_include(erpc_dir.join("erpc_c", "config")) @@ -515,21 +553,70 @@ def run(self): if '.cpp' in file: self._compiler.add_source(self._out_dir.join(file)) - # Add all header includes into main code - headers = ['#include "'+f + - '"' for f in os.listdir(str(self._out_dir)) if '.h' in f] - self.MAIN_CODE = '\n'.join(headers) + self.MAIN_CODE - - # Add both .c and .cpp copies of the main file. - for main_filename in ("main_c.c", "main_cxx.cpp"): - main = self._objs_dir.join(main_filename) - main.write(self.MAIN_CODE) - self._compiler.add_source(main) + mainCode = self.getMainSourceCode() + mainFilename = self.getMainFilename() + main = self._objs_dir.join(mainFilename) + main.write(mainCode) + self._compiler.add_source(main) # Run the compiler. self._compiler.run() +class ErpcgenCCompileTest(ErpcgenCCppCompileTestCommon): + # @brief Tests that generated C code will compile successfully. + # + # An objects directory is created under the test case directory. It is used to hold the + # .o files written by the compiler. A .c file with the main() function is also written to + # the objects directory. + + def __init__(self, caseDir: str, outDir: str): + super(ErpcgenCCompileTest, self).__init__(outDir) + self._objs_dir = caseDir.mkdir(OBJECTS_DIR_NAME + "_c") + self._compiler = CCompiler(self._objs_dir) + + def getMainSourceCode(self): + headers = ['#include "'+f + + '"' for f in os.listdir(str(self._out_dir)) if f[-2:] == '.h'] + return '\n'.join(headers) + self.MAIN_CODE + + def getMainFilename(self): + return "main.c" + + def getObjectsDir(self): + return self._objs_dir + + def getCompiler(self): + return self._compiler + + +class ErpcgenCppCompileTest(ErpcgenCCppCompileTestCommon): + # @brief Tests that generated Cpp code will compile successfully. + # + # An objects directory is created under the test case directory. It is used to hold the + # .o files written by the compiler. A .cpp file with the main() function is also written to + # the objects directory. + + def __init__(self, caseDir: str, outDir: str): + super(ErpcgenCppCompileTest, self).__init__(outDir) + self._objs_dir = caseDir.mkdir(OBJECTS_DIR_NAME + "_cpp") + self._compiler = CCompiler(self._objs_dir) + + def getMainSourceCode(self): + headers = ['#include "'+f + + '"' for f in os.listdir(str(self._out_dir)) if f[-4:] == '.hpp'] + return '\n'.join(headers) + self.MAIN_CODE + + def getMainFilename(self): + return "main.cpp" + + def getObjectsDir(self): + return self._objs_dir + + def getCompiler(self): + return self._compiler + + class ErpcgenPythonCompileTest(ErpcgenCompileTest): # @brief Tests that generated Python code can be successfully compiled. # @@ -572,7 +659,7 @@ class ErpcgenTestCase(object): # Map of language names to compilation test classes. COMPILE_TEST_CLASSES = { - 'c': ErpcgenCCompileTest, + 'c': ErpcgenCCppCompileTest, 'py': ErpcgenPythonCompileTest, } diff --git a/erpcgen/test/test_builtin_types.yml b/erpcgen/test/test_builtin_types.yml index a1abf140..5b53c484 100644 --- a/erpcgen/test/test_builtin_types.yml +++ b/erpcgen/test/test_builtin_types.yml @@ -21,7 +21,7 @@ idl: | interface myintf { {fns[fore]} somefunc({type} i) {fns[after]} } -test.h: +c_test_client.h: - if: not type in ('bool', 'float', 'double') then: - void somefunc({type}_t i); @@ -46,7 +46,7 @@ idl: | interface myintf { somefunc() -> {type} } -test.h: +c_test_client.h: - if: not type in ('bool', 'float', 'double') then: - '{type}_t somefunc(void);' @@ -71,7 +71,7 @@ idl: | struct structwithint { {type} i } -test.h: +test_common.h: - 'struct structwithint {' - if: not type in ('bool', 'float', 'double') then: diff --git a/erpcgen/test/test_comments.yml b/erpcgen/test/test_comments.yml index 0db04396..ea322664 100644 --- a/erpcgen/test/test_comments.yml +++ b/erpcgen/test/test_comments.yml @@ -73,7 +73,7 @@ idl: | sendReceiveStruct(A a) -> A ///< 33 comment; } /*!<30 comment */ -test.h: +test_common.h: - "/*" - not: "!" - "* Comment" @@ -127,6 +127,8 @@ test.h: - //! 10 comment - //!11 comment - //!< 12 comment + +c_test_client.h: - /*! @brief DoxygenComments identifiers */ - //! 28 comment - //!29 comment @@ -136,7 +138,7 @@ test.h: - ///< 33 comment; - - //@} /*!<30 comment */ - - // _test_h_ + - // _c_test_client_h_ test_client.cpp: - "/*" @@ -158,7 +160,7 @@ test_client.cpp: - // DoxygenComments interface sendReceiveList function client shim. - // DoxygenComments interface sendReceiveStruct function client shim. -test_server.h: +test_server.hpp: - "/*" - not: "!" - "* Comment" @@ -173,7 +175,7 @@ test_server.h: - "*/" - /*! @brief Call the correct server shim based on method unique ID. */ - /*! @brief Server shim for sendReceiveList of DoxygenComments interface. */ - - // _test_server_h_ + - // _test_server_hpp_ test_server.cpp: - "/*" diff --git a/erpcgen/test/test_enum.yml b/erpcgen/test/test_enum.yml index a0a294ea..76e6611b 100644 --- a/erpcgen/test/test_enum.yml +++ b/erpcgen/test/test_enum.yml @@ -11,7 +11,7 @@ idl: | B, C } -test.h: +test_common.h: # named enums get a typedef - if: name then: @@ -38,7 +38,7 @@ idl: | B, C } -test.h: +test_common.h: # named enums get a typedef - if: name then: @@ -68,7 +68,7 @@ idl: | B = 30, C = {c_val} } -test.h: +test_common.h: # named enums get a typedef - if: name then: @@ -99,7 +99,7 @@ idl: | enum {name} { A{a_val}{opt_comma} } -test.h: +test_common.h: # named enums get a typedef - if: name then: @@ -123,7 +123,7 @@ idl: | A = 0, B = -1 } -test.h: +test_common.h: # named enums get a typedef - if: name then: @@ -148,7 +148,7 @@ idl: | D= 1*five, E = 2*five, } -test.h: +test_common.h: # named enums get a typedef - A = 0 - B = 5 diff --git a/erpcgen/test/test_error_checks_c.yml b/erpcgen/test/test_error_checks_c.yml index ad1c0d66..28e751bd 100644 --- a/erpcgen/test/test_error_checks_c.yml +++ b/erpcgen/test/test_error_checks_c.yml @@ -25,9 +25,9 @@ test_client.cpp: - if (codec == NULL) - err = kErpcStatus_MemoryError; - codec->startWriteMessage - - g_client->performRequest + - m_clientManager->performRequest - err = codec->getStatus(); - - g_client->callErrorHandler(err, + - m_clientManager->callErrorHandler(err, - if: type[1] != 'NULL' then: - if (err != kErpcStatus_Success) @@ -115,9 +115,9 @@ test_client.cpp: - not: if (result == NULL) - not: codec->updateStatus; - codec->startWriteMessage - - g_client->performRequest + - m_clientManager->performRequest - err = codec->getStatus(); - - g_client->callErrorHandler(err, kErrorTest_f_id) + - m_clientManager->callErrorHandler(err, m_fId) - if: type[1] != 'NULL' then: - if (err != kErpcStatus_Success) @@ -164,9 +164,9 @@ test_client.cpp: - if (codec == NULL) - err = kErpcStatus_MemoryError; - codec->startWriteMessage - - g_client->performRequest + - m_clientManager->performRequest - err = codec->getStatus(); - - g_client->callErrorHandler(err, + - m_clientManager->callErrorHandler(err, - if: type[1] != 'NULL' then: - if (err != kErpcStatus_Success) @@ -214,7 +214,7 @@ test_client.cpp: - if (codec == NULL) - err = kErpcStatus_MemoryError; - codec->startWriteMessage - - g_client->performRequest + - m_clientManager->performRequest - err = codec->getStatus(); test_server.cpp: @@ -261,9 +261,9 @@ test_client.cpp: - not: if (codec == NULL) - not: err = kErpcStatus_MemoryError; - codec->startWriteMessage - - g_client->performRequest + - m_clientManager->performRequest - err = codec->getStatus(); - - g_client->callErrorHandler(err, + - m_clientManager->callErrorHandler(err, test_server.cpp: - erpc_status_t err = kErpcStatus_Success; @@ -312,10 +312,10 @@ test_client.cpp: - err = kErpcStatus_MemoryError; - else - codec->startWriteMessage - - g_client->performRequest(request); + - m_clientManager->performRequest(request); - err = codec->getStatus(); - - g_client->releaseRequest(request); - - g_client->callErrorHandler(err, kErrorTest_f_id); + - m_clientManager->releaseRequest(request); + - m_clientManager->callErrorHandler(err, m_fId); test_server.cpp: - erpc_status_t err = kErpcStatus_Success; diff --git a/erpcgen/test/test_error_return_c.yml b/erpcgen/test/test_error_return_c.yml index 73ba7041..8c2571c3 100644 --- a/erpcgen/test/test_error_return_c.yml +++ b/erpcgen/test/test_error_return_c.yml @@ -28,7 +28,7 @@ idl: | f() -> {type[0]} } test_client.cpp: - - g_client->releaseRequest(request); + - m_clientManager->releaseRequest(request); - if: type[1] != 'NULL' then: - if (err != kErpcStatus_Success) @@ -71,7 +71,7 @@ idl: | f() -> {type[0]} } test_client.cpp: - - g_client->releaseRequest(request); + - m_clientManager->releaseRequest(request); - if: type[0] != 'A' and type[0] != 'string' then: - if (err != kErpcStatus_Success) diff --git a/erpcgen/test/test_expressions.yml b/erpcgen/test/test_expressions.yml index 6b3f5dcf..1d3ee2f6 100644 --- a/erpcgen/test/test_expressions.yml +++ b/erpcgen/test/test_expressions.yml @@ -15,7 +15,7 @@ idl: | const int32 a = 2 const int32 b = a * two + three -1 -test.h: +test_common.h: # named enums get a typedef - if: name then: diff --git a/erpcgen/test/test_extern_c.yml b/erpcgen/test/test_extern_c.yml index 6e778483..0b9d9575 100644 --- a/erpcgen/test/test_extern_c.yml +++ b/erpcgen/test/test_extern_c.yml @@ -2,7 +2,7 @@ name: extern c empty desc: do the extern "C" blocks get produced for empty input idl: "" -test.h: +test_common.h: - | #if defined(__cplusplus) extern "C" { @@ -19,7 +19,7 @@ idl: | interface Foo { foofn() -> void } -test.h: +test_common.h: - | #if defined(__cplusplus) extern "C" { diff --git a/erpcgen/test/test_forward_declaration_c.yml b/erpcgen/test/test_forward_declaration_c.yml index c39f0594..79b01021 100644 --- a/erpcgen/test/test_forward_declaration_c.yml +++ b/erpcgen/test/test_forward_declaration_c.yml @@ -1,42 +1,3 @@ ---- -name: struct before function -desc: forward declaration of structure before function which is using type. -params: - dir: - - "in" - - "out" -idl: - struct forwardStruct; - - oneway forwardCallback_t(forwardStruct s); - - struct forwardStruct - { - forwardCallback_t pCallback; /*!< Pointer to callback function */ - } - - interface foo - { - myFun({dir} forwardCallback_t pCallback1_t) -> void - - forwardCallback_t forwardCallback; - } - -test.h: - - typedef struct forwardStruct forwardStruct; - - typedef void (*forwardCallback_t)(const forwardStruct * s); - - - struct forwardStruct - - "{" - - forwardCallback_t pCallback; - - "};" -test_server.cpp: - - if: dir == 'in' - then: - - not: erpc_free(pCallback1_t); - else: - - erpc_free(pCallback1_t); - --- name: struct before struct desc: forward declaration of structure before structure which is using type. @@ -58,7 +19,7 @@ idl: myFun(in forwardStruct s) -> void } -test.h: +test_common.h: - typedef struct struct2 struct2; - typedef struct forwardStruct forwardStruct; @@ -102,7 +63,7 @@ idl: | { myFun(in forwardUnion u @discriminator(discriminator), unionCases discriminator) -> void } -test.h: +test_common.h: - typedef struct structure structure; - typedef union forwardUnion forwardUnion; diff --git a/erpcgen/test/test_import.yml b/erpcgen/test/test_import.yml index 03c4095c..ab41d3b9 100644 --- a/erpcgen/test/test_import.yml +++ b/erpcgen/test/test_import.yml @@ -4,10 +4,16 @@ desc: C/Py import test is the same. idl: | import "imports/test2.erpc" -test.h: +c_test_client.h: - void hello1(int32_t a); - void hello2(int32_t a); - void hello3(int32_t a); - void hello4(int32_t a); - void hello5(int32_t a); +c_test_server.h: + - void hello1(int32_t a); + - void hello2(int32_t a); + - void hello3(int32_t a); + - void hello4(int32_t a); + - void hello5(int32_t a); diff --git a/erpcgen/test/test_include.yml b/erpcgen/test/test_include.yml index c1d886b4..8bc3ece5 100644 --- a/erpcgen/test/test_include.yml +++ b/erpcgen/test/test_include.yml @@ -21,24 +21,5 @@ idl: | interface foo { bar(in string x) -> void } -test.h: +test_common.h: - '#include "stdio.h"' ---- -name: C include two interfaces -desc: -idl: | - program test; - - @include("stdio.h") - @include("stdio.h") - interface fooA { - barA(in string xA) -> void - } - - @include("stdio.h") - interface fooB { - barB(in string xB) -> void - } -test_server.cpp: - - '#include "stdio.h"' - - not: '#include "stdio.h"' \ No newline at end of file diff --git a/erpcgen/test/test_includes/test_includes_union.h b/erpcgen/test/test_includes/test_includes_union.h index 97cef1a0..01e78bea 100644 --- a/erpcgen/test/test_includes/test_includes_union.h +++ b/erpcgen/test/test_includes/test_includes_union.h @@ -6,10 +6,15 @@ * SPDX-License-Identifier: BSD-3-Clause */ -#include +#ifndef TEST_INCLUDES_UNION +#define TEST_INCLUDES_UNION + +#include typedef union unionType { int32_t x; float y; }unionType; + +#endif diff --git a/erpcgen/test/test_name_c.yml b/erpcgen/test/test_name_c.yml index 0354379c..4d4196bb 100644 --- a/erpcgen/test/test_name_c.yml +++ b/erpcgen/test/test_name_c.yml @@ -31,22 +31,27 @@ idl: | oneway functionName2(S a @name(m)) } -test.h: +test_common.h: - enum EnumName - D - struct StructName StructName - StructName type - struct StructName - int32_t d + +c_test_client.h: - function(const StructName * m) test_client.cpp: - write_StructName_struct - write_StructName_struct - data->d - - void function(const StructName * m) + - void I_client::function(const StructName * m) - write_StructName_struct(codec, m) - - void functionName2(const StructName * m) + - void I_client::functionName2(const StructName * m) + +c_test_server.h: + - function(const StructName * m) test_server.cpp: - read_StructName_struct @@ -58,5 +63,7 @@ test_server.cpp: - function(m); - erpc_free(m); - functionName2(m); + +c_test_server.cpp: + - ERPC_MANUALLY_CONSTRUCTED_STATIC(I_service, s_I_service); - create_I_service - - s_I_service diff --git a/erpcgen/test/test_nullable_c.yml b/erpcgen/test/test_nullable_c.yml index c60c69cc..1ee80060 100644 --- a/erpcgen/test/test_nullable_c.yml +++ b/erpcgen/test/test_nullable_c.yml @@ -11,7 +11,7 @@ idl: | bar({dir} string a @nullable @max_length(8)) -> void } test_client.cpp: - - re: void bar\(\w*\s*char \* a\) + - re: void foo_client::bar\(\w*\s*char \* a\) - if (a == NULL) - codec->writeNullFlag(true) - if: dir in ('in', 'inout') @@ -58,7 +58,7 @@ idl: | bar({dir} ustring a @nullable @max_length(8)) -> void } test_client.cpp: - - re: void bar\(\w*\s*unsigned\s*char\s*\* a\) + - re: void foo_client::bar\(\w*\s*unsigned\s*char\s*\* a\) - if (a == NULL) - codec->writeNullFlag(true) - if: dir in ('in', 'inout') @@ -113,11 +113,12 @@ idl: | interface foo { bar(Vector v @nullable) -> void } -test.h: +test_common.h: - '{type[1]} v[3]' +c_test_client.h: - void bar(const Vector * v); test_client.cpp: - - re: void bar\(const Vector \* v\) + - re: void foo_client::bar\(const Vector \* v\) - if (v == NULL) - writeNullFlag(true) - "{" @@ -152,7 +153,7 @@ test_client.cpp: - writeNullFlag(false) - write_list_bool_1_t_struct - '}' - - void bar(const erpc_pair * s) + - void foo_client::bar(const erpc_pair * s) - write_erpc_pair_struct test_server.cpp: - void read_erpc_pair_struct @@ -182,7 +183,7 @@ test_client.cpp: - writeNullFlag(false) - write_binary_t_struct - '}' - - void bar(const erpc_pair * s) + - void foo_client::bar(const erpc_pair * s) - write_erpc_pair_struct test_server.cpp: - void read_erpc_pair_struct @@ -339,9 +340,9 @@ idl: | test_client.cpp: - if: dir == 'inout' then: - - void bar(const bool * l, uint32_t * c) + - void foo_client::bar(const bool * l, uint32_t * c) else: - - void bar(const bool * l, uint32_t c) + - void foo_client::bar(const bool * l, uint32_t c) - if: dir == 'inout' and ann == '@nullable' then: - if ((l == NULL) || (c == NULL)) @@ -404,7 +405,7 @@ idl: | } test_client.cpp: - - void bar(bool * l, uint32_t * c) + - void foo_client::bar(bool * l, uint32_t * c) - if: ann == '@nullable' then: - if ((l == NULL) || (c == NULL)) diff --git a/erpcgen/test/test_redundant_definitions.yml b/erpcgen/test/test_redundant_definitions.yml index ea947b13..230f77dd 100644 --- a/erpcgen/test/test_redundant_definitions.yml +++ b/erpcgen/test/test_redundant_definitions.yml @@ -40,7 +40,7 @@ idl: | interface foo { bar(in Vector vector_x, out Wector vector_y) -> void } -test.h: +test_common.h: - typedef struct Vector Vector - typedef struct Wector Wector - struct Vector @@ -50,7 +50,7 @@ test_server.cpp: - read_Vector_struct - not: read_Wector_struct - write_Wector_struct -test_client.cpp: +test_client.cpp: - write_Vector_struct - not: read_Vector_struct - read_Wector_struct @@ -124,44 +124,52 @@ idl: | interface fooA { barA(out Vector vector_x, in Wector vector_y) -> void } -test.h: +test_common.h: - typedef struct Vector Vector - typedef struct Wector Wector - typedef struct NoGroup NoGroup; - struct Vector - struct Wector - struct NoGroup +c_test_server.h: - enum _foo_ids - void bar(const NoGroup * noGroup_z) test_server.cpp: - read_NoGroup_struct - not: write_NoGroup_struct - - not: Vector_struct + - not: Vector_struct - not: Wector_struct - foo_service::bar_shim -test_client.cpp: +c_test_client.h: + - enum _foo_ids + - void bar(const NoGroup * noGroup_z) +test_client.cpp: - not: read_NoGroup_struct - write_NoGroup_struct - - not: Vector_struct + - not: Vector_struct - not: Wector_struct - bar(const NoGroup * noGroup_z) -test_A.h: +test_A_common.h: - typedef struct Vector Vector - typedef struct Wector Wector - typedef struct NoGroup NoGroup; - struct Vector - struct Wector - struct NoGroup +c_test_A_server.h: - enum _fooA_ids - void barA(Vector * vector_x, const Wector * vector_y) -test_A_server.cpp: +test_A_server.cpp: - read_Wector_struct - not: write_Wector_struct - write_Vector_struct - not: read_Vector_struct - not: NoGroup_struct - fooA_service::barA_shim -test_A_client.cpp: +c_test_A_client.h: + - enum _fooA_ids + - void barA(Vector * vector_x, const Wector * vector_y) +test_A_client.cpp: - write_Wector_struct - not: read_Wector_struct - read_Vector_struct @@ -200,14 +208,14 @@ idl: | interface foo_B { bar_B(out VectorB b) -> void } -test.h: +test_A_common.h: - typedef struct VectorA VectorA - typedef struct VectorB VectorB - struct VectorA - struct VectorB - not: bar_A(const VectorA * a) - not: bar_AA(const VectorA * aa, VectorB * bb) -test_A.h: +c_test_A_client.h: - not: typedef - bar_A(const VectorA * a) - bar_AA(const VectorA * aa, VectorB * bb) @@ -216,10 +224,10 @@ test_A_server.cpp: - write_VectorB_struct - not: write_VectorA_struct - not: read_VectorB_struct -test_B.h: +c_test_B_client.h: - not: typedef - bar_B(VectorB * b) -test_B_server.cpp: +test_B_server.cpp: - write_VectorB_struct - not: read_VectorB_struct - not: VectorA_struct @@ -235,4 +243,4 @@ test_B_server.cpp: # interface foo { # bar(zz discriminator, Scalar scalar_y @discriminator(discriminator)) -> void -# } \ No newline at end of file +# } diff --git a/erpcgen/test/test_scope_c.yml b/erpcgen/test/test_scope_c.yml index e9775256..b0d20a20 100644 --- a/erpcgen/test/test_scope_c.yml +++ b/erpcgen/test/test_scope_c.yml @@ -5,7 +5,7 @@ idl: | interface test { bar(int32 x) -> void } -test.h: +test_common.h: - | #if !defined(ERPC_TYPE_DEFINITIONS_ERPCSHIM) #define ERPC_TYPE_DEFINITIONS_ERPCSHIM @@ -21,7 +21,7 @@ idl: | interface test { bar(int32 x) -> void } -test.h: +test_common.h: - | #if !defined(ERPC_TYPE_DEFINITIONS_TEST) #define ERPC_TYPE_DEFINITIONS_TEST @@ -38,7 +38,7 @@ idl: | interface test { bar(int32 x) -> void } -test.h: +test_common.h: - | #if !defined(ERPC_TYPE_DEFINITIONS_MYSCOPE) #define ERPC_TYPE_DEFINITIONS_MYSCOPE @@ -55,7 +55,7 @@ idl: | interface test { bar(int32 x) -> void } -test.h: +test_common.h: - | #if !defined(ERPC_TYPE_DEFINITIONS) #define ERPC_TYPE_DEFINITIONS diff --git a/erpcgen/test/test_service_c.yml b/erpcgen/test/test_service_c.yml index 5865cfac..5446b86f 100644 --- a/erpcgen/test/test_service_c.yml +++ b/erpcgen/test/test_service_c.yml @@ -8,17 +8,18 @@ idl: | oneway f() } -test_server.h: +c_test_server.h: - erpc_service_t create_ErrorTest_service(void); - void destroy_ErrorTest_service(erpc_service_t service); -test_server.cpp: +c_test_server.cpp: - ERPC_MANUALLY_CONSTRUCTED_STATIC(ErrorTest_service, s_ErrorTest_service); + - ERPC_MANUALLY_CONSTRUCTED_STATIC(ErrorTest_server, s_ErrorTest_server); - erpc_service_t create_ErrorTest_service(void) - "{" - erpc_service_t service; - "#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC" - - service = new (nothrow) ErrorTest_service(); + - service = new (nothrow) ErrorTest_service(new (nothrow)ErrorTest_server()); - "#else" - if (s_ErrorTest_service.isUsed()) - "{" @@ -26,7 +27,8 @@ test_server.cpp: - "}" - else - "{" - - s_ErrorTest_service.construct(); + - s_ErrorTest_server.construct(); + - s_ErrorTest_service.construct(s_ErrorTest_server.get()); - service = s_ErrorTest_service.get(); - "}" - "#endif" @@ -35,11 +37,15 @@ test_server.cpp: - void destroy_ErrorTest_service(erpc_service_t service) - "{" - "#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC" - - erpc_assert(service != NULL); + - if (service) + - "{" + - delete (ErrorTest_server *)(((ErrorTest_service *)service)->getHandler()); - delete (ErrorTest_service *)service; + - "}" - "#else" - (void)service; - erpc_assert(service == s_ErrorTest_service.get()); - s_ErrorTest_service.destroy(); + - s_ErrorTest_server.destroy(); - "#endif" - "}" diff --git a/erpcgen/test/test_struct.yml b/erpcgen/test/test_struct.yml index afb5f5ce..b376b48f 100644 --- a/erpcgen/test/test_struct.yml +++ b/erpcgen/test/test_struct.yml @@ -20,7 +20,7 @@ idl: | interface B { testF(inout A b) ->void } -test.h: +test_common.h: - typedef struct A A; - struct A - if: type in ('bool', 'float', 'double') @@ -41,7 +41,7 @@ idl: | interface foo { bar(ListType x) -> ListType } -test.h: +test_common.h: - typedef struct list_int32_1_t list_int32_1_t; - typedef list_int32_1_t ListType; - struct list_int32_1_t @@ -52,7 +52,7 @@ test_client.cpp: - read_list_int32_1_t_struct - if(NULL == data) - return; - - ListType * bar(const ListType * x) + - ListType * foo_client::bar(const ListType * x) test_server.cpp: - read_list_int32_1_t_struct - if(NULL == data) @@ -72,7 +72,7 @@ idl: | interface foo { bar(Vector x, binary y) -> void } -test.h: +test_common.h: - typedef struct binary_t binary_t; - typedef struct Vector Vector; - struct binary_t @@ -97,7 +97,7 @@ idl: | foo(Vector a) -> void bar() -> Vector } -test.h: +test_common.h: - typedef struct binary_t binary_t; - typedef struct Vector Vector; - struct binary_t diff --git a/erpcgen/test/test_types_header.yml b/erpcgen/test/test_types_header.yml deleted file mode 100644 index 97b461b9..00000000 --- a/erpcgen/test/test_types_header.yml +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: types header file -desc: places all type definitions into separate header file "test_types.h" -idl: | - @types_header("test_types.h") - program test - - struct Vector { - int8 a - int16 b - int32 c - } - - interface test { - bar(Vector x) -> void - } -test.h: - - '#include "test_types.h"' - - not: // Aliases data types declarations - - not: typedef struct Vector Vector; - - not: // Structures data types declarations - - not: struct Vector - - void bar(const Vector * x); -test_types.h: - - '#if !defined(_test_types_h_)' - - '#include ' - - '#include ' - - '#include ' - - // Aliases data types declarations - - typedef struct Vector Vector; - - // Structures/unions data types declarations - - struct Vector - - not: void bar(const Vector * x); diff --git a/erpcgen/test/test_union_c.yml b/erpcgen/test/test_union_c.yml index 2673fa9f..04b04e78 100644 --- a/erpcgen/test/test_union_c.yml +++ b/erpcgen/test/test_union_c.yml @@ -21,7 +21,7 @@ idl: | myUnion(fruitType discriminator, unionType unionVariable @discriminator(discriminator)) -> void } -test.h: +test_common.h: - not: typedef union unionType unionType; - not: union unionType - not: int32 x; @@ -72,7 +72,7 @@ idl: | myUnion(fruitType discriminator, unionType unionVariable @discriminator(discriminator)) -> void } -test.h: +test_common.h: - typedef union unionType unionType; - union unionType - "{" @@ -95,6 +95,8 @@ test.h: - int32_t blah; - "};" - "};" + +c_test_client.h: - void myUnion(fruitType discriminator, const unionType * unionVariable); test_client.cpp: @@ -146,10 +148,12 @@ test_client.cpp: - break; - "}" - "}" - - void myUnion(fruitType discriminator, const unionType * unionVariable) + - void foo_client::myUnion(fruitType discriminator, const unionType * unionVariable) - not: codec->read(static_cast(discriminator)); - write_unionType_union(codec, static_cast(discriminator), unionVariable) +c_test_server.h: + - void myUnion(fruitType discriminator, const unionType * unionVariable); test_server.cpp: - static void read_unionType_union(erpc::Codec * codec, int32_t & discriminator, unionType * data); @@ -268,15 +272,20 @@ idl: | myUnion(structType structVariable) -> void } -test.h: +test_common.h: - struct structType - fruitType discriminator - unionType unionVariable + +c_test_client.h: - void myUnion(const structType * structVariable); test_client.cpp: - write_unionType_union(codec, static_cast(data->discriminator), &data->unionVariable); +c_test_server.h: + - void myUnion(const structType * structVariable); + test_server.cpp: - int32_t _tmp_local_i32; - read_unionType_union(codec, _tmp_local_i32, &data->unionVariable); diff --git a/erpcsniffer/src/Sniffer.cpp b/erpcsniffer/src/Sniffer.cpp index 16e25c8f..b517280c 100644 --- a/erpcsniffer/src/Sniffer.cpp +++ b/erpcsniffer/src/Sniffer.cpp @@ -667,7 +667,7 @@ string Sniffer::getDataTypeName(DataType *dataType) } } -string Sniffer::getPrototype(erpcgen::Function *function) +string Sniffer::getPrototype(Function *function) { string prototype = getDataTypeName(function->getReturnType()); if (function->isOneway()) diff --git a/erpcsniffer/src/erpcsniffer.cpp b/erpcsniffer/src/erpcsniffer.cpp index 361080d8..342e6a12 100644 --- a/erpcsniffer/src/erpcsniffer.cpp +++ b/erpcsniffer/src/erpcsniffer.cpp @@ -118,11 +118,11 @@ class erpcsnifferTool const char *m_outputFilePath; /*!< Path to the output file. */ const char *m_ErpcFile; /*!< ERPC file. */ string_vector_t m_positionalArgs; - transports_t m_transport; /*!< Transport used for receiving messages. */ - uint64_t m_quantity; /*!< Quantity of logs to store. */ - uint32_t m_baudrate; /*!< Baudrate rate speed. */ - const char *m_port; /*!< Name or number of port. Based on used transport. */ - const char *m_host; /*!< Host name */ + transports_t m_transport; /*!< Transport used for receiving messages. */ + uint64_t m_quantity; /*!< Quantity of logs to store. */ + uint32_t m_baudrate; /*!< Baudrate rate speed. */ + const char *m_port; /*!< Name or number of port. Based on used transport. */ + const char *m_host; /*!< Host name */ public: /*! @@ -225,7 +225,7 @@ class erpcsnifferTool } else { - Log::error(format_string("error: unknown transport type %s", transport.c_str()).c_str()); + Log::error("error: unknown transport type %s", transport.c_str()); return 1; } break; diff --git a/run_tests.sh b/run_tests.sh index a98162bd..a523782c 100755 --- a/run_tests.sh +++ b/run_tests.sh @@ -7,10 +7,11 @@ make clean if [ "$1" = "clang" ]; then echo "Compiling by clang compiler." CC=clang CXX=clang++ make all + python3 test/run_unit_tests.py clang else echo "Compiling by default gnu compiler." CC=gcc CXX=g++ make all + python3 test/run_unit_tests.py gcc fi pytest erpcgen/test/ -python3 test/run_unit_tests.py diff --git a/test/common/gtestListener.hpp b/test/common/gtestListener.hpp index 8ceed314..1c64134f 100644 --- a/test/common/gtestListener.hpp +++ b/test/common/gtestListener.hpp @@ -10,9 +10,9 @@ #ifndef _EMBEDDED_RPC__GTESTLISTENER_H_ #define _EMBEDDED_RPC__GTESTLISTENER_H_ +#include "c_test_unit_test_common_client.h" #include "gtest.h" #include "myAlloc.hpp" -#include "test_unit_test_common.h" //////////////////////////////////////////////////////////////////////////////// // Classes @@ -26,10 +26,10 @@ class LeakChecker : public ::testing::EmptyTestEventListener { int serverAlloc = getServerAllocated(); - EXPECT_EQ(MyAlloc::allocated(), 0) - << "Leaked (on client side) : " << MyAlloc::allocated() << " unit(s) need be freed!"; + EXPECT_EQ(::MyAlloc::allocated(), 0) + << "Leaked (on client side) : " << ::MyAlloc::allocated() << " unit(s) need be freed!"; EXPECT_EQ(serverAlloc, 0) << "Leaked (on server side) : " << serverAlloc << " unit(s) need be freed!"; - MyAlloc::allocated(0); + ::MyAlloc::allocated(0); } }; diff --git a/test/common/myAlloc.hpp b/test/common/myAlloc.hpp index ad30476d..b2d11bdc 100644 --- a/test/common/myAlloc.hpp +++ b/test/common/myAlloc.hpp @@ -10,6 +10,8 @@ #ifndef _EMBEDDED_RPC__MYALLOC_H_ #define _EMBEDDED_RPC__MYALLOC_H_ +#if defined(__cplusplus) + #include "erpc_port.h" //////////////////////////////////////////////////////////////////////////////// @@ -38,15 +40,13 @@ class MyAlloc static int allocated_; }; -namespace std { -using ::MyAlloc; -} - //////////////////////////////////////////////////////////////////////////////// // Definitions //////////////////////////////////////////////////////////////////////////////// -#define erpc_malloc(X) MyAlloc::my_malloc(X) -#define erpc_free(X) MyAlloc::my_free((X)) +#define erpc_malloc(X) ::MyAlloc::my_malloc(X) +#define erpc_free(X) ::MyAlloc::my_free((X)) + +#endif // __cplusplus #endif // _EMBEDDED_RPC__MYALLOC_H_ diff --git a/test/common/unit_test_arbitrator_app0.cpp b/test/common/unit_test_arbitrator_app0.cpp index a15b6ad5..ee20aa6e 100644 --- a/test/common/unit_test_arbitrator_app0.cpp +++ b/test/common/unit_test_arbitrator_app0.cpp @@ -12,11 +12,12 @@ #include "erpc_transport_setup.h" #include "FreeRTOS.h" -#include "gtest.h" #include "semphr.h" #include "task.h" -#include "test_firstInterface.h" -#include "test_secondInterface_server.h" + +#include "c_test_firstInterface_client.h" +#include "c_test_secondInterface_server.h" +#include "gtest.h" #include "unit_test.h" #ifdef __cplusplus @@ -237,8 +238,8 @@ int main(void) { int fake_argc = 1; const auto fake_arg0 = "dummy"; - char* fake_argv0 = const_cast(fake_arg0); - char** fake_argv = &fake_argv0; + char *fake_argv0 = const_cast(fake_arg0); + char **fake_argv = &fake_argv0; ::testing::InitGoogleTest(&fake_argc, fake_argv); BOARD_InitHardware(); @@ -271,6 +272,7 @@ int main(void) } } +extern "C" { void quitSecondInterfaceServer() { /* removing the service from the server */ @@ -281,3 +283,4 @@ void quitSecondInterfaceServer() erpc_server_stop(server); increaseWaitQuit(); } +} diff --git a/test/common/unit_test_arbitrator_app1.cpp b/test/common/unit_test_arbitrator_app1.cpp index 5d81c78b..24720b7d 100644 --- a/test/common/unit_test_arbitrator_app1.cpp +++ b/test/common/unit_test_arbitrator_app1.cpp @@ -14,8 +14,9 @@ #include "FreeRTOS.h" #include "semphr.h" #include "task.h" -#include "test_firstInterface_server.h" -#include "test_secondInterface.h" + +#include "c_test_firstInterface_server.h" +#include "c_test_secondInterface_client.h" #include "unit_test.h" #ifdef __cplusplus @@ -206,6 +207,7 @@ int main(void) } } +extern "C" { void stopSecondSide() { ++stopTest; @@ -252,3 +254,4 @@ int testClient() } return 0; } +} diff --git a/test/common/unit_test_client.cpp b/test/common/unit_test_client.cpp index 09830b11..e685f6cc 100644 --- a/test/common/unit_test_client.cpp +++ b/test/common/unit_test_client.cpp @@ -26,10 +26,12 @@ int main(void); } #include "board.h" + +#include "c_test_unit_test_common_client.h" #include "gtest.h" #include "gtestListener.hpp" #include "myAlloc.hpp" -#include "test_unit_test_common.h" +#include "unit_test_wrapped.h" #ifdef UNITY_DUMP_RESULTS #include "corn_g_test.h" @@ -83,7 +85,7 @@ class MinimalistPrinter : public ::testing::EmptyTestEventListener // Definitions //////////////////////////////////////////////////////////////////////////////// -int MyAlloc::allocated_ = 0; +int ::MyAlloc::allocated_ = 0; #if defined(RPMSG) #define APP_ERPC_READY_EVENT_DATA (1) @@ -111,8 +113,8 @@ int main(void) { int fake_argc = 1; const auto fake_arg0 = "dummy"; - char* fake_argv0 = const_cast(fake_arg0); - char** fake_argv = &fake_argv0; + char *fake_argv0 = const_cast(fake_arg0); + char **fake_argv = &fake_argv0; ::testing::InitGoogleTest(&fake_argc, fake_argv); ::testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners(); @@ -191,6 +193,8 @@ int main(void) #endif client = erpc_client_init(transport, message_buffer_factory); + initInterfaces_common(client); + initInterfaces(client); int i = RUN_ALL_TESTS(); quit(); @@ -204,3 +208,8 @@ int main(void) return i; } + +void initInterfaces_common(erpc_client_t client) +{ + initCommon_client(client); +} diff --git a/test/common/unit_test_serial_client.cpp b/test/common/unit_test_serial_client.cpp index 38c37c35..57b31d96 100644 --- a/test/common/unit_test_serial_client.cpp +++ b/test/common/unit_test_serial_client.cpp @@ -11,10 +11,11 @@ #include "erpc_serial_transport.hpp" #include "Logging.hpp" +#include "c_test_unit_test_common_client.h" #include "gtest.h" #include "gtestListener.hpp" #include "myAlloc.hpp" -#include "test_unit_test_common.h" +#include "unit_test_wrapped.h" using namespace erpc; @@ -42,7 +43,7 @@ MyMessageBufferFactory g_msgFactory; BasicCodecFactory g_basicCodecFactory; ClientManager *g_client; -int MyAlloc::allocated_ = 0; +int ::MyAlloc::allocated_ = 0; //////////////////////////////////////////////////////////////////////////////// // Set up global fixture @@ -69,6 +70,9 @@ int main(int argc, char **argv) g_client->setMessageBufferFactory(&g_msgFactory); g_client->setTransport(&g_transport); g_client->setCodecFactory(&g_basicCodecFactory); + erpc_client_t client = reinterpret_cast(g_client); + initInterfaces_common(client); + initInterfaces(client); int ret = RUN_ALL_TESTS(); quit(); @@ -78,6 +82,11 @@ int main(int argc, char **argv) return ret; } +void initInterfaces_common(erpc_client_t client) +{ + initCommon_client(client); +} + //////////////////////////////////////////////////////////////////////////////// // EOF //////////////////////////////////////////////////////////////////////////////// diff --git a/test/common/unit_test_serial_server.cpp b/test/common/unit_test_serial_server.cpp index 0dc4f61e..b6969c32 100644 --- a/test/common/unit_test_serial_server.cpp +++ b/test/common/unit_test_serial_server.cpp @@ -11,13 +11,15 @@ #include "erpc_simple_server.hpp" #include "Logging.hpp" +#include "c_test_unit_test_common_server.h" #include "myAlloc.hpp" -#include "test_unit_test_common_server.h" +#include "test_unit_test_common_server.hpp" #include "unit_test.h" #include using namespace erpc; +using namespace erpcShim; class MyMessageBufferFactory : public MessageBufferFactory { @@ -43,7 +45,7 @@ MyMessageBufferFactory g_msgFactory; BasicCodecFactory g_basicCodecFactory; SimpleServer g_server; -int MyAlloc::allocated_ = 0; +int ::MyAlloc::allocated_ = 0; Common_service *svc_common; @@ -78,12 +80,43 @@ int main(int argc, const char *argv[]) return 0; } +//////////////////////////////////////////////////////////////////////////////// +// Common service implementations here +//////////////////////////////////////////////////////////////////////////////// +void quit() +{ + remove_common_service(&g_server); + remove_services(&g_server); + exit(0); +} + +int32_t getServerAllocated() +{ + int result = ::MyAlloc::allocated(); + ::MyAlloc::allocated(0); + return result; +} + +class Common_server : public Common_interface +{ +public: + void quit(void) { ::quit(); } + + int32_t getServerAllocated(void) + { + int32_t result; + result = ::getServerAllocated(); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Server helper functions //////////////////////////////////////////////////////////////////////////////// void add_common_service(SimpleServer *server) { - svc_common = new Common_service(); + svc_common = new Common_service(new Common_server()); server->addService(svc_common); } @@ -91,28 +124,13 @@ void add_common_service(SimpleServer *server) void remove_common_service(SimpleServer *server) { server->removeService(svc_common); + delete svc_common->getHandler(); delete svc_common; } extern "C" void erpc_add_service_to_server(void *service) {} extern "C" void erpc_remove_service_from_server(void *service) {} -//////////////////////////////////////////////////////////////////////////////// -// Common service implementations here -//////////////////////////////////////////////////////////////////////////////// -void quit() -{ - remove_common_service(&g_server); - remove_services(&g_server); - exit(0); -} - -int32_t getServerAllocated() -{ - int result = MyAlloc::allocated(); - MyAlloc::allocated(0); - return result; -} //////////////////////////////////////////////////////////////////////////////// // EOF //////////////////////////////////////////////////////////////////////////////// diff --git a/test/common/unit_test_server.cpp b/test/common/unit_test_server.cpp index c10dda3a..7c54afa8 100644 --- a/test/common/unit_test_server.cpp +++ b/test/common/unit_test_server.cpp @@ -15,6 +15,7 @@ extern "C" { #if defined(UART) #include "fsl_lpuart_cmsis.h" + #include "app_core0.h" #else #if defined(RPMSG) @@ -22,6 +23,7 @@ extern "C" { #endif #define APP_ERPC_READY_EVENT_DATA (1) #include "mcmgr.h" + #include "app_core1.h" #endif #if defined(__CC_ARM) || defined(__ARMCC_VERSION) @@ -31,15 +33,16 @@ int main(void); #endif #include "board.h" + +#include "c_test_unit_test_common_server.h" #include "myAlloc.hpp" -#include "test_unit_test_common_server.h" #include "unit_test_wrapped.h" //////////////////////////////////////////////////////////////////////////////// // Variables //////////////////////////////////////////////////////////////////////////////// -int MyAlloc::allocated_ = 0; +int ::MyAlloc::allocated_ = 0; erpc_service_t service_common = NULL; erpc_server_t server; @@ -117,6 +120,12 @@ void add_common_service(erpc_server_t server) erpc_add_service_to_server(server, service_common); } +void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) +{ + erpc_remove_service_from_server(server, service); + destroy_Common_service(service); +} + //////////////////////////////////////////////////////////////////////////////// // Common service implementations here //////////////////////////////////////////////////////////////////////////////// @@ -134,7 +143,7 @@ void quit() int32_t getServerAllocated() { - int result = MyAlloc::allocated(); - MyAlloc::allocated(0); + int result = ::MyAlloc::allocated(); + ::MyAlloc::allocated(0); return result; } diff --git a/test/common/unit_test_tcp_arbitrator_client.cpp b/test/common/unit_test_tcp_arbitrator_client.cpp index 0c1330a1..f29664d3 100644 --- a/test/common/unit_test_tcp_arbitrator_client.cpp +++ b/test/common/unit_test_tcp_arbitrator_client.cpp @@ -13,13 +13,14 @@ #include "erpc_transport_arbitrator.hpp" #include "Logging.hpp" +#include "c_test_firstInterface_client.h" +#include "c_test_unit_test_common_client.h" #include "gtest.h" -#include "test_firstInterface.h" -#include "test_secondInterface.h" #include "unit_test.h" +#include "unit_test_wrapped.h" + #include #include - #include using namespace erpc; @@ -154,6 +155,8 @@ int main(int argc, char **argv) add_services(&g_server); g_client->setServer(&g_server); + erpc_client_t client = reinterpret_cast(g_client); + initInterfaces(client); int i = -1; err = (erpc_status_t)-1; @@ -190,6 +193,7 @@ int main(int argc, char **argv) return i; } +extern "C" { void quitSecondInterfaceServer() { // removing SecondInterface service from the server @@ -198,3 +202,4 @@ void quitSecondInterfaceServer() g_server.stop(); increaseWaitQuit(); } +} diff --git a/test/common/unit_test_tcp_arbitrator_server.cpp b/test/common/unit_test_tcp_arbitrator_server.cpp index d196b0b4..b1956165 100644 --- a/test/common/unit_test_tcp_arbitrator_server.cpp +++ b/test/common/unit_test_tcp_arbitrator_server.cpp @@ -13,10 +13,10 @@ #include "erpc_transport_arbitrator.hpp" #include "Logging.hpp" +#include "c_test_secondInterface_server.h" #include "myAlloc.hpp" -#include "test_firstInterface.h" -#include "test_secondInterface.h" #include "unit_test.h" +#include "unit_test_wrapped.h" #include @@ -146,6 +146,8 @@ int main(int argc, char **argv) g_server.setMessageBufferFactory(&g_msgFactory); add_services(&g_server); g_client->setServer(&g_server); + erpc_client_t client = reinterpret_cast(g_client); + initInterfaces(client); err = (erpc_status_t)-1; @@ -181,6 +183,7 @@ int main(int argc, char **argv) return isTestPassing; } +extern "C" { void stopSecondSide() { ++stopTest; @@ -208,6 +211,7 @@ void whenReady() { waitClient++; } +} int testClient() { diff --git a/test/common/unit_test_tcp_client.cpp b/test/common/unit_test_tcp_client.cpp index 0dca069c..403873b4 100644 --- a/test/common/unit_test_tcp_client.cpp +++ b/test/common/unit_test_tcp_client.cpp @@ -11,10 +11,11 @@ #include "erpc_tcp_transport.hpp" #include "Logging.hpp" +#include "c_test_unit_test_common_client.h" #include "gtest.h" #include "gtestListener.hpp" #include "myAlloc.hpp" -#include "test_unit_test_common.h" +#include "unit_test_wrapped.h" using namespace erpc; @@ -47,7 +48,7 @@ ClientManager *g_client; Crc16 g_crc16; -int MyAlloc::allocated_ = 0; +int ::MyAlloc::allocated_ = 0; //////////////////////////////////////////////////////////////////////////////// // Set up global fixture @@ -90,6 +91,9 @@ int main(int argc, char **argv) #if USE_MESSAGE_LOGGING g_client->addMessageLogger(&g_messageLogger); #endif // USE_MESSAGE_LOGGING + erpc_client_t client = reinterpret_cast(g_client); + initInterfaces_common(client); + initInterfaces(client); int ret = RUN_ALL_TESTS(); quit(); @@ -100,6 +104,11 @@ int main(int argc, char **argv) return ret; } +void initInterfaces_common(erpc_client_t client) +{ + initCommon_client(client); +} + //////////////////////////////////////////////////////////////////////////////// // EOF //////////////////////////////////////////////////////////////////////////////// diff --git a/test/common/unit_test_tcp_server.cpp b/test/common/unit_test_tcp_server.cpp index d689d380..fb732ee6 100644 --- a/test/common/unit_test_tcp_server.cpp +++ b/test/common/unit_test_tcp_server.cpp @@ -11,11 +11,13 @@ #include "erpc_tcp_transport.hpp" #include "Logging.hpp" +#include "c_test_unit_test_common_server.h" #include "myAlloc.hpp" -#include "test_unit_test_common_server.h" +#include "test_unit_test_common_server.hpp" #include "unit_test.h" using namespace erpc; +using namespace erpcShim; class MyMessageBufferFactory : public MessageBufferFactory { @@ -43,7 +45,7 @@ SimpleServer g_server; Crc16 g_crc16; -int MyAlloc::allocated_ = 0; +int ::MyAlloc::allocated_ = 0; Common_service *svc_common; @@ -87,12 +89,43 @@ int main(int argc, const char *argv[]) return 0; } +//////////////////////////////////////////////////////////////////////////////// +// Common service implementations here +//////////////////////////////////////////////////////////////////////////////// +void quit() +{ + remove_common_service(&g_server); + remove_services(&g_server); + g_server.stop(); +} + +int32_t getServerAllocated() +{ + int result = ::MyAlloc::allocated(); + ::MyAlloc::allocated(0); + return result; +} + +class Common_server : public Common_interface +{ +public: + void quit(void) { ::quit(); } + + int32_t getServerAllocated(void) + { + int32_t result; + result = ::getServerAllocated(); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Server helper functions //////////////////////////////////////////////////////////////////////////////// void add_common_service(SimpleServer *server) { - svc_common = new Common_service(); + svc_common = new Common_service(new Common_server()); server->addService(svc_common); } @@ -100,28 +133,13 @@ void add_common_service(SimpleServer *server) void remove_common_service(SimpleServer *server) { server->removeService(svc_common); + delete svc_common->getHandler(); delete svc_common; } extern "C" void erpc_add_service_to_server(void *service) {} extern "C" void erpc_remove_service_from_server(void *service) {} -//////////////////////////////////////////////////////////////////////////////// -// Common service implementations here -//////////////////////////////////////////////////////////////////////////////// -void quit() -{ - remove_common_service(&g_server); - remove_services(&g_server); - g_server.stop(); -} - -int32_t getServerAllocated() -{ - int result = MyAlloc::allocated(); - MyAlloc::allocated(0); - return result; -} //////////////////////////////////////////////////////////////////////////////// // EOF //////////////////////////////////////////////////////////////////////////////// diff --git a/test/common/unit_test_wrapped.h b/test/common/unit_test_wrapped.h index 72c386ce..21f38dbf 100644 --- a/test/common/unit_test_wrapped.h +++ b/test/common/unit_test_wrapped.h @@ -9,13 +9,20 @@ #ifndef _EMBEDDED_RPC__UNIT_TEST_WRAPPED_H_ #define _EMBEDDED_RPC__UNIT_TEST_WRAPPED_H_ +#include "erpc_client_manager.h" +#include "erpc_server_setup.h" + //////////////////////////////////////////////////////////////////////////////// // Function Prototypes //////////////////////////////////////////////////////////////////////////////// +typedef void *erpc_service_t; #ifdef __cplusplus extern "C" { #endif +void initInterfaces(erpc_client_t client); +void initInterfaces_common(erpc_client_t client); + void add_services_to_server(erpc_server_t server); void remove_services_from_server(erpc_server_t server); void remove_common_services_from_server(erpc_server_t server, erpc_service_t service); diff --git a/test/mk/erpc_src.mk b/test/mk/erpc_src.mk index ace22ad9..fbaa7788 100644 --- a/test/mk/erpc_src.mk +++ b/test/mk/erpc_src.mk @@ -44,6 +44,7 @@ SOURCES += $(UT_COMMON_SRC)/addOne.cpp \ $(ERPC_C_ROOT)/infra/erpc_message_buffer.cpp \ $(ERPC_C_ROOT)/infra/erpc_message_loggers.cpp \ $(ERPC_C_ROOT)/infra/erpc_transport_arbitrator.cpp \ + $(ERPC_C_ROOT)/infra/erpc_utils.cpp \ $(ERPC_C_ROOT)/port/erpc_port_stdlib.cpp \ $(ERPC_C_ROOT)/port/erpc_threading_pthreads.cpp \ $(ERPC_C_ROOT)/transports/erpc_tcp_transport.cpp diff --git a/test/mk/test.mk b/test/mk/test.mk index 8853482b..028524db 100644 --- a/test/mk/test.mk +++ b/test/mk/test.mk @@ -45,7 +45,7 @@ UNIT_OUT_DIR = $(OUTPUT_ROOT)/$(DEBUG_OR_RELEASE)/$(os_name)/test/ ERPC_NAME ?= test ERPC_NAME_APP ?= $(ERPC_NAME) -TEST_DIR = $(OUTPUT_ROOT)/test/$(TEST_NAME)/$(os_name)/$(TRANSPORT)/gcc/$(TEST_NAME)_$(APP_TYPE)/$(DEBUG_OR_RELEASE) +TEST_DIR = $(OUTPUT_ROOT)/test/$(TEST_NAME)/$(os_name)/$(TRANSPORT)/$(CC)/$(TEST_NAME)_$(APP_TYPE)/$(DEBUG_OR_RELEASE) RPC_OBJS_ROOT = $(TEST_DIR) TARGET_OUTPUT_ROOT = $(RPC_OBJS_ROOT) @@ -75,12 +75,16 @@ INCLUDES += $(TARGET_OUTPUT_ROOT) \ #------------------------------- IDL_FILE = $(CUR_DIR).erpc -ifneq "$(TEST_NAME)" "test_arbitrator" +ifeq (,$(filter $(TEST_NAME),test_arbitrator test_callbacks)) INCLUDES += $(ERPC_ROOT)/test/common/config SOURCES += $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_$(APP_TYPE).cpp \ $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_interface.cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME_APP)_$(APP_TYPE).cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp \ $(CUR_DIR)_$(APP_TYPE)_impl.cpp \ $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_$(APP_TYPE).cpp @@ -91,7 +95,7 @@ all: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAM # Define dependency. $(OUTPUT_ROOT)/test/$(TEST_NAME)/$(CUR_DIR)_$(APP_TYPE)_impl.cpp: $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_$(APP_TYPE).cpp $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_$(APP_TYPE).cpp -$(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_interface.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/c_$(ERPC_NAME_APP)_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp # Run erpcgen for C. $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp: $(IDL_FILE) @@ -110,12 +114,16 @@ ifeq "$(is_mingw)" "1" LIBRARIES += -lws2_32 endif else +ifeq (,$(filter $(TEST_NAME),test_arbitrator)) + INCLUDES += $(ERPC_ROOT)/test/common/config +else + INCLUDES += $(OUTPUT_ROOT)/test/$(TEST_NAME)/config +endif + ERPC_C_ROOT = $(ERPC_ROOT)/erpc_c include $(ERPC_ROOT)/test/mk/erpc_src.mk - INCLUDES += $(OUTPUT_ROOT)/test/$(TEST_NAME)/config - ifeq "$(TYPE)" "CLIENT" include $(TEST_ROOT)/$(TEST_NAME)/client.mk else diff --git a/test/mk/unit_test.mk b/test/mk/unit_test.mk index 0d7ce17a..92a8c62c 100644 --- a/test/mk/unit_test.mk +++ b/test/mk/unit_test.mk @@ -27,8 +27,8 @@ CLIENT_NAME = $(TEST_NAME)_client SERVER_NAME = $(TEST_NAME)_server ERPCGEN_PATH = $(ERPC_ROOT)/$(BUILD_TYPE)/$(os_name)/erpcgen/erpcgen UT_OUTPUT_DIR = $(OUTPUT_ROOT)/test/$(TEST_NAME) -TCP_CLIENT_PATH = $(UT_OUTPUT_DIR)/$(os_name)/tcp/gcc/$(CLIENT_NAME)/$(DEBUG_OR_RELEASE)/$(CLIENT_NAME)_tcp_test -TCP_SERVER_PATH = $(UT_OUTPUT_DIR)/$(os_name)/tcp/gcc/$(SERVER_NAME)/$(DEBUG_OR_RELEASE)/$(SERVER_NAME)_tcp_test +TCP_CLIENT_PATH = $(UT_OUTPUT_DIR)/$(os_name)/tcp/$(CC)/$(CLIENT_NAME)/$(DEBUG_OR_RELEASE)/$(CLIENT_NAME)_tcp_test +TCP_SERVER_PATH = $(UT_OUTPUT_DIR)/$(os_name)/tcp/$(CC)/$(SERVER_NAME)/$(DEBUG_OR_RELEASE)/$(SERVER_NAME)_tcp_test test_server_serial = test_server_serial test_client_serial = test_client_serial diff --git a/test/run_unit_tests.py b/test/run_unit_tests.py index 229a4883..a65d897a 100644 --- a/test/run_unit_tests.py +++ b/test/run_unit_tests.py @@ -12,20 +12,21 @@ # then run # $./run_unit_tests.py [tcp] # to run this script with optional transport layer argument -import subprocess +from subprocess import call import re import os import sys -import time -#define output text colour class + class bcolors: + # define output text colour class GREEN = '\033[36m' BLUE = '\033[38;5;097m' - ORANGE= '\033[38;5;172m' + ORANGE = '\033[38;5;172m' RED = '\033[31m' ENDC = '\033[0m' + def isTestDir(dir): regex = re.compile('test_*') if os.path.isdir(dir) and re.match(regex, dir): @@ -33,16 +34,19 @@ def isTestDir(dir): else: return False + testClientCommand = "run-tcp-client" testServerCommand = "run-tcp-server" transportLayer = "tcp" target = "release" +compilerC = "" +compilerCpp = "" make = "make" # Process command line options # Check for 2 or more arguments because argv[0] is the script name if len(sys.argv) > 2: - print ("Too many arguments. Please specify only the transport layer to use. Options are: tcp") + print("Too many arguments. Please specify only the transport layer to use. Options are: tcp") sys.exit(1) if len(sys.argv) >= 2: for arg in sys.argv[1:]: @@ -54,12 +58,19 @@ def isTestDir(dir): target = "debug" elif arg == "-r": target = "release" + elif arg == "clang": + compilerC = "clang" + compilerCpp = "clang++" + elif arg == "gcc": + compilerC = "gcc" + compilerCpp = "gcc++" elif "-m" in arg: make = arg[2:] else: print("Invalid argument/s. Options are: tcp, -r, -d\n") sys.exit(1) + unitTestPath = "./test/" # enter Unit Test Directory os.chdir(unitTestPath) @@ -72,13 +83,24 @@ def isTestDir(dir): build = "build=" + target testsExitStatus = 0 +clientCmd = [make, build, testClientCommand] +serverCmd = [make, build, testServerCommand] +compilerParamC = "" +compilerParamCpp = "" +if compilerC != "": + compilerParamC = "CC="+compilerC + compilerParamCpp = "CXX="+compilerParamCpp + clientCmd.append(compilerParamC) + serverCmd.append(compilerParamC) + clientCmd.append(compilerParamCpp) + serverCmd.append(compilerParamCpp) + for dir in testDirs: - print(bcolors.BLUE + "\nRunning " + bcolors.ORANGE + dir + bcolors.BLUE +" unit tests with " - + bcolors.ORANGE + transportLayer + bcolors.BLUE + " transport layer." + bcolors.ENDC) + print(bcolors.BLUE + "\nRunning " + bcolors.ORANGE + dir + bcolors.BLUE + " unit tests with " + + bcolors.ORANGE + transportLayer + bcolors.BLUE + " transport layer." + bcolors.ENDC) os.chdir(dir) - subprocess.Popen([make, build, testServerCommand]) - time.sleep(0.1) - testsExitStatus += subprocess.call([make, build, testClientCommand]) + call(serverCmd) + testsExitStatus += call(clientCmd) os.chdir('..') # For completeness, change back to erpc/ directory diff --git a/test/test_annotations/external.h b/test/test_annotations/external.h index 2ccab8a7..f6d7bef0 100644 --- a/test/test_annotations/external.h +++ b/test/test_annotations/external.h @@ -14,6 +14,8 @@ // Definitions //////////////////////////////////////////////////////////////////////////////// +#include + // Enumerators data types declarations typedef enum myEnum { diff --git a/test/test_annotations/test_annotations_client_impl.cpp b/test/test_annotations/test_annotations_client_impl.cpp index a354d1de..3407606b 100644 --- a/test/test_annotations/test_annotations_client_impl.cpp +++ b/test/test_annotations/test_annotations_client_impl.cpp @@ -6,13 +6,19 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" //////////////////////////////////////////////////////////////////////////////// // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initAnnotateTest_client(client); +} + TEST(test_annotations, AnnotationServiceID) { EXPECT_EQ(kAnnotateTest_service_id, 5); diff --git a/test/test_annotations/test_annotations_server_impl.cpp b/test/test_annotations/test_annotations_server_impl.cpp index 66c7d202..74f4761d 100644 --- a/test/test_annotations/test_annotations_server_impl.cpp +++ b/test/test_annotations/test_annotations_server_impl.cpp @@ -8,13 +8,18 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "c_test_unit_test_common_server.h" +#include "test_server.hpp" +#include "test_unit_test_common_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include +using namespace erpc; +using namespace erpcShim; + AnnotateTest_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -35,6 +40,30 @@ myInt testIfMyIntAndConstExist(myInt a) return a; } +class AnnotateTest_server : public AnnotateTest_interface +{ +public: + int32_t add(int32_t a, int32_t b) + { + int32_t result; + result = ::add(a, b); + + return result; + } + + void testIfFooStructExist(const fooStruct *a) { ::testIfFooStructExist(a); } + + void testIfMyEnumExist(myEnum a) { ::testIfMyEnumExist(a); } + + myInt testIfMyIntAndConstExist(myInt a) + { + myInt result; + result = ::testIfMyIntAndConstExist(a); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -44,7 +73,7 @@ void add_services(erpc::SimpleServer *server) /* Define services to add using dynamic memory allocation * Exapmle:ArithmeticService_service * svc = new ArithmeticService_service(); */ - svc = new AnnotateTest_service(); + svc = new AnnotateTest_service(new AnnotateTest_server()); /* Add services * Example: server->addService (svc); */ @@ -63,6 +92,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -81,12 +111,6 @@ void remove_services_from_server(erpc_server_t server) erpc_remove_service_from_server(server, service_test); destroy_AnnotateTest_service(service_test); } - -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_arbitrator/client.mk b/test/test_arbitrator/client.mk index 8c7d6f02..a9a9851d 100644 --- a/test/test_arbitrator/client.mk +++ b/test/test_arbitrator/client.mk @@ -16,7 +16,11 @@ #------------------------------------------------------------------------------- SOURCES += $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp \ - $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp\ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_interface.cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_interface.cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_secondInterface_server.cpp \ $(CUR_DIR)_$(APP_TYPE)_impl.cpp \ $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_arbitrator_$(APP_TYPE).cpp @@ -27,6 +31,9 @@ all: $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp $(ERPC_OUT_DIR) $(OUTPUT_ROOT)/test/$(TEST_NAME)/$(CUR_DIR)_$(APP_TYPE)_impl.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_arbitrator_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp +$(ERPC_OUT_DIR)/c_$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp +$(ERPC_OUT_DIR)/c_$(ERPC_NAME)_secondInterface_server.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_interface.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_interface.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp # Run erpcgen for C. $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_server.cpp: $(IDL_FILE) diff --git a/test/test_arbitrator/server.mk b/test/test_arbitrator/server.mk index 07bca589..566799c1 100644 --- a/test/test_arbitrator/server.mk +++ b/test/test_arbitrator/server.mk @@ -16,7 +16,11 @@ #------------------------------------------------------------------------------- SOURCES += $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_interface.cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_secondInterface_client.cpp \ $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_interface.cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp \ $(CUR_DIR)_$(APP_TYPE)_impl.cpp \ $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_arbitrator_$(APP_TYPE).cpp @@ -27,6 +31,10 @@ all: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp $(ERPC_OUT_DIR)/$(E $(OUTPUT_ROOT)/test/$(TEST_NAME)/$(CUR_DIR)_$(APP_TYPE)_impl.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_arbitrator_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp +$(ERPC_OUT_DIR)/c_$(ERPC_NAME)_secondInterface_client.cpp : $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp +$(ERPC_OUT_DIR)/c_$(ERPC_NAME)_firstInterface_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_firstInterface_interface.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_interface.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp + # Run erpcgen for C. $(ERPC_OUT_DIR)/$(ERPC_NAME)_secondInterface_client.cpp: $(IDL_FILE) diff --git a/test/test_arbitrator/test_arbitrator.erpc b/test/test_arbitrator/test_arbitrator.erpc index 62202f09..890c45cc 100644 --- a/test/test_arbitrator/test_arbitrator.erpc +++ b/test/test_arbitrator/test_arbitrator.erpc @@ -8,6 +8,7 @@ @crc @output_dir("erpc_outputs/") +@namespace("") program test; import "../common/unit_test_common.erpc" diff --git a/test/test_arbitrator/test_arbitrator_client_impl.cpp b/test/test_arbitrator/test_arbitrator_client_impl.cpp index ec009e76..22839f2b 100644 --- a/test/test_arbitrator/test_arbitrator_client_impl.cpp +++ b/test/test_arbitrator/test_arbitrator_client_impl.cpp @@ -8,14 +8,19 @@ #include "erpc_simple_server.hpp" +#include "c_test_firstInterface_client.h" +#include "c_test_secondInterface_server.h" #include "gtest.h" -#include "test_firstInterface.h" -#include "test_secondInterface_server.h" +#include "test_secondInterface_server.hpp" +#include "unit_test.h" +#include "unit_test_wrapped.h" //////////////////////////////////////////////////////////////////////////////// // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +using namespace erpc; + #define number 15 #define nestedCallsCount 10 volatile int j = 0; @@ -23,6 +28,11 @@ volatile int numbers[number]; volatile bool enabled = false; SecondInterface_service *svc; +void initInterfaces(erpc_client_t client) +{ + initFirstInterface_client(client); +} + TEST(test_arbitrator, FirstSendReceiveInt) { for (int i = 0; i < number; i++) @@ -99,12 +109,38 @@ void enableFirstSide() enabled = true; } +class SecondInterface_server : public SecondInterface_interface +{ +public: + void secondSendInt(int32_t a) { ::secondSendInt(a); } + + int32_t secondReceiveInt(void) + { + int32_t result; + result = ::secondReceiveInt(); + + return result; + } + + void quitSecondInterfaceServer(void) { ::quitSecondInterfaceServer(); } + + void enableFirstSide(void) { ::enableFirstSide(); } + + int32_t callFirstSide(void) + { + int32_t result; + result = ::callFirstSide(); + + return result; + } +}; + void add_services(erpc::SimpleServer *server) { /* Define services to add using dynamic memory allocation * Exapmle:ArithmeticService_service * svc = new ArithmeticService_service(); */ - svc = new SecondInterface_service(); + svc = new SecondInterface_service(new SecondInterface_server()); /* Add services * Example: server->addService(svc); @@ -124,5 +160,6 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } diff --git a/test/test_arbitrator/test_arbitrator_server_impl.cpp b/test/test_arbitrator/test_arbitrator_server_impl.cpp index f4ccc399..cb039760 100644 --- a/test/test_arbitrator/test_arbitrator_server_impl.cpp +++ b/test/test_arbitrator/test_arbitrator_server_impl.cpp @@ -8,18 +8,28 @@ #include "erpc_simple_server.hpp" -#include "test_firstInterface_server.h" -#include "test_secondInterface.h" +#include "c_test_firstInterface_server.h" +#include "c_test_secondInterface_client.h" +#include "test_firstInterface_server.hpp" +#include "unit_test_wrapped.h" //////////////////////////////////////////////////////////////////////////////// // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +using namespace erpc; + #define number 15 volatile int i = 0; volatile int numbers[number]; FirstInterface_service *svc; +extern "C" { +void initInterfaces(erpc_client_t client) +{ + initSecondInterface_client(client); +} + void firstSendInt(int32_t a) { numbers[i] = a; @@ -41,13 +51,60 @@ int32_t callSecondSide() { return callFirstSide() + 1; } +} + +class FirstInterface_server : public FirstInterface_interface +{ +public: + void whenReady(void) { ::whenReady(); } + + void firstSendInt(int32_t a) { ::firstSendInt(a); } + + int32_t firstReceiveInt(void) + { + int32_t result; + result = ::firstReceiveInt(); + + return result; + } + + void stopSecondSide(void) { ::stopSecondSide(); } + + int32_t getResultFromSecondSide(void) + { + int32_t result; + result = ::getResultFromSecondSide(); + + return result; + } + + void testCasesAreDone(void) { ::testCasesAreDone(); } + + void quitFirstInterfaceServer(void) { ::quitFirstInterfaceServer(); } + + int32_t nestedCallTest(void) + { + int32_t result; + result = ::nestedCallTest(); + + return result; + } + + int32_t callSecondSide(void) + { + int32_t result; + result = ::callSecondSide(); + + return result; + } +}; void add_services(erpc::SimpleServer *server) { /* Define services to add using dynamic memory allocation * Exapmle:ArithmeticService_service * svc = new ArithmeticService_service(); */ - svc = new FirstInterface_service(); + svc = new FirstInterface_service(new FirstInterface_server()); /* Add services * Example: server->addService(svc); @@ -67,5 +124,6 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } diff --git a/test/test_arrays/test_arrays_client_impl.cpp b/test/test_arrays/test_arrays_client_impl.cpp index 6b1ca2d7..4b80e35b 100644 --- a/test/test_arrays/test_arrays_client_impl.cpp +++ b/test/test_arrays/test_arrays_client_impl.cpp @@ -6,8 +6,9 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" #include @@ -15,6 +16,11 @@ // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initPointersService_client(client); +} + TEST(test_arrays, sendReceivedInt32) { uint32_t array_count = 12; diff --git a/test/test_arrays/test_arrays_server_impl.cpp b/test/test_arrays/test_arrays_server_impl.cpp index c0e70ca0..b48f66fb 100644 --- a/test/test_arrays/test_arrays_server_impl.cpp +++ b/test/test_arrays/test_arrays_server_impl.cpp @@ -8,14 +8,18 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "c_test_unit_test_common_server.h" +#include "test_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include #include +using namespace erpc; +using namespace erpcShim; + PointersService_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -374,16 +378,185 @@ void test_array_allDirection(const int32_t a[5], const int32_t b[5], int32_t c[5 void testFunction(){}; +class PointersService_server : public PointersService_interface +{ +public: + int32_t (*sendReceivedInt32(const int32_t arrayNumbers[12]))[12] + { + int32_t(*result)[12] = NULL; + result = ::sendReceivedInt32(arrayNumbers); + + return result; + } + + int32_t (*sendReceived2Int32(int32_t arrayNumbers[12][10]))[12][10] + { + int32_t(*result)[12][10] = NULL; + result = ::sendReceived2Int32(arrayNumbers); + + return result; + } + + char *(*sendReceivedString(char *arrayStrings[12]))[12] + { + char *(*result)[12] = NULL; + result = ::sendReceivedString(arrayStrings); + + return result; + } + + char *(*sendReceived2String(char *arrayStrings[3][5]))[3][5] + { + char *(*result)[3][5] = NULL; + result = ::sendReceived2String(arrayStrings); + + return result; + } + + enumColor (*sendReceivedEnum(const enumColor arrayEnums[3]))[3] + { + enumColor(*result)[3] = NULL; + result = ::sendReceivedEnum(arrayEnums); + + return result; + } + + enumColor (*sendReceived2Enum(enumColor arrayEnums[3][3]))[3][3] + { + enumColor(*result)[3][3] = NULL; + result = ::sendReceived2Enum(arrayEnums); + + return result; + } + + list_int32_1_t (*sendReceivedList(const list_int32_1_t arrayLists[2]))[2] + { + list_int32_1_t(*result)[2] = NULL; + result = ::sendReceivedList(arrayLists); + + return result; + } + + list_int32_1_t (*sendReceived2List(list_int32_1_t arrayLists[2][2]))[2][2] + { + list_int32_1_t(*result)[2][2] = NULL; + result = ::sendReceived2List(arrayLists); + + return result; + } + + ArrayIntType *sendReceivedInt32Type(const ArrayIntType arrayNumbers) + { + ArrayIntType *result = NULL; + result = ::sendReceivedInt32Type(arrayNumbers); + + return result; + } + + Array2IntType *sendReceived2Int32Type(Array2IntType arrayNumbers) + { + Array2IntType *result = NULL; + result = ::sendReceived2Int32Type(arrayNumbers); + + return result; + } + + ArrayStringType *sendReceivedStringType(ArrayStringType arrayStrings) + { + ArrayStringType *result = NULL; + result = ::sendReceivedStringType(arrayStrings); + + return result; + } + + Array2StringType *sendReceived2StringType(Array2StringType arrayStrings) + { + Array2StringType *result = NULL; + result = ::sendReceived2StringType(arrayStrings); + + return result; + } + + ArrayEnumType *sendReceivedEnumType(const ArrayEnumType arrayEnums) + { + ArrayEnumType *result = NULL; + result = ::sendReceivedEnumType(arrayEnums); + + return result; + } + + Array2EnumType *sendReceived2EnumType(Array2EnumType arrayEnums) + { + Array2EnumType *result = NULL; + result = ::sendReceived2EnumType(arrayEnums); + + return result; + } + + ArrayStructType *sendReceivedStructType(const ArrayStructType arrayStructs) + { + ArrayStructType *result = NULL; + result = ::sendReceivedStructType(arrayStructs); + + return result; + } + + Array2StructType *sendReceived2StructType(Array2StructType arrayStructs) + { + Array2StructType *result = NULL; + result = ::sendReceived2StructType(arrayStructs); + + return result; + } + + ArrayListType *sendReceivedListType(const ArrayListType arrayLists) + { + ArrayListType *result = NULL; + result = ::sendReceivedListType(arrayLists); + + return result; + } + + Array2ListType *sendReceived2ListType(Array2ListType arrayLists) + { + Array2ListType *result = NULL; + result = ::sendReceived2ListType(arrayLists); + + return result; + } + + AllTypes (*sendReceiveStruct(const AllTypes arrayStructs[2]))[2] + { + AllTypes(*result)[2] = NULL; + result = ::sendReceiveStruct(arrayStructs); + + return result; + } + + AllTypes (*sendReceive2Struct(AllTypes arrayStructs[1][1]))[1][1] + { + AllTypes(*result)[1][1] = NULL; + result = ::sendReceive2Struct(arrayStructs); + + return result; + } + + void test_array_allDirection(const int32_t a[5], const int32_t b[5], int32_t c[5], int32_t d[5]) + { + ::test_array_allDirection(a, b, c, d); + } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// void add_services(erpc::SimpleServer *server) { - // define services to add on heap - // allocate on heap so service doesn't go out of scope at end of method - svc = new PointersService_service(); - + /* Define services to add using dynamic memory allocation + * Exapmle:ArithmeticService_service * svc = new ArithmeticService_service(); + */ + svc = new PointersService_service(new PointersService_server()); // add services server->addService(svc); } @@ -400,6 +573,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -418,12 +592,6 @@ void remove_services_from_server(erpc_server_t server) erpc_remove_service_from_server(server, service_test); destroy_PointersService_service(service_test); } - -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_binary/test_binary_client_impl.cpp b/test/test_binary/test_binary_client_impl.cpp index 917a457f..58d74128 100644 --- a/test/test_binary/test_binary_client_impl.cpp +++ b/test/test_binary/test_binary_client_impl.cpp @@ -6,8 +6,9 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" using namespace std; @@ -15,6 +16,11 @@ using namespace std; // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initBinary_client(client); +} + /*TEST(test_binary, sendReceiveBinary) { binary *result, send; diff --git a/test/test_binary/test_binary_server_impl.cpp b/test/test_binary/test_binary_server_impl.cpp index b073d243..7e1ad36a 100644 --- a/test/test_binary/test_binary_server_impl.cpp +++ b/test/test_binary/test_binary_server_impl.cpp @@ -8,13 +8,16 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "test_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include +using namespace erpc; +using namespace erpcShim; + Binary_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -70,6 +73,21 @@ void test_binary_allDirectionLength(const uint8_t *a, const binary_t *b, binary_ free((void *)a); free((void *)b); }*/ +class Binary_server : public Binary_interface +{ +public: + void sendBinary(const binary_t *a) { ::sendBinary(a); } + + void test_binary_allDirection(const binary_t *a, const binary_t *b, binary_t *e) + { + ::test_binary_allDirection(a, b, e); + } + + void test_binary_allDirectionLength(const uint8_t *a, const binary_t *b, binary_t *d, uint32_t p1) + { + ::test_binary_allDirectionLength(a, b, d, p1); + } +}; //////////////////////////////////////////////////////////////////////////////// // Add service to server code @@ -80,7 +98,7 @@ void add_services(erpc::SimpleServer *server) /* Define services to add using dynamic memory allocation * Exapmle:ArithmeticService_service * svc = new ArithmeticService_service(); */ - svc = new Binary_service(); + svc = new Binary_service(new Binary_server()); /* Add services * Example: server->addService(svc); @@ -100,6 +118,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -119,11 +138,6 @@ void remove_services_from_server(erpc_server_t server) destroy_Binary_service(service_test); } -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_builtin/test_builtin_client_impl.cpp b/test/test_builtin/test_builtin_client_impl.cpp index a318947f..e355192c 100644 --- a/test/test_builtin/test_builtin_client_impl.cpp +++ b/test/test_builtin/test_builtin_client_impl.cpp @@ -6,8 +6,9 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" #include @@ -17,6 +18,11 @@ using namespace std; // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initBuiltinServices_client(client); +} + int32_t int32A = 2; int32_t int32B = -20; diff --git a/test/test_builtin/test_builtin_server_impl.cpp b/test/test_builtin/test_builtin_server_impl.cpp index 0cd2bf57..5daced06 100644 --- a/test/test_builtin/test_builtin_server_impl.cpp +++ b/test/test_builtin/test_builtin_server_impl.cpp @@ -8,14 +8,17 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "test_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include #include +using namespace erpc; +using namespace erpcShim; + BuiltinServices_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -150,6 +153,94 @@ char *returnHello() return hello; } +class BuiltinServices_server : public BuiltinServices_interface +{ +public: + void test_int32_in(int32_t a) { ::test_int32_in(a); } + + void test_int32_in2(int32_t b) { ::test_int32_in2(b); } + + void test_int32_out(int32_t *c) { ::test_int32_out(c); } + + void test_int32_inout(int32_t *e) { ::test_int32_inout(e); } + + int32_t test_int32_return(void) + { + int32_t result; + result = ::test_int32_return(); + + return result; + } + + int32_t test_int32_allDirection(int32_t a, int32_t b, int32_t *c, int32_t *e) + { + int32_t result; + result = ::test_int32_allDirection(a, b, c, e); + + return result; + } + + void test_float_inout(float a, float *b) { ::test_float_inout(a, b); } + + void test_double_inout(double a, double *b) { ::test_double_inout(a, b); } + + void test_string_in(const char *a) { ::test_string_in(a); } + + void test_string_in2(const char *b) { ::test_string_in2(b); } + + void test_string_out(char *c) { ::test_string_out(c); } + + void test_string_inout(char *e) { ::test_string_inout(e); } + + char *test_string_return(void) + { + char *result = NULL; + result = ::test_string_return(); + + return result; + } + + char *test_string_allDirection(const char *a, const char *b, char *c, char *e) + { + char *result = NULL; + result = ::test_string_allDirection(a, b, c, e); + + return result; + } + + char *test_string_empty(const char *a, const char *b, char *c, char *e) + { + char *result = NULL; + result = ::test_string_empty(a, b, c, e); + + return result; + } + + int32_t sendHello(const char *str) + { + int32_t result; + result = ::sendHello(str); + + return result; + } + + int32_t sendTwoStrings(const char *myStr1, const char *myStr2) + { + int32_t result; + result = ::sendTwoStrings(myStr1, myStr2); + + return result; + } + + char *returnHello(void) + { + char *result = NULL; + result = ::returnHello(); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -158,7 +249,7 @@ void add_services(erpc::SimpleServer *server) { // define services to add on heap // allocate on heap so service doesn't go out of scope at end of method - svc = new BuiltinServices_service(); + svc = new BuiltinServices_service(new BuiltinServices_server()); // add services server->addService(svc); @@ -176,6 +267,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -194,12 +286,6 @@ void remove_services_from_server(erpc_server_t server) erpc_remove_service_from_server(server, service_test); destroy_BuiltinServices_service(service_test); } - -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_callbacks/callbacks1.h b/test/test_callbacks/callbacks1.h deleted file mode 100644 index b1d511c7..00000000 --- a/test/test_callbacks/callbacks1.h +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Copyright 2017 NXP - * All rights reserved. - * - * - * SPDX-License-Identifier: BSD-3-Clause - */ - -void callback1a(int32_t a, int32_t b); - -void callback1b(int32_t param1, int32_t param2); diff --git a/test/test_callbacks/callbacks2.h b/test/test_callbacks/callbacks2.h deleted file mode 100644 index f3f4120c..00000000 --- a/test/test_callbacks/callbacks2.h +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright 2017 NXP - * All rights reserved. - * - * - * SPDX-License-Identifier: BSD-3-Clause - */ - -void callback2(int32_t param1, int32_t param2); diff --git a/test/test_callbacks/client.mk b/test/test_callbacks/client.mk new file mode 100644 index 00000000..749e4209 --- /dev/null +++ b/test/test_callbacks/client.mk @@ -0,0 +1,44 @@ +#------------------------------------------------------------------------------- +# Copyright (C) 2016 Freescale Semiconductor, Inc. +# Copyright 2016 NXP +# All Rights Reserved. +# +# THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESS OR IMPLIED +# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +# SHALL FREESCALE 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. +#------------------------------------------------------------------------------- + +SOURCES += $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_$(APP_TYPE).cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME_APP)_$(APP_TYPE).cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_core1_interface.cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_interface.cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp \ + $(CUR_DIR)_$(APP_TYPE)_impl.cpp \ + $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_$(APP_TYPE).cpp + +.PHONY: all +all: $(ERPC_OUT_DIR)/$(ERPC_NAME)_core0_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_core0_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_core1_interface.cpp + +# Define dependency. +$(OUTPUT_ROOT)/test/$(TEST_NAME)/$(CUR_DIR)_$(APP_TYPE)_impl.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_core0_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_core0_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_core0_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(ERPC_OUT_DIR)/c_$(ERPC_NAME)_core0_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_core0_$(APP_TYPE).cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_$(APP_TYPE).cpp +$(ERPC_OUT_DIR)/c_$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_core1_interface.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_interface.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp + +# Run erpcgen for C. +$(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp: $(IDL_FILE) + @$(call printmessage,orange,Running erpcgen-c $(TEST_NAME), $(subst $(ERPC_ROOT)/,,$<)) + $(at)$(ERPCGEN) -gc -o $(RPC_OBJS_ROOT)/ $(IDL_FILE) diff --git a/test/test_callbacks/server.mk b/test/test_callbacks/server.mk new file mode 100644 index 00000000..1d3d056d --- /dev/null +++ b/test/test_callbacks/server.mk @@ -0,0 +1,44 @@ +#------------------------------------------------------------------------------- +# Copyright (C) 2016 Freescale Semiconductor, Inc. +# Copyright 2016 NXP +# All Rights Reserved. +# +# THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESS OR IMPLIED +# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +# SHALL FREESCALE 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. +#------------------------------------------------------------------------------- + +SOURCES += $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_server.cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME_APP)_server.cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_core1_interface.cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp \ + $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_interface.cpp \ + $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp \ + $(CUR_DIR)_$(APP_TYPE)_impl.cpp \ + $(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_$(APP_TYPE).cpp + +.PHONY: all +all: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_server.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/c_$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp $(ERPC_OUT_DIR)/$(ERPC_NAME)_core1_interface.cpp + +# Define dependency. +$(OUTPUT_ROOT)/test/$(TEST_NAME)/$(CUR_DIR)_$(APP_TYPE)_impl.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_server.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(UT_COMMON_SRC)/unit_test_$(TRANSPORT)_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_server.cpp $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_server.cpp +$(ERPC_OUT_DIR)/c_$(ERPC_NAME_APP)_server.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(ERPC_OUT_DIR)/c_$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_$(APP_TYPE).cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_core1_interface.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp +$(ERPC_OUT_DIR)/$(ERPC_NAME)_unit_test_common_interface.cpp: $(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_interface.cpp + +# Run erpcgen for C. +$(ERPC_OUT_DIR)/$(ERPC_NAME_APP)_server.cpp: $(IDL_FILE) + @$(call printmessage,orange,Running erpcgen-c $(TEST_NAME), $(subst $(ERPC_ROOT)/,,$<)) + $(at)$(ERPCGEN) -gc -o $(RPC_OBJS_ROOT)/ $(IDL_FILE) diff --git a/test/test_callbacks/test_callbacks.erpc b/test/test_callbacks/test_callbacks.erpc index 0ae0aeff..9c7db83e 100644 --- a/test/test_callbacks/test_callbacks.erpc +++ b/test/test_callbacks/test_callbacks.erpc @@ -10,17 +10,17 @@ program test import "../common/unit_test_common.erpc" -oneway callback1_t(int32 a, int32 b) -oneway callback2_t(int32, int32) -callback3_t(int32 arg1, int32 arg2) -> int32 - @c:include("test_core1.h") @group("core0") interface ClientCore0Services { - myFun(in callback1_t pCallback1_in, out callback1_t pCallback1_out) -> void + type oneway callback1_t(int32 a, int32 b) + type callback3_t(int32 arg1, int32 arg2) -> int32 + type oneway callback2_t(int32, int32) + + myFun(in callback1_t pCallback1_in, out callback1_t pCallback1_out) -> int32 - myFun2(callback2_t pCallback2_in, out callback2_t pCallback2_out) -> void + myFun2(ClientCore1Services::callback2_t pCallback2_in, out ClientCore1Services::callback2_t pCallback2_out) -> void myFun3(callback3_t callback, in int32 arg1, in int32 arg2) -> int32 @@ -29,17 +29,16 @@ interface ClientCore0Services callback3_t my_mul; callback3_t my_div; - @c:include("callbacks1.h") callback1_t callback1a; - @c:include("callbacks1.h") callback1_t callback1b(param1, param2); } @group("core1") interface ClientCore1Services { - @c:include("callbacks2.h") + type oneway callback2_t(int32, int32) + callback2_t callback2(param1, param2); } diff --git a/test/test_callbacks/test_callbacks_client_impl.cpp b/test/test_callbacks/test_callbacks_client_impl.cpp index b85a6e46..76f11b94 100644 --- a/test/test_callbacks/test_callbacks_client_impl.cpp +++ b/test/test_callbacks/test_callbacks_client_impl.cpp @@ -5,9 +5,9 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_core0_client.h" #include "gtest.h" -#include "test_core0.h" -#include "test_core1_server.h" +#include "unit_test_wrapped.h" void callback2(int32_t param1, int32_t param2) {} @@ -15,6 +15,11 @@ void callback2(int32_t param1, int32_t param2) {} // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initClientCore0Services_client(client); +} + TEST(test_callbacks, In_Out_table_1) { callback1_t pCallback1_out = NULL; diff --git a/test/test_callbacks/test_callbacks_server_impl.cpp b/test/test_callbacks/test_callbacks_server_impl.cpp index 7f6884d2..cfb1be71 100644 --- a/test/test_callbacks/test_callbacks_server_impl.cpp +++ b/test/test_callbacks/test_callbacks_server_impl.cpp @@ -6,15 +6,19 @@ */ #include "erpc_server_setup.h" +#include "erpc_utils.hpp" -#include "test_core0_server.h" -#include "test_core1.h" -#include "test_unit_test_common_server.h" +#include "c_test_core0_server.h" +#include "c_test_core1_server.h" +#include "test_core0_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include +using namespace erpc; +using namespace erpcShim; + ClientCore0Services_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -24,18 +28,17 @@ ClientCore0Services_service *svc; callback1_t *cb1 = NULL; callback2_t *cb2 = NULL; -void myFun(const callback1_t pCallback1_in, callback1_t *pCallback1_out) +int32_t myFun(const callback1_t pCallback1_in, callback1_t *pCallback1_out) { - cb1 = NULL; pCallback1_in(1, 2); - *pCallback1_out = (callback1_t)cb1; + *pCallback1_out = pCallback1_in; + return 0; } void myFun2(const callback2_t pCallback2_in, callback2_t *pCallback2_out) { - cb2 = NULL; pCallback2_in(1, 2); - *pCallback2_out = (callback2_t)cb2; + *pCallback2_out = pCallback2_in; } void callback1a(int32_t a, int32_t b) @@ -83,6 +86,110 @@ int32_t my_div(int32_t arg1, int32_t arg2) return 0; } +static const callback1_t _callback1_t[2] = { callback1a, callback1b }; +static const callback2_t _callback2_t[1] = { callback2 }; +static const callback3_t _callback3_t[4] = { my_add, my_sub, my_mul, my_div }; + +class ClientCore0Services_server : public ClientCore0Services_interface +{ +public: + int32_t myFun(const callback1_t pCallback1_in, callback1_t *pCallback1_out) + { + uint16_t _fnIndex; + ::callback1_t _pCallback1_in = NULL; + ::callback1_t _pCallback1_out = NULL; + int32_t result; + + if (ClientCore0Services_interface::get_callbackIdx_callback1_t(&pCallback1_in, _fnIndex)) + { + _pCallback1_in = ::_callback1_t[_fnIndex]; + } + + result = ::myFun(_pCallback1_in, &_pCallback1_out); + + if (findIndexOfFunction((arrayOfFunctionPtr_t)::_callback1_t, sizeof(::_callback1_t) / sizeof(::callback1_t), + (functionPtr_t)_pCallback1_out, _fnIndex)) + { + ClientCore0Services_interface::get_callbackAddress_callback1_t(_fnIndex, pCallback1_out); + } + + return result; + } + + void myFun2(const ClientCore1Services_interface::callback2_t pCallback2_in, + ClientCore1Services_interface::callback2_t *pCallback2_out) + { + uint16_t _fnIndex; + ::callback2_t _pCallback2_in = NULL; + ::callback2_t _pCallback2_out = NULL; + + if (ClientCore1Services_interface::get_callbackIdx_callback2_t(&pCallback2_in, _fnIndex)) + { + _pCallback2_in = ::_callback2_t[_fnIndex]; + } + + ::myFun2(_pCallback2_in, &_pCallback2_out); + + if (findIndexOfFunction((arrayOfFunctionPtr_t)::_callback2_t, sizeof(::_callback2_t) / sizeof(::callback2_t), + (functionPtr_t)_pCallback2_out, _fnIndex)) + { + ClientCore1Services_interface::get_callbackAddress_callback2_t(_fnIndex, pCallback2_out); + } + } + + int32_t myFun3(const callback3_t callback, int32_t arg1, int32_t arg2) + { + uint16_t _fnIndex; + ::callback3_t _callback = NULL; + int32_t result; + + if (ClientCore0Services_interface::get_callbackIdx_callback3_t(&callback, _fnIndex)) + { + _callback = ::_callback3_t[_fnIndex]; + } + + result = ::myFun3(_callback, arg1, arg2); + + return result; + } + + int32_t my_add(int32_t arg1, int32_t arg2) + { + int32_t result; + result = ::my_add(arg1, arg2); + + return result; + } + + int32_t my_sub(int32_t arg1, int32_t arg2) + { + int32_t result; + result = ::my_sub(arg1, arg2); + + return result; + } + + int32_t my_mul(int32_t arg1, int32_t arg2) + { + int32_t result; + result = ::my_mul(arg1, arg2); + + return result; + } + + int32_t my_div(int32_t arg1, int32_t arg2) + { + int32_t result; + result = ::my_div(arg1, arg2); + + return result; + } + + void callback1a(int32_t a, int32_t b) { ::callback1a(a, b); } + + void callback1b(int32_t param1, int32_t param2) { ::callback1b(param1, param2); } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -91,7 +198,7 @@ void add_services(erpc::SimpleServer *server) { // define services to add on heap // allocate on heap so service doesn't go out of scope at end of method - svc = new ClientCore0Services_service(); + svc = new ClientCore0Services_service(new ClientCore0Services_server()); // add services server->addService(svc); @@ -109,6 +216,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -127,12 +235,6 @@ void remove_services_from_server(erpc_server_t server) erpc_remove_service_from_server(server, service_test); destroy_ClientCore0Services_service(service_test); } - -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_const/test_const_client_impl.cpp b/test/test_const/test_const_client_impl.cpp index 3db9141a..cd3e6e26 100644 --- a/test/test_const/test_const_client_impl.cpp +++ b/test/test_const/test_const_client_impl.cpp @@ -7,12 +7,15 @@ */ #include "gtest.h" -#include "test.h" +#include "test_common.h" +#include "unit_test_wrapped.h" //////////////////////////////////////////////////////////////////////////////// // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) {} + TEST(test_const, CheckConsts) { EXPECT_EQ(a, 3); diff --git a/test/test_const/test_const_server_impl.cpp b/test/test_const/test_const_server_impl.cpp index 91c52740..90a83e7f 100644 --- a/test/test_const/test_const_server_impl.cpp +++ b/test/test_const/test_const_server_impl.cpp @@ -8,8 +8,8 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "c_test_unit_test_common_server.h" #include "unit_test.h" #include "unit_test_wrapped.h" @@ -53,12 +53,6 @@ extern "C" { #endif void add_services_to_server(erpc_server_t server) {} void remove_services_from_server(erpc_server_t server) {} - -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_enums/test_enums_client_impl.cpp b/test/test_enums/test_enums_client_impl.cpp index 10530f7d..fda78c0e 100644 --- a/test/test_enums/test_enums_client_impl.cpp +++ b/test/test_enums/test_enums_client_impl.cpp @@ -6,13 +6,19 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" //////////////////////////////////////////////////////////////////////////////// // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initEnumsService_client(client); +} + enumColor enumColorA = green; enumColor enumColorB = red; diff --git a/test/test_enums/test_enums_server_impl.cpp b/test/test_enums/test_enums_server_impl.cpp index 9d437a83..7bd98846 100644 --- a/test/test_enums/test_enums_server_impl.cpp +++ b/test/test_enums/test_enums_server_impl.cpp @@ -8,13 +8,17 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "c_test_unit_test_common_server.h" +#include "test_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include +using namespace erpc; +using namespace erpcShim; + EnumsService_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -75,6 +79,50 @@ enumErrorCode test_enumErrorCode_allDirection(enumErrorCode a, enumErrorCode b, return a; } +class EnumsService_server : public EnumsService_interface +{ +public: + void test_enumColor_in(enumColor a) { ::test_enumColor_in(a); } + + void test_enumColor_in2(enumColor b) { ::test_enumColor_in2(b); } + + void test_enumColor_out(enumColor *c) { ::test_enumColor_out(c); } + + void test_enumColor_inout(enumColor *e) { ::test_enumColor_inout(e); } + + enumColor test_enumColor_return(void) + { + enumColor result; + result = ::test_enumColor_return(); + + return result; + } + + enumColor test_enumColor_allDirection(enumColor a, enumColor b, enumColor *c, enumColor *e) + { + enumColor result; + result = ::test_enumColor_allDirection(a, b, c, e); + + return result; + } + + enumColor2 test_enumColor2_allDirection(enumColor2 a, enumColor2 b, enumColor2 *c, enumColor2 *e) + { + enumColor2 result; + result = ::test_enumColor2_allDirection(a, b, c, e); + + return result; + } + + enumErrorCode test_enumErrorCode_allDirection(enumErrorCode a, enumErrorCode b, enumErrorCode *c, enumErrorCode *e) + { + enumErrorCode result; + result = ::test_enumErrorCode_allDirection(a, b, c, e); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -83,7 +131,7 @@ void add_services(erpc::SimpleServer *server) { // define services to add on heap // allocate on heap so service doesn't go out of scope at end of method - svc = new EnumsService_service(); + svc = new EnumsService_service(new EnumsService_server()); // add services server->addService(svc); @@ -101,6 +149,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -119,12 +168,6 @@ void remove_services_from_server(erpc_server_t server) erpc_remove_service_from_server(server, service_test); destroy_EnumsService_service(service_test); } - -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_lists/test_lists_client_impl.cpp b/test/test_lists/test_lists_client_impl.cpp index 22e44e80..f648712a 100644 --- a/test/test_lists/test_lists_client_impl.cpp +++ b/test/test_lists/test_lists_client_impl.cpp @@ -6,8 +6,9 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" #include @@ -17,6 +18,11 @@ using namespace std; // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initPointersService_client(client); +} + TEST(test_list, SendReceivedInt32) { list_int32_1_t *received_list, send_list; diff --git a/test/test_lists/test_lists_server_impl.cpp b/test/test_lists/test_lists_server_impl.cpp index 8950ee43..7f5e517b 100644 --- a/test/test_lists/test_lists_server_impl.cpp +++ b/test/test_lists/test_lists_server_impl.cpp @@ -8,14 +8,18 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "c_test_unit_test_common_server.h" +#include "test_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include #include +using namespace erpc; +using namespace erpcShim; + PointersService_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -309,6 +313,111 @@ int32_t sendGapAdvertisingData(const gapAdvertisingData_t *ad) return 33; } +class PointersService_server : public PointersService_interface +{ +public: + list_int32_1_t *sendReceivedInt32(const list_int32_1_t *listNumbers) + { + list_int32_1_t *result = NULL; + result = ::sendReceivedInt32(listNumbers); + + return result; + } + + list_int32_2_t *sendReceived2Int32(const list_int32_2_t *listNumbers) + { + list_int32_2_t *result = NULL; + result = ::sendReceived2Int32(listNumbers); + + return result; + } + + list_enumColor_1_t *sendReceivedEnum(const list_enumColor_1_t *listColors) + { + list_enumColor_1_t *result = NULL; + result = ::sendReceivedEnum(listColors); + + return result; + } + + list_enumColor_2_t *sendReceived2Enum(const list_enumColor_2_t *listColors) + { + list_enumColor_2_t *result = NULL; + result = ::sendReceived2Enum(listColors); + + return result; + } + + list_C_1_t *sendReceivedStruct(const list_C_1_t *listColors) + { + list_C_1_t *result = NULL; + result = ::sendReceivedStruct(listColors); + + return result; + } + + list_C_2_t *sendReceived2Struct(const list_C_2_t *listColors) + { + list_C_2_t *result = NULL; + result = ::sendReceived2Struct(listColors); + + return result; + } + + list_string_1_t *sendReceivedString(const list_string_1_t *listNumbers) + { + list_string_1_t *result = NULL; + result = ::sendReceivedString(listNumbers); + + return result; + } + + list_string_2_t *sendReceived2String(const list_string_2_t *listNumbers) + { + list_string_2_t *result = NULL; + result = ::sendReceived2String(listNumbers); + + return result; + } + + void test_list_allDirection(const list_uint32_1_t *a, const list_uint32_1_t *b, list_uint32_1_t *e) + { + ::test_list_allDirection(a, b, e); + } + + int32_t testLengthAnnotation(const int32_t *myList, uint32_t len) + { + int32_t result; + result = ::testLengthAnnotation(myList, len); + + return result; + } + + int32_t testLengthAnnotationInStruct(const listStruct *s) + { + int32_t result; + result = ::testLengthAnnotationInStruct(s); + + return result; + } + + listStruct *returnSentStructLengthAnnotation(const listStruct *s) + { + listStruct *result = NULL; + result = ::returnSentStructLengthAnnotation(s); + + return result; + } + + int32_t sendGapAdvertisingData(const gapAdvertisingData_t *ad) + { + int32_t result; + result = ::sendGapAdvertisingData(ad); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -317,7 +426,7 @@ void add_services(erpc::SimpleServer *server) { // define services to add on heap // allocate on heap so service doesn't go out of scope at end of method - svc = new PointersService_service(); + svc = new PointersService_service(new PointersService_server()); // add services server->addService(svc); @@ -335,6 +444,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -354,11 +464,6 @@ void remove_services_from_server(erpc_server_t server) destroy_PointersService_service(service_test); } -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_shared/test_shared_client_impl.cpp b/test/test_shared/test_shared_client_impl.cpp index db39dfc2..8fea5a99 100644 --- a/test/test_shared/test_shared_client_impl.cpp +++ b/test/test_shared/test_shared_client_impl.cpp @@ -5,13 +5,19 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" //////////////////////////////////////////////////////////////////////////////// // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initSharedService_client(client); +} + TEST(test_shared, sendReceiveBaseSharedStruct) { BaseSharedStruct sm = { 4, 5 }; diff --git a/test/test_shared/test_shared_server_impl.cpp b/test/test_shared/test_shared_server_impl.cpp index 5b3b9fb7..5890d6f8 100644 --- a/test/test_shared/test_shared_server_impl.cpp +++ b/test/test_shared/test_shared_server_impl.cpp @@ -7,13 +7,17 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "c_test_unit_test_common_server.h" +#include "test_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include +using namespace erpc; +using namespace erpcShim; + SharedService_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -29,6 +33,20 @@ BaseSharedStruct *sendReceiveBaseSharedStruct(const BaseSharedStruct *s) void inoutBaseSharedStruct(BaseSharedStruct **s) {} /* end typedef unit tests */ +class SharedService_server : public SharedService_interface +{ +public: + BaseSharedStruct *sendReceiveBaseSharedStruct(const BaseSharedStruct *a) + { + BaseSharedStruct *result = NULL; + result = ::sendReceiveBaseSharedStruct(a); + + return result; + } + + void inoutBaseSharedStruct(BaseSharedStruct **a) { ::inoutBaseSharedStruct(a); } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -37,7 +55,7 @@ void add_services(erpc::SimpleServer *server) { // define services to add on heap // allocate on heap so service doesn't go out of scope at end of method - svc = new SharedService_service(); + svc = new SharedService_service(new SharedService_server()); // add services server->addService(svc); @@ -55,6 +73,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -74,11 +93,6 @@ void remove_services_from_server(erpc_server_t server) destroy_SharedService_service(service_test); } -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_struct/test_struct_client_impl.cpp b/test/test_struct/test_struct_client_impl.cpp index bcb87b8c..7fbdd9f1 100644 --- a/test/test_struct/test_struct_client_impl.cpp +++ b/test/test_struct/test_struct_client_impl.cpp @@ -6,8 +6,9 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_ArithmeticService_client.h" #include "gtest.h" -#include "test_ArithmeticService.h" +#include "unit_test_wrapped.h" #include @@ -17,6 +18,12 @@ using namespace std; // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initArithmeticService1_client(client); + initArithmeticService2_client(client); +} + TEST(test_struct, GetMember1) { C c = { 4, 5 }; diff --git a/test/test_struct/test_struct_server_impl.cpp b/test/test_struct/test_struct_server_impl.cpp index 27ebbae5..9214bcfd 100644 --- a/test/test_struct/test_struct_server_impl.cpp +++ b/test/test_struct/test_struct_server_impl.cpp @@ -8,14 +8,18 @@ #include "erpc_server_setup.h" -#include "test_ArithmeticService_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_ArithmeticService_server.h" +#include "c_test_unit_test_common_server.h" +#include "test_ArithmeticService_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include #include +using namespace erpc; +using namespace erpcShim; + ArithmeticService1_service *svc1; ArithmeticService2_service *svc2; @@ -179,6 +183,131 @@ bool testSendingByrefMembers(const StructWithByrefMembers *s) return false; } +class ArithmeticService1_server : public ArithmeticService1_interface +{ +public: + int32_t getMember(const C *c) + { + int32_t result; + result = ::getMember(c); + + return result; + } + + B *returnStruct(float a, float b) + { + B *result = NULL; + result = ::returnStruct(a, b); + + return result; + } + + B *getMemberTest2(const A *a) + { + B *result = NULL; + result = ::getMemberTest2(a); + + return result; + } + + int32_t sendNestedStruct(const D *d) + { + int32_t result; + result = ::sendNestedStruct(d); + + return result; + } + + int32_t checkString(const primate *p) + { + int32_t result; + result = ::checkString(p); + + return result; + } + + stringStruct *returnStrings(void) + { + stringStruct *result = NULL; + result = ::returnStrings(); + + return result; + } +}; + +class ArithmeticService2_server : public ArithmeticService2_interface +{ +public: + int32_t sendManyInts(const F *f) + { + int32_t result; + result = ::sendManyInts(f); + + return result; + } + + int32_t sendManyUInts(const G *g) + { + int32_t result; + result = ::sendManyUInts(g); + + return result; + } + + char *getStudentName(const student *stud) + { + char *result = NULL; + result = ::getStudentName(stud); + + return result; + } + + float getStudentTestAverage(const student *stud) + { + float result; + result = ::getStudentTestAverage(stud); + + return result; + } + + int32_t getStudentYear(const student *stud) + { + int32_t result; + result = ::getStudentYear(stud); + + return result; + } + + int32_t getStudentAge(const student *stud) + { + int32_t result; + result = ::getStudentAge(stud); + + return result; + } + + student *createStudent(const char *name, const float test_scores[3], school_year_t year, int32_t age) + { + student *result = NULL; + result = ::createStudent(name, test_scores, year, age); + + return result; + } + + void test_struct_allDirection(const AllTypes *a, const AllTypes *b, AllTypes *e) + { + ::test_struct_allDirection(a, b, e); + } + + bool testSendingByrefMembers(const StructWithByrefMembers *s) + { + bool result; + result = ::testSendingByrefMembers(s); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -187,8 +316,8 @@ void add_services(erpc::SimpleServer *server) { // define services to add on heap // allocate on heap so service doesn't go out of scope at end of method - svc1 = new ArithmeticService1_service(); - svc2 = new ArithmeticService2_service(); + svc1 = new ArithmeticService1_service(new ArithmeticService1_server()); + svc2 = new ArithmeticService2_service(new ArithmeticService2_server()); // add services server->addService(svc1); @@ -208,6 +337,8 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc2); /* Delete unused service */ + delete svc1->getHandler(); + delete svc2->getHandler(); delete svc1; delete svc2; } @@ -233,11 +364,6 @@ void remove_services_from_server(erpc_server_t server) destroy_ArithmeticService2_service(service2); } -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_typedef/test_typedef_client_impl.cpp b/test/test_typedef/test_typedef_client_impl.cpp index 7138825d..64ebeb30 100644 --- a/test/test_typedef/test_typedef_client_impl.cpp +++ b/test/test_typedef/test_typedef_client_impl.cpp @@ -6,8 +6,9 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" #include @@ -15,6 +16,11 @@ // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initTypedefService_client(client); +} + TEST(test_typedef, SendReceiveInt) { int32type a = 10, b = 2 * a + 1, pB; diff --git a/test/test_typedef/test_typedef_server_impl.cpp b/test/test_typedef/test_typedef_server_impl.cpp index c1e02bd6..eeeabca9 100644 --- a/test/test_typedef/test_typedef_server_impl.cpp +++ b/test/test_typedef/test_typedef_server_impl.cpp @@ -8,14 +8,18 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "c_test_unit_test_common_server.h" +#include "test_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include #include +using namespace erpc; +using namespace erpcShim; + TypedefService_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -129,6 +133,58 @@ MultiListArray arrayNumbers, uint32_t arrayNumbers_1_count, uint32_t arrayNumber }*/ /* end typedef unit tests */ +class TypedefService_server : public TypedefService_interface +{ +public: + int32type sendReceiveInt(int32type a) + { + int32type result; + result = ::sendReceiveInt(a); + + return result; + } + + Colors sendReceiveEnum(Colors a) + { + Colors result; + result = ::sendReceiveEnum(a); + + return result; + } + + B *sendReceiveStruct(const B *a) + { + B *result = NULL; + result = ::sendReceiveStruct(a); + + return result; + } + + ListType *sendReceiveListType(const ListType *listNumbers) + { + ListType *result = NULL; + result = ::sendReceiveListType(listNumbers); + + return result; + } + + ListType2 *sendReceive2ListType(const ListType2 *listNumbers) + { + ListType2 *result = NULL; + result = ::sendReceive2ListType(listNumbers); + + return result; + } + + newString sendReceiveString(newString hello) + { + newString result = NULL; + result = ::sendReceiveString(hello); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -137,7 +193,7 @@ void add_services(erpc::SimpleServer *server) { // define services to add on heap // allocate on heap so service doesn't go out of scope at end of method - svc = new TypedefService_service(); + svc = new TypedefService_service(new TypedefService_server()); // add services server->addService(svc); @@ -155,6 +211,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -174,11 +231,6 @@ void remove_services_from_server(erpc_server_t server) destroy_TypedefService_service(service_test); } -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif diff --git a/test/test_unions/test_unions_client_impl.cpp b/test/test_unions/test_unions_client_impl.cpp index 167374e7..17d29af3 100644 --- a/test/test_unions/test_unions_client_impl.cpp +++ b/test/test_unions/test_unions_client_impl.cpp @@ -6,8 +6,9 @@ * SPDX-License-Identifier: BSD-3-Clause */ +#include "c_test_client.h" #include "gtest.h" -#include "test.h" +#include "unit_test_wrapped.h" #include @@ -17,6 +18,11 @@ using namespace std; // Unit test Implementation code //////////////////////////////////////////////////////////////////////////////// +void initInterfaces(erpc_client_t client) +{ + initArithmeticService_client(client); +} + TEST(test_unions, testGenericCallback) { gapGenericEvent_t event = { diff --git a/test/test_unions/test_unions_server_impl.cpp b/test/test_unions/test_unions_server_impl.cpp index 457d9957..ea53611b 100644 --- a/test/test_unions/test_unions_server_impl.cpp +++ b/test/test_unions/test_unions_server_impl.cpp @@ -8,14 +8,18 @@ #include "erpc_server_setup.h" -#include "test_server.h" -#include "test_unit_test_common_server.h" +#include "c_test_server.h" +#include "c_test_unit_test_common_server.h" +#include "test_server.hpp" #include "unit_test.h" #include "unit_test_wrapped.h" #include #include +using namespace erpc; +using namespace erpcShim; + ArithmeticService_service *svc; //////////////////////////////////////////////////////////////////////////////// @@ -207,6 +211,42 @@ InnerList *testInnerList(const InnerList *il) return newList; } +class ArithmeticService_server : public ArithmeticService_interface +{ +public: + gapGenericEvent_t *testGenericCallback(const gapGenericEvent_t *event) + { + gapGenericEvent_t *result = NULL; + result = ::testGenericCallback(event); + + return result; + } + + foo *sendMyFoo(const foo *f) + { + foo *result = NULL; + result = ::sendMyFoo(f); + + return result; + } + + foo *sendMyUnion(fruit discriminator, const unionType *unionVariable) + { + foo *result = NULL; + result = ::sendMyUnion(discriminator, unionVariable); + + return result; + } + + InnerList *testInnerList(const InnerList *il) + { + InnerList *result = NULL; + result = ::testInnerList(il); + + return result; + } +}; + //////////////////////////////////////////////////////////////////////////////// // Add service to server code //////////////////////////////////////////////////////////////////////////////// @@ -215,7 +255,7 @@ void add_services(erpc::SimpleServer *server) { // define services to add on heap // allocate on heap so service doesn't go out of scope at end of method - svc = new ArithmeticService_service(); + svc = new ArithmeticService_service(new ArithmeticService_server()); // add services server->addService(svc); @@ -233,6 +273,7 @@ void remove_services(erpc::SimpleServer *server) server->removeService(svc); /* Delete unused service */ + delete svc->getHandler(); delete svc; } @@ -252,11 +293,6 @@ void remove_services_from_server(erpc_server_t server) destroy_ArithmeticService_service(service_test); } -void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) -{ - erpc_remove_service_from_server(server, service); - destroy_Common_service(service); -} #ifdef __cplusplus } #endif From 958569be6e695d1be30e52e3c6c7963a6a5448c3 Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Tue, 24 Oct 2023 16:55:45 +0200 Subject: [PATCH 13/24] Feature/buffer head (#378) * Framed transport header data stored in MessageBuffer Signed-off-by: Cervenka Dusan * RPMSG compile issues. !!! removed one mbf file and one file renamed. Signed-off-by: Cervenka Dusan * Fixed rpmsg tty Signed-off-by: Cervenka Dusan * swapping rpmsg inheritance Signed-off-by: Cervenka Dusan * Added missing override keyword Signed-off-by: Cervenka Dusan * Use using keyword to fix warnings Signed-off-by: Cervenka Dusan * Fix crcHeader for python Signed-off-by: Cervenka Dusan --------- Signed-off-by: Cervenka Dusan --- .../infra/erpc_arbitrated_client_manager.cpp | 2 +- erpc_c/infra/erpc_basic_codec.cpp | 14 + erpc_c/infra/erpc_basic_codec.hpp | 23 +- erpc_c/infra/erpc_client_manager.cpp | 15 +- erpc_c/infra/erpc_codec.hpp | 29 +- erpc_c/infra/erpc_framed_transport.cpp | 103 ++++-- erpc_c/infra/erpc_framed_transport.hpp | 48 ++- erpc_c/infra/erpc_message_buffer.cpp | 80 +++-- erpc_c/infra/erpc_message_buffer.hpp | 335 ++++++++++-------- erpc_c/infra/erpc_message_loggers.hpp | 2 +- erpc_c/infra/erpc_server.cpp | 2 +- erpc_c/infra/erpc_server.hpp | 2 +- erpc_c/infra/erpc_simple_server.cpp | 84 +++-- erpc_c/infra/erpc_simple_server.hpp | 27 +- erpc_c/infra/erpc_transport.hpp | 9 + erpc_c/infra/erpc_transport_arbitrator.cpp | 63 +++- erpc_c/infra/erpc_transport_arbitrator.hpp | 103 +++--- erpc_c/setup/erpc_mbf_setup.h | 14 - erpc_c/setup/erpc_setup_mbf_rpmsg.cpp | 19 +- erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp | 151 -------- .../transports/erpc_dspi_master_transport.hpp | 7 +- .../transports/erpc_dspi_slave_transport.hpp | 7 +- .../transports/erpc_i2c_slave_transport.hpp | 7 +- .../erpc_inter_thread_buffer_transport.hpp | 4 +- .../transports/erpc_lpi2c_slave_transport.hpp | 7 +- .../transports/erpc_lpspi_slave_transport.hpp | 7 +- erpc_c/transports/erpc_mu_transport.cpp | 5 + erpc_c/transports/erpc_mu_transport.hpp | 6 +- .../transports/erpc_rpmsg_linux_transport.hpp | 4 +- ...transport.hpp => erpc_rpmsg_lite_base.hpp} | 16 +- .../erpc_rpmsg_lite_rtos_transport.cpp | 35 +- .../erpc_rpmsg_lite_rtos_transport.hpp | 30 +- .../transports/erpc_rpmsg_lite_transport.cpp | 34 +- .../transports/erpc_rpmsg_lite_transport.hpp | 30 +- .../erpc_rpmsg_tty_rtos_transport.cpp | 136 +++---- .../erpc_rpmsg_tty_rtos_transport.hpp | 68 ++-- erpc_c/transports/erpc_serial_transport.hpp | 19 +- .../transports/erpc_spi_master_transport.hpp | 7 +- .../transports/erpc_spi_slave_transport.hpp | 7 +- .../erpc_spidev_master_transport.hpp | 7 +- erpc_c/transports/erpc_tcp_transport.hpp | 8 +- .../transports/erpc_uart_cmsis_transport.hpp | 7 +- erpc_c/transports/erpc_usb_cdc_transport.hpp | 7 +- erpc_python/erpc/transport.py | 20 +- .../src/templates/cpp_server_header.template | 4 +- .../src/templates/cpp_server_source.template | 16 +- erpcsniffer/src/Sniffer.cpp | 2 +- test/common/gtest/gtest.h | 2 + .../unit_test_tcp_arbitrator_client.cpp | 3 - .../unit_test_tcp_arbitrator_server.cpp | 15 +- 50 files changed, 873 insertions(+), 779 deletions(-) delete mode 100644 erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp rename erpc_c/transports/{erpc_rpmsg_lite_base_transport.hpp => erpc_rpmsg_lite_base.hpp} (87%) diff --git a/erpc_c/infra/erpc_arbitrated_client_manager.cpp b/erpc_c/infra/erpc_arbitrated_client_manager.cpp index 7338189f..53d3c4e6 100644 --- a/erpc_c/infra/erpc_arbitrated_client_manager.cpp +++ b/erpc_c/infra/erpc_arbitrated_client_manager.cpp @@ -73,7 +73,7 @@ void ArbitratedClientManager::performClientRequest(RequestContext &request) // Send the request. if (request.getCodec()->isStatusOk() == true) { - err = m_arbitrator->send(request.getCodec()->getBuffer()); + err = m_arbitrator->send(&request.getCodec()->getBufferRef()); request.getCodec()->updateStatus(err); } diff --git a/erpc_c/infra/erpc_basic_codec.cpp b/erpc_c/infra/erpc_basic_codec.cpp index 7fc54407..d59a697f 100644 --- a/erpc_c/infra/erpc_basic_codec.cpp +++ b/erpc_c/infra/erpc_basic_codec.cpp @@ -27,6 +27,13 @@ using namespace erpc; const uint32_t BasicCodec::kBasicCodecVersion = 1UL; +BasicCodec::BasicCodec(void) +: Codec() +{ +} + +BasicCodec::~BasicCodec(void) {} + void BasicCodec::startWriteMessage(message_type_t type, uint32_t service, uint32_t request, uint32_t sequence) { uint32_t header = @@ -367,6 +374,13 @@ void BasicCodec::readNullFlag(bool &isNull) ERPC_MANUALLY_CONSTRUCTED_ARRAY_STATIC(BasicCodec, s_basicCodecManual, ERPC_CODEC_COUNT); +BasicCodecFactory::BasicCodecFactory(void) +: CodecFactory() +{ +} + +BasicCodecFactory::~BasicCodecFactory(void) {} + Codec *BasicCodecFactory::create(void) { ERPC_CREATE_NEW_OBJECT(BasicCodec, s_basicCodecManual, ERPC_CODEC_COUNT) diff --git a/erpc_c/infra/erpc_basic_codec.hpp b/erpc_c/infra/erpc_basic_codec.hpp index c39a0c64..3dc0faa9 100644 --- a/erpc_c/infra/erpc_basic_codec.hpp +++ b/erpc_c/infra/erpc_basic_codec.hpp @@ -43,10 +43,15 @@ class BasicCodec : public Codec public: static const uint32_t kBasicCodecVersion; /*!< Codec version. */ - BasicCodec(void) - : Codec() - { - } + /*! + * @brief Constructor. + */ + BasicCodec(void); + + /*! + * @brief CodecFactory destructor + */ + virtual ~BasicCodec(void); //! @name Encoding //@{ @@ -344,6 +349,16 @@ class BasicCodec : public Codec class BasicCodecFactory : public CodecFactory { public: + /*! + * @brief Constructor. + */ + BasicCodecFactory(void); + + /*! + * @brief CodecFactory destructor + */ + virtual ~BasicCodecFactory(void); + /*! * @brief Return created codec. * diff --git a/erpc_c/infra/erpc_client_manager.cpp b/erpc_c/infra/erpc_client_manager.cpp index 34e62ad9..ef064b3d 100644 --- a/erpc_c/infra/erpc_client_manager.cpp +++ b/erpc_c/infra/erpc_client_manager.cpp @@ -78,7 +78,7 @@ void ClientManager::performClientRequest(RequestContext &request) // Send invocation request to server. if (request.getCodec()->isStatusOk() == true) { - err = m_transport->send(request.getCodec()->getBuffer()); + err = m_transport->send(&request.getCodec()->getBufferRef()); request.getCodec()->updateStatus(err); } @@ -88,7 +88,7 @@ void ClientManager::performClientRequest(RequestContext &request) if (request.getCodec()->isStatusOk() == true) { // Receive reply. - err = m_transport->receive(request.getCodec()->getBuffer()); + err = m_transport->receive(&request.getCodec()->getBufferRef()); request.getCodec()->updateStatus(err); } @@ -126,7 +126,7 @@ void ClientManager::performNestedClientRequest(RequestContext &request) // Send invocation request to server. if (request.getCodec()->isStatusOk() == true) { - err = m_transport->send(request.getCodec()->getBuffer()); + err = m_transport->send(&request.getCodec()->getBufferRef()); request.getCodec()->updateStatus(err); } @@ -167,7 +167,7 @@ void ClientManager::verifyReply(RequestContext &request) // Some transport layers change the request's message buffer pointer (for things like zero // copy support), so inCodec must be reset to work with correct buffer. - request.getCodec()->reset(); + request.getCodec()->reset(m_transport->reserveHeaderSize()); // Extract the reply header. request.getCodec()->startReadMessage(msgType, service, requestNumber, sequence); @@ -186,13 +186,14 @@ Codec *ClientManager::createBufferAndCodec(void) { Codec *codec = m_codecFactory->create(); MessageBuffer message; + uint8_t reservedMessageSpace = m_transport->reserveHeaderSize(); if (codec != NULL) { - message = m_messageFactory->create(); + message = m_messageFactory->create(reservedMessageSpace); if (NULL != message.get()) { - codec->setBuffer(message); + codec->setBuffer(message, reservedMessageSpace); } else { @@ -209,7 +210,7 @@ void ClientManager::releaseRequest(RequestContext &request) { if (request.getCodec() != NULL) { - m_messageFactory->dispose(request.getCodec()->getBuffer()); + m_messageFactory->dispose(&request.getCodec()->getBufferRef()); m_codecFactory->dispose(request.getCodec()); } } diff --git a/erpc_c/infra/erpc_codec.hpp b/erpc_c/infra/erpc_codec.hpp index c436f38b..af075bba 100644 --- a/erpc_c/infra/erpc_codec.hpp +++ b/erpc_c/infra/erpc_codec.hpp @@ -59,8 +59,7 @@ class Codec * This function initializes object attributes. */ Codec(void) - : m_buffer() - , m_cursor() + : m_cursor() , m_status(kErpcStatus_Success) { } @@ -75,24 +74,31 @@ class Codec * * @return Pointer to used message buffer. */ - MessageBuffer *getBuffer(void) { return &m_buffer; } + MessageBuffer getBuffer(void) { return m_cursor.getBuffer(); } + + MessageBuffer &getBufferRef(void) { return m_cursor.getBufferRef(); } /*! * @brief Prototype for set message buffer used for read and write data. * * @param[in] buf Message buffer to set. + * @param[in] skip How many bytes to skip from reading. */ - virtual void setBuffer(MessageBuffer &buf) + virtual void setBuffer(MessageBuffer &buf, uint8_t skip = 0) { - m_buffer = buf; - m_cursor.set(&m_buffer); + m_cursor.setBuffer(buf, skip); m_status = kErpcStatus_Success; } - /*! @brief Reset the codec to initial state. */ - virtual void reset(void) + /*! + * @brief Reset the codec to initial state. + * + * @param[in] skip How many bytes to skip from reading. + */ + virtual void reset(uint8_t skip = 0) { - m_cursor.set(&m_buffer); + MessageBuffer buffer = m_cursor.getBuffer(); + m_cursor.setBuffer(buffer, skip); m_status = kErpcStatus_Success; } @@ -394,9 +400,8 @@ class Codec virtual void readNullFlag(bool &isNull) = 0; protected: - MessageBuffer m_buffer; /*!< Message buffer object */ - MessageBuffer::Cursor m_cursor; /*!< Copy data to message buffers. */ - erpc_status_t m_status; /*!< Status of serialized data. */ + Cursor m_cursor; /*!< Copy data to message buffers. */ + erpc_status_t m_status; /*!< Status of serialized data. */ }; /*! diff --git a/erpc_c/infra/erpc_framed_transport.cpp b/erpc_c/infra/erpc_framed_transport.cpp index a27dfb05..b533241a 100644 --- a/erpc_c/infra/erpc_framed_transport.cpp +++ b/erpc_c/infra/erpc_framed_transport.cpp @@ -34,6 +34,12 @@ FramedTransport::FramedTransport(void) FramedTransport::~FramedTransport(void) {} +uint8_t FramedTransport::reserveHeaderSize(void) +{ + return sizeof(FramedTransport::Header::m_crcHeader) + sizeof(FramedTransport::Header::m_messageSize) + + sizeof(FramedTransport::Header::m_crcBody); +} + void FramedTransport::setCrc16(Crc16 *crcImpl) { erpc_assert(crcImpl); @@ -47,36 +53,57 @@ Crc16 *FramedTransport::getCrc16(void) erpc_status_t FramedTransport::receive(MessageBuffer *message) { - Header h; + Header h = { 0, 0, 0 }; erpc_status_t retVal; uint16_t computedCrc; + uint8_t offset = 0; erpc_assert((m_crcImpl != NULL) && ("Uninitialized Crc16 object." != NULL)); + // e.g. rpmsg tty may have nullptr and buffer is assigned in receive function. + if ((message->get() != nullptr) && (message->getLength() < reserveHeaderSize())) + { + retVal = kErpcStatus_MemoryError; + } + else { #if !ERPC_THREADS_IS(NONE) Mutex::Guard lock(m_receiveLock); #endif // Receive header first. - retVal = underlyingReceive((uint8_t *)&h, sizeof(h)); + retVal = underlyingReceive(message, reserveHeaderSize(), 0); + if ((retVal == kErpcStatus_Success) && (message->getLength() < reserveHeaderSize())) + { + retVal = kErpcStatus_MemoryError; + } if (retVal == kErpcStatus_Success) { + static_cast(memcpy(&h.m_crcHeader, message->get(), sizeof(h.m_crcHeader))); + offset = sizeof(h.m_crcHeader); + static_cast(memcpy(&h.m_messageSize, &message->get()[offset], sizeof(h.m_messageSize))); + offset += sizeof(h.m_messageSize); + static_cast(memcpy(&h.m_crcBody, &message->get()[offset], sizeof(h.m_crcBody))); + offset += sizeof(h.m_crcBody); + + ERPC_READ_AGNOSTIC_16(h.m_crcHeader); ERPC_READ_AGNOSTIC_16(h.m_messageSize); - ERPC_READ_AGNOSTIC_16(h.m_crc); + ERPC_READ_AGNOSTIC_16(h.m_crcBody); - // received size can't be zero. - if (h.m_messageSize == 0U) + computedCrc = + m_crcImpl->computeCRC16(reinterpret_cast(&h.m_messageSize), sizeof(h.m_messageSize)) + + m_crcImpl->computeCRC16(reinterpret_cast(&h.m_crcBody), sizeof(h.m_crcBody)); + if (computedCrc != h.m_crcHeader) { - retVal = kErpcStatus_ReceiveFailed; + retVal = kErpcStatus_CrcCheckFailed; } } if (retVal == kErpcStatus_Success) { // received size can't be larger then buffer length. - if (h.m_messageSize > message->getLength()) + if ((h.m_messageSize + reserveHeaderSize()) > message->getLength()) { retVal = kErpcStatus_ReceiveFailed; } @@ -84,20 +111,20 @@ erpc_status_t FramedTransport::receive(MessageBuffer *message) if (retVal == kErpcStatus_Success) { - // Receive rest of the message now we know its size. - retVal = underlyingReceive(message->get(), h.m_messageSize); + // rpmsg tty can receive all data in one buffer, others need second call. + if (message->getUsed() < (h.m_messageSize + reserveHeaderSize())) + { + // Receive rest of the message now we know its size. + retVal = underlyingReceive(message, h.m_messageSize, offset); + } } } if (retVal == kErpcStatus_Success) { // Verify CRC. - computedCrc = m_crcImpl->computeCRC16(message->get(), h.m_messageSize); - if (computedCrc == h.m_crc) - { - message->setUsed(h.m_messageSize); - } - else + computedCrc = m_crcImpl->computeCRC16(&message->get()[offset], h.m_messageSize); + if (computedCrc != h.m_crcBody) { retVal = kErpcStatus_CrcCheckFailed; } @@ -111,27 +138,51 @@ erpc_status_t FramedTransport::send(MessageBuffer *message) erpc_status_t ret; uint16_t messageLength; Header h; + uint8_t offset; erpc_assert((m_crcImpl != NULL) && ("Uninitialized Crc16 object." != NULL)); -#if !ERPC_THREADS_IS(NONE) - Mutex::Guard lock(m_sendLock); -#endif - - messageLength = message->getUsed(); + messageLength = message->getUsed() - reserveHeaderSize(); // Send header first. h.m_messageSize = messageLength; - h.m_crc = m_crcImpl->computeCRC16(message->get(), messageLength); + h.m_crcBody = m_crcImpl->computeCRC16(&message->get()[reserveHeaderSize()], messageLength); + h.m_crcHeader = + m_crcImpl->computeCRC16(reinterpret_cast(&h.m_messageSize), sizeof(h.m_messageSize)) + + m_crcImpl->computeCRC16(reinterpret_cast(&h.m_crcBody), sizeof(h.m_crcBody)); + ERPC_WRITE_AGNOSTIC_16(h.m_crcHeader); ERPC_WRITE_AGNOSTIC_16(h.m_messageSize); - ERPC_WRITE_AGNOSTIC_16(h.m_crc); + ERPC_WRITE_AGNOSTIC_16(h.m_crcBody); - ret = underlyingSend((uint8_t *)&h, sizeof(h)); - if (ret == kErpcStatus_Success) + static_cast(memcpy(message->get(), reinterpret_cast(&h.m_crcHeader), sizeof(h.m_crcHeader))); + offset = sizeof(h.m_crcHeader); + static_cast( + memcpy(&message->get()[offset], reinterpret_cast(&h.m_messageSize), sizeof(h.m_messageSize))); + offset += sizeof(h.m_messageSize); + static_cast( + memcpy(&message->get()[offset], reinterpret_cast(&h.m_crcBody), sizeof(h.m_crcBody))); + + ret = underlyingSend(message, message->getUsed(), 0); + + return ret; +} + +erpc_status_t FramedTransport::underlyingSend(MessageBuffer *message, uint32_t size, uint32_t offset) +{ + erpc_status_t retVal = underlyingSend(&message->get()[offset], size); + + return retVal; +} + +erpc_status_t FramedTransport::underlyingReceive(MessageBuffer *message, uint32_t size, uint32_t offset) +{ + erpc_status_t retVal = underlyingReceive(&message->get()[offset], size); + + if (retVal == kErpcStatus_Success) { - ret = underlyingSend(message->get(), messageLength); + message->setUsed(size + offset); } - return ret; + return retVal; } diff --git a/erpc_c/infra/erpc_framed_transport.hpp b/erpc_c/infra/erpc_framed_transport.hpp index 580b0ab8..443f1cf4 100644 --- a/erpc_c/infra/erpc_framed_transport.hpp +++ b/erpc_c/infra/erpc_framed_transport.hpp @@ -56,6 +56,14 @@ namespace erpc { class FramedTransport : public Transport { public: + /*! @brief Contents of the header that prefixes each message. */ + struct Header + { + uint16_t m_crcHeader; //!< CRC-16 over this header structure data + uint16_t m_messageSize; //!< Size in bytes of the message, excluding the header. + uint16_t m_crcBody; //!< CRC-16 over the message data. + }; + /*! * @brief Constructor. */ @@ -66,6 +74,13 @@ class FramedTransport : public Transport */ virtual ~FramedTransport(void); + /** + * @brief Size of data placed in MessageBuffer before serializing eRPC data. + * + * @return uint8_t Amount of bytes, reserved before serialized data. + */ + virtual uint8_t reserveHeaderSize(void) override; + /*! * @brief Receives an entire message. * @@ -95,13 +110,6 @@ class FramedTransport : public Transport */ virtual erpc_status_t send(MessageBuffer *message) override; - /*! @brief Contents of the header that prefixes each message. */ - struct Header - { - uint16_t m_messageSize; //!< Size in bytes of the message, excluding the header. - uint16_t m_crc; //!< CRC-16 over the message data. - }; - /*! * @brief This functions sets the CRC-16 implementation. * @@ -124,6 +132,32 @@ class FramedTransport : public Transport Mutex m_receiveLock; //!< Mutex protecting receive. #endif + /*! + * @brief Adds ability to framed transport to overwrite MessageBuffer when sending data. + * + * Usually we don't want to do that. + * + * @param message MessageBuffer to send. + * @param size size of message to send. + * @param offset data start address offset + * + * @return erpc_status_t kErpcStatus_Success when it finished successful otherwise error. + */ + virtual erpc_status_t underlyingSend(MessageBuffer *message, uint32_t size, uint32_t offset); + + /*! + * @brief Adds ability to framed transport to overwrite MessageBuffer when receiving data. + * + * Usually we don't want to do that. + * + * @param message MessageBuffer to send. + * @param size size of message to send. + * @param offset data start address offset + * + * @return erpc_status_t kErpcStatus_Success when it finished successful otherwise error. + */ + virtual erpc_status_t underlyingReceive(MessageBuffer *message, uint32_t size, uint32_t offset); + /*! * @brief Subclasses must implement this function to send data. * diff --git a/erpc_c/infra/erpc_message_buffer.cpp b/erpc_c/infra/erpc_message_buffer.cpp index 8c2cfc90..e578079c 100644 --- a/erpc_c/infra/erpc_message_buffer.cpp +++ b/erpc_c/infra/erpc_message_buffer.cpp @@ -9,6 +9,7 @@ */ #include "erpc_message_buffer.hpp" + #include "erpc_config_internal.h" #include @@ -20,6 +21,13 @@ using namespace std; // Code //////////////////////////////////////////////////////////////////////////////// +MessageBuffer::MessageBuffer(const MessageBuffer &buffer) +{ + m_buf = buffer.m_buf; + m_len = buffer.m_len; + m_used = buffer.m_used; +} + void MessageBuffer::setUsed(uint16_t used) { erpc_assert(used <= m_len); @@ -100,7 +108,7 @@ void MessageBuffer::swap(MessageBuffer *other) m_buf = temp.m_buf; } -void MessageBuffer::Cursor::set(MessageBuffer *buffer) +void Cursor::setBuffer(MessageBuffer &buffer, uint8_t reserved) { erpc_assert(buffer != NULL); @@ -108,62 +116,72 @@ void MessageBuffer::Cursor::set(MessageBuffer *buffer) // RPMSG when nested calls are enabled can set NULL buffer. // erpc_assert(buffer->get() && "Data buffer wasn't set to MessageBuffer."); // receive function should return err if it couldn't set data buffer. - m_pos = buffer->get(); + m_pos = buffer.get() + reserved; +} + +MessageBuffer Cursor::getBuffer(void) +{ + return m_buffer; +} + +MessageBuffer &Cursor::getBufferRef(void) +{ + return m_buffer; } -uint8_t &MessageBuffer::Cursor::operator[](int index) +uint8_t &Cursor::operator[](int index) { - erpc_assert(((m_pos + index) >= m_buffer->get()) && - ((uint16_t)(m_pos - m_buffer->get()) + index <= m_buffer->getLength())); + erpc_assert(((m_pos + index) >= m_buffer.get()) && + ((uint16_t)(m_pos - m_buffer.get()) + index <= m_buffer.getLength())); return m_pos[index]; } -const uint8_t &MessageBuffer::Cursor::operator[](int index) const +const uint8_t &Cursor::operator[](int index) const { - erpc_assert(((m_pos + index) >= m_buffer->get()) && - ((uint16_t)(m_pos - m_buffer->get()) + index <= m_buffer->getLength())); + erpc_assert(((m_pos + index) >= m_buffer.get()) && + ((uint16_t)(m_pos - m_buffer.get()) + index <= m_buffer.getLength())); return m_pos[index]; } -MessageBuffer::Cursor &MessageBuffer::Cursor::operator+=(uint16_t n) +Cursor &Cursor::operator+=(uint16_t n) { - erpc_assert((uint32_t)(m_pos - m_buffer->get()) + n <= m_buffer->getLength()); + erpc_assert((uint32_t)(m_pos - m_buffer.get()) + n <= m_buffer.getLength()); m_pos += n; return *this; } -MessageBuffer::Cursor &MessageBuffer::Cursor::operator-=(uint16_t n) +Cursor &Cursor::operator-=(uint16_t n) { - erpc_assert(((uintptr_t)m_pos >= n) && (m_pos - n) >= m_buffer->get()); + erpc_assert(((uintptr_t)m_pos >= n) && (m_pos - n) >= m_buffer.get()); m_pos -= n; return *this; } -MessageBuffer::Cursor &MessageBuffer::Cursor::operator++(void) +Cursor &Cursor::operator++(void) { - erpc_assert((uint16_t)(m_pos - m_buffer->get()) < m_buffer->getLength()); + erpc_assert((uint16_t)(m_pos - m_buffer.get()) < m_buffer.getLength()); ++m_pos; return *this; } -MessageBuffer::Cursor &MessageBuffer::Cursor::operator--(void) +Cursor &Cursor::operator--(void) { - erpc_assert(m_pos > m_buffer->get()); + erpc_assert(m_pos > m_buffer.get()); --m_pos; return *this; } -erpc_status_t MessageBuffer::Cursor::read(void *data, uint32_t length) +erpc_status_t Cursor::read(void *data, uint32_t length) { erpc_assert((m_pos != NULL) && ("Data buffer wasn't set to MessageBuffer." != NULL)); @@ -193,10 +211,10 @@ erpc_status_t MessageBuffer::Cursor::read(void *data, uint32_t length) return err; } -erpc_status_t MessageBuffer::Cursor::write(const void *data, uint32_t length) +erpc_status_t Cursor::write(const void *data, uint32_t length) { erpc_assert((m_pos != NULL) && ("Data buffer wasn't set to MessageBuffer." != NULL)); - erpc_assert(m_pos == (m_buffer->get() + m_buffer->getUsed())); + erpc_assert(m_pos == (m_buffer.get() + m_buffer.getUsed())); erpc_status_t err = kErpcStatus_Success; @@ -214,15 +232,33 @@ erpc_status_t MessageBuffer::Cursor::write(const void *data, uint32_t length) { (void)memcpy(m_pos, data, length); m_pos += length; - m_buffer->setUsed(m_buffer->getUsed() + length); + m_buffer.setUsed(m_buffer.getUsed() + length); } } return err; } -erpc_status_t MessageBufferFactory::prepareServerBufferForSend(MessageBuffer *message) +MessageBufferFactory::MessageBufferFactory(void) {} + +MessageBufferFactory::~MessageBufferFactory(void) {} + +MessageBuffer MessageBufferFactory::create(uint8_t reserveHeaderSize) +{ + MessageBuffer messageBuffer = create(); + + messageBuffer.setUsed(reserveHeaderSize); + + return messageBuffer; +} + +bool MessageBufferFactory::createServerBuffer(void) +{ + return true; +} + +erpc_status_t MessageBufferFactory::prepareServerBufferForSend(MessageBuffer &message, uint8_t reserveHeaderSize) { - message->setUsed(0); + message.setUsed(reserveHeaderSize); return kErpcStatus_Success; } diff --git a/erpc_c/infra/erpc_message_buffer.hpp b/erpc_c/infra/erpc_message_buffer.hpp index d815ca74..857c422f 100644 --- a/erpc_c/infra/erpc_message_buffer.hpp +++ b/erpc_c/infra/erpc_message_buffer.hpp @@ -64,6 +64,8 @@ class MessageBuffer { } + MessageBuffer(const MessageBuffer &buffer); + /*! * @brief This function set new buffer and his length. * @@ -183,162 +185,173 @@ class MessageBuffer */ const uint8_t &operator[](int index) const { return m_buf[index]; } +private: + uint8_t *volatile m_buf; /*!< Buffer used to read write data. */ + uint16_t volatile m_len; /*!< Length of buffer. */ + uint16_t volatile m_used; /*!< Used buffer bytes. */ +}; + +/*! + * @brief Cursor within a MessageBuffer. + */ +class Cursor +{ +public: + /*! + * @brief Constructor. + * + * This function initializes object attributes. + */ + Cursor(void) + : m_buffer() + , m_pos(NULL) + { + } + /*! - * @brief Cursor within a MessageBuffer. + * @brief Constructor. + * + * This function initializes object attributes. + * + * @param[in] buffer MessageBuffer for sending/receiving. */ - class Cursor + explicit Cursor(MessageBuffer &buffer) + : m_buffer(buffer) + , m_pos(buffer.get()) { - public: - /*! - * @brief Constructor. - * - * This function initializes object attributes. - */ - Cursor(void) - : m_buffer(NULL) - , m_pos(NULL) - { - } - - /*! - * @brief Constructor. - * - * This function initializes object attributes. - * - * @param[in] buffer MessageBuffer for sending/receiving. - */ - explicit Cursor(MessageBuffer *buffer) - : m_buffer(buffer) - , m_pos(buffer->get()) - { - } - - /*! - * @brief Set message buffer. - * - * @param[in] buffer Message buffer to set. - */ - void set(MessageBuffer *buffer); - - /*! - * @brief Return position in buffer. - * - * Return position, where it last write/read. - * - * @return Return position in buffer. - */ - uint8_t *get(void) { return m_pos; } - - /*! - * @brief Return position in buffer. - * - * Return position, where it last write/read. - * - * @return Return position in buffer. - */ - const uint8_t *get(void) const { return m_pos; } - - /*! - * @brief Return remaining free space in current buffer. - * - * @return Remaining free space in current buffer. - */ - uint16_t getRemaining(void) const { return m_buffer->getLength() - (uint16_t)(m_pos - m_buffer->get()); } - - /*! - * @brief Return remaining space from used of current buffer. - * - * @return Remaining space from used of current buffer. - */ - uint16_t getRemainingUsed(void) const { return m_buffer->getUsed() - (uint16_t)(m_pos - m_buffer->get()); } - - /*! - * @brief Read data from current buffer. - * - * @param[out] data Pointer to value, where copy read data. - * @param[in] length How much bytes need be read. - * - * @retval kErpcStatus_Success - * @retval kErpcStatus_BufferOverrun - */ - erpc_status_t read(void *data, uint32_t length); - - /*! - * @brief Read data from current buffer. - * - * @param[out] data Pointer to value to be sent. - * @param[in] length How much bytes need be wrote. - * - * @retval kErpcStatus_Success - * @retval kErpcStatus_BufferOverrun - */ - erpc_status_t write(const void *data, uint32_t length); - - /*! - * @brief Casting operator return local buffer. - */ - operator uint8_t *(void) { return m_pos; } - - /*! - * @brief Casting operator return local buffer. - */ - operator const uint8_t *(void) const { return m_pos; } - - /*! - * @brief Array operator return value of buffer at given index. - * - * @param[in] index Index in buffer. - */ - uint8_t &operator[](int index); - - /*! - * @brief Array operator return value of buffer at given index. - * - * @param[in] index Index in buffer. - */ - const uint8_t &operator[](int index) const; - - /*! - * @brief Sum operator return local buffer. - * - * @param[in] n Summing with n. - * - * @return Current cursor instance. - */ - Cursor &operator+=(uint16_t n); - - /*! - * @brief Subtract operator return local buffer. - * - * @param[in] n Subtracting with n. - * - * @return Current cursor instance. - */ - Cursor &operator-=(uint16_t n); - - /*! - * @brief Sum +1 operator. - * - * @return Current cursor instance. - */ - Cursor &operator++(void); - - /*! - * @brief Subtract -1 operator. - * - * @return Current cursor instance. - */ - Cursor &operator--(void); - - private: - MessageBuffer *m_buffer; /*!< Buffer for reading or writing data. */ - uint8_t *m_pos; /*!< Position in buffer, where it last write/read */ - }; + } + + /*! + * @brief Set message buffer. + * + * @param[in] buffer Message buffer to set. + * @param[in] reserved Moved cursor position outside of reserved memory. + */ + void setBuffer(MessageBuffer &buffer, uint8_t reserved = 0); + + /*! + * @brief Get message buffer. + */ + MessageBuffer getBuffer(void); + + /*! + * @brief Get message buffer. + */ + MessageBuffer &getBufferRef(void); + + /*! + * @brief Return position in buffer. + * + * Return position, where it last write/read. + * + * @return Return position in buffer. + */ + uint8_t *get(void) { return m_pos; } + + /*! + * @brief Return position in buffer. + * + * Return position, where it last write/read. + * + * @return Return position in buffer. + */ + const uint8_t *get(void) const { return m_pos; } + + /*! + * @brief Return remaining free space in current buffer. + * + * @return Remaining free space in current buffer. + */ + uint16_t getRemaining(void) const { return m_buffer.getLength() - (uint16_t)(m_pos - m_buffer.get()); } + + /*! + * @brief Return remaining space from used of current buffer. + * + * @return Remaining space from used of current buffer. + */ + uint16_t getRemainingUsed(void) const { return m_buffer.getUsed() - (uint16_t)(m_pos - m_buffer.get()); } + + /*! + * @brief Read data from current buffer. + * + * @param[out] data Pointer to value, where copy read data. + * @param[in] length How much bytes need be read. + * + * @retval kErpcStatus_Success + * @retval kErpcStatus_BufferOverrun + */ + erpc_status_t read(void *data, uint32_t length); + + /*! + * @brief Read data from current buffer. + * + * @param[out] data Pointer to value to be sent. + * @param[in] length How much bytes need be wrote. + * + * @retval kErpcStatus_Success + * @retval kErpcStatus_BufferOverrun + */ + erpc_status_t write(const void *data, uint32_t length); + + /*! + * @brief Casting operator return local buffer. + */ + operator uint8_t *(void) { return m_pos; } + + /*! + * @brief Casting operator return local buffer. + */ + operator const uint8_t *(void) const { return m_pos; } + + /*! + * @brief Array operator return value of buffer at given index. + * + * @param[in] index Index in buffer. + */ + uint8_t &operator[](int index); + + /*! + * @brief Array operator return value of buffer at given index. + * + * @param[in] index Index in buffer. + */ + const uint8_t &operator[](int index) const; + + /*! + * @brief Sum operator return local buffer. + * + * @param[in] n Summing with n. + * + * @return Current cursor instance. + */ + Cursor &operator+=(uint16_t n); + + /*! + * @brief Subtract operator return local buffer. + * + * @param[in] n Subtracting with n. + * + * @return Current cursor instance. + */ + Cursor &operator-=(uint16_t n); + + /*! + * @brief Sum +1 operator. + * + * @return Current cursor instance. + */ + Cursor &operator++(void); + + /*! + * @brief Subtract -1 operator. + * + * @return Current cursor instance. + */ + Cursor &operator--(void); private: - uint8_t *volatile m_buf; /*!< Buffer used to read write data. */ - uint16_t volatile m_len; /*!< Length of buffer. */ - uint16_t volatile m_used; /*!< Used buffer bytes. */ + MessageBuffer m_buffer; /*!< Buffer for reading or writing data. */ + uint8_t *m_pos; /*!< Position in buffer, where it last write/read */ }; /*! @@ -354,12 +367,12 @@ class MessageBufferFactory * * This function initializes object attributes. */ - MessageBufferFactory(void) {} + MessageBufferFactory(void); /*! * @brief MessageBufferFactory destructor */ - virtual ~MessageBufferFactory(void) {} + virtual ~MessageBufferFactory(void); /*! * @brief This function creates new message buffer. @@ -368,12 +381,23 @@ class MessageBufferFactory */ virtual MessageBuffer create(void) = 0; + /*! + * @brief This function creates new message buffer with reserved bytes at the beginning + * + * Reserved bytes can be used by transport to write transport related header file data. + * + * @param[in] reserveHeaderSize Reserved amount of bytes at the beginning of message buffer. + * + * @return New created MessageBuffer. + */ + MessageBuffer create(uint8_t reserveHeaderSize); + /*! * @brief This function informs server if it has to create buffer for received message. * * @return Has to return TRUE when server need create buffer for receiving message. */ - virtual bool createServerBuffer(void) { return true; } + virtual bool createServerBuffer(void); /*! * @brief This function is preparing output buffer on server side. @@ -382,8 +406,9 @@ class MessageBufferFactory * In case of using new buffer function has to free given buffer. * * @param[in] message MessageBuffer which can be reused. + * @param[in] reserveHeaderSize Reserved amount of bytes at the beginning of message buffer. */ - virtual erpc_status_t prepareServerBufferForSend(MessageBuffer *message); + virtual erpc_status_t prepareServerBufferForSend(MessageBuffer &message, uint8_t reserveHeaderSize = 0); /*! * @brief This function disposes message buffer. diff --git a/erpc_c/infra/erpc_message_loggers.hpp b/erpc_c/infra/erpc_message_loggers.hpp index a060d163..528c7702 100644 --- a/erpc_c/infra/erpc_message_loggers.hpp +++ b/erpc_c/infra/erpc_message_loggers.hpp @@ -86,7 +86,7 @@ class MessageLoggers /*! * @brief Transport destructor */ - virtual ~MessageLoggers(void); + ~MessageLoggers(void); /*! * @brief This function add given transport to newly created MessageLogger object. diff --git a/erpc_c/infra/erpc_server.cpp b/erpc_c/infra/erpc_server.cpp index 2fe306bb..0a2d558e 100644 --- a/erpc_c/infra/erpc_server.cpp +++ b/erpc_c/infra/erpc_server.cpp @@ -91,7 +91,7 @@ erpc_status_t Server::processMessage(Codec *codec, message_type_t msgType, uint3 if (err == kErpcStatus_Success) { - err = service->handleInvocation(methodId, sequence, codec, m_messageFactory); + err = service->handleInvocation(methodId, sequence, codec, m_messageFactory, m_transport); } return err; diff --git a/erpc_c/infra/erpc_server.hpp b/erpc_c/infra/erpc_server.hpp index ea0ea203..b16df195 100644 --- a/erpc_c/infra/erpc_server.hpp +++ b/erpc_c/infra/erpc_server.hpp @@ -87,7 +87,7 @@ class Service * @return Based on handleInvocation implementation. */ virtual erpc_status_t handleInvocation(uint32_t methodId, uint32_t sequence, Codec *codec, - MessageBufferFactory *messageFactory) = 0; + MessageBufferFactory *messageFactory, Transport *transport) = 0; protected: uint32_t m_serviceId; /*!< Service unique id. */ diff --git a/erpc_c/infra/erpc_simple_server.cpp b/erpc_c/infra/erpc_simple_server.cpp index 3ac59c37..9d268849 100644 --- a/erpc_c/infra/erpc_simple_server.cpp +++ b/erpc_c/infra/erpc_simple_server.cpp @@ -15,17 +15,49 @@ using namespace erpc; //////////////////////////////////////////////////////////////////////////////// // Code //////////////////////////////////////////////////////////////////////////////// +SimpleServer::SimpleServer(void) +: m_isServerOn(true) +{ +} -void SimpleServer::disposeBufferAndCodec(Codec *codec) +SimpleServer::~SimpleServer(void) {} + +erpc_status_t SimpleServer::run(void) { - if (codec != NULL) + erpc_status_t err = kErpcStatus_Success; + while ((err == kErpcStatus_Success) && m_isServerOn) { - if (codec->getBuffer() != NULL) + err = runInternal(); + } + return err; +} + +erpc_status_t SimpleServer::poll(void) +{ + erpc_status_t err; + + if (m_isServerOn) + { + if (m_transport->hasMessage() == true) { - m_messageFactory->dispose(codec->getBuffer()); + err = runInternal(); } - m_codecFactory->dispose(codec); + else + { + err = kErpcStatus_Success; + } + } + else + { + err = kErpcStatus_ServerIsDown; } + + return err; +} + +void SimpleServer::stop(void) +{ + m_isServerOn = false; } erpc_status_t SimpleServer::runInternal(void) @@ -103,7 +135,7 @@ erpc_status_t SimpleServer::runInternalBegin(Codec **codec, MessageBuffer &buff, if (err == kErpcStatus_Success) { - (*codec)->setBuffer(buff); + (*codec)->setBuffer(buff, m_transport->reserveHeaderSize()); err = readHeadOfMessage(*codec, msgType, serviceId, methodId, sequence); if (err != kErpcStatus_Success) @@ -130,7 +162,7 @@ erpc_status_t SimpleServer::runInternalEnd(Codec *codec, message_type_t msgType, if (err == kErpcStatus_Success) { #endif - err = m_transport->send(codec->getBuffer()); + err = m_transport->send(&codec->getBufferRef()); #if ERPC_MESSAGE_LOGGING } #endif @@ -151,16 +183,6 @@ erpc_status_t SimpleServer::runInternalEnd(Codec *codec, message_type_t msgType, return err; } -erpc_status_t SimpleServer::run(void) -{ - erpc_status_t err = kErpcStatus_Success; - while ((err == kErpcStatus_Success) && m_isServerOn) - { - err = runInternal(); - } - return err; -} - #if ERPC_NESTED_CALLS erpc_status_t SimpleServer::run(RequestContext &request) { @@ -188,7 +210,7 @@ erpc_status_t SimpleServer::run(RequestContext &request) if (sequence == request.getSequence()) { // Swap the received message buffer with the client's message buffer. - request.getCodec()->getBuffer()->swap(&buff); + request.getCodec()->getBufferRef().swap(&buff); codec->setBuffer(buff); } @@ -212,30 +234,14 @@ erpc_status_t SimpleServer::run(RequestContext &request) } #endif -erpc_status_t SimpleServer::poll(void) +void SimpleServer::disposeBufferAndCodec(Codec *codec) { - erpc_status_t err; - - if (m_isServerOn) + if (codec != NULL) { - if (m_transport->hasMessage() == true) + if (codec->getBuffer() != NULL) { - err = runInternal(); + m_messageFactory->dispose(&codec->getBufferRef()); } - else - { - err = kErpcStatus_Success; - } - } - else - { - err = kErpcStatus_ServerIsDown; + m_codecFactory->dispose(codec); } - - return err; -} - -void SimpleServer::stop(void) -{ - m_isServerOn = false; } diff --git a/erpc_c/infra/erpc_simple_server.hpp b/erpc_c/infra/erpc_simple_server.hpp index 21083348..efe0ebc0 100644 --- a/erpc_c/infra/erpc_simple_server.hpp +++ b/erpc_c/infra/erpc_simple_server.hpp @@ -37,10 +37,9 @@ class SimpleServer : public Server * * This function initializes object attributes. */ - SimpleServer(void) - : m_isServerOn(true) - { - } + SimpleServer(void); + + virtual ~SimpleServer(void); /*! * @brief Run server in infinite loop. @@ -66,6 +65,16 @@ class SimpleServer : public Server virtual void stop(void) override; protected: + bool m_isServerOn; /*!< Information if server is ON or OFF. */ + + /*! + * @brief Run server implementation. + * + * This function call functions for receiving data, process this data and + * if reply exist, send it back. + */ + erpc_status_t runInternal(void); + /*! * @brief This function handle receiving request message and reading base info about message. * @@ -104,22 +113,12 @@ class SimpleServer : public Server virtual erpc_status_t run(RequestContext &request) override; #endif - /*! - * @brief Run server implementation. - * - * This function call functions for receiving data, process this data and - * if reply exist, send it back. - */ - erpc_status_t runInternal(void); - /*! * @brief Disposing message buffers and codecs. * * @param[in] codec Pointer to codec to dispose. It contains also message buffer to dispose. */ void disposeBufferAndCodec(Codec *codec); - - bool m_isServerOn; /*!< Information if server is ON or OFF. */ }; } // namespace erpc diff --git a/erpc_c/infra/erpc_transport.hpp b/erpc_c/infra/erpc_transport.hpp index 88fe2e16..88fde0e3 100644 --- a/erpc_c/infra/erpc_transport.hpp +++ b/erpc_c/infra/erpc_transport.hpp @@ -46,6 +46,13 @@ class Transport */ virtual ~Transport(void) {} + /** + * @brief Size of data placed in MessageBuffer before serializing eRPC data. + * + * @return uint8_t Amount of bytes, reserved before serialized data. + */ + virtual uint8_t reserveHeaderSize(void) { return 0; } + /*! * @brief Prototype for receiving message. * @@ -106,10 +113,12 @@ class TransportFactory * @brief Constructor. */ TransportFactory(void) {} + /*! * @brief TransportFactory destructor */ virtual ~TransportFactory(void) {} + /*! * @brief Return created transport object. * diff --git a/erpc_c/infra/erpc_transport_arbitrator.cpp b/erpc_c/infra/erpc_transport_arbitrator.cpp index 453fa341..5d57f686 100644 --- a/erpc_c/infra/erpc_transport_arbitrator.cpp +++ b/erpc_c/infra/erpc_transport_arbitrator.cpp @@ -44,24 +44,9 @@ TransportArbitrator::~TransportArbitrator(void) freeClientList(m_clientFreeList); } -void TransportArbitrator::setCrc16(Crc16 *crcImpl) +uint8_t TransportArbitrator::reserveHeaderSize(void) { - erpc_assert(crcImpl != NULL); - erpc_assert(m_sharedTransport != NULL); - m_sharedTransport->setCrc16(crcImpl); -} - -Crc16 *TransportArbitrator::getCrc16(void) -{ - erpc_assert(m_sharedTransport != NULL); - return m_sharedTransport->getCrc16(); -} - -bool TransportArbitrator::hasMessage(void) -{ - erpc_assert((m_sharedTransport != NULL) && ("shared transport is not set" != NULL)); - - return m_sharedTransport->hasMessage(); + return m_sharedTransport->reserveHeaderSize(); } erpc_status_t TransportArbitrator::receive(MessageBuffer *message) @@ -96,7 +81,7 @@ erpc_status_t TransportArbitrator::receive(MessageBuffer *message) break; } - m_codec->setBuffer(*message); + m_codec->setBuffer(*message, m_sharedTransport->reserveHeaderSize()); // Parse the message header. m_codec->startReadMessage(msgType, service, requestNumber, sequence); @@ -125,7 +110,7 @@ erpc_status_t TransportArbitrator::receive(MessageBuffer *message) if (client->m_isValid && (sequence == client->m_request->getSequence())) { // Swap the received message buffer with the client's message buffer. - client->m_request->getCodec()->getBuffer()->swap(message); + client->m_request->getCodec()->getBufferRef().swap(message); // Wake up the client receive thread. client->m_sem.put(); @@ -151,6 +136,46 @@ erpc_status_t TransportArbitrator::send(MessageBuffer *message) return m_sharedTransport->send(message); } +bool TransportArbitrator::hasMessage(void) +{ + erpc_assert((m_sharedTransport != NULL) && ("shared transport is not set" != NULL)); + + return m_sharedTransport->hasMessage(); +} + +void TransportArbitrator::setCrc16(Crc16 *crcImpl) +{ + erpc_assert(crcImpl != NULL); + erpc_assert(m_sharedTransport != NULL); + m_sharedTransport->setCrc16(crcImpl); +} + +Crc16 *TransportArbitrator::getCrc16(void) +{ + erpc_assert(m_sharedTransport != NULL); + return m_sharedTransport->getCrc16(); +} + +void TransportArbitrator::setSharedTransport(Transport *shared) +{ + m_sharedTransport = shared; +} + +Transport *TransportArbitrator::getSharedTransport(void) +{ + return m_sharedTransport; +} + +void TransportArbitrator::setCodec(Codec *codec) +{ + m_codec = codec; +} + +Codec *TransportArbitrator::getCodec(void) +{ + return m_codec; +} + TransportArbitrator::client_token_t TransportArbitrator::prepareClientReceive(RequestContext &request) { PendingClientInfo *info = addPendingClient(); diff --git a/erpc_c/infra/erpc_transport_arbitrator.hpp b/erpc_c/infra/erpc_transport_arbitrator.hpp index 891ed7a3..3077d500 100644 --- a/erpc_c/infra/erpc_transport_arbitrator.hpp +++ b/erpc_c/infra/erpc_transport_arbitrator.hpp @@ -53,44 +53,84 @@ class TransportArbitrator : public Transport */ virtual ~TransportArbitrator(void); + /** + * @brief Size of data placed in MessageBuffer before serializing eRPC data. + * + * @return uint8_t Amount of bytes, reserved before serialized data. + */ + virtual uint8_t reserveHeaderSize(void) override; + + /*! + * @brief Prototype for receiving message. + * + * Each transport layer need define this function. + * + * @param[out] message Will return pointer to received message buffer. + * + * @return based on receive implementation. + */ + virtual erpc_status_t receive(MessageBuffer *message) override; + + /*! + * @brief Prototype for send message. + * + * Each transport layer need define this function. + * + * @param[in] message Pass message buffer to send. + * + * @return based on send implementation. + */ + virtual erpc_status_t send(MessageBuffer *message) override; + + /*! + * @brief Check if the underlying shared transport has a message + * + * @retval The underlying transport is expected to return true when a message is available to + * process and false otherwise. + */ + virtual bool hasMessage(void) override; + + /*! + * @brief This functions sets the CRC-16 implementation. + * + * @param[in] crcImpl Object containing crc-16 compute function. + */ + virtual void setCrc16(Crc16 *crcImpl) override; + + /*! + * @brief This functions gets the CRC-16 object. + * + * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. + */ + virtual Crc16 * getCrc16(void) override; + /*! * @brief This function set shared client/server transport. * * @param[in] shared Shared client/server transport. */ - void setSharedTransport(Transport *shared) { m_sharedTransport = shared; } + void setSharedTransport(Transport *shared); /*! * @brief This function returns shared client/server transport. * * @return Transport * Returns shared client/server transport. */ - Transport * getSharedTransport(void) { return m_sharedTransport; } + Transport * getSharedTransport(void); /*! * @brief This function set codec. * * @param[in] codec Codec. */ - void setCodec(Codec *codec) { m_codec = codec; } + void setCodec(Codec *codec); /*! * @brief This function get codec. * * @return Codec * Pointer to codec used within transport. */ - Codec * getCodec(void) { return m_codec; } - - /*! - * @brief Prototype for receiving message. - * - * Each transport layer need define this function. - * - * @param[out] message Will return pointer to received message buffer. - * - * @return based on receive implementation. - */ - virtual erpc_status_t receive(MessageBuffer *message) override; + Codec * getCodec(void); /*! * @brief Add a client request to the client list. @@ -117,39 +157,6 @@ class TransportArbitrator : public Transport */ erpc_status_t clientReceive(client_token_t token); - /*! - * @brief Prototype for send message. - * - * Each transport layer need define this function. - * - * @param[in] message Pass message buffer to send. - * - * @return based on send implementation. - */ - virtual erpc_status_t send(MessageBuffer *message) override; - - /*! - * @brief This functions sets the CRC-16 implementation. - * - * @param[in] crcImpl Object containing crc-16 compute function. - */ - virtual void setCrc16(Crc16 *crcImpl) override; - - /*! - * @brief This functions gets the CRC-16 object. - * - * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. - */ - virtual Crc16 * getCrc16(void) override; - - /*! - * @brief Check if the underlying shared transport has a message - * - * @retval The underlying transport is expected to return true when a message is available to - * process and false otherwise. - */ - virtual bool hasMessage(void) override; - /*! * @brief Request info for a client trying to receive a response. */ diff --git a/erpc_c/setup/erpc_mbf_setup.h b/erpc_c/setup/erpc_mbf_setup.h index f760914a..87ba45d3 100644 --- a/erpc_c/setup/erpc_mbf_setup.h +++ b/erpc_c/setup/erpc_mbf_setup.h @@ -48,20 +48,6 @@ erpc_mbf_t erpc_mbf_dynamic_init(void); */ void erpc_mbf_dynamic_deinit(erpc_mbf_t mbf); -/*! - * @brief Create MessageBuffer factory which is using RPMSG LITE TTY buffers. - * - * Has to be used with RPMSG lite TTY transport. - */ -erpc_mbf_t erpc_mbf_rpmsg_tty_init(erpc_transport_t transport); - -/*! - * @brief Deinit MessageBuffer factory. - * - * @param[in] mbf MessageBuffer factory which was initialized in init function. - */ -void erpc_mbf_rpmsg_tty_deinit(erpc_mbf_t mbf); - /*! * @brief Create MessageBuffer factory which is using RPMSG LITE zero copy buffers. * diff --git a/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp b/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp index ccf03eea..2d0c2e7d 100644 --- a/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp +++ b/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp @@ -12,7 +12,7 @@ #include "erpc_manually_constructed.hpp" #include "erpc_mbf_setup.h" #include "erpc_message_buffer.hpp" -#include "erpc_rpmsg_lite_base_transport.hpp" +#include "erpc_rpmsg_lite_base.hpp" extern "C" { #include "rpmsg_lite.h" @@ -20,6 +20,8 @@ extern "C" { using namespace erpc; +#define TIMEOUT_MS 10 + //////////////////////////////////////////////////////////////////////////////// // Classes //////////////////////////////////////////////////////////////////////////////// @@ -51,7 +53,7 @@ class RPMsgMessageBufferFactory : public MessageBufferFactory { void *buf = NULL; uint32_t size = 0; - buf = rpmsg_lite_alloc_tx_buffer(m_rpmsg, &size, RL_BLOCK); + buf = rpmsg_lite_alloc_tx_buffer(m_rpmsg, &size, TIMEOUT_MS); erpc_assert(NULL != buf); return MessageBuffer(reinterpret_cast(buf), size); @@ -77,14 +79,15 @@ class RPMsgMessageBufferFactory : public MessageBufferFactory } } - virtual erpc_status_t prepareServerBufferForSend(MessageBuffer *message) + virtual erpc_status_t prepareServerBufferForSend(MessageBuffer &message, uint8_t reserveHeaderSize = 0) { erpc_status_t status; - dispose(message); - *message = create(); - if (message->get() != NULL) + dispose(&message); + message = create(); + if (message.get() != NULL) { + message.setUsed(reserveHeaderSize); status = kErpcStatus_Success; } else @@ -118,12 +121,12 @@ erpc_mbf_t erpc_mbf_rpmsg_init(erpc_transport_t transport) } else { - s_msgFactory.construct(reinterpret_cast(transport)->get_rpmsg_lite_instance()); + s_msgFactory.construct(reinterpret_cast(transport)->get_rpmsg_lite_instance()); msgFactory = s_msgFactory.get(); } #elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC msgFactory = - new RPMsgMessageBufferFactory(reinterpret_cast(transport)->get_rpmsg_lite_instance()); + new RPMsgMessageBufferFactory(reinterpret_cast(transport)->get_rpmsg_lite_instance()); #else #error "Unknown eRPC allocation policy!" #endif diff --git a/erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp b/erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp deleted file mode 100644 index d6a6cd3a..00000000 --- a/erpc_c/setup/erpc_setup_mbf_rpmsg_tty.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2017 NXP - * Copyright 2021 ACRIOS Systems s.r.o. - * All rights reserved. - * - * - * SPDX-License-Identifier: BSD-3-Clause - */ - -#include "erpc_config_internal.h" -#include "erpc_framed_transport.hpp" -#include "erpc_manually_constructed.hpp" -#include "erpc_mbf_setup.h" -#include "erpc_message_buffer.hpp" -#include "erpc_rpmsg_lite_base_transport.hpp" - -extern "C" { -#include "rpmsg_lite.h" -} - -using namespace erpc; - -#define TIMEOUT_MS 10 - -//////////////////////////////////////////////////////////////////////////////// -// Classes -//////////////////////////////////////////////////////////////////////////////// - -/*! - * @brief RPMsg TTY message buffer factory - */ -class RPMsgTTYMessageBufferFactory : public MessageBufferFactory -{ -public: - /*! - * @brief Constructor. - * - * @param [in] rpmsg Pointer to instance of RPMSG lite. - */ - explicit RPMsgTTYMessageBufferFactory(struct rpmsg_lite_instance *rpmsg) { m_rpmsg = rpmsg; } - - /*! - * @brief Destructor - */ - virtual ~RPMsgTTYMessageBufferFactory(void) {} - - /*! - * @brief This function creates new message buffer. - * - * @return MessageBuffer New created MessageBuffer. - */ - virtual MessageBuffer create(void) - { - void *buf = NULL; - uint32_t size = 0; - buf = rpmsg_lite_alloc_tx_buffer(m_rpmsg, &size, TIMEOUT_MS); - - erpc_assert(NULL != buf); - return MessageBuffer(&(reinterpret_cast(buf))[sizeof(FramedTransport::Header)], - size - sizeof(FramedTransport::Header)); - } - - /*! - * @brief This function disposes message buffer. - * - * @param[in] buf MessageBuffer to dispose. - */ - virtual void dispose(MessageBuffer *buf) - { - erpc_assert(buf != NULL); - void *tmp = reinterpret_cast(buf->get()); - if (tmp != NULL) - { - int32_t ret; - ret = rpmsg_lite_release_rx_buffer( - m_rpmsg, reinterpret_cast(reinterpret_cast(tmp) - sizeof(FramedTransport::Header))); - if (ret != RL_SUCCESS) - { - // error - } - } - } - - virtual erpc_status_t prepareServerBufferForSend(MessageBuffer *message) - { - erpc_status_t status; - - dispose(message); - *message = create(); - if (message->get() != NULL) - { - status = kErpcStatus_Success; - } - else - { - status = kErpcStatus_MemoryError; - } - - return status; - } - - virtual bool createServerBuffer(void) { return false; } - -protected: - struct rpmsg_lite_instance *m_rpmsg; /*!< Pointer to instance of RPMSG lite. */ -}; - -//////////////////////////////////////////////////////////////////////////////// -// Variables -//////////////////////////////////////////////////////////////////////////////// - -ERPC_MANUALLY_CONSTRUCTED_STATIC(RPMsgTTYMessageBufferFactory, s_msgFactory); - -erpc_mbf_t erpc_mbf_rpmsg_tty_init(erpc_transport_t transport) -{ - RPMsgTTYMessageBufferFactory *msgFactory; - -#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC - if (s_msgFactory.isUsed()) - { - msgFactory = NULL; - } - else - { - s_msgFactory.construct(reinterpret_cast(transport)->get_rpmsg_lite_instance()); - msgFactory = s_msgFactory.get(); - } -#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC - msgFactory = - new RPMsgTTYMessageBufferFactory(reinterpret_cast(transport)->get_rpmsg_lite_instance()); -#else -#error "Unknown eRPC allocation policy!" -#endif - - return reinterpret_cast(msgFactory); -} - -void erpc_mbf_rpmsg_tty_deinit(erpc_mbf_t mbf) -{ -#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC - (void)mbf; - s_msgFactory.destroy(); -#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC - erpc_assert(mbf != NULL); - - RPMsgTTYMessageBufferFactory *msgFactory = reinterpret_cast(mbf); - - delete msgFactory; -#endif -} diff --git a/erpc_c/transports/erpc_dspi_master_transport.hpp b/erpc_c/transports/erpc_dspi_master_transport.hpp index 3605542d..108a0d42 100644 --- a/erpc_c/transports/erpc_dspi_master_transport.hpp +++ b/erpc_c/transports/erpc_dspi_master_transport.hpp @@ -63,6 +63,9 @@ class DspiMasterTransport : public FramedTransport uint32_t m_srcClock_Hz; /*!< Source clock of DSPI peripheral used in this transport layer */ private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from DSPI peripheral. * @@ -72,7 +75,7 @@ class DspiMasterTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed DSPI failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to DSPI peripheral. @@ -83,7 +86,7 @@ class DspiMasterTransport : public FramedTransport * @retval kErpcStatus_SendFailed DSPI failed to send data. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_dspi_slave_transport.hpp b/erpc_c/transports/erpc_dspi_slave_transport.hpp index f9d8039a..65cc214d 100644 --- a/erpc_c/transports/erpc_dspi_slave_transport.hpp +++ b/erpc_c/transports/erpc_dspi_slave_transport.hpp @@ -78,6 +78,9 @@ class DspiSlaveTransport : public FramedTransport #endif private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from DSPI peripheral. * @@ -87,7 +90,7 @@ class DspiSlaveTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed DSPI failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to DSPI peripheral. @@ -98,7 +101,7 @@ class DspiSlaveTransport : public FramedTransport * @retval kErpcStatus_SendFailed DSPI failed to send data. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_i2c_slave_transport.hpp b/erpc_c/transports/erpc_i2c_slave_transport.hpp index 425b2807..6cd23287 100644 --- a/erpc_c/transports/erpc_i2c_slave_transport.hpp +++ b/erpc_c/transports/erpc_i2c_slave_transport.hpp @@ -78,6 +78,9 @@ class I2cSlaveTransport : public FramedTransport #endif private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from I2C peripheral. * @@ -87,7 +90,7 @@ class I2cSlaveTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed I2C failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to I2C peripheral. @@ -98,7 +101,7 @@ class I2cSlaveTransport : public FramedTransport * @retval kErpcStatus_SendFailed I2C failed to send data. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_inter_thread_buffer_transport.hpp b/erpc_c/transports/erpc_inter_thread_buffer_transport.hpp index 907a92f0..655aba2d 100644 --- a/erpc_c/transports/erpc_inter_thread_buffer_transport.hpp +++ b/erpc_c/transports/erpc_inter_thread_buffer_transport.hpp @@ -57,8 +57,8 @@ class InterThreadBufferTransport : public Transport void linkWithPeer(InterThreadBufferTransport *peer); - virtual erpc_status_t receive(MessageBuffer *message); - virtual erpc_status_t send(MessageBuffer *message); + virtual erpc_status_t receive(MessageBuffer *message)override; + virtual erpc_status_t send(MessageBuffer *message)override; virtual int32_t getAvailable(void) const { return 0; } diff --git a/erpc_c/transports/erpc_lpi2c_slave_transport.hpp b/erpc_c/transports/erpc_lpi2c_slave_transport.hpp index 407ed7ac..53ab6c9a 100644 --- a/erpc_c/transports/erpc_lpi2c_slave_transport.hpp +++ b/erpc_c/transports/erpc_lpi2c_slave_transport.hpp @@ -77,6 +77,9 @@ class LPI2cSlaveTransport : public FramedTransport #endif private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from LPI2C peripheral. * @@ -86,7 +89,7 @@ class LPI2cSlaveTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed LPI2C failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to LPI2C peripheral. @@ -97,7 +100,7 @@ class LPI2cSlaveTransport : public FramedTransport * @retval kErpcStatus_SendFailed LPI2C failed to send data. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_lpspi_slave_transport.hpp b/erpc_c/transports/erpc_lpspi_slave_transport.hpp index 7c5c726a..8e0bd40f 100644 --- a/erpc_c/transports/erpc_lpspi_slave_transport.hpp +++ b/erpc_c/transports/erpc_lpspi_slave_transport.hpp @@ -78,6 +78,9 @@ class LPSpiSlaveTransport : public FramedTransport #endif private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from LPSPI peripheral. * @@ -87,7 +90,7 @@ class LPSpiSlaveTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed LPSPI failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to LPSPI peripheral. @@ -98,7 +101,7 @@ class LPSpiSlaveTransport : public FramedTransport * @retval kErpcStatus_SendFailed LPSPI failed to send data. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_mu_transport.cpp b/erpc_c/transports/erpc_mu_transport.cpp index 15de63f8..e6c64a63 100644 --- a/erpc_c/transports/erpc_mu_transport.cpp +++ b/erpc_c/transports/erpc_mu_transport.cpp @@ -287,6 +287,11 @@ erpc_status_t MUTransport::send(MessageBuffer *message) return status; } +bool MUTransport::hasMessage(void) +{ + return m_newMessage; +} + extern "C" { #if ERPC_TRANSPORT_MU_USE_MCMGR diff --git a/erpc_c/transports/erpc_mu_transport.hpp b/erpc_c/transports/erpc_mu_transport.hpp index 16a819e1..2c3602ec 100644 --- a/erpc_c/transports/erpc_mu_transport.hpp +++ b/erpc_c/transports/erpc_mu_transport.hpp @@ -127,7 +127,7 @@ class MUTransport : public Transport * * @return kErpcStatus_Success */ - virtual erpc_status_t receive(MessageBuffer *message); + virtual erpc_status_t receive(MessageBuffer *message) override; /*! * @brief Function to send prepared message. @@ -137,7 +137,7 @@ class MUTransport : public Transport * @retval kErpcStatus_SendFailed Failed to send message buffer. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t send(MessageBuffer *message); + virtual erpc_status_t send(MessageBuffer *message) override; /*! * @brief Function to check if is new message to receive. @@ -146,7 +146,7 @@ class MUTransport : public Transport * * @return True if exist new message, else false. */ - virtual bool hasMessage(void) { return m_newMessage; } + virtual bool hasMessage(void) override; #if ERPC_TRANSPORT_MU_USE_MCMGR /*! diff --git a/erpc_c/transports/erpc_rpmsg_linux_transport.hpp b/erpc_c/transports/erpc_rpmsg_linux_transport.hpp index ce13725c..b66dc8ab 100644 --- a/erpc_c/transports/erpc_rpmsg_linux_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_linux_transport.hpp @@ -56,7 +56,7 @@ class RPMsgLinuxTransport : public Transport * @retval kErpcStatus_Success When message was received successfully. * @retval kErpcStatus_Fail When message wasn't received successfully. */ - virtual erpc_status_t receive(MessageBuffer *message); + virtual erpc_status_t receive(MessageBuffer *message) override; /*! * @brief This function sends the eRPC messages. @@ -66,7 +66,7 @@ class RPMsgLinuxTransport : public Transport * @retval kErpcStatus_Success When message was sent successfully. * @retval kErpcStatus_Fail When message wasn't sent successfully. */ - virtual erpc_status_t send(MessageBuffer *message); + virtual erpc_status_t send(MessageBuffer *message) override; private: RPMsgEndpoint *m_endPoint; /*!< Object operating with endpoints. */ diff --git a/erpc_c/transports/erpc_rpmsg_lite_base_transport.hpp b/erpc_c/transports/erpc_rpmsg_lite_base.hpp similarity index 87% rename from erpc_c/transports/erpc_rpmsg_lite_base_transport.hpp rename to erpc_c/transports/erpc_rpmsg_lite_base.hpp index 32433d52..bc30c4dc 100755 --- a/erpc_c/transports/erpc_rpmsg_lite_base_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_lite_base.hpp @@ -8,15 +8,14 @@ * SPDX-License-Identifier: BSD-3-Clause */ -#ifndef _EMBEDDED_RPC__RPMSG_LITE_BASE_TRANSPORT_H_ -#define _EMBEDDED_RPC__RPMSG_LITE_BASE_TRANSPORT_H_ +#ifndef _EMBEDDED_RPC__RPMSG_LITE_BASE_H_ +#define _EMBEDDED_RPC__RPMSG_LITE_BASE_H_ #include "erpc_config_internal.h" -#include "erpc_transport.hpp" extern "C" { -#include "rpmsg_lite.h" #include "rpmsg_env_specific.h" +#include "rpmsg_lite.h" } #if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC @@ -47,13 +46,12 @@ namespace erpc { * @ingroup rpmsg_lite_transport * @ingroup rpmsg_lite_rtos_transport */ -class RPMsgBaseTransport : public Transport +class RPMsgBase { public: - RPMsgBaseTransport(void) - : Transport(){}; + RPMsgBase(void){}; - virtual ~RPMsgBaseTransport(void) {} + virtual ~RPMsgBase(void) {} /*! * @brief This function returns pointer to instance of RPMSG lite @@ -82,4 +80,4 @@ class RPMsgBaseTransport : public Transport /*! @} */ -#endif // _EMBEDDED_RPC__RPMSG_LITE_BASE_TRANSPORT_H_ +#endif // _EMBEDDED_RPC__RPMSG_LITE_BASE_H_ diff --git a/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.cpp b/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.cpp index 76858d91..8eb1350b 100644 --- a/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.cpp +++ b/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.cpp @@ -9,6 +9,7 @@ */ #include "erpc_rpmsg_lite_rtos_transport.hpp" + #include "erpc_config_internal.h" extern "C" { @@ -20,15 +21,16 @@ using namespace erpc; //////////////////////////////////////////////////////////////////////////////// // Variables //////////////////////////////////////////////////////////////////////////////// -uint8_t RPMsgBaseTransport::s_initialized = 0U; -struct rpmsg_lite_instance *RPMsgBaseTransport::s_rpmsg; +uint8_t RPMsgBase::s_initialized = 0U; +struct rpmsg_lite_instance *RPMsgBase::s_rpmsg; //////////////////////////////////////////////////////////////////////////////// // Code //////////////////////////////////////////////////////////////////////////////// RPMsgRTOSTransport::RPMsgRTOSTransport(void) -: RPMsgBaseTransport() +: RPMsgBase() +, Transport() , m_rdev(NULL) , m_app_rp_chnl(NULL) , m_dst_addr(0) @@ -71,17 +73,6 @@ RPMsgRTOSTransport::~RPMsgRTOSTransport(void) } } -void RPMsgRTOSTransport::setCrc16(Crc16 *crcImpl) -{ - erpc_assert(crcImpl != NULL); - m_crcImpl = crcImpl; -} - -Crc16 *RPMsgRTOSTransport::getCrc16(void) -{ - return m_crcImpl; -} - erpc_status_t RPMsgRTOSTransport::init(uint32_t src_addr, uint32_t dst_addr, void *base_address, uint32_t length, uint32_t rpmsg_link_id) { @@ -288,3 +279,19 @@ erpc_status_t RPMsgRTOSTransport::send(MessageBuffer *message) return status; } + +bool RPMsgRTOSTransport::hasMessage(void) +{ + return ((rpmsg_queue_get_current_size(m_rpmsg_queue) > 0) ? true : false); +} + +void RPMsgRTOSTransport::setCrc16(Crc16 *crcImpl) +{ + erpc_assert(crcImpl != NULL); + m_crcImpl = crcImpl; +} + +Crc16 *RPMsgRTOSTransport::getCrc16(void) +{ + return m_crcImpl; +} diff --git a/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.hpp b/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.hpp index f237d0b0..8bbd6547 100644 --- a/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.hpp @@ -12,7 +12,8 @@ #include "erpc_crc16.hpp" #include "erpc_message_buffer.hpp" -#include "erpc_rpmsg_lite_base_transport.hpp" +#include "erpc_rpmsg_lite_base.hpp" +#include "erpc_transport.hpp" extern "C" { #include "rpmsg_lite.h" @@ -39,7 +40,7 @@ namespace erpc { * * @ingroup rpmsg_lite_rtos_transport */ -class RPMsgRTOSTransport : public RPMsgBaseTransport +class RPMsgRTOSTransport : public Transport, public RPMsgBase { public: /*! @@ -96,7 +97,7 @@ class RPMsgRTOSTransport : public RPMsgBaseTransport * @retval kErpcStatus_ReceiveFailed Failed to receive message buffer. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t receive(MessageBuffer *message); + virtual erpc_status_t receive(MessageBuffer *message) override; /*! * @brief Function to send prepared message. @@ -106,29 +107,30 @@ class RPMsgRTOSTransport : public RPMsgBaseTransport * @retval kErpcStatus_SendFailed Failed to send message buffer. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t send(MessageBuffer *message); + virtual erpc_status_t send(MessageBuffer *message) override; + + /*! + * @brief Function to check if is message in receive queue and wait for processing. + * + * This function should be called before function receive() to avoid waiting for new message. + * + * @return True if exist received message, else false. + */ + virtual bool hasMessage(void) override; /*! * @brief This functions sets the CRC-16 implementation. * * @param[in] crcImpl Object containing crc-16 compute function. */ - virtual void setCrc16(Crc16 *crcImpl); + virtual void setCrc16(Crc16 *crcImpl) override; /*! * @brief This functions gets the CRC-16 object. * * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. */ - virtual Crc16 *getCrc16(void); - /*! - * @brief Function to check if is message in receive queue and wait for processing. - * - * This function should be called before function receive() to avoid waiting for new message. - * - * @return True if exist received message, else false. - */ - virtual bool hasMessage(void) { return ((rpmsg_queue_get_current_size(m_rpmsg_queue) > 0) ? true : false); } + virtual Crc16 *getCrc16(void) override; protected: /* Remote device */ diff --git a/erpc_c/transports/erpc_rpmsg_lite_transport.cpp b/erpc_c/transports/erpc_rpmsg_lite_transport.cpp index 3211bc75..729c50ad 100644 --- a/erpc_c/transports/erpc_rpmsg_lite_transport.cpp +++ b/erpc_c/transports/erpc_rpmsg_lite_transport.cpp @@ -20,8 +20,8 @@ using namespace erpc; //////////////////////////////////////////////////////////////////////////////// // Variables //////////////////////////////////////////////////////////////////////////////// -uint8_t RPMsgBaseTransport::s_initialized = 0U; -struct rpmsg_lite_instance *RPMsgBaseTransport::s_rpmsg = NULL; +uint8_t RPMsgBase::s_initialized = 0U; +struct rpmsg_lite_instance *RPMsgBase::s_rpmsg = NULL; //////////////////////////////////////////////////////////////////////////////// // Code @@ -40,7 +40,8 @@ int32_t RPMsgTransport::rpmsg_read_cb(void *payload, uint32_t payload_len, uint3 } RPMsgTransport::RPMsgTransport(void) -: RPMsgBaseTransport() +: RPMsgBase() +, Transport() , m_dst_addr(0) , m_rpmsg_ept(NULL) , m_crcImpl(NULL) @@ -72,17 +73,6 @@ RPMsgTransport::~RPMsgTransport(void) } } -void RPMsgTransport::setCrc16(Crc16 *crcImpl) -{ - erpc_assert(crcImpl != NULL); - m_crcImpl = crcImpl; -} - -Crc16 *RPMsgTransport::getCrc16(void) -{ - return m_crcImpl; -} - erpc_status_t RPMsgTransport::init(uint32_t src_addr, uint32_t dst_addr, void *base_address, uint32_t length, uint32_t rpmsg_link_id) { @@ -227,3 +217,19 @@ erpc_status_t RPMsgTransport::send(MessageBuffer *message) return (ret_val != RL_SUCCESS) ? kErpcStatus_SendFailed : kErpcStatus_Success; } + +bool RPMsgTransport::hasMessage(void) +{ + return ((0UL < m_messageQueue.size()) ? true : false); +} + +void RPMsgTransport::setCrc16(Crc16 *crcImpl) +{ + erpc_assert(crcImpl != NULL); + m_crcImpl = crcImpl; +} + +Crc16 *RPMsgTransport::getCrc16(void) +{ + return m_crcImpl; +} diff --git a/erpc_c/transports/erpc_rpmsg_lite_transport.hpp b/erpc_c/transports/erpc_rpmsg_lite_transport.hpp index 6537eae6..78738a8f 100644 --- a/erpc_c/transports/erpc_rpmsg_lite_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_lite_transport.hpp @@ -13,8 +13,9 @@ #include "erpc_config_internal.h" #include "erpc_crc16.hpp" #include "erpc_message_buffer.hpp" -#include "erpc_rpmsg_lite_base_transport.hpp" +#include "erpc_rpmsg_lite_base.hpp" #include "erpc_static_queue.hpp" +#include "erpc_transport.hpp" extern "C" { #include "rpmsg_lite.h" @@ -40,7 +41,7 @@ namespace erpc { * * @ingroup rpmsg_lite_transport */ -class RPMsgTransport : public RPMsgBaseTransport +class RPMsgTransport : public Transport, public RPMsgBase { public: /*! @@ -100,7 +101,7 @@ class RPMsgTransport : public RPMsgBaseTransport * * @return kErpcStatus_Success */ - virtual erpc_status_t receive(MessageBuffer *message); + virtual erpc_status_t receive(MessageBuffer *message) override; /*! * @brief Function to send prepared message. @@ -110,29 +111,30 @@ class RPMsgTransport : public RPMsgBaseTransport * @retval kErpcStatus_SendFailed Failed to send message buffer. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t send(MessageBuffer *message); + virtual erpc_status_t send(MessageBuffer *message) override; + + /*! + * @brief Function to check if is message in receive queue and wait for processing. + * + * This function should be called before function receive() to avoid waiting for new message. + * + * @return True if exist received message, else false. + */ + virtual bool hasMessage(void) override; /*! * @brief This functions sets the CRC-16 implementation. * * @param[in] crcImpl Object containing crc-16 compute function. */ - virtual void setCrc16(Crc16 *crcImpl); + virtual void setCrc16(Crc16 *crcImpl) override; /*! * @brief This functions gets the CRC-16 object. * * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. */ - virtual Crc16 *getCrc16(void); - /*! - * @brief Function to check if is message in receive queue and wait for processing. - * - * This function should be called before function receive() to avoid waiting for new message. - * - * @return True if exist received message, else false. - */ - virtual bool hasMessage(void) { return ((0UL < m_messageQueue.size()) ? true : false); } + virtual Crc16 *getCrc16(void) override; protected: /*! diff --git a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp index 6b5c4522..e7450629 100644 --- a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp +++ b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp @@ -11,7 +11,6 @@ #include "erpc_rpmsg_tty_rtos_transport.hpp" #include "erpc_config_internal.h" -#include "erpc_framed_transport.hpp" extern "C" { #include "rpmsg_ns.h" @@ -23,19 +22,19 @@ using namespace std; //////////////////////////////////////////////////////////////////////////////// // Variables //////////////////////////////////////////////////////////////////////////////// -uint8_t RPMsgBaseTransport::s_initialized = 0U; -struct rpmsg_lite_instance *RPMsgBaseTransport::s_rpmsg; +uint8_t RPMsgBase::s_initialized = 0U; +struct rpmsg_lite_instance *RPMsgBase::s_rpmsg; //////////////////////////////////////////////////////////////////////////////// // Code //////////////////////////////////////////////////////////////////////////////// RPMsgTTYRTOSTransport::RPMsgTTYRTOSTransport(void) -: RPMsgBaseTransport() +: FramedTransport() +, RPMsgBase() , m_dst_addr(0) , m_rpmsg_queue(NULL) , m_rpmsg_ept(NULL) -, m_crcImpl(NULL) { } @@ -72,17 +71,6 @@ RPMsgTTYRTOSTransport::~RPMsgTTYRTOSTransport(void) } } -void RPMsgTTYRTOSTransport::setCrc16(Crc16 *crcImpl) -{ - erpc_assert(crcImpl != NULL); - m_crcImpl = crcImpl; -} - -Crc16 *RPMsgTTYRTOSTransport::getCrc16(void) -{ - return m_crcImpl; -} - erpc_status_t RPMsgTTYRTOSTransport::init(uint32_t src_addr, uint32_t dst_addr, void *base_address, uint32_t length, uint32_t rpmsg_link_id) { @@ -252,101 +240,65 @@ erpc_status_t RPMsgTTYRTOSTransport::init(uint32_t src_addr, uint32_t dst_addr, return status; } -erpc_status_t RPMsgTTYRTOSTransport::receive(MessageBuffer *message) +erpc_status_t RPMsgTTYRTOSTransport::underlyingSend(MessageBuffer *message, uint32_t size, uint32_t offset) { - erpc_status_t status = kErpcStatus_Success; - FramedTransport::Header h; - char *buf = NULL; - char *buf2 = NULL; - uint32_t length = 0; - int32_t ret_val = rpmsg_queue_recv_nocopy(s_rpmsg, m_rpmsg_queue, &m_dst_addr, &buf, &length, RL_BLOCK); - uint16_t computedCrc; - - erpc_assert((m_crcImpl != NULL) && ("Uninitialized Crc16 object." != NULL)); + erpc_status_t status; + int32_t ret_val; + ret_val = rpmsg_lite_send_nocopy(s_rpmsg, m_rpmsg_ept, m_dst_addr, &message->get()[offset], size); if (ret_val == RL_SUCCESS) { - erpc_assert(buf != NULL); - if (length < sizeof(h)) - { - status = kErpcStatus_ReceiveFailed; - } - if (status == kErpcStatus_Success) - { - static_cast(memcpy(reinterpret_cast(&h), buf, sizeof(h))); - /* If header and body is sent in two packets, we need call receive again to get body part. */ - if (length == sizeof(h)) - { - ret_val = rpmsg_queue_recv_nocopy(s_rpmsg, m_rpmsg_queue, &m_dst_addr, &buf2, &length, RL_BLOCK); - if (ret_val == RL_SUCCESS) - { - erpc_assert(buf2 != NULL); - erpc_assert((length + sizeof(h)) <= ERPC_DEFAULT_BUFFER_SIZE); - static_cast(memcpy(&buf[sizeof(h)], buf2, length)); - } - static_cast(rpmsg_lite_release_rx_buffer(s_rpmsg, buf2)); - } - else - { - length -= sizeof(h); /* offset for MessageBuffer */ - } - buf = &buf[sizeof(h)]; /* offset for MessageBuffer */ - } + + message->set(NULL, 0); + status = kErpcStatus_Success; } - if (status == kErpcStatus_Success) + else { - if (ret_val == RL_SUCCESS) - { - message->set(reinterpret_cast(buf), length); - - /* Verify CRC. */ - computedCrc = m_crcImpl->computeCRC16(reinterpret_cast(buf), h.m_messageSize); - if (computedCrc != h.m_crc) - { - status = kErpcStatus_CrcCheckFailed; - } - else - { - message->setUsed(h.m_messageSize); - } - } - else - { - status = kErpcStatus_ReceiveFailed; - } + status = kErpcStatus_SendFailed; } return status; } -erpc_status_t RPMsgTTYRTOSTransport::send(MessageBuffer *message) +erpc_status_t RPMsgTTYRTOSTransport::underlyingReceive(MessageBuffer *message, uint32_t size, uint32_t offset) { - erpc_status_t status = kErpcStatus_Success; - FramedTransport::Header h; - uint8_t *buf = message->get(); - uint32_t length = message->getLength(); - uint32_t used = message->getUsed(); - int32_t ret_val; - - erpc_assert((m_crcImpl != NULL) && ("Uninitialized Crc16 object." != NULL)); - message->set(NULL, 0); - - h.m_crc = m_crcImpl->computeCRC16(buf, used); - h.m_messageSize = used; - - static_cast(memcpy(&buf[-sizeof(h)], (uint8_t *)&h, sizeof(h))); - - ret_val = rpmsg_lite_send_nocopy(s_rpmsg, m_rpmsg_ept, m_dst_addr, &buf[-sizeof(h)], used + sizeof(h)); + char *buf = NULL; + uint32_t length = 0; + int32_t ret_val = rpmsg_queue_recv_nocopy(s_rpmsg, m_rpmsg_queue, &m_dst_addr, &buf, &length, RL_BLOCK); + erpc_status_t status; if (ret_val == RL_SUCCESS) { + if (offset == 0) + { + message->set(reinterpret_cast(buf), length); + message->setUsed(length); + } + else + { + erpc_assert(buf != NULL); + erpc_assert((length + offset) <= ERPC_DEFAULT_BUFFER_SIZE); + static_cast(memcpy(&message->get()[offset], buf, length)); + message->setUsed(length + offset); + static_cast(rpmsg_lite_release_rx_buffer(s_rpmsg, buf)); + } status = kErpcStatus_Success; } else { - message->set(buf, length); - message->setUsed(used); - status = kErpcStatus_SendFailed; + status = kErpcStatus_ReceiveFailed; } return status; } + +erpc_status_t RPMsgTTYRTOSTransport::underlyingReceive(uint8_t *data, uint32_t size) +{ + // unused as underlyingReceive(MessageBuffer *message, uint32_t size, uint32_t offset) + return kErpcStatus_ReceiveFailed; +} + +erpc_status_t RPMsgTTYRTOSTransport::underlyingSend(const uint8_t *data, uint32_t size) +{ + // unused as underlyingReceive(MessageBuffer *message, uint32_t size, uint32_t offset) + return kErpcStatus_SendFailed; +} diff --git a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.hpp b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.hpp index 30d3ee02..5d97ae49 100644 --- a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.hpp +++ b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.hpp @@ -11,8 +11,9 @@ #define _EMBEDDED_RPC__RPMSG_LITE_TTY_RTOS_TRANSPORT_H_ #include "erpc_crc16.hpp" +#include "erpc_framed_transport.hpp" #include "erpc_message_buffer.hpp" -#include "erpc_rpmsg_lite_base_transport.hpp" +#include "erpc_rpmsg_lite_base.hpp" extern "C" { #include "rpmsg_lite.h" @@ -40,7 +41,7 @@ namespace erpc { * * @ingroup rpmsg_tty_rtos_transport */ -class RPMsgTTYRTOSTransport : public RPMsgBaseTransport +class RPMsgTTYRTOSTransport : public FramedTransport, public RPMsgBase { public: /*! @@ -94,48 +95,63 @@ class RPMsgTTYRTOSTransport : public RPMsgBaseTransport virtual erpc_status_t init(uint32_t src_addr, uint32_t dst_addr, void *base_address, uint32_t rpmsg_link_id, void (*ready_cb)(void), char *nameservice_name); +protected: + uint32_t m_dst_addr; /*!< Destination address used by rpmsg. */ + rpmsg_queue_handle m_rpmsg_queue; /*!< Handle of RPMsg queue. */ + struct rpmsg_lite_endpoint *m_rpmsg_ept; /*!< Pointer to RPMsg Lite Endpoint structure. */ + + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! - * @brief Store incoming message to message buffer. + * @brief Adds ability to framed transport to overwrite MessageBuffer when receiving data. * - * In loop while no message come. + * Usually we don't want to do that. * - * @param[in] message Message buffer, to which will be stored incoming - * message. + * @param message MessageBuffer to send. + * @param size size of message to send. + * @param offset data start address offset * - * @retval kErpcStatus_ReceiveFailed Failed to receive message buffer. - * @retval kErpcStatus_Success Successfully received all data. + * @return erpc_status_t kErpcStatus_Success when it finished successful otherwise error. */ - virtual erpc_status_t receive(MessageBuffer *message); + virtual erpc_status_t underlyingReceive(MessageBuffer *message, uint32_t size, uint32_t offset) override; /*! - * @brief Function to send prepared message. + * @brief Adds ability to framed transport to overwrite MessageBuffer when sending data. + * + * Usually we don't want to do that. * - * @param[in] message Pass message buffer to send. + * @param message MessageBuffer to send. + * @param size size of message to send. + * @param offset data start address offset * - * @retval kErpcStatus_SendFailed Failed to send message buffer. - * @retval kErpcStatus_Success Successfully sent all data. + * @return erpc_status_t kErpcStatus_Success when it finished successful otherwise error. */ - virtual erpc_status_t send(MessageBuffer *message); + virtual erpc_status_t underlyingSend(MessageBuffer *message, uint32_t size, uint32_t offset) override; /*! - * @brief This functions sets the CRC-16 implementation. + * @brief This function read data. * - * @param[in] crcImpl Object containing crc-16 compute function. + * @param[inout] data Preallocated buffer for receiving data. + * @param[in] size Size of data to read. + * + * @retval #kErpcStatus_Success When data was read successfully. + * @retval #kErpcStatus_ReceiveFailed When reading data ends with error. + * @retval #kErpcStatus_ConnectionClosed Peer closed the connection. */ - virtual void setCrc16(Crc16 *crcImpl); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! - * @brief This functions gets the CRC-16 object. + * @brief This function writes data. + * + * @param[in] data Buffer to send. + * @param[in] size Size of data to send. * - * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. + * @retval #kErpcStatus_Success When data was written successfully. + * @retval #kErpcStatus_SendFailed When writing data ends with error. + * @retval #kErpcStatus_ConnectionClosed Peer closed the connection. */ - virtual Crc16 * getCrc16(void) override; - -protected: - uint32_t m_dst_addr; /*!< Destination address used by rpmsg. */ - rpmsg_queue_handle m_rpmsg_queue; /*!< Handle of RPMsg queue. */ - struct rpmsg_lite_endpoint *m_rpmsg_ept; /*!< Pointer to RPMsg Lite Endpoint structure. */ - Crc16 *m_crcImpl; //!< CRC object. + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_serial_transport.hpp b/erpc_c/transports/erpc_serial_transport.hpp index ea0033bb..6b41ae11 100644 --- a/erpc_c/transports/erpc_serial_transport.hpp +++ b/erpc_c/transports/erpc_serial_transport.hpp @@ -65,27 +65,30 @@ class SerialTransport : public FramedTransport erpc_status_t init(uint8_t vtime, uint8_t vmin); private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! - * @brief Write data to Serial peripheral. + * @brief Receive data from Serial peripheral. * - * @param[in] data Buffer to send. - * @param[in] size Size of data to send. + * @param[inout] data Preallocated buffer for receiving data. + * @param[in] size Size of data to read. * * @retval kErpcStatus_ReceiveFailed Serial failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! - * @brief Receive data from Serial peripheral. + * @brief Write data to Serial peripheral. * - * @param[inout] data Preallocated buffer for receiving data. - * @param[in] size Size of data to read. + * @param[in] data Buffer to send. + * @param[in] size Size of data to send. * * @retval kErpcStatus_ReceiveFailed Serial failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; private: int m_serialHandle; /*!< Serial handle id. */ diff --git a/erpc_c/transports/erpc_spi_master_transport.hpp b/erpc_c/transports/erpc_spi_master_transport.hpp index e90e27a2..e2de9bae 100644 --- a/erpc_c/transports/erpc_spi_master_transport.hpp +++ b/erpc_c/transports/erpc_spi_master_transport.hpp @@ -65,6 +65,9 @@ class SpiMasterTransport : public FramedTransport uint32_t m_srcClock_Hz; /*!< Source clock of SPI peripheral used in this transport layer */ private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from SPI peripheral. * @@ -74,7 +77,7 @@ class SpiMasterTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed SPI failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to SPI peripheral. @@ -85,7 +88,7 @@ class SpiMasterTransport : public FramedTransport * @retval kErpcStatus_SendFailed SPI failed to send data. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_spi_slave_transport.hpp b/erpc_c/transports/erpc_spi_slave_transport.hpp index bc4e22b9..865cb2b9 100644 --- a/erpc_c/transports/erpc_spi_slave_transport.hpp +++ b/erpc_c/transports/erpc_spi_slave_transport.hpp @@ -79,6 +79,9 @@ class SpiSlaveTransport : public FramedTransport #endif private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from SPI peripheral. * @@ -88,7 +91,7 @@ class SpiSlaveTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed SPI failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to SPI peripheral. @@ -99,7 +102,7 @@ class SpiSlaveTransport : public FramedTransport * @retval kErpcStatus_SendFailed SPI failed to send data. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_spidev_master_transport.hpp b/erpc_c/transports/erpc_spidev_master_transport.hpp index 1af54c34..354af858 100644 --- a/erpc_c/transports/erpc_spidev_master_transport.hpp +++ b/erpc_c/transports/erpc_spidev_master_transport.hpp @@ -56,6 +56,9 @@ class SpidevMasterTransport : public FramedTransport uint32_t m_speed_Hz; /*!< SPI clock speed in Hz. */ private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from SPI peripheral. * @@ -65,7 +68,7 @@ class SpidevMasterTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed SPI failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to SPI peripheral. @@ -76,7 +79,7 @@ class SpidevMasterTransport : public FramedTransport * @retval kErpcStatus_SendFailed SPI failed to send data. * @retval kErpcStatus_Success Successfully sent all data. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_tcp_transport.hpp b/erpc_c/transports/erpc_tcp_transport.hpp index 8bb74d4f..1e171fbf 100644 --- a/erpc_c/transports/erpc_tcp_transport.hpp +++ b/erpc_c/transports/erpc_tcp_transport.hpp @@ -97,6 +97,10 @@ class TCPTransport : public FramedTransport Thread m_serverThread; /*!< Pointer to server thread. */ bool m_runServer; /*!< Thread is executed while this is true. */ + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + + /*! * @brief This function connect client to the server. * @@ -115,7 +119,7 @@ class TCPTransport : public FramedTransport * @retval #kErpcStatus_ReceiveFailed When reading data ends with error. * @retval #kErpcStatus_ConnectionClosed Peer closed the connection. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief This function writes data. @@ -127,7 +131,7 @@ class TCPTransport : public FramedTransport * @retval #kErpcStatus_SendFailed When writing data ends with error. * @retval #kErpcStatus_ConnectionClosed Peer closed the connection. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; /*! * @brief Server thread function. diff --git a/erpc_c/transports/erpc_uart_cmsis_transport.hpp b/erpc_c/transports/erpc_uart_cmsis_transport.hpp index 42e5e831..04fb5751 100644 --- a/erpc_c/transports/erpc_uart_cmsis_transport.hpp +++ b/erpc_c/transports/erpc_uart_cmsis_transport.hpp @@ -83,6 +83,9 @@ class UartTransport : public FramedTransport Semaphore m_txSemaphore; /*!< Semaphore used by RTOS to block task until the sending is not complete */ #endif private: + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from UART peripheral. * @@ -92,7 +95,7 @@ class UartTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed UART failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to UART peripheral. @@ -102,7 +105,7 @@ class UartTransport : public FramedTransport * * @retval kErpcStatus_Success Always returns success status. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_c/transports/erpc_usb_cdc_transport.hpp b/erpc_c/transports/erpc_usb_cdc_transport.hpp index ee4abf69..ccd7b5ab 100644 --- a/erpc_c/transports/erpc_usb_cdc_transport.hpp +++ b/erpc_c/transports/erpc_usb_cdc_transport.hpp @@ -96,6 +96,9 @@ class UsbCdcTransport : public FramedTransport uint8_t *m_usbRingBuffer; uint32_t m_usbRingBufferLength; + using FramedTransport::underlyingReceive; + using FramedTransport::underlyingSend; + /*! * @brief Receive data from USB CDC peripheral. * @@ -105,7 +108,7 @@ class UsbCdcTransport : public FramedTransport * @retval kErpcStatus_ReceiveFailed USB CDC failed to receive data. * @retval kErpcStatus_Success Successfully received all data. */ - virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingReceive(uint8_t *data, uint32_t size) override; /*! * @brief Write data to USB CDC peripheral. @@ -115,7 +118,7 @@ class UsbCdcTransport : public FramedTransport * * @retval kErpcStatus_Success Always returns success status. */ - virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size); + virtual erpc_status_t underlyingSend(const uint8_t *data, uint32_t size) override; }; } // namespace erpc diff --git a/erpc_python/erpc/transport.py b/erpc_python/erpc/transport.py index 725a0abb..00df5908 100644 --- a/erpc_python/erpc/transport.py +++ b/erpc_python/erpc/transport.py @@ -48,7 +48,7 @@ def receive(self): class FramedTransport(Transport): - HEADER_LEN = 4 + HEADER_LEN = 6 def __init__(self): super(FramedTransport, self).__init__() @@ -70,9 +70,12 @@ def send(self, message): try: self._sendLock.acquire() - crc = self._Crc16.computeCRC16(message) + crcBody = self._Crc16.computeCRC16(message) + messageLength = len(message) + crcHeader = self._Crc16.computeCRC16(bytearray(struct.pack('prepareServerBufferForSend(codec->getBuffer()); +{$serverIndent} {% if generateErrorChecks %}err = {% endif %}messageFactory->prepareServerBufferForSend(codec->getBufferRef(), transport->reserveHeaderSize()); {% if generateErrorChecks %} } @@ -126,7 +126,7 @@ extern bool nestingDetection; { {% endif -- generateErrorChecks %} {$serverIndent} // preparing codec for serializing data -{$serverIndent} codec->reset(); +{$serverIndent} codec->reset(transport->reserveHeaderSize()); {$serverIndent} // Build response message. {$serverIndent} codec->startWriteMessage(message_type_t::kReplyMessage, {$serverIDName}, {$functionIDName}, sequence); @@ -181,14 +181,14 @@ extern bool nestingDetection; {% for iface in group.interfaces %} {% for cb in iface.callbacksInt if (count(cb.callbacks) > 1) %} // Common function for serializing and deserializing callback functions of same type. -static erpc_status_t {$iface.interfaceClassName}_{$cb.name}_shim({$iface.interfaceClassName} *m_handler, uint32_t serviceID, uint32_t functionID, {$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence); +static erpc_status_t {$iface.interfaceClassName}_{$cb.name}_shim({$iface.interfaceClassName} *m_handler, uint32_t serviceID, uint32_t functionID, {$codecClass} * codec, MessageBufferFactory *messageFactory, Transport * transport, uint32_t sequence); {% endfor %} {% endfor %} {% for iface in group.interfaces %} {% for cb in iface.callbacksInt if (count(cb.callbacks) > 1) %} // Common function for serializing and deserializing callback functions of same type. -static erpc_status_t {$iface.interfaceClassName}_{$cb.name}_shim({$iface.interfaceClassName} *m_handler, uint32_t serviceID, uint32_t functionID, {$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence) +static erpc_status_t {$iface.interfaceClassName}_{$cb.name}_shim({$iface.interfaceClassName} *m_handler, uint32_t serviceID, uint32_t functionID, {$codecClass} * codec, MessageBufferFactory *messageFactory, Transport * transport, uint32_t sequence) { {$ serverShimCode(iface, "m_handler", cb.callbacksData, "serviceID", "functionID") >} } @@ -213,7 +213,7 @@ static erpc_status_t {$iface.interfaceClassName}_{$cb.name}_shim({$iface.interfa } // Call the correct server shim based on method unique ID. -erpc_status_t {$iface.serviceClassName}::handleInvocation(uint32_t methodId, uint32_t sequence, Codec * codec, MessageBufferFactory *messageFactory) +erpc_status_t {$iface.serviceClassName}::handleInvocation(uint32_t methodId, uint32_t sequence, Codec * codec, MessageBufferFactory *messageFactory, Transport * transport) { erpc_status_t erpcStatus; {% if codecClass != "Codec" %} @@ -224,7 +224,7 @@ erpc_status_t {$iface.serviceClassName}::handleInvocation(uint32_t methodId, uin {% for fn in iface.functions %} case {$iface.interfaceClassName}::{$getClassFunctionIdName(fn)}: { - erpcStatus = {$fn.name}_shim({%if codecClass == "Codec" %}codec{% else %}_codec{% endif %}, messageFactory, sequence); + erpcStatus = {$fn.name}_shim({%if codecClass == "Codec" %}codec{% else %}_codec{% endif %}, messageFactory, transport, sequence); break; } @@ -241,10 +241,10 @@ erpc_status_t {$iface.serviceClassName}::handleInvocation(uint32_t methodId, uin {% for fn in iface.functions %} // Server shim for {$fn.name} of {$iface.name} interface. -erpc_status_t {$iface.serviceClassName}::{$fn.name}_shim({$codecClass} * codec, MessageBufferFactory *messageFactory, uint32_t sequence) +erpc_status_t {$iface.serviceClassName}::{$fn.name}_shim({$codecClass} * codec, MessageBufferFactory *messageFactory, Transport * transport, uint32_t sequence) { {% if fn.isCallback %} - return {$iface.interfaceClassName}_{$fn.callbackFNameNoGroup}_shim(m_handler, {$iface.interfaceClassName}::m_serviceId, {$iface.interfaceClassName}::{$getClassFunctionIdName(fn)}, codec, messageFactory, sequence); + return {$iface.interfaceClassName}_{$fn.callbackFNameNoGroup}_shim(m_handler, {$iface.interfaceClassName}::m_serviceId, {$iface.interfaceClassName}::{$getClassFunctionIdName(fn)}, codec, messageFactory, transport, sequence); {% else -- fn.isCallback >%} {$ serverShimCode(iface, "m_handler", fn, iface.interfaceClassName & "::m_serviceId", iface.interfaceClassName & "::" & getClassFunctionIdName(fn)) >} {% endif -- fn.isCallback >%} diff --git a/erpcsniffer/src/Sniffer.cpp b/erpcsniffer/src/Sniffer.cpp index b517280c..585aaec5 100644 --- a/erpcsniffer/src/Sniffer.cpp +++ b/erpcsniffer/src/Sniffer.cpp @@ -64,7 +64,7 @@ erpc_status_t Sniffer::run() } Log::info("message received\n"); - m_codec->setBuffer(message); + m_codec->setBuffer(message, m_transport->reserveHeaderSize()); // Save time when message was received. time_t now = chrono::system_clock::to_time_t(currentTime); diff --git a/test/common/gtest/gtest.h b/test/common/gtest/gtest.h index e07c3371..ef9a6231 100644 --- a/test/common/gtest/gtest.h +++ b/test/common/gtest/gtest.h @@ -9910,6 +9910,8 @@ linked_ptr make_linked_ptr(T* ptr) { #if GTEST_OS_BARE_METAL #include +#else +#include #endif #if GTEST_HAS_STD_TUPLE_ diff --git a/test/common/unit_test_tcp_arbitrator_client.cpp b/test/common/unit_test_tcp_arbitrator_client.cpp index f29664d3..19c5f56a 100644 --- a/test/common/unit_test_tcp_arbitrator_client.cpp +++ b/test/common/unit_test_tcp_arbitrator_client.cpp @@ -64,7 +64,6 @@ void increaseWaitQuit() { Mutex::Guard lock(waitQuitMutex); waitQuit++; - Mutex::Guard unlock(waitQuitMutex); } void runServer(void *arg) @@ -90,7 +89,6 @@ void runClient(void *arg) { break; } - Mutex::Guard unlock(waitQuitMutex); } // send to ERPC second (server) app ready to quit state @@ -176,7 +174,6 @@ int main(int argc, char **argv) { break; } - Mutex::Guard unlock(waitQuitMutex); } // Close transport diff --git a/test/common/unit_test_tcp_arbitrator_server.cpp b/test/common/unit_test_tcp_arbitrator_server.cpp index b1956165..bf812acf 100644 --- a/test/common/unit_test_tcp_arbitrator_server.cpp +++ b/test/common/unit_test_tcp_arbitrator_server.cpp @@ -63,7 +63,6 @@ void increaseWaitQuit() { Mutex::Guard lock(waitQuitMutex); waitQuit++; - Mutex::Guard unlock(waitQuitMutex); } void runServer(void *arg) @@ -84,14 +83,14 @@ void runClient(void *arg) while (true) { isTestPassing = testClient(); - Mutex::Guard lock(waitQuitMutex); - if (waitQuit != 0 || isTestPassing != 0 || stopTest != 0) { - enableFirstSide(); - Mutex::Guard unlock(waitQuitMutex); - break; + Mutex::Guard lock(waitQuitMutex); + if (waitQuit != 0 || isTestPassing != 0 || stopTest != 0) + { + enableFirstSide(); + break; + } } - Mutex::Guard unlock(waitQuitMutex); } while (true) @@ -101,7 +100,6 @@ void runClient(void *arg) { break; } - Mutex::Guard unlock(waitQuitMutex); } // send to ERPC first (client) app ready to quit state @@ -166,7 +164,6 @@ int main(int argc, char **argv) { break; } - Mutex::Guard unlock(waitQuitMutex); } // Close transport From 685c5277e8343e51f25c68b2f31a2994e1852b63 Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Thu, 2 Nov 2023 07:35:37 +0100 Subject: [PATCH 14/24] Fixed clang configuration file (#360) * Fixed clang configuration file + reformatted code. Signed-off-by: Cervenka Dusan * Applying changes related to clang-format 16 Signed-off-by: Cervenka Dusan * Clang format now works without String quotation. Signed-off-by: Cervenka Dusan * Adding ability to have includes in groups. Signed-off-by: Cervenka Dusan * Change requested by Michal P. and NXP company -- includes will not be sorted at all (not even in groups) -- Constructutor and inheritance will use AfterColon format style Signed-off-by: Cervenka Dusan * Update clang-format.yml Update clang-format version Signed-off-by: Cervenka Dusan --------- Signed-off-by: Cervenka Dusan --- .clang-format | 63 ++++---- .clang-format-ignore | 9 ++ .github/workflows/clang-format.yml | 11 +- .../infra/erpc_arbitrated_client_manager.cpp | 1 + .../infra/erpc_arbitrated_client_manager.hpp | 8 +- erpc_c/infra/erpc_basic_codec.cpp | 10 +- erpc_c/infra/erpc_client_manager.h | 16 +- erpc_c/infra/erpc_client_server_common.hpp | 21 ++- erpc_c/infra/erpc_codec.hpp | 6 +- erpc_c/infra/erpc_crc16.cpp | 10 +- erpc_c/infra/erpc_framed_transport.cpp | 9 +- erpc_c/infra/erpc_message_buffer.hpp | 26 +--- erpc_c/infra/erpc_message_loggers.hpp | 7 +- erpc_c/infra/erpc_pre_post_action.h | 4 +- erpc_c/infra/erpc_server.hpp | 12 +- erpc_c/infra/erpc_simple_server.cpp | 5 +- erpc_c/infra/erpc_transport_arbitrator.cpp | 17 +- erpc_c/infra/erpc_transport_arbitrator.hpp | 6 +- erpc_c/infra/erpc_utils.hpp | 4 +- .../port/erpc_setup_extensions_freertos.cpp | 30 ++-- erpc_c/port/erpc_threading.h | 6 +- erpc_c/port/erpc_threading_freertos.cpp | 43 ++--- erpc_c/port/erpc_threading_mbed.cpp | 24 +-- erpc_c/port/erpc_threading_pthreads.cpp | 24 +-- erpc_c/port/erpc_threading_threadx.cpp | 27 +--- erpc_c/port/erpc_threading_win32.cpp | 28 +--- erpc_c/port/erpc_threading_zephyr.cpp | 27 +--- erpc_c/setup/erpc_arbitrated_client_setup.cpp | 4 +- erpc_c/setup/erpc_client_setup.cpp | 4 +- erpc_c/setup/erpc_setup_mbf_rpmsg.cpp | 3 +- erpc_c/setup/erpc_setup_mbf_static.cpp | 3 +- .../transports/erpc_dspi_master_transport.cpp | 6 +- .../transports/erpc_dspi_master_transport.hpp | 1 + .../transports/erpc_dspi_slave_transport.cpp | 10 +- .../transports/erpc_dspi_slave_transport.hpp | 1 + .../transports/erpc_i2c_slave_transport.cpp | 10 +- .../erpc_inter_thread_buffer_transport.hpp | 13 +- .../transports/erpc_lpi2c_slave_transport.cpp | 10 +- .../transports/erpc_lpspi_slave_transport.cpp | 10 +- erpc_c/transports/erpc_mu_transport.cpp | 21 +-- .../transports/erpc_rpmsg_linux_transport.cpp | 6 +- erpc_c/transports/erpc_rpmsg_lite_base.hpp | 0 .../erpc_rpmsg_lite_rtos_transport.cpp | 12 +- .../transports/erpc_rpmsg_lite_transport.cpp | 9 +- .../erpc_rpmsg_tty_rtos_transport.cpp | 8 +- erpc_c/transports/erpc_serial_transport.cpp | 6 +- .../transports/erpc_spi_master_transport.cpp | 6 +- .../transports/erpc_spi_slave_transport.cpp | 10 +- .../erpc_spidev_master_transport.cpp | 6 +- erpc_c/transports/erpc_tcp_transport.cpp | 34 ++-- erpc_c/transports/erpc_tcp_transport.hpp | 11 +- .../transports/erpc_uart_cmsis_transport.cpp | 8 +- erpc_c/transports/erpc_usb_cdc_transport.cpp | 14 +- erpcgen/src/AstNode.cpp | 7 +- erpcgen/src/AstNode.hpp | 18 +-- erpcgen/src/AstWalker.hpp | 5 +- erpcgen/src/CGenerator.cpp | 147 ++++++++++++------ erpcgen/src/CGenerator.hpp | 10 +- erpcgen/src/ErpcLexer.cpp | 12 +- erpcgen/src/ErpcLexer.hpp | 10 +- erpcgen/src/Generator.cpp | 31 ++-- erpcgen/src/InterfaceDefinition.cpp | 11 +- erpcgen/src/Logging.hpp | 18 +-- erpcgen/src/ParseErrors.hpp | 50 ++---- erpcgen/src/PythonGenerator.cpp | 42 +++-- erpcgen/src/SymbolScanner.cpp | 12 +- erpcgen/src/SymbolScanner.hpp | 23 +-- erpcgen/src/Token.cpp | 5 +- erpcgen/src/Token.hpp | 29 +--- erpcgen/src/Value.hpp | 71 ++------- erpcgen/src/erpcgen.cpp | 38 ++--- erpcgen/src/options.cpp | 37 ++--- erpcgen/src/options.hpp | 14 +- erpcgen/src/smart_ptr.hpp | 22 +-- erpcgen/src/types/AliasType.hpp | 10 +- erpcgen/src/types/Annotation.hpp | 21 +-- erpcgen/src/types/ArrayType.hpp | 6 +- erpcgen/src/types/BuiltinType.hpp | 5 +- erpcgen/src/types/ConstType.hpp | 6 +- erpcgen/src/types/DataType.hpp | 15 +- erpcgen/src/types/EnumMember.hpp | 12 +- erpcgen/src/types/EnumType.hpp | 10 +- erpcgen/src/types/Function.hpp | 24 +-- erpcgen/src/types/FunctionType.hpp | 6 +- erpcgen/src/types/Group.hpp | 8 +- erpcgen/src/types/Interface.hpp | 8 +- erpcgen/src/types/ListType.hpp | 6 +- erpcgen/src/types/Program.hpp | 5 +- erpcgen/src/types/StructMember.hpp | 20 +-- erpcgen/src/types/StructType.hpp | 10 +- erpcgen/src/types/Symbol.hpp | 28 +--- erpcgen/src/types/SymbolScope.hpp | 7 +- erpcgen/src/types/Type.cpp | 12 +- erpcgen/src/types/UnionCase.hpp | 22 +-- erpcgen/src/types/UnionType.hpp | 16 +- erpcgen/src/types/VoidType.hpp | 5 +- erpcsniffer/src/Sniffer.cpp | 81 ++++++---- erpcsniffer/src/Sniffer.hpp | 10 +- erpcsniffer/src/erpc_config.h | 28 +++- erpcsniffer/src/erpcsniffer.cpp | 68 ++++---- run_clang_format.py | 16 +- test/common/config/erpc_config.h | 40 +++-- test/common/unit_test_server.cpp | 4 + test/test_arbitrator/config/erpc_config.h | 41 +++-- test/test_unions/test_unions_server_impl.cpp | 36 +++-- 105 files changed, 796 insertions(+), 1082 deletions(-) create mode 100644 .clang-format-ignore mode change 100755 => 100644 erpc_c/transports/erpc_rpmsg_lite_base.hpp diff --git a/.clang-format b/.clang-format index c2333882..6cec9388 100644 --- a/.clang-format +++ b/.clang-format @@ -1,15 +1,17 @@ -#https://releases.llvm.org/5.0.2/tools/clang/docs/ClangFormatStyleOptions.html -AlignTrailingComments: true +#https://releases.llvm.org/16.0.0/tools/clang/docs/ClangFormatStyleOptions.html +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: false -AllowShortFunctionsOnASingleLine: "Inline" -AllowShortIfStatementsOnASingleLine: false +AllowShortBlocksOnASingleLine: Never +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never AllowShortLoopsOnASingleLine: false AlwaysBreakBeforeMultilineStrings: true -BasedOnStyle: "Google" +BasedOnStyle: Google #BinPackParameters : false -BreakBeforeBinaryOperators: false -BreakBeforeBraces: "Custom" +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom BreakBeforeTernaryOperators: false ColumnLimit: 120 ContinuationIndentWidth: 4 @@ -18,54 +20,61 @@ DisableFormat: false IndentCaseLabels: true IndentWrappedFunctionNames: false IndentWidth: 4 -Language: "Cpp" +Language: Cpp MaxEmptyLinesToKeep: 1 -PointerBindsToType: false SpaceBeforeAssignmentOperators: true -SpaceBeforeParens: "ControlStatements" +SpaceBeforeParens: ControlStatements SpacesBeforeTrailingComments: 1 SpacesInCStyleCastParentheses: false SpacesInParentheses: false -Standard: "Cpp03" +Standard: c++11 TabWidth: 1 -UseTab: "Never" +UseTab: Never AccessModifierOffset: -4 -AlignAfterOpenBracket: "Align" -AlignEscapedNewlines: "Left" -AlignOperands: true +AlignAfterOpenBracket: Align +AlignEscapedNewlines: Left +AlignOperands: Align AllowShortCaseLabelsOnASingleLine: false -AlwaysBreakAfterReturnType: "None" -AlwaysBreakTemplateDeclarations: true -BreakBeforeInheritanceComma: false -BreakConstructorInitializers: "BeforeComma" +AlwaysBreakAfterReturnType: None +AlwaysBreakTemplateDeclarations: Yes +BreakInheritanceList: AfterColon +BreakConstructorInitializers: AfterColon CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 0 Cpp11BracedListStyle: false FixNamespaceComments: true -NamespaceIndentation: "None" -PointerAlignment: "Right" -SortIncludes: true -SortUsingDeclarations: true -SpacesInAngles: false +NamespaceIndentation: None +PointerAlignment: Right +SortIncludes: Never +SortUsingDeclarations: Lexicographic +SpacesInAngles: Never SpaceAfterCStyleCast: false SpaceInEmptyParentheses: false SpacesInSquareBrackets: false KeepEmptyLinesAtTheStartOfBlocks: true BraceWrapping: + AfterCaseLabel: true AfterClass: true - AfterControlStatement: true + AfterControlStatement: Always AfterEnum: true AfterFunction: true AfterNamespace: false AfterObjCDeclaration: true AfterStruct: true AfterUnion: true + AfterExternBlock: false BeforeCatch: true BeforeElse: true -IncludeBlocks: "Preserve" # for future version of clang + BeforeWhile: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true + +IncludeBlocks: Preserve IncludeCategories: - Regex: "^<" # system includes Priority: 10 - Regex: '^"erpc_' # erpc public includes Priority: 1 +CommentPragmas: "#" diff --git a/.clang-format-ignore b/.clang-format-ignore new file mode 100644 index 00000000..d103944b --- /dev/null +++ b/.clang-format-ignore @@ -0,0 +1,9 @@ +#list of ignored files to format +./erpc_c/port/erpc_serial.cpp +./erpcgen/src/cpptemplate/cpptempl.hpp +./erpcgen/src/cpptemplate/cpptempl.cpp +./erpcgen/src/cpptemplate/cpptempl_test.cpp +./erpcgen/test/test_includes/test_includes_union.h +./test/common/gtest/gtest.h +./test/common/gtest/gtest.cpp +./test/common/retarget_cpp_streamed_io.c diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 8c7729ba..f5be8afe 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -1,15 +1,14 @@ name: clang-format lint -on: [push] +on: [push, pull_request] jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: DoozyX/clang-format-lint-action@v0.10 + - uses: actions/checkout@v4 + - uses: DoozyX/clang-format-lint-action@v0.16.2 with: - source: '.' - exclude: 'test/common/gtest/gtest.h test/common/gtest/gtest.cpp erpcgen/src/cpptemplate/cpptempl.h erpcgen/src/cpptemplate/cpptempl.cpp erpcgen/src/cpptemplate/cpptempl_test.cpp' - clangFormatVersion: 10 + source: '.' + clangFormatVersion: 16 diff --git a/erpc_c/infra/erpc_arbitrated_client_manager.cpp b/erpc_c/infra/erpc_arbitrated_client_manager.cpp index 53d3c4e6..f46682a7 100644 --- a/erpc_c/infra/erpc_arbitrated_client_manager.cpp +++ b/erpc_c/infra/erpc_arbitrated_client_manager.cpp @@ -9,6 +9,7 @@ */ #include "erpc_arbitrated_client_manager.hpp" + #include "erpc_transport_arbitrator.hpp" #if ERPC_THREADS_IS(NONE) diff --git a/erpc_c/infra/erpc_arbitrated_client_manager.hpp b/erpc_c/infra/erpc_arbitrated_client_manager.hpp index 33b65ab7..dc271345 100644 --- a/erpc_c/infra/erpc_arbitrated_client_manager.hpp +++ b/erpc_c/infra/erpc_arbitrated_client_manager.hpp @@ -45,11 +45,7 @@ class ArbitratedClientManager : public ClientManager * * This function initializes object attributes. */ - ArbitratedClientManager(void) - : ClientManager() - , m_arbitrator(NULL) - { - } + ArbitratedClientManager(void) : ClientManager(), m_arbitrator(NULL) {} /*! * @brief Sets the transport arbitrator instance. @@ -63,7 +59,7 @@ class ArbitratedClientManager : public ClientManager * * @return TransportArbitrator * Transport arbitrator instance. */ - TransportArbitrator * getArbitrator(void) { return m_arbitrator; }; + TransportArbitrator *getArbitrator(void) { return m_arbitrator; }; protected: TransportArbitrator *m_arbitrator; //!< Optional transport arbitrator. May be NULL. diff --git a/erpc_c/infra/erpc_basic_codec.cpp b/erpc_c/infra/erpc_basic_codec.cpp index d59a697f..6bdb68e3 100644 --- a/erpc_c/infra/erpc_basic_codec.cpp +++ b/erpc_c/infra/erpc_basic_codec.cpp @@ -27,10 +27,7 @@ using namespace erpc; const uint32_t BasicCodec::kBasicCodecVersion = 1UL; -BasicCodec::BasicCodec(void) -: Codec() -{ -} +BasicCodec::BasicCodec(void) : Codec() {} BasicCodec::~BasicCodec(void) {} @@ -374,10 +371,7 @@ void BasicCodec::readNullFlag(bool &isNull) ERPC_MANUALLY_CONSTRUCTED_ARRAY_STATIC(BasicCodec, s_basicCodecManual, ERPC_CODEC_COUNT); -BasicCodecFactory::BasicCodecFactory(void) -: CodecFactory() -{ -} +BasicCodecFactory::BasicCodecFactory(void) : CodecFactory() {} BasicCodecFactory::~BasicCodecFactory(void) {} diff --git a/erpc_c/infra/erpc_client_manager.h b/erpc_c/infra/erpc_client_manager.h index 2a301642..63a8bd12 100644 --- a/erpc_c/infra/erpc_client_manager.h +++ b/erpc_c/infra/erpc_client_manager.h @@ -61,13 +61,11 @@ class ClientManager : public ClientServerCommon * * This function initializes object attributes. */ - ClientManager(void) - : ClientServerCommon() - , m_sequence(0) - , m_errorHandler(NULL) + ClientManager(void) : + ClientServerCommon(), m_sequence(0), m_errorHandler(NULL) #if ERPC_NESTED_CALLS - , m_server(NULL) - , m_serverThreadId(NULL) + , + m_server(NULL), m_serverThreadId(NULL) #endif { } @@ -195,10 +193,8 @@ class RequestContext * @param[in] codec Set in inout codec. * @param[in] isOneway Set information if codec is only oneway or bidirectional. */ - RequestContext(uint32_t sequence, Codec *codec, bool argIsOneway) - : m_sequence(sequence) - , m_codec(codec) - , m_oneway(argIsOneway) + RequestContext(uint32_t sequence, Codec *codec, bool argIsOneway) : + m_sequence(sequence), m_codec(codec), m_oneway(argIsOneway) { } diff --git a/erpc_c/infra/erpc_client_server_common.hpp b/erpc_c/infra/erpc_client_server_common.hpp index 68ee2a94..159d3d8e 100644 --- a/erpc_c/infra/erpc_client_server_common.hpp +++ b/erpc_c/infra/erpc_client_server_common.hpp @@ -66,7 +66,7 @@ class ClientServerCommon #endif #if ERPC_MESSAGE_LOGGING #ifdef ERPC_OTHER_INHERITANCE - , + , #else #define ERPC_OTHER_INHERITANCE 1 : @@ -75,7 +75,7 @@ class ClientServerCommon #endif #if ERPC_PRE_POST_ACTION #ifdef ERPC_OTHER_INHERITANCE - , + , #else #define ERPC_OTHER_INHERITANCE 1 : @@ -83,15 +83,12 @@ class ClientServerCommon PrePostAction() #endif #ifdef ERPC_OTHER_INHERITANCE - , + , #else #define ERPC_OTHER_INHERITANCE 1 : #endif - m_messageFactory(NULL) - , m_codecFactory(NULL) - , m_transport(NULL) - {}; + m_messageFactory(NULL), m_codecFactory(NULL), m_transport(NULL){}; /*! * @brief ClientServerCommon destructor @@ -103,21 +100,21 @@ class ClientServerCommon * * @param[in] factory Message buffer factory to use. */ - void setMessageBufferFactory(MessageBufferFactory *factory) { m_messageFactory = factory; } + void setMessageBufferFactory(MessageBufferFactory * factory) { m_messageFactory = factory; } /*! * @brief This function sets codec factory to use. * * @param[in] factory Codec factory to use. */ - void setCodecFactory(CodecFactory *factory) { m_codecFactory = factory; } + void setCodecFactory(CodecFactory * factory) { m_codecFactory = factory; } /*! * @brief This function sets codec factory to use. * * @return CodecFactory * Codec factory to use. */ - CodecFactory * getCodecFactory(void) { return m_codecFactory; } + CodecFactory *getCodecFactory(void) { return m_codecFactory; } /*! * @brief This function sets transport layer to use. @@ -126,14 +123,14 @@ class ClientServerCommon * * @param[in] transport Transport layer to use. */ - void setTransport(Transport *transport) { m_transport = transport; } + void setTransport(Transport * transport) { m_transport = transport; } /*! * @brief This function gets transport instance. * * @return Transport * Pointer to transport instance. */ - Transport * getTransport(void) { return m_transport; } + Transport *getTransport(void) { return m_transport; } protected: MessageBufferFactory *m_messageFactory; //!< Message buffer factory to use. diff --git a/erpc_c/infra/erpc_codec.hpp b/erpc_c/infra/erpc_codec.hpp index af075bba..763cb377 100644 --- a/erpc_c/infra/erpc_codec.hpp +++ b/erpc_c/infra/erpc_codec.hpp @@ -58,11 +58,7 @@ class Codec * * This function initializes object attributes. */ - Codec(void) - : m_cursor() - , m_status(kErpcStatus_Success) - { - } + Codec(void) : m_cursor(), m_status(kErpcStatus_Success) {} /*! * @brief Codec destructor diff --git a/erpc_c/infra/erpc_crc16.cpp b/erpc_c/infra/erpc_crc16.cpp index 8408a12e..ebaf498b 100644 --- a/erpc_c/infra/erpc_crc16.cpp +++ b/erpc_c/infra/erpc_crc16.cpp @@ -15,15 +15,9 @@ using namespace erpc; // Code //////////////////////////////////////////////////////////////////////////////// -Crc16::Crc16(uint32_t crcStart) -: m_crcStart(crcStart) -{ -} +Crc16::Crc16(uint32_t crcStart) : m_crcStart(crcStart) {} -Crc16::Crc16(void) -: m_crcStart(0xEF4A) -{ -} +Crc16::Crc16(void) : m_crcStart(0xEF4A) {} Crc16::~Crc16(void) {} diff --git a/erpc_c/infra/erpc_framed_transport.cpp b/erpc_c/infra/erpc_framed_transport.cpp index b533241a..9e1a002e 100644 --- a/erpc_c/infra/erpc_framed_transport.cpp +++ b/erpc_c/infra/erpc_framed_transport.cpp @@ -22,12 +22,11 @@ using namespace erpc; // Code //////////////////////////////////////////////////////////////////////////////// -FramedTransport::FramedTransport(void) -: Transport() -, m_crcImpl(NULL) +FramedTransport::FramedTransport(void) : +Transport(), m_crcImpl(NULL) #if !ERPC_THREADS_IS(NONE) -, m_sendLock() -, m_receiveLock() +, +m_sendLock(), m_receiveLock() #endif { } diff --git a/erpc_c/infra/erpc_message_buffer.hpp b/erpc_c/infra/erpc_message_buffer.hpp index 857c422f..f70bafa9 100644 --- a/erpc_c/infra/erpc_message_buffer.hpp +++ b/erpc_c/infra/erpc_message_buffer.hpp @@ -42,12 +42,7 @@ class MessageBuffer * * This function initializes object attributes. */ - MessageBuffer(void) - : m_buf(NULL) - , m_len(0) - , m_used(0) - { - } + MessageBuffer(void) : m_buf(NULL), m_len(0), m_used(0) {} /*! * @brief Constructor. @@ -57,12 +52,7 @@ class MessageBuffer * @param[in] buffer Pointer to buffer. * @param[in] length Length of buffer. */ - MessageBuffer(uint8_t *buffer, uint16_t length) - : m_buf(buffer) - , m_len(length) - , m_used(0) - { - } + MessageBuffer(uint8_t *buffer, uint16_t length) : m_buf(buffer), m_len(length), m_used(0) {} MessageBuffer(const MessageBuffer &buffer); @@ -202,11 +192,7 @@ class Cursor * * This function initializes object attributes. */ - Cursor(void) - : m_buffer() - , m_pos(NULL) - { - } + Cursor(void) : m_buffer(), m_pos(NULL) {} /*! * @brief Constructor. @@ -215,11 +201,7 @@ class Cursor * * @param[in] buffer MessageBuffer for sending/receiving. */ - explicit Cursor(MessageBuffer &buffer) - : m_buffer(buffer) - , m_pos(buffer.get()) - { - } + explicit Cursor(MessageBuffer &buffer) : m_buffer(buffer), m_pos(buffer.get()) {} /*! * @brief Set message buffer. diff --git a/erpc_c/infra/erpc_message_loggers.hpp b/erpc_c/infra/erpc_message_loggers.hpp index 528c7702..7d259abe 100644 --- a/erpc_c/infra/erpc_message_loggers.hpp +++ b/erpc_c/infra/erpc_message_loggers.hpp @@ -34,9 +34,7 @@ class MessageLogger /*! * @brief MessageLogger constructor. */ - explicit MessageLogger(Transport *transport) - : m_next(NULL) - , m_transport(transport){}; + explicit MessageLogger(Transport *transport) : m_next(NULL), m_transport(transport){}; /*! * @brief MessageLogger destructor @@ -80,8 +78,7 @@ class MessageLoggers /*! * @brief Constructor. */ - MessageLoggers(void) - : m_logger(NULL){}; + MessageLoggers(void) : m_logger(NULL){}; /*! * @brief Transport destructor diff --git a/erpc_c/infra/erpc_pre_post_action.h b/erpc_c/infra/erpc_pre_post_action.h index f38a0be9..3f8574e1 100644 --- a/erpc_c/infra/erpc_pre_post_action.h +++ b/erpc_c/infra/erpc_pre_post_action.h @@ -42,9 +42,7 @@ class PrePostAction /*! * @brief PrePostAction constructor. */ - PrePostAction(void) - : m_preCB(NULL) - , m_postCB(NULL){}; + PrePostAction(void) : m_preCB(NULL), m_postCB(NULL){}; /*! * @brief This function sets "before eRPC call start" callback function. diff --git a/erpc_c/infra/erpc_server.hpp b/erpc_c/infra/erpc_server.hpp index b16df195..b7ec3f24 100644 --- a/erpc_c/infra/erpc_server.hpp +++ b/erpc_c/infra/erpc_server.hpp @@ -44,11 +44,7 @@ class Service * * This function initializes object attributes. */ - Service(uint32_t serviceId) - : m_serviceId(serviceId) - , m_next(NULL) - { - } + Service(uint32_t serviceId) : m_serviceId(serviceId), m_next(NULL) {} /*! * @brief Service destructor @@ -107,11 +103,7 @@ class Server : public ClientServerCommon * * This function initializes object attributes. */ - Server(void) - : ClientServerCommon() - , m_firstService(NULL) - { - } + Server(void) : ClientServerCommon(), m_firstService(NULL) {} /*! * @brief Server destructor diff --git a/erpc_c/infra/erpc_simple_server.cpp b/erpc_c/infra/erpc_simple_server.cpp index 9d268849..58738707 100644 --- a/erpc_c/infra/erpc_simple_server.cpp +++ b/erpc_c/infra/erpc_simple_server.cpp @@ -15,10 +15,7 @@ using namespace erpc; //////////////////////////////////////////////////////////////////////////////// // Code //////////////////////////////////////////////////////////////////////////////// -SimpleServer::SimpleServer(void) -: m_isServerOn(true) -{ -} +SimpleServer::SimpleServer(void) : m_isServerOn(true) {} SimpleServer::~SimpleServer(void) {} diff --git a/erpc_c/infra/erpc_transport_arbitrator.cpp b/erpc_c/infra/erpc_transport_arbitrator.cpp index 5d57f686..dce2f021 100644 --- a/erpc_c/infra/erpc_transport_arbitrator.cpp +++ b/erpc_c/infra/erpc_transport_arbitrator.cpp @@ -8,6 +8,7 @@ * SPDX-License-Identifier: BSD-3-Clause */ #include "erpc_transport_arbitrator.hpp" + #include "erpc_config_internal.h" #include "erpc_manually_constructed.hpp" @@ -27,13 +28,8 @@ using namespace erpc; ERPC_MANUALLY_CONSTRUCTED_ARRAY_STATIC(TransportArbitrator::PendingClientInfo, s_pendingClientInfoArray, ERPC_CLIENTS_THREADS_AMOUNT); -TransportArbitrator::TransportArbitrator(void) -: Transport() -, m_sharedTransport(NULL) -, m_codec(NULL) -, m_clientList(NULL) -, m_clientFreeList(NULL) -, m_clientListMutex() +TransportArbitrator::TransportArbitrator(void) : +Transport(), m_sharedTransport(NULL), m_codec(NULL), m_clientList(NULL), m_clientFreeList(NULL), m_clientListMutex() { } @@ -277,11 +273,8 @@ void TransportArbitrator::freeClientList(PendingClientInfo *list) } } -TransportArbitrator::PendingClientInfo::PendingClientInfo(void) -: m_request(NULL) -, m_sem(0) -, m_isValid(false) -, m_next(NULL) +TransportArbitrator::PendingClientInfo::PendingClientInfo(void) : +m_request(NULL), m_sem(0), m_isValid(false), m_next(NULL) { } diff --git a/erpc_c/infra/erpc_transport_arbitrator.hpp b/erpc_c/infra/erpc_transport_arbitrator.hpp index 3077d500..049c58af 100644 --- a/erpc_c/infra/erpc_transport_arbitrator.hpp +++ b/erpc_c/infra/erpc_transport_arbitrator.hpp @@ -102,7 +102,7 @@ class TransportArbitrator : public Transport * * @return Crc16* Pointer to CRC-16 object containing crc-16 compute function. */ - virtual Crc16 * getCrc16(void) override; + virtual Crc16 *getCrc16(void) override; /*! * @brief This function set shared client/server transport. @@ -116,7 +116,7 @@ class TransportArbitrator : public Transport * * @return Transport * Returns shared client/server transport. */ - Transport * getSharedTransport(void); + Transport *getSharedTransport(void); /*! * @brief This function set codec. @@ -130,7 +130,7 @@ class TransportArbitrator : public Transport * * @return Codec * Pointer to codec used within transport. */ - Codec * getCodec(void); + Codec *getCodec(void); /*! * @brief Add a client request to the client list. diff --git a/erpc_c/infra/erpc_utils.hpp b/erpc_c/infra/erpc_utils.hpp index 9b2f97d5..060aec3a 100644 --- a/erpc_c/infra/erpc_utils.hpp +++ b/erpc_c/infra/erpc_utils.hpp @@ -13,5 +13,5 @@ typedef void *functionPtr_t; typedef functionPtr_t *arrayOfFunctionPtr_t; bool findIndexOfFunction(const arrayOfFunctionPtr_t sourceArrayOfFunctionPtr, uint16_t sourceArrayLength, - const functionPtr_t functionPtr, uint16_t &retVal); -} + const functionPtr_t functionPtr, uint16_t &retVal); +} // namespace erpc diff --git a/erpc_c/port/erpc_setup_extensions_freertos.cpp b/erpc_c/port/erpc_setup_extensions_freertos.cpp index 5f878016..0d446b43 100644 --- a/erpc_c/port/erpc_setup_extensions_freertos.cpp +++ b/erpc_c/port/erpc_setup_extensions_freertos.cpp @@ -23,11 +23,15 @@ ERPC_MANUALLY_CONSTRUCTED_STATIC(Semaphore, s_semaphore); void erpc::erpc_pre_cb_default(void) { - erpc_assert((s_erpc_call_in_progress != NULL) && - ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != NULL)); + erpc_assert( + (s_erpc_call_in_progress != NULL) && + ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != + NULL)); (void)s_erpc_call_in_progress->get(s_erpc_call_in_progress->kWaitForever); - erpc_assert((s_erpc_call_timer_cb != NULL) && - ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != NULL)); + erpc_assert( + (s_erpc_call_timer_cb != NULL) && + ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != + NULL)); (void)xTimerStart(s_erpc_call_timer_cb, 0); } @@ -85,8 +89,10 @@ void erpc_deinit_call_progress_detection_default(void) bool erpc_is_call_in_progress_default(void) { - erpc_assert((s_erpc_call_in_progress != NULL) && - ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != NULL)); + erpc_assert( + (s_erpc_call_in_progress != NULL) && + ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != + NULL)); if (s_erpc_call_in_progress->get(0)) { s_erpc_call_in_progress->put(); @@ -98,12 +104,16 @@ bool erpc_is_call_in_progress_default(void) void erpc_reset_in_progress_state_default(void) { - erpc_assert((s_erpc_call_in_progress != NULL) && - ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != NULL)); + erpc_assert( + (s_erpc_call_in_progress != NULL) && + ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != + NULL)); s_erpc_call_in_progress->get(0); s_erpc_call_in_progress->put(); - erpc_assert((s_erpc_call_timer_cb != NULL) && - ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != NULL)); + erpc_assert( + (s_erpc_call_timer_cb != NULL) && + ("If you want use default pre cb action, do not forget call erpc_init_call_progress_detection_default." != + NULL)); (void)xTimerStop(s_erpc_call_timer_cb, 0); } diff --git a/erpc_c/port/erpc_threading.h b/erpc_c/port/erpc_threading.h index 1f3d66ad..3441b95c 100644 --- a/erpc_c/port/erpc_threading.h +++ b/erpc_c/port/erpc_threading.h @@ -349,11 +349,7 @@ class Mutex * * @param[in] mutex to lock. */ - Guard(Mutex &mutex) - : m_mutex(mutex) - { - (void)m_mutex.lock(); - } + Guard(Mutex &mutex) : m_mutex(mutex) { (void)m_mutex.lock(); } /*! * @brief Destructor. */ diff --git a/erpc_c/port/erpc_threading_freertos.cpp b/erpc_c/port/erpc_threading_freertos.cpp index bb9eae46..e694596e 100644 --- a/erpc_c/port/erpc_threading_freertos.cpp +++ b/erpc_c/port/erpc_threading_freertos.cpp @@ -26,26 +26,15 @@ Thread *Thread::s_first = NULL; // Code //////////////////////////////////////////////////////////////////////////////// -Thread::Thread(const char *name) -: m_name(name) -, m_entry(0) -, m_arg(0) -, m_stackSize(0) -, m_priority(0) -, m_task(0) -, m_next(0) +Thread::Thread(const char *name) : +m_name(name), m_entry(0), m_arg(0), m_stackSize(0), m_priority(0), m_task(0), m_next(0) { } Thread::Thread(thread_entry_t entry, uint32_t priority, uint32_t stackSize, const char *name, - thread_stack_pointer stackPtr) -: m_name(name) -, m_entry(entry) -, m_arg(0) -, m_stackSize(stackSize) -, m_priority(priority) -, m_task(0) -, m_next(0) + thread_stack_pointer stackPtr) : +m_name(name), +m_entry(entry), m_arg(0), m_stackSize(stackSize), m_priority(priority), m_task(0), m_next(0) { } @@ -73,10 +62,10 @@ void Thread::start(void *arg) #if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC if (m_stackPtr != NULL) { - m_task = - xTaskCreateStatic(threadEntryPointStub, (m_name != NULL ? m_name : "task"), - (configSTACK_DEPTH_TYPE)((m_stackSize + sizeof(uint32_t) - 1U) / sizeof(uint32_t)), // Round up number of words. - this, m_priority, m_stackPtr, &m_staticTask); + m_task = xTaskCreateStatic(threadEntryPointStub, (m_name != NULL ? m_name : "task"), + (configSTACK_DEPTH_TYPE)((m_stackSize + sizeof(uint32_t) - 1U) / + sizeof(uint32_t)), // Round up number of words. + this, m_priority, m_stackPtr, &m_staticTask); taskCreated = true; } #endif @@ -84,10 +73,10 @@ void Thread::start(void *arg) #if configSUPPORT_DYNAMIC_ALLOCATION if (m_stackPtr == NULL) { - if (pdPASS == - xTaskCreate(threadEntryPointStub, (m_name != NULL ? m_name : "task"), - (configSTACK_DEPTH_TYPE)((m_stackSize + sizeof(uint32_t) - 1U) / sizeof(uint32_t)), // Round up number of words. - this, m_priority, &m_task)) + if (pdPASS == xTaskCreate(threadEntryPointStub, (m_name != NULL ? m_name : "task"), + (configSTACK_DEPTH_TYPE)((m_stackSize + sizeof(uint32_t) - 1U) / + sizeof(uint32_t)), // Round up number of words. + this, m_priority, &m_task)) { taskCreated = true; } @@ -201,8 +190,7 @@ void Thread::threadEntryPointStub(void *arg) #endif // INCLUDE_vTaskDelete } -Mutex::Mutex(void) -: m_mutex(0) +Mutex::Mutex(void) : m_mutex(0) { #if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC m_mutex = xSemaphoreCreateRecursiveMutexStatic(&m_staticQueue); @@ -234,8 +222,7 @@ bool Mutex::unlock(void) return (pdTRUE == xSemaphoreGiveRecursive(m_mutex) ? true : false); } -Semaphore::Semaphore(int count) -: m_sem(0) +Semaphore::Semaphore(int count) : m_sem(0) { // Set max count to highest signed int. #if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC diff --git a/erpc_c/port/erpc_threading_mbed.cpp b/erpc_c/port/erpc_threading_mbed.cpp index 9f537a9a..ca59756c 100644 --- a/erpc_c/port/erpc_threading_mbed.cpp +++ b/erpc_c/port/erpc_threading_mbed.cpp @@ -28,26 +28,15 @@ Thread *Thread::s_first = NULL; // Code //////////////////////////////////////////////////////////////////////////////// -Thread::Thread(const char *name) -: m_name(name) -, m_entry(0) -, m_arg(0) -, m_stackSize(0) -, m_priority(0) -, m_thread(NULL) -, m_next(NULL) +Thread::Thread(const char *name) : +m_name(name), m_entry(0), m_arg(0), m_stackSize(0), m_priority(0), m_thread(NULL), m_next(NULL) { } Thread::Thread(thread_entry_t entry, uint32_t priority, uint32_t stackSize, const char *name, - thread_stack_pointer stackPtr) -: m_name(name) -, m_entry(entry) -, m_arg(0) -, m_stackSize(stackSize) -, m_priority(priority) -, m_thread(NULL) -, m_next(NULL) + thread_stack_pointer stackPtr) : +m_name(name), +m_entry(entry), m_arg(0), m_stackSize(stackSize), m_priority(priority), m_thread(NULL), m_next(NULL) { } @@ -198,8 +187,7 @@ bool Mutex::unlock(void) return m_mutex->unlock(); } -Semaphore::Semaphore(int count) -: m_count(count) +Semaphore::Semaphore(int count) : m_count(count) { m_sem = new rtos::Semaphore(m_count); } diff --git a/erpc_c/port/erpc_threading_pthreads.cpp b/erpc_c/port/erpc_threading_pthreads.cpp index 18ba49d3..418cbf4e 100644 --- a/erpc_c/port/erpc_threading_pthreads.cpp +++ b/erpc_c/port/erpc_threading_pthreads.cpp @@ -34,24 +34,12 @@ const uint32_t sToUs = 1000000; // Code //////////////////////////////////////////////////////////////////////////////// -Thread::Thread(const char *name) -: m_name(name) -, m_entry(0) -, m_arg(0) -, m_stackSize(0) -, m_priority(0) -, m_thread(0) -{ -} +Thread::Thread(const char *name) : m_name(name), m_entry(0), m_arg(0), m_stackSize(0), m_priority(0), m_thread(0) {} Thread::Thread(thread_entry_t entry, uint32_t priority, uint32_t stackSize, const char *name, - thread_stack_pointer stackPtr) -: m_name(name) -, m_entry(entry) -, m_arg(0) -, m_stackSize(stackSize) -, m_priority(priority) -, m_thread(0) + thread_stack_pointer stackPtr) : +m_name(name), +m_entry(entry), m_arg(0), m_stackSize(stackSize), m_priority(priority), m_thread(0) { } @@ -163,9 +151,7 @@ bool Mutex::unlock(void) return pthread_mutex_unlock(&m_mutex) == 0; } -Semaphore::Semaphore(int count) -: m_count(count) -, m_mutex() +Semaphore::Semaphore(int count) : m_count(count), m_mutex() { pthread_cond_init(&m_cond, NULL); } diff --git a/erpc_c/port/erpc_threading_threadx.cpp b/erpc_c/port/erpc_threading_threadx.cpp index 2c4939ff..397749c7 100644 --- a/erpc_c/port/erpc_threading_threadx.cpp +++ b/erpc_c/port/erpc_threading_threadx.cpp @@ -31,26 +31,15 @@ static TX_BYTE_POOL tx_app_byte_pool; // Code //////////////////////////////////////////////////////////////////////////////// -Thread::Thread(const char *name) -: m_name(name) -, m_entry(0) -, m_arg(0) -, m_stackSize(0) -, m_priority(0) -, m_thread() -, m_next() +Thread::Thread(const char *name) : +m_name(name), m_entry(0), m_arg(0), m_stackSize(0), m_priority(0), m_thread(), m_next() { } Thread::Thread(thread_entry_t entry, uint32_t priority, uint32_t stackSize, const char *name, - thread_stack_pointer stackPtr) -: m_name(name) -, m_entry(entry) -, m_arg(0) -, m_stackSize(stackSize) -, m_priority(priority) -, m_thread() -, m_next() + thread_stack_pointer stackPtr) : +m_name(name), +m_entry(entry), m_arg(0), m_stackSize(stackSize), m_priority(priority), m_thread(), m_next() { } @@ -209,8 +198,7 @@ void Thread::threadEntryPointStub(ULONG arg) tx_interrupt_control(my_old_posture); } -Mutex::Mutex(void) -: m_mutex() +Mutex::Mutex(void) : m_mutex() { CHAR name[] = "erpc_mutex"; tx_mutex_create(&m_mutex, name, TX_INHERIT); @@ -239,8 +227,7 @@ bool Mutex::unlock(void) return (status == TX_SUCCESS); } -Semaphore::Semaphore(int count) -: m_sem() +Semaphore::Semaphore(int count) : m_sem() { CHAR name[] = "erpc_sem"; tx_semaphore_create(&m_sem, name, count); diff --git a/erpc_c/port/erpc_threading_win32.cpp b/erpc_c/port/erpc_threading_win32.cpp index 459c5b0a..7d13d5dd 100644 --- a/erpc_c/port/erpc_threading_win32.cpp +++ b/erpc_c/port/erpc_threading_win32.cpp @@ -29,28 +29,15 @@ CRITICAL_SECTION Thread::m_critical_section; // Code //////////////////////////////////////////////////////////////////////////////// -Thread::Thread(const char *name) -: m_name(name) -, m_entry(0) -, m_arg(0) -, m_stackSize(0) -, m_priority(0) -, m_thread(0) -, m_thrdaddr(0) -, m_next(0) +Thread::Thread(const char *name) : +m_name(name), m_entry(0), m_arg(0), m_stackSize(0), m_priority(0), m_thread(0), m_thrdaddr(0), m_next(0) { } Thread::Thread(thread_entry_t entry, uint32_t priority, uint32_t stackSize, const char *name, - thread_stack_pointer stackPtr) -: m_name(name) -, m_entry(entry) -, m_arg(0) -, m_stackSize(stackSize) -, m_priority(priority) -, m_thread(0) -, m_thrdaddr(0) -, m_next(0) + thread_stack_pointer stackPtr) : +m_name(name), +m_entry(entry), m_arg(0), m_stackSize(stackSize), m_priority(priority), m_thread(0), m_thrdaddr(0), m_next(0) { } @@ -172,10 +159,7 @@ bool Mutex::unlock(void) return ReleaseMutex(m_mutex); } -Semaphore::Semaphore(int count) -: m_count(count) -, m_sem() -, m_mutex() +Semaphore::Semaphore(int count) : m_count(count), m_sem(), m_mutex() { m_sem = CreateSemaphore(NULL, m_count, 1, ""); } diff --git a/erpc_c/port/erpc_threading_zephyr.cpp b/erpc_c/port/erpc_threading_zephyr.cpp index 24928cc3..e71c3c8c 100644 --- a/erpc_c/port/erpc_threading_zephyr.cpp +++ b/erpc_c/port/erpc_threading_zephyr.cpp @@ -17,26 +17,15 @@ using namespace erpc; // Code //////////////////////////////////////////////////////////////////////////////// -Thread::Thread(const char *name) -: m_name(name) -, m_entry(0) -, m_arg(0) -, m_stackSize(0) -, m_priority(0) -, m_thread(0) -, m_stack(0) +Thread::Thread(const char *name) : +m_name(name), m_entry(0), m_arg(0), m_stackSize(0), m_priority(0), m_thread(0), m_stack(0) { } Thread::Thread(thread_entry_t entry, uint32_t priority, uint32_t stackSize, const char *name, - thread_stack_pointer stackPtr) -: m_name(name) -, m_entry(entry) -, m_arg(0) -, m_stackSize(stackSize) -, m_priority(priority) -, m_thread(0) -, m_stack(0) + thread_stack_pointer stackPtr) : +m_name(name), +m_entry(entry), m_arg(0), m_stackSize(stackSize), m_priority(priority), m_thread(0), m_stack(0) { } @@ -92,8 +81,7 @@ void *Thread::threadEntryPointStub(void *arg1, void *arg2, void *arg3) k_thread_abort(k_current_get()); } -Mutex::Mutex(void) -: m_mutex(0) +Mutex::Mutex(void) : m_mutex(0) { k_mutex_init(&m_mutex); } @@ -116,8 +104,7 @@ bool Mutex::unlock(void) return true; } -Semaphore::Semaphore(int count) -: m_sem(0) +Semaphore::Semaphore(int count) : m_sem(0) { // Set max count to highest signed int. k_sem_init(&m_sem, count, 0x7fffffff); diff --git a/erpc_c/setup/erpc_arbitrated_client_setup.cpp b/erpc_c/setup/erpc_arbitrated_client_setup.cpp index a37a73ec..5ebcdbee 100644 --- a/erpc_c/setup/erpc_arbitrated_client_setup.cpp +++ b/erpc_c/setup/erpc_arbitrated_client_setup.cpp @@ -32,9 +32,9 @@ using namespace erpc; // global client variables ERPC_MANUALLY_CONSTRUCTED_STATIC(ArbitratedClientManager, s_client); #if defined(__MINGW32__) -__declspec( selectany ) +__declspec(selectany) #endif -ClientManager *g_client; + ClientManager *g_client; #if !defined(__MINGW32__) #pragma weak g_client #endif diff --git a/erpc_c/setup/erpc_client_setup.cpp b/erpc_c/setup/erpc_client_setup.cpp index 36631c8a..cd669f7e 100644 --- a/erpc_c/setup/erpc_client_setup.cpp +++ b/erpc_c/setup/erpc_client_setup.cpp @@ -30,9 +30,9 @@ using namespace erpc; // global client variables ERPC_MANUALLY_CONSTRUCTED_STATIC(ClientManager, s_client); #if defined(__MINGW32__) -__declspec( selectany ) +__declspec(selectany) #endif -ClientManager *g_client; + ClientManager *g_client; #if !defined(__MINGW32__) #pragma weak g_client #endif diff --git a/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp b/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp index 2d0c2e7d..86d2aa66 100644 --- a/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp +++ b/erpc_c/setup/erpc_setup_mbf_rpmsg.cpp @@ -125,8 +125,7 @@ erpc_mbf_t erpc_mbf_rpmsg_init(erpc_transport_t transport) msgFactory = s_msgFactory.get(); } #elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC - msgFactory = - new RPMsgMessageBufferFactory(reinterpret_cast(transport)->get_rpmsg_lite_instance()); + msgFactory = new RPMsgMessageBufferFactory(reinterpret_cast(transport)->get_rpmsg_lite_instance()); #else #error "Unknown eRPC allocation policy!" #endif diff --git a/erpc_c/setup/erpc_setup_mbf_static.cpp b/erpc_c/setup/erpc_setup_mbf_static.cpp index c4293ae5..52b62d33 100644 --- a/erpc_c/setup/erpc_setup_mbf_static.cpp +++ b/erpc_c/setup/erpc_setup_mbf_static.cpp @@ -38,7 +38,8 @@ class StaticMessageBufferFactory : public MessageBufferFactory */ StaticMessageBufferFactory(void) #if !ERPC_THREADS_IS(NONE) - : m_semaphore(1) + : + m_semaphore(1) #endif { (void)memset(m_freeBufferBitmap, 0xff, sizeof(m_freeBufferBitmap)); diff --git a/erpc_c/transports/erpc_dspi_master_transport.cpp b/erpc_c/transports/erpc_dspi_master_transport.cpp index fa2abc8d..705407a4 100644 --- a/erpc_c/transports/erpc_dspi_master_transport.cpp +++ b/erpc_c/transports/erpc_dspi_master_transport.cpp @@ -100,10 +100,8 @@ static inline void DSpidevMasterTransport_WaitForSlaveReadyMarker(SPI_Type *spiB } #endif -DspiMasterTransport::DspiMasterTransport(SPI_Type *spiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) -: m_spiBaseAddr(spiBaseAddr) -, m_baudRate(baudRate) -, m_srcClock_Hz(srcClock_Hz) +DspiMasterTransport::DspiMasterTransport(SPI_Type *spiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) : +m_spiBaseAddr(spiBaseAddr), m_baudRate(baudRate), m_srcClock_Hz(srcClock_Hz) { } diff --git a/erpc_c/transports/erpc_dspi_master_transport.hpp b/erpc_c/transports/erpc_dspi_master_transport.hpp index 108a0d42..bba057c5 100644 --- a/erpc_c/transports/erpc_dspi_master_transport.hpp +++ b/erpc_c/transports/erpc_dspi_master_transport.hpp @@ -11,6 +11,7 @@ #define _EMBEDDED_RPC__DSPI_MASTER_TRANSPORT_H_ #include "erpc_framed_transport.hpp" + #include extern "C" { diff --git a/erpc_c/transports/erpc_dspi_slave_transport.cpp b/erpc_c/transports/erpc_dspi_slave_transport.cpp index b0f68a5b..86b0f076 100644 --- a/erpc_c/transports/erpc_dspi_slave_transport.cpp +++ b/erpc_c/transports/erpc_dspi_slave_transport.cpp @@ -94,13 +94,11 @@ static void DSPI_SlaveUserCallback(SPI_Type *base, dspi_slave_handle_t *handle, transport->transfer_cb(); } -DspiSlaveTransport::DspiSlaveTransport(SPI_Type *spiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) -: m_spiBaseAddr(spiBaseAddr) -, m_baudRate(baudRate) -, m_srcClock_Hz(srcClock_Hz) -, m_isInited(false) +DspiSlaveTransport::DspiSlaveTransport(SPI_Type *spiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) : +m_spiBaseAddr(spiBaseAddr), m_baudRate(baudRate), m_srcClock_Hz(srcClock_Hz), m_isInited(false) #if ERPC_THREADS -, m_txrxSemaphore() +, +m_txrxSemaphore() #endif { s_dspi_slave_instance = this; diff --git a/erpc_c/transports/erpc_dspi_slave_transport.hpp b/erpc_c/transports/erpc_dspi_slave_transport.hpp index 65cc214d..e2cf0604 100644 --- a/erpc_c/transports/erpc_dspi_slave_transport.hpp +++ b/erpc_c/transports/erpc_dspi_slave_transport.hpp @@ -15,6 +15,7 @@ #include "erpc_threading.h" #endif #include "erpc_framed_transport.hpp" + #include extern "C" { diff --git a/erpc_c/transports/erpc_i2c_slave_transport.cpp b/erpc_c/transports/erpc_i2c_slave_transport.cpp index 7fa3b52a..d69bc8a4 100644 --- a/erpc_c/transports/erpc_i2c_slave_transport.cpp +++ b/erpc_c/transports/erpc_i2c_slave_transport.cpp @@ -144,13 +144,11 @@ static void I2C_SlaveUserCallback(I2C_Type *base, volatile i2c_slave_transfer_t } } -I2cSlaveTransport::I2cSlaveTransport(I2C_Type *i2cBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) -: m_i2cBaseAddr(i2cBaseAddr) -, m_baudRate(baudRate) -, m_srcClock_Hz(srcClock_Hz) -, m_isInited(false) +I2cSlaveTransport::I2cSlaveTransport(I2C_Type *i2cBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) : +m_i2cBaseAddr(i2cBaseAddr), m_baudRate(baudRate), m_srcClock_Hz(srcClock_Hz), m_isInited(false) #if ERPC_THREADS -, m_txrxSemaphore() +, +m_txrxSemaphore() #endif { s_i2c_slave_instance = this; diff --git a/erpc_c/transports/erpc_inter_thread_buffer_transport.hpp b/erpc_c/transports/erpc_inter_thread_buffer_transport.hpp index 655aba2d..dabba2bb 100644 --- a/erpc_c/transports/erpc_inter_thread_buffer_transport.hpp +++ b/erpc_c/transports/erpc_inter_thread_buffer_transport.hpp @@ -44,21 +44,16 @@ namespace erpc { class InterThreadBufferTransport : public Transport { public: - InterThreadBufferTransport(void) - : Transport() - , m_state(NULL) - , m_peer(NULL) - , m_inSem() - , m_outSem(1) - , m_inBuffer(NULL) + InterThreadBufferTransport(void) : + Transport(), m_state(NULL), m_peer(NULL), m_inSem(), m_outSem(1), m_inBuffer(NULL) { } virtual ~InterThreadBufferTransport(void); void linkWithPeer(InterThreadBufferTransport *peer); - virtual erpc_status_t receive(MessageBuffer *message)override; - virtual erpc_status_t send(MessageBuffer *message)override; + virtual erpc_status_t receive(MessageBuffer *message) override; + virtual erpc_status_t send(MessageBuffer *message) override; virtual int32_t getAvailable(void) const { return 0; } diff --git a/erpc_c/transports/erpc_lpi2c_slave_transport.cpp b/erpc_c/transports/erpc_lpi2c_slave_transport.cpp index 96e3e7dc..c0ce3e00 100644 --- a/erpc_c/transports/erpc_lpi2c_slave_transport.cpp +++ b/erpc_c/transports/erpc_lpi2c_slave_transport.cpp @@ -138,13 +138,11 @@ static void LPI2C_SlaveUserCallback(LPI2C_Type *base, lpi2c_slave_transfer_t *tr } } -LPI2cSlaveTransport::LPI2cSlaveTransport(LPI2C_Type *lpi2cBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) -: m_lpi2cBaseAddr(lpi2cBaseAddr) -, m_baudRate(baudRate) -, m_srcClock_Hz(srcClock_Hz) -, m_isInited(false) +LPI2cSlaveTransport::LPI2cSlaveTransport(LPI2C_Type *lpi2cBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) : +m_lpi2cBaseAddr(lpi2cBaseAddr), m_baudRate(baudRate), m_srcClock_Hz(srcClock_Hz), m_isInited(false) #if ERPC_THREADS -, m_txrxSemaphore() +, +m_txrxSemaphore() #endif { s_lpi2c_slave_instance = this; diff --git a/erpc_c/transports/erpc_lpspi_slave_transport.cpp b/erpc_c/transports/erpc_lpspi_slave_transport.cpp index 94f3ecc2..7d8ee191 100644 --- a/erpc_c/transports/erpc_lpspi_slave_transport.cpp +++ b/erpc_c/transports/erpc_lpspi_slave_transport.cpp @@ -108,13 +108,11 @@ static void LPSPI_SlaveUserCallback(LPSPI_Type *base, lpspi_slave_handle_t *hand transport->transfer_cb(); } -LPSpiSlaveTransport::LPSpiSlaveTransport(LPSPI_Type *lpspiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) -: m_lpspiBaseAddr(lpspiBaseAddr) -, m_baudRate(baudRate) -, m_srcClock_Hz(srcClock_Hz) -, m_isInited(false) +LPSpiSlaveTransport::LPSpiSlaveTransport(LPSPI_Type *lpspiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) : +m_lpspiBaseAddr(lpspiBaseAddr), m_baudRate(baudRate), m_srcClock_Hz(srcClock_Hz), m_isInited(false) #if ERPC_THREADS -, m_txrxSemaphore() +, +m_txrxSemaphore() #endif { s_lpspi_slave_instance = this; diff --git a/erpc_c/transports/erpc_mu_transport.cpp b/erpc_c/transports/erpc_mu_transport.cpp index e6c64a63..af7832b5 100644 --- a/erpc_c/transports/erpc_mu_transport.cpp +++ b/erpc_c/transports/erpc_mu_transport.cpp @@ -76,22 +76,15 @@ void MUTransport::mu_irq_callback(void) } #endif /* ERPC_TRANSPORT_MU_USE_MCMGR */ -MUTransport::MUTransport(void) -: Transport() -, m_newMessage(false) -, m_rxMsgSize(0) -, m_rxCntBytes(0) -, m_rxBuffer(NULL) -, m_txMsgSize(0) -, m_txCntBytes(0) -, m_txBuffer(NULL) +MUTransport::MUTransport(void) : +Transport(), m_newMessage(false), m_rxMsgSize(0), m_rxCntBytes(0), m_rxBuffer(NULL), m_txMsgSize(0), m_txCntBytes(0), +m_txBuffer(NULL) #if !ERPC_THREADS_IS(NONE) -, m_rxSemaphore() -, m_txSemaphore() -, m_sendLock() -, m_receiveLock() +, +m_rxSemaphore(), m_txSemaphore(), m_sendLock(), m_receiveLock() #endif -, m_muBase(NULL) +, +m_muBase(NULL) { s_mu_instance = this; } diff --git a/erpc_c/transports/erpc_rpmsg_linux_transport.cpp b/erpc_c/transports/erpc_rpmsg_linux_transport.cpp index 2b229429..17a756bb 100644 --- a/erpc_c/transports/erpc_rpmsg_linux_transport.cpp +++ b/erpc_c/transports/erpc_rpmsg_linux_transport.cpp @@ -17,10 +17,8 @@ using namespace erpc; // Code //////////////////////////////////////////////////////////////////////////////// -RPMsgLinuxTransport::RPMsgLinuxTransport(RPMsgEndpoint *endPoint, int16_t remote) -: Transport() -, m_endPoint(endPoint) -, m_remote(remote) +RPMsgLinuxTransport::RPMsgLinuxTransport(RPMsgEndpoint *endPoint, int16_t remote) : +Transport(), m_endPoint(endPoint), m_remote(remote) { } diff --git a/erpc_c/transports/erpc_rpmsg_lite_base.hpp b/erpc_c/transports/erpc_rpmsg_lite_base.hpp old mode 100755 new mode 100644 diff --git a/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.cpp b/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.cpp index 8eb1350b..708031b2 100644 --- a/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.cpp +++ b/erpc_c/transports/erpc_rpmsg_lite_rtos_transport.cpp @@ -28,15 +28,9 @@ struct rpmsg_lite_instance *RPMsgBase::s_rpmsg; // Code //////////////////////////////////////////////////////////////////////////////// -RPMsgRTOSTransport::RPMsgRTOSTransport(void) -: RPMsgBase() -, Transport() -, m_rdev(NULL) -, m_app_rp_chnl(NULL) -, m_dst_addr(0) -, m_rpmsg_queue(NULL) -, m_rpmsg_ept(NULL) -, m_crcImpl(NULL) +RPMsgRTOSTransport::RPMsgRTOSTransport(void) : +RPMsgBase(), Transport(), m_rdev(NULL), m_app_rp_chnl(NULL), m_dst_addr(0), m_rpmsg_queue(NULL), m_rpmsg_ept(NULL), +m_crcImpl(NULL) { } diff --git a/erpc_c/transports/erpc_rpmsg_lite_transport.cpp b/erpc_c/transports/erpc_rpmsg_lite_transport.cpp index 729c50ad..79bd9565 100644 --- a/erpc_c/transports/erpc_rpmsg_lite_transport.cpp +++ b/erpc_c/transports/erpc_rpmsg_lite_transport.cpp @@ -39,14 +39,7 @@ int32_t RPMsgTransport::rpmsg_read_cb(void *payload, uint32_t payload_len, uint3 return RL_HOLD; } -RPMsgTransport::RPMsgTransport(void) -: RPMsgBase() -, Transport() -, m_dst_addr(0) -, m_rpmsg_ept(NULL) -, m_crcImpl(NULL) -{ -} +RPMsgTransport::RPMsgTransport(void) : RPMsgBase(), Transport(), m_dst_addr(0), m_rpmsg_ept(NULL), m_crcImpl(NULL) {} RPMsgTransport::~RPMsgTransport(void) { diff --git a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp index e7450629..b3da88b0 100644 --- a/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp +++ b/erpc_c/transports/erpc_rpmsg_tty_rtos_transport.cpp @@ -29,12 +29,8 @@ struct rpmsg_lite_instance *RPMsgBase::s_rpmsg; // Code //////////////////////////////////////////////////////////////////////////////// -RPMsgTTYRTOSTransport::RPMsgTTYRTOSTransport(void) -: FramedTransport() -, RPMsgBase() -, m_dst_addr(0) -, m_rpmsg_queue(NULL) -, m_rpmsg_ept(NULL) +RPMsgTTYRTOSTransport::RPMsgTTYRTOSTransport(void) : +FramedTransport(), RPMsgBase(), m_dst_addr(0), m_rpmsg_queue(NULL), m_rpmsg_ept(NULL) { } diff --git a/erpc_c/transports/erpc_serial_transport.cpp b/erpc_c/transports/erpc_serial_transport.cpp index 80d9b45c..ea882eb7 100644 --- a/erpc_c/transports/erpc_serial_transport.cpp +++ b/erpc_c/transports/erpc_serial_transport.cpp @@ -32,10 +32,8 @@ using namespace erpc; // Code //////////////////////////////////////////////////////////////////////////////// -SerialTransport::SerialTransport(const char *portName, speed_t baudRate) -: m_serialHandle(0) -, m_portName(portName) -, m_baudRate(baudRate) +SerialTransport::SerialTransport(const char *portName, speed_t baudRate) : +m_serialHandle(0), m_portName(portName), m_baudRate(baudRate) { } diff --git a/erpc_c/transports/erpc_spi_master_transport.cpp b/erpc_c/transports/erpc_spi_master_transport.cpp index 20a216de..2fe79f6b 100644 --- a/erpc_c/transports/erpc_spi_master_transport.cpp +++ b/erpc_c/transports/erpc_spi_master_transport.cpp @@ -101,10 +101,8 @@ static inline void SpidevMasterTransport_WaitForSlaveReadyMarker(SPI_Type *spiBa } #endif -SpiMasterTransport::SpiMasterTransport(SPI_Type *spiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) -: m_spiBaseAddr(spiBaseAddr) -, m_baudRate(baudRate) -, m_srcClock_Hz(srcClock_Hz) +SpiMasterTransport::SpiMasterTransport(SPI_Type *spiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) : +m_spiBaseAddr(spiBaseAddr), m_baudRate(baudRate), m_srcClock_Hz(srcClock_Hz) { } diff --git a/erpc_c/transports/erpc_spi_slave_transport.cpp b/erpc_c/transports/erpc_spi_slave_transport.cpp index f4d034b2..34b9483c 100644 --- a/erpc_c/transports/erpc_spi_slave_transport.cpp +++ b/erpc_c/transports/erpc_spi_slave_transport.cpp @@ -112,13 +112,11 @@ static void SPI_SlaveUserCallback(SPI_Type *base, spi_slave_handle_t *handle, st transport->transfer_cb(); } -SpiSlaveTransport::SpiSlaveTransport(SPI_Type *spiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) -: m_spiBaseAddr(spiBaseAddr) -, m_baudRate(baudRate) -, m_srcClock_Hz(srcClock_Hz) -, m_isInited(false) +SpiSlaveTransport::SpiSlaveTransport(SPI_Type *spiBaseAddr, uint32_t baudRate, uint32_t srcClock_Hz) : +m_spiBaseAddr(spiBaseAddr), m_baudRate(baudRate), m_srcClock_Hz(srcClock_Hz), m_isInited(false) #if ERPC_THREADS -, m_txrxSemaphore() +, +m_txrxSemaphore() #endif { s_spi_slave_instance = this; diff --git a/erpc_c/transports/erpc_spidev_master_transport.cpp b/erpc_c/transports/erpc_spidev_master_transport.cpp index 972b10d9..0d7d3a08 100644 --- a/erpc_c/transports/erpc_spidev_master_transport.cpp +++ b/erpc_c/transports/erpc_spidev_master_transport.cpp @@ -84,10 +84,8 @@ static inline void SpidevMasterTransport_WaitForSlaveReadyMarker(int spi_fd) } #endif -SpidevMasterTransport::SpidevMasterTransport(const char *spidev, uint32_t speed_Hz) -: m_spidevHandle(0) -, m_spidev(spidev) -, m_speed_Hz(speed_Hz) +SpidevMasterTransport::SpidevMasterTransport(const char *spidev, uint32_t speed_Hz) : +m_spidevHandle(0), m_spidev(spidev), m_speed_Hz(speed_Hz) { } diff --git a/erpc_c/transports/erpc_tcp_transport.cpp b/erpc_c/transports/erpc_tcp_transport.cpp index 5709cbf8..9712ce6c 100644 --- a/erpc_c/transports/erpc_tcp_transport.cpp +++ b/erpc_c/transports/erpc_tcp_transport.cpp @@ -51,7 +51,7 @@ using namespace erpc; #if defined(__MINGW32__) #ifndef AI_NUMERICSERV -#define AI_NUMERICSERV 0x00000008 // Servicename must be a numeric port number +#define AI_NUMERICSERV 0x00000008 // Servicename must be a numeric port number #endif #endif @@ -59,17 +59,17 @@ using namespace erpc; // Code //////////////////////////////////////////////////////////////////////////////// -TCPTransport::TCPTransport(bool isServer) -: m_isServer(isServer) -, m_host(NULL) -, m_port(0) +TCPTransport::TCPTransport(bool isServer) : +m_isServer(isServer), m_host(NULL), m_port(0) #if defined(__MINGW32__) -, m_socket(INVALID_SOCKET) +, +m_socket(INVALID_SOCKET) #else -, m_socket(-1) +, +m_socket(-1) #endif -, m_serverThread(serverThreadStub) -, m_runServer(true) +, +m_serverThread(serverThreadStub), m_runServer(true) { #if defined(__MINGW32__) WSADATA ws; @@ -77,17 +77,17 @@ TCPTransport::TCPTransport(bool isServer) #endif } -TCPTransport::TCPTransport(const char *host, uint16_t port, bool isServer) -: m_isServer(isServer) -, m_host(host) -, m_port(port) +TCPTransport::TCPTransport(const char *host, uint16_t port, bool isServer) : +m_isServer(isServer), m_host(host), m_port(port) #if defined(__MINGW32__) -, m_socket(INVALID_SOCKET) +, +m_socket(INVALID_SOCKET) #else -, m_socket(-1) +, +m_socket(-1) #endif -, m_serverThread(serverThreadStub) -, m_runServer(true) +, +m_serverThread(serverThreadStub), m_runServer(true) { #if defined(__MINGW32__) WSADATA ws; diff --git a/erpc_c/transports/erpc_tcp_transport.hpp b/erpc_c/transports/erpc_tcp_transport.hpp index 1e171fbf..7e1f4da9 100644 --- a/erpc_c/transports/erpc_tcp_transport.hpp +++ b/erpc_c/transports/erpc_tcp_transport.hpp @@ -86,13 +86,13 @@ class TCPTransport : public FramedTransport virtual erpc_status_t close(bool stopServer = true); protected: - bool m_isServer; /*!< If true then server is using transport, else client. */ - const char *m_host; /*!< Specify the host name or IP address of the computer. */ - uint16_t m_port; /*!< Specify the listening port number. */ + bool m_isServer; /*!< If true then server is using transport, else client. */ + const char *m_host; /*!< Specify the host name or IP address of the computer. */ + uint16_t m_port; /*!< Specify the listening port number. */ #if defined(__MINGW32__) - SOCKET m_socket; /*!< Socket number. */ + SOCKET m_socket; /*!< Socket number. */ #else - int m_socket; /*!< Socket number. */ + int m_socket; /*!< Socket number. */ #endif Thread m_serverThread; /*!< Pointer to server thread. */ bool m_runServer; /*!< Thread is executed while this is true. */ @@ -100,7 +100,6 @@ class TCPTransport : public FramedTransport using FramedTransport::underlyingReceive; using FramedTransport::underlyingSend; - /*! * @brief This function connect client to the server. * diff --git a/erpc_c/transports/erpc_uart_cmsis_transport.cpp b/erpc_c/transports/erpc_uart_cmsis_transport.cpp index 9dddd85d..3d69e710 100644 --- a/erpc_c/transports/erpc_uart_cmsis_transport.cpp +++ b/erpc_c/transports/erpc_uart_cmsis_transport.cpp @@ -26,11 +26,11 @@ static UartTransport *s_uart_instance = NULL; // Code //////////////////////////////////////////////////////////////////////////////// -UartTransport::UartTransport(ARM_DRIVER_USART *uartDrv) -: m_uartDrv(uartDrv) +UartTransport::UartTransport(ARM_DRIVER_USART *uartDrv) : +m_uartDrv(uartDrv) #if !ERPC_THREADS_IS(NONE) -, m_rxSemaphore() -, m_txSemaphore() +, +m_rxSemaphore(), m_txSemaphore() #endif { s_uart_instance = this; diff --git a/erpc_c/transports/erpc_usb_cdc_transport.cpp b/erpc_c/transports/erpc_usb_cdc_transport.cpp index a960077a..67bf3008 100644 --- a/erpc_c/transports/erpc_usb_cdc_transport.cpp +++ b/erpc_c/transports/erpc_usb_cdc_transport.cpp @@ -83,15 +83,13 @@ void UsbCdcTransport::rx_cb(void) UsbCdcTransport::UsbCdcTransport(serial_handle_t serialHandle, serial_manager_config_t *serialConfig, serial_port_usb_cdc_config_t *usbCdcConfig, uint8_t *usbRingBuffer, - uint32_t usbRingBufferLength) -: m_serialHandle(serialHandle) -, m_serialConfig(serialConfig) -, m_usbCdcConfig(usbCdcConfig) -, m_usbRingBuffer(usbRingBuffer) -, m_usbRingBufferLength(usbRingBufferLength) + uint32_t usbRingBufferLength) : +m_serialHandle(serialHandle), +m_serialConfig(serialConfig), m_usbCdcConfig(usbCdcConfig), m_usbRingBuffer(usbRingBuffer), +m_usbRingBufferLength(usbRingBufferLength) #if !ERPC_THREADS_IS(NONE) -, m_rxSemaphore() -, m_txSemaphore() +, +m_rxSemaphore(), m_txSemaphore() #endif { s_usbcdc_instance = this; diff --git a/erpcgen/src/AstNode.cpp b/erpcgen/src/AstNode.cpp index a04e7012..05b868b7 100644 --- a/erpcgen/src/AstNode.cpp +++ b/erpcgen/src/AstNode.cpp @@ -22,9 +22,7 @@ using namespace std; // Code //////////////////////////////////////////////////////////////////////////////// -AstNode::AstNode(const AstNode &other) -: m_token(other.m_token) -, m_parent(other.m_parent) +AstNode::AstNode(const AstNode &other) : m_token(other.m_token), m_parent(other.m_parent) { // Clone children. for (auto it : other.m_children) @@ -220,7 +218,8 @@ string AstNode::getDescription() const case TOK_ARRAY: case TOK_UNION_CASE: break; - default: { + default: + { output += " " + valToString + " "; if (valToString.size() == 1) { diff --git a/erpcgen/src/AstNode.hpp b/erpcgen/src/AstNode.hpp index a2ed1878..e748e854 100644 --- a/erpcgen/src/AstNode.hpp +++ b/erpcgen/src/AstNode.hpp @@ -53,11 +53,7 @@ class AstNode * @see AstNode::AstNode(Token * token, AstNode * parent) * @see AstNode::AstNode(const AstNode & other) */ - explicit AstNode(const Token &token) - : m_token(token) - , m_parent(nullptr) - { - } + explicit AstNode(const Token &token) : m_token(token), m_parent(nullptr) {} /*! * @brief This function is constructor of AstNode class. @@ -71,11 +67,7 @@ class AstNode * @see AstNode::AstNode(Token * token) * @see AstNode::AstNode(const AstNode & other) */ - AstNode(Token &token, AstNode *parent) - : m_token(token) - , m_parent(parent) - { - } + AstNode(Token &token, AstNode *parent) : m_token(token), m_parent(parent) {} /*! * @brief This function is copy constructor of AstNode class. @@ -401,11 +393,7 @@ class AstPrinter * * @param[in] root Pointer to root node. */ - explicit AstPrinter(AstNode *root) - : m_root(root) - , m_depth(0) - { - } + explicit AstPrinter(AstNode *root) : m_root(root), m_depth(0) {} /*! * @brief This function call for dispatch function. diff --git a/erpcgen/src/AstWalker.hpp b/erpcgen/src/AstWalker.hpp index 4f4a7ddb..459225b5 100644 --- a/erpcgen/src/AstWalker.hpp +++ b/erpcgen/src/AstWalker.hpp @@ -53,10 +53,7 @@ class AstWalker * * @param[in] inputFile Parsed file name. */ - explicit AstWalker(const std::string &inputFile) - : m_fileName(inputFile) - { - } + explicit AstWalker(const std::string &inputFile) : m_fileName(inputFile) {} /*! * @brief destructor diff --git a/erpcgen/src/CGenerator.cpp b/erpcgen/src/CGenerator.cpp index 676dab38..b3f8787f 100644 --- a/erpcgen/src/CGenerator.cpp +++ b/erpcgen/src/CGenerator.cpp @@ -53,8 +53,7 @@ static uint8_t listCounter = 0; //////////////////////////////////////////////////////////////////////////////// // Code //////////////////////////////////////////////////////////////////////////////// -CGenerator::CGenerator(InterfaceDefinition *def) -: Generator(def, generator_type_t::kC) +CGenerator::CGenerator(InterfaceDefinition *def) : Generator(def, generator_type_t::kC) { /* Set copyright rules. */ if (m_def->hasProgramSymbol()) @@ -232,19 +231,22 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da switch (dataType->getDataType()) { - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { AliasType *aliasType = dynamic_cast(dataType); assert(aliasType); aliasType->setElementType(findChildDataType(dataTypes, aliasType->getElementType())); break; } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { ArrayType *arrayType = dynamic_cast(dataType); assert(arrayType); arrayType->setElementType(findChildDataType(dataTypes, arrayType->getElementType())); break; } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { if (dataType->isBinary()) { // check if binary data type was replaced with structure wrapper @@ -275,7 +277,8 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da dataTypes.insert(dataType); break; } - case DataType::data_type_t::kFunctionType: { + case DataType::data_type_t::kFunctionType: + { FunctionType *funcType = dynamic_cast(dataType); assert(funcType); @@ -298,7 +301,8 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da } break; } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { // The only child node of a list node is the element type. ListType *listType = dynamic_cast(dataType); DataType *trueContainerDataType = listType->getTrueContainerDataType(); @@ -390,7 +394,8 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da break; } } - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *structType = dynamic_cast(dataType); assert(structType); @@ -415,7 +420,8 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da } break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { // Keil need extra pragma option when unions are used. m_templateData["usedUnionType"] = true; UnionType *currentUnion = dynamic_cast(dataType); @@ -429,7 +435,8 @@ DataType *CGenerator::findChildDataType(set &dataTypes, DataType *da } break; } - default: { + default: + { break; } } @@ -796,7 +803,8 @@ void CGenerator::makeAliasesTemplateData() aliasInfo["unnamedName"] = getOutputName(aliasType); switch (elementDataType->getDataType()) { - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *structType = dynamic_cast(elementDataType); assert(structType); aliasInfo["unnamed"] = getStructDefinitionTemplateData( @@ -804,7 +812,8 @@ void CGenerator::makeAliasesTemplateData() aliasInfo["unnamedType"] = "struct"; break; } - case DataType::data_type_t::kEnumType: { + case DataType::data_type_t::kEnumType: + { EnumType *enumType = dynamic_cast(elementDataType); assert(enumType); aliasInfo["unnamed"] = getEnumTemplateData(enumType); @@ -1807,15 +1816,18 @@ void CGenerator::setSymbolDataToSide(const Symbol *symbolType, const setgetDirection()) { case param_direction_t::kOutDirection: - case param_direction_t::kInoutDirection: { + case param_direction_t::kInoutDirection: + { direction = direction_t::kInOut; break; } - case param_direction_t::kInDirection: { + case param_direction_t::kInDirection: + { direction = direction_t::kIn; break; } - default: { + default: + { throw internal_error("Unsupported direction type of structure member."); } } @@ -1828,15 +1840,18 @@ void CGenerator::setSymbolDataToSide(const Symbol *symbolType, const setgetBuiltinType()) { - case BuiltinType::builtin_type_t::kBoolType: { + case BuiltinType::builtin_type_t::kBoolType: + { return "false"; } - case BuiltinType::builtin_type_t::kUInt8Type: { + case BuiltinType::builtin_type_t::kUInt8Type: + { return "0xFFU"; } - case BuiltinType::builtin_type_t::kUInt16Type: { + case BuiltinType::builtin_type_t::kUInt16Type: + { return "0xFFFFU"; } - case BuiltinType::builtin_type_t::kUInt32Type: { + case BuiltinType::builtin_type_t::kUInt32Type: + { return "0xFFFFFFFFU"; } - case BuiltinType::builtin_type_t::kUInt64Type: { + case BuiltinType::builtin_type_t::kUInt64Type: + { return "0xFFFFFFFFFFFFFFFFU"; } - default: { + default: + { return "-1"; } } @@ -2184,7 +2205,8 @@ string CGenerator::getTypenameName(DataType *t, const string &name) string returnName; switch (t->getDataType()) { - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { // Array type requires the array element count to come after the variable/member name. returnName = name; ArrayType *a = dynamic_cast(t); @@ -2194,7 +2216,8 @@ string CGenerator::getTypenameName(DataType *t, const string &name) returnName = getTypenameName(a->getElementType(), returnName); break; } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { assert(nullptr != dynamic_cast(t)); returnName = getBuiltinTypename(dynamic_cast(t)); if (!(t->isString() && name != "" && name[0] == '*')) @@ -2204,14 +2227,16 @@ string CGenerator::getTypenameName(DataType *t, const string &name) returnName += name; break; } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { const ListType *a = dynamic_cast(t); assert(a); returnName = "* " + name; returnName = getTypenameName(a->getElementType(), returnName); break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *unionType = dynamic_cast(t); assert(unionType); if (unionType->isNonEncapsulatedUnion()) @@ -2227,7 +2252,8 @@ string CGenerator::getTypenameName(DataType *t, const string &name) } break; } - case DataType::data_type_t::kVoidType: { + case DataType::data_type_t::kVoidType: + { returnName = "void"; returnName += returnSpaceWhenNotEmpty(name) + name; break; @@ -2235,7 +2261,8 @@ string CGenerator::getTypenameName(DataType *t, const string &name) case DataType::data_type_t::kAliasType: case DataType::data_type_t::kEnumType: case DataType::data_type_t::kFunctionType: - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { returnName = getOutputName(t); returnName += returnSpaceWhenNotEmpty(name) + name; break; @@ -2453,13 +2480,15 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT switch (t->getDataType()) { - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { AliasType *aliasType = dynamic_cast(t); assert(aliasType); return getEncodeDecodeCall(name, group, aliasType->getElementType(), structType, inDataContainer, structMember, needTempVariableI32, isFunctionParam); } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { static uint8_t arrayCounter; ArrayType *arrayType = dynamic_cast(t); assert(arrayType); @@ -2492,12 +2521,14 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT --arrayCounter; break; } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { getEncodeDecodeBuiltin(group, dynamic_cast(t), templateData, structType, structMember, isFunctionParam); break; } - case DataType::data_type_t::kEnumType: { + case DataType::data_type_t::kEnumType: + { needTempVariableI32 = true; templateData["decode"] = m_templateData["decodeEnumType"]; templateData["encode"] = m_templateData["encodeEnumType"]; @@ -2512,7 +2543,8 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT } break; } - case DataType::data_type_t::kFunctionType: { + case DataType::data_type_t::kFunctionType: + { FunctionType *funType = dynamic_cast(t); assert(funType); const FunctionType::c_function_list_t &callbacks = funType->getCallbackFuns(); @@ -2539,7 +2571,8 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT templateData["decode"] = m_templateData["decodeFunctionType"]; break; } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { ListType *listType = dynamic_cast(t); assert(listType); DataType *elementType = listType->getElementType(); @@ -2684,7 +2717,8 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT structMember, needTempVariableI32, isFunctionParam); break; } - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { // needDealloc(templateData, t, structType, structMember); string typeName = getOutputName(t); if (typeName != "") @@ -2704,7 +2738,8 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT } break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *unionType = dynamic_cast(t); assert(unionType); @@ -2821,7 +2856,8 @@ data_map CGenerator::getEncodeDecodeCall(const string &name, Group *group, DataT } break; } - default: { + default: + { throw internal_error("unknown member type"); } } @@ -2958,27 +2994,32 @@ bool CGenerator::isNeedCallFree(DataType *dataType) DataType *trueDataType = dataType->getTrueDataType(); switch (trueDataType->getDataType()) { - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { ArrayType *arrayType = dynamic_cast(trueDataType); assert(arrayType); return isNeedCallFree(arrayType->getElementType()); } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { BuiltinType *builtinType = dynamic_cast(trueDataType); assert(builtinType); return builtinType->isString() || builtinType->isBinary(); } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { return true; } - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *structType = dynamic_cast(trueDataType); assert(structType); set loopDetection; return structType->containListMember() || structType->containStringMember() || containsByrefParamToFree(structType, loopDetection); } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *unionType = dynamic_cast(trueDataType); assert(unionType); for (auto unionCase : unionType->getCases()) @@ -3112,12 +3153,14 @@ bool CGenerator::containsString(DataType *dataType) DataType *trueDataType = dataType->getTrueContainerDataType(); switch (trueDataType->getDataType()) { - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *s = dynamic_cast(trueDataType); assert(s); return s->containStringMember(); } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *u = dynamic_cast(trueDataType); assert(u); for (UnionCase *unionCase : u->getUniqueCases()) @@ -3136,7 +3179,8 @@ bool CGenerator::containsString(DataType *dataType) } return false; } - default: { + default: + { if (trueDataType->isString()) { return true; @@ -3155,12 +3199,14 @@ bool CGenerator::containsList(DataType *dataType) DataType *trueDataType = dataType->getTrueContainerDataType(); switch (trueDataType->getDataType()) { - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *s = dynamic_cast(trueDataType); assert(s); return s->containListMember(); } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *u = dynamic_cast(trueDataType); assert(u); for (UnionCase *unionCase : u->getUniqueCases()) @@ -3179,7 +3225,8 @@ bool CGenerator::containsList(DataType *dataType) } return false; } - default: { + default: + { return false; } } diff --git a/erpcgen/src/CGenerator.hpp b/erpcgen/src/CGenerator.hpp index e6a9949f..590ab508 100644 --- a/erpcgen/src/CGenerator.hpp +++ b/erpcgen/src/CGenerator.hpp @@ -62,11 +62,11 @@ class CGenerator : public Generator cpptempl::data_list m_symbolsTemplate; /*!< List of all symbol templates */ std::vector - m_listBinaryTypes; /*!< - * Contains binary types transformed to list. - * More ListType are present when @length annotation is used for binary type. - * If binary without @length is used then it is placed on first place in this vector. - */ + m_listBinaryTypes; /*!< + * Contains binary types transformed to list. + * More ListType are present when @length annotation is used for binary type. + * If binary without @length is used then it is placed on first place in this vector. + */ std::vector m_structListTypes; /*!< * Contains list types transformed to struct{list<>}. diff --git a/erpcgen/src/ErpcLexer.cpp b/erpcgen/src/ErpcLexer.cpp index 79f0f02c..d3763b86 100644 --- a/erpcgen/src/ErpcLexer.cpp +++ b/erpcgen/src/ErpcLexer.cpp @@ -33,11 +33,7 @@ using namespace std; // Code //////////////////////////////////////////////////////////////////////////////// -ErpcLexer::ErpcLexer(const char *inputFile) -: m_value(nullptr) -, m_indents(0) -, m_currentFileInfo(NULL) -, m_idlCrc16(0) +ErpcLexer::ErpcLexer(const char *inputFile) : m_value(nullptr), m_indents(0), m_currentFileInfo(NULL), m_idlCrc16(0) { m_currentFileInfo = openFile(inputFile); yyrestart(m_currentFileInfo->m_savedFile.get()); // instead of yyFlexLexer(idlFile); @@ -79,14 +75,16 @@ int ErpcLexer::processStringEscapes(const char *in, char *out) { switch (*in) { - case '\\': { + case '\\': + { // start of an escape sequence char c = *++in; switch (c) { case 0: // end of the string, bail break; - case 'x': { + case 'x': + { // start of a hex char escape sequence // read high and low nibbles, checking for end of string diff --git a/erpcgen/src/ErpcLexer.hpp b/erpcgen/src/ErpcLexer.hpp index 42c0358f..e0f0a28a 100644 --- a/erpcgen/src/ErpcLexer.hpp +++ b/erpcgen/src/ErpcLexer.hpp @@ -60,13 +60,9 @@ class CurrentFileInfo * @param[in] fileName Name of analyzed file. * @param[in] currentFolderPath Path to folder of current file. */ - CurrentFileInfo(std::ifstream *savedFile, const std::string &fileName, const std::string ¤tFolderPath) - : m_savedFile(savedFile) - , m_previous(NULL) - , m_line(1) - , m_column(0) - , m_fileName(fileName) - , m_currentFolderPath(currentFolderPath) + CurrentFileInfo(std::ifstream *savedFile, const std::string &fileName, const std::string ¤tFolderPath) : + m_savedFile(savedFile), m_previous(NULL), m_line(1), m_column(0), m_fileName(fileName), + m_currentFolderPath(currentFolderPath) { } diff --git a/erpcgen/src/Generator.cpp b/erpcgen/src/Generator.cpp index 8530b4ed..8555c16a 100644 --- a/erpcgen/src/Generator.cpp +++ b/erpcgen/src/Generator.cpp @@ -30,11 +30,8 @@ using namespace std; // Code //////////////////////////////////////////////////////////////////////////////// -Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) -: m_idlCrc16(def->getIdlCrc16()) -, m_def(def) -, m_globals(&(def->getGlobals())) -, m_generatorType(generatorType) +Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) : +m_idlCrc16(def->getIdlCrc16()), m_def(def), m_globals(&(def->getGlobals())), m_generatorType(generatorType) { string scopeName = "erpcShim"; string scopeNameC; @@ -164,12 +161,14 @@ Generator::Generator(InterfaceDefinition *def, generator_type_t generatorType) // set codec information switch (m_def->getCodecType()) { - case InterfaceDefinition::codec_t::kBasicCodec: { + case InterfaceDefinition::codec_t::kBasicCodec: + { m_templateData["codecClass"] = "BasicCodec"; m_templateData["codecHeader"] = "erpc_basic_codec.hpp"; break; } - default: { + default: + { m_templateData["codecClass"] = "Codec"; m_templateData["codecHeader"] = "erpc_codec.hpp"; break; @@ -319,7 +318,8 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat switch (dataType->getDataType()) { - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { AliasType *aliasType = dynamic_cast(dataType); if (aliasType != nullptr) { @@ -327,7 +327,8 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { ArrayType *arrayType = dynamic_cast(dataType); if (arrayType != nullptr) { @@ -335,7 +336,8 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { ListType *listType = dynamic_cast(dataType); if (listType != nullptr) { @@ -343,7 +345,8 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *structType = dynamic_cast(dataType); if (structType != nullptr) { @@ -354,7 +357,8 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { // Keil need extra pragma option when unions are used. m_templateData["usedUnionType"] = true; UnionType *unionType = dynamic_cast(dataType); @@ -367,7 +371,8 @@ DataType *Generator::findChildDataType(set &dataTypes, DataType *dat } break; } - default: { + default: + { break; } } diff --git a/erpcgen/src/InterfaceDefinition.cpp b/erpcgen/src/InterfaceDefinition.cpp index 88b74c13..3f47e58e 100644 --- a/erpcgen/src/InterfaceDefinition.cpp +++ b/erpcgen/src/InterfaceDefinition.cpp @@ -27,14 +27,9 @@ using namespace std; // Code //////////////////////////////////////////////////////////////////////////////// -InterfaceDefinition::InterfaceDefinition() -: m_ast(nullptr) -, m_globals() -, m_program(nullptr) -, m_programName("") -, m_outputFilename("") -, m_codec(codec_t::kNotSpecified) -, m_idlCrc16(0) +InterfaceDefinition::InterfaceDefinition() : +m_ast(nullptr), m_globals(), m_program(nullptr), m_programName(""), m_outputFilename(""), +m_codec(codec_t::kNotSpecified), m_idlCrc16(0) { init(); } diff --git a/erpcgen/src/Logging.hpp b/erpcgen/src/Logging.hpp index 244d5f94..9369f352 100644 --- a/erpcgen/src/Logging.hpp +++ b/erpcgen/src/Logging.hpp @@ -62,11 +62,7 @@ class Logger public: //! \brief Default constructor. - Logger() - : m_filter(log_level_t::kInfo) - , m_level(log_level_t::kInfo) - { - } + Logger() : m_filter(log_level_t::kInfo), m_level(log_level_t::kInfo) {} //! \brief Destructor. virtual ~Logger() {} @@ -197,9 +193,8 @@ class Log //! //! Saves the current logging output level of the global logger, //! as managed by the Log class, and sets the new level to \a level. - explicit SetOutputLevel(Logger::log_level_t level) - : m_logger(Log::getLogger()) - , m_saved(Logger::log_level_t::kInfo) + explicit SetOutputLevel(Logger::log_level_t level) : + m_logger(Log::getLogger()), m_saved(Logger::log_level_t::kInfo) { assert(m_logger); m_saved = m_logger->getOutputLevel(); @@ -210,9 +205,7 @@ class Log //! //! Saves the current logging output level of \a logger and sets //! the new level to \a level. - SetOutputLevel(Logger *logger, Logger::log_level_t level) - : m_logger(logger) - , m_saved(logger->getOutputLevel()) + SetOutputLevel(Logger *logger, Logger::log_level_t level) : m_logger(logger), m_saved(logger->getOutputLevel()) { assert(m_logger); m_logger->setOutputLevel(level); @@ -236,8 +229,7 @@ class StdoutLogger : public Logger { public: //! \brief Default constructor. - explicit StdoutLogger(Logger::log_level_t stderrLevel = Logger::log_level_t::kWarning) - : m_stderrLevel(stderrLevel) + explicit StdoutLogger(Logger::log_level_t stderrLevel = Logger::log_level_t::kWarning) : m_stderrLevel(stderrLevel) { } diff --git a/erpcgen/src/ParseErrors.hpp b/erpcgen/src/ParseErrors.hpp index 07a26635..b89a250d 100644 --- a/erpcgen/src/ParseErrors.hpp +++ b/erpcgen/src/ParseErrors.hpp @@ -39,11 +39,7 @@ class erpc_error : public std::runtime_error * * @param[in] __arg Exception error message. */ - explicit erpc_error(const std::string &__arg) - : std::runtime_error(__arg) - , m_message(__arg) - { - } + explicit erpc_error(const std::string &__arg) : std::runtime_error(__arg), m_message(__arg) {} protected: std::string m_message; /*!< Error message. */ @@ -55,10 +51,8 @@ class erpc_error : public std::runtime_error * @param[in] __arg Exception error message. * @param[in] errorName Exception error name. */ - explicit erpc_error(const std::string &__arg, const std::string &errorName) - : std::runtime_error(__arg) - , m_message(__arg) - , m_errName(errorName) + explicit erpc_error(const std::string &__arg, const std::string &errorName) : + std::runtime_error(__arg), m_message(__arg), m_errName(errorName) { } }; @@ -74,10 +68,7 @@ class syntax_error : public erpc_error * * @param[in] __arg Exception error message. */ - explicit syntax_error(const std::string &__arg) - : erpc_error(__arg) - { - } + explicit syntax_error(const std::string &__arg) : erpc_error(__arg) {} }; /*! @@ -93,11 +84,10 @@ class syntax_error2 : public erpc_error * @param[in] loc Location of token. * @param[in] fileName File name where error occurred. */ - explicit syntax_error2(const std::string &__arg, token_loc_t loc, std::string &fileName) - : erpc_error(__arg, "syntax error") - , m_errLoc(loc) - , m_what(format_string("file %s:%d:%d: %s, %s", fileName.c_str(), m_errLoc.m_firstLine, m_errLoc.m_firstChar, - m_errName.c_str(), m_message.c_str())) + explicit syntax_error2(const std::string &__arg, token_loc_t loc, std::string &fileName) : + erpc_error(__arg, "syntax error"), m_errLoc(loc), + m_what(format_string("file %s:%d:%d: %s, %s", fileName.c_str(), m_errLoc.m_firstLine, m_errLoc.m_firstChar, + m_errName.c_str(), m_message.c_str())) { } @@ -108,11 +98,10 @@ class syntax_error2 : public erpc_error * @param[in] loc Location of token for which error occurred. * @param[in] fileName File name where error occurred. */ - explicit syntax_error2(const char *__arg, token_loc_t loc, std::string &fileName) - : erpc_error(std::string(__arg), "syntax error") - , m_errLoc(loc) - , m_what(format_string("file %s:%d:%d: %s, %s", fileName.c_str(), m_errLoc.m_firstLine, m_errLoc.m_firstChar, - m_errName.c_str(), m_message.c_str())) + explicit syntax_error2(const char *__arg, token_loc_t loc, std::string &fileName) : + erpc_error(std::string(__arg), "syntax error"), m_errLoc(loc), + m_what(format_string("file %s:%d:%d: %s, %s", fileName.c_str(), m_errLoc.m_firstLine, m_errLoc.m_firstChar, + m_errName.c_str(), m_message.c_str())) { } @@ -139,10 +128,7 @@ class lexical_error : public erpc_error * * @param[in] __arg Exception error message. */ - explicit lexical_error(const std::string &__arg) - : erpc_error(__arg) - { - } + explicit lexical_error(const std::string &__arg) : erpc_error(__arg) {} }; /*! @@ -156,10 +142,7 @@ class semantic_error : public erpc_error * * @param[in] __arg Exception error message. */ - explicit semantic_error(const std::string &__arg) - : erpc_error(__arg) - { - } + explicit semantic_error(const std::string &__arg) : erpc_error(__arg) {} }; /*! @@ -173,10 +156,7 @@ class internal_error : public erpc_error * * @param[in] __arg Exception error message. */ - explicit internal_error(const std::string &__arg) - : erpc_error(__arg) - { - } + explicit internal_error(const std::string &__arg) : erpc_error(__arg) {} }; /*! diff --git a/erpcgen/src/PythonGenerator.cpp b/erpcgen/src/PythonGenerator.cpp index e56dc373..3c1f581f 100644 --- a/erpcgen/src/PythonGenerator.cpp +++ b/erpcgen/src/PythonGenerator.cpp @@ -37,10 +37,8 @@ extern const char *const kPyGlobalInit; // Code //////////////////////////////////////////////////////////////////////////////// -PythonGenerator::PythonGenerator(InterfaceDefinition *def) -: Generator(def, generator_type_t::kPython) -, m_suffixStrip("") -, m_suffixStripSize(0) +PythonGenerator::PythonGenerator(InterfaceDefinition *def) : +Generator(def, generator_type_t::kPython), m_suffixStrip(""), m_suffixStripSize(0) { /* Set copyright rules. */ if (m_def->hasProgramSymbol()) @@ -437,7 +435,8 @@ data_map PythonGenerator::makeGroupSymbolsTemplateData(Group *group) switch (dataType->getDataType()) { - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *structType = dynamic_cast(symbol); if (structType == nullptr) { @@ -461,7 +460,8 @@ data_map PythonGenerator::makeGroupSymbolsTemplateData(Group *group) } break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *unionType = dynamic_cast(symbol); if (unionType == nullptr) { @@ -491,7 +491,8 @@ data_map PythonGenerator::makeGroupSymbolsTemplateData(Group *group) } break; } - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { AliasType *aliasType = dynamic_cast(symbol); if (aliasType == nullptr) break; @@ -588,11 +589,13 @@ data_map PythonGenerator::getTypeInfo(DataType *t) info["isNonEncapsulatedUnion"] = false; switch (t->getDataType()) { - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { info = getTypeInfo(t->getTrueDataType()); break; } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { // Array type requires the array element count to come after the variable/member name. ArrayType *a = dynamic_cast(t); assert(a); @@ -601,16 +604,19 @@ data_map PythonGenerator::getTypeInfo(DataType *t) info["elementType"] = getTypeInfo(a->getElementType()); break; } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { assert(dynamic_cast(t)); info["type"] = getBuiltinTypename(dynamic_cast(t)); break; } - case DataType::data_type_t::kEnumType: { + case DataType::data_type_t::kEnumType: + { info["type"] = "enum"; break; } - case DataType::data_type_t::kFunctionType: { + case DataType::data_type_t::kFunctionType: + { info["type"] = "function"; FunctionType *funType = dynamic_cast(t); assert(funType); @@ -632,18 +638,21 @@ data_map PythonGenerator::getTypeInfo(DataType *t) } break; } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { const ListType *a = dynamic_cast(t); assert(a); info["type"] = "list"; info["elementType"] = getTypeInfo(a->getElementType()); break; } - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { info["type"] = "struct"; break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *unionType = dynamic_cast(t); assert(unionType); info["type"] = "union"; @@ -762,7 +771,8 @@ data_map PythonGenerator::getTypeInfo(DataType *t) info["cases"] = unionCases; break; } - case DataType::data_type_t::kVoidType: { + case DataType::data_type_t::kVoidType: + { info["type"] = "void"; break; } diff --git a/erpcgen/src/SymbolScanner.cpp b/erpcgen/src/SymbolScanner.cpp index 21c6c2ec..97ec47ab 100644 --- a/erpcgen/src/SymbolScanner.cpp +++ b/erpcgen/src/SymbolScanner.cpp @@ -1446,11 +1446,13 @@ DataType *SymbolScanner::lookupDataType(const AstNode *typeNode) const Token &typeToken = typeNode->getToken(); switch (typeToken.getToken()) { - case TOK_ARRAY: { + case TOK_ARRAY: + { return createArrayType(typeNode); } - case TOK_IDENT: { + case TOK_IDENT: + { DataType *dataType = nullptr; if (m_currentInterface != nullptr) { @@ -1462,10 +1464,12 @@ DataType *SymbolScanner::lookupDataType(const AstNode *typeNode) } return dataType; } - case TOK_LIST: { + case TOK_LIST: + { return createListType(typeNode); } - case TOK_UNION: { + case TOK_UNION: + { assert(nullptr != m_currentStruct); return lookupDataTypeByName(typeNode->getChild(3)->getToken(), &(m_currentStruct->getScope()), false); } diff --git a/erpcgen/src/SymbolScanner.hpp b/erpcgen/src/SymbolScanner.hpp index 5b72e808..da70bc39 100644 --- a/erpcgen/src/SymbolScanner.hpp +++ b/erpcgen/src/SymbolScanner.hpp @@ -39,14 +39,9 @@ class SymbolScanner : public AstWalker * * @param[in] globals Global symbol scope variable. */ - explicit SymbolScanner(SymbolScope *globals) - : m_globals(globals) - , m_currentInterface(nullptr) - , m_currentStruct(nullptr) - , m_currentProgram(nullptr) - , m_currentEnum(nullptr) - , m_currentAlias(nullptr) - , m_currentUnion(nullptr) + explicit SymbolScanner(SymbolScope *globals) : + m_globals(globals), m_currentInterface(nullptr), m_currentStruct(nullptr), m_currentProgram(nullptr), + m_currentEnum(nullptr), m_currentAlias(nullptr), m_currentUnion(nullptr) { } @@ -58,15 +53,9 @@ class SymbolScanner : public AstWalker * @param[in] globals Global symbol scope variable. * @param[in] fileName name of IDL from which AST was built. */ - SymbolScanner(SymbolScope *globals, const std::string &fileName) - : AstWalker(fileName) - , m_globals(globals) - , m_currentInterface(nullptr) - , m_currentStruct(nullptr) - , m_currentProgram(nullptr) - , m_currentEnum(nullptr) - , m_currentAlias(nullptr) - , m_currentUnion(nullptr) + SymbolScanner(SymbolScope *globals, const std::string &fileName) : + AstWalker(fileName), m_globals(globals), m_currentInterface(nullptr), m_currentStruct(nullptr), + m_currentProgram(nullptr), m_currentEnum(nullptr), m_currentAlias(nullptr), m_currentUnion(nullptr) { } diff --git a/erpcgen/src/Token.cpp b/erpcgen/src/Token.cpp index 66becef8..634f5269 100644 --- a/erpcgen/src/Token.cpp +++ b/erpcgen/src/Token.cpp @@ -19,10 +19,7 @@ using namespace std; // Code //////////////////////////////////////////////////////////////////////////////// -Token::Token(const Token &other) -: m_token(other.m_token) -, m_value() -, m_location(other.m_location) +Token::Token(const Token &other) : m_token(other.m_token), m_value(), m_location(other.m_location) { if (other.m_value) { diff --git a/erpcgen/src/Token.hpp b/erpcgen/src/Token.hpp index 04b8be69..c1544c05 100644 --- a/erpcgen/src/Token.hpp +++ b/erpcgen/src/Token.hpp @@ -29,13 +29,7 @@ struct token_loc_t int m_lastLine; /*!< Ending line of the token. */ int m_lastChar; /*!< Ending character position on ending line. */ - token_loc_t() - : m_firstLine(0) - , m_firstChar(0) - , m_lastLine(0) - , m_lastChar(0) - { - } + token_loc_t() : m_firstLine(0), m_firstChar(0), m_lastLine(0), m_lastChar(0) {} /*! * @brief Default copy constructor. @@ -71,12 +65,7 @@ class Token * @see Token::Token(int token, Value * value, const token_loc_t & loc) * @see Token::Token(const Token & other) */ - explicit Token(int token) - : m_token(token) - , m_value() - , m_location() - { - } + explicit Token(int token) : m_token(token), m_value(), m_location() {} /*! * @brief Constructor. @@ -91,12 +80,7 @@ class Token * @see Token::Token(int token, Value * value, const token_loc_t & loc) * @see Token::Token(const Token & other) */ - Token(int token, Value *value) - : m_token(token) - , m_value(value) - , m_location() - { - } + Token(int token, Value *value) : m_token(token), m_value(value), m_location() {} /*! * @brief Constructor. @@ -112,12 +96,7 @@ class Token * @see Token::Token(int token, Value * value) * @see Token::Token(const Token & other) */ - Token(int token, Value *value, const token_loc_t &loc) - : m_token(token) - , m_value(value) - , m_location(loc) - { - } + Token(int token, Value *value, const token_loc_t &loc) : m_token(token), m_value(value), m_location(loc) {} /*! * @brief This function is copy constructor. diff --git a/erpcgen/src/Value.hpp b/erpcgen/src/Value.hpp index 7ac88972..65e1f41f 100644 --- a/erpcgen/src/Value.hpp +++ b/erpcgen/src/Value.hpp @@ -32,10 +32,7 @@ class Value * * @param[in] theType Value type. */ - Value(value_type_t theType) - : m_type(theType) - { - } + Value(value_type_t theType) : m_type(theType) {} /*! * @brief Destructor. @@ -99,22 +96,15 @@ class IntegerValue : public Value /*! * @brief Constructor. */ - explicit IntegerValue(int_type_t type = kSigned) - : Value(kIntegerValue) - , m_value(0) - , m_intType(type) - { - } + explicit IntegerValue(int_type_t type = kSigned) : Value(kIntegerValue), m_value(0), m_intType(type) {} /*! * @brief Constructor. * * @param[in] value IntegerValue value. */ - explicit IntegerValue(uint64_t value, int_type_t type = kSigned) - : Value(kIntegerValue) - , m_value(value) - , m_intType(type) + explicit IntegerValue(uint64_t value, int_type_t type = kSigned) : + Value(kIntegerValue), m_value(value), m_intType(type) { } @@ -123,10 +113,7 @@ class IntegerValue : public Value * * @param[in] other IntegerValue to copy. */ - IntegerValue(const IntegerValue &other) - : Value(other.getType()) - , m_value(other.m_value) - , m_intType(other.m_intType) + IntegerValue(const IntegerValue &other) : Value(other.getType()), m_value(other.m_value), m_intType(other.m_intType) { } @@ -219,44 +206,28 @@ class FloatValue : public Value /*! * @brief Constructor. */ - FloatValue() - : Value(kFloatValue) - , m_value(0.0) - { - } + FloatValue() : Value(kFloatValue), m_value(0.0) {} /*! * @brief Constructor. * * @param[in] value FloatValue value. */ - explicit FloatValue(double value) - : Value(kFloatValue) - , m_value(value) - { - } + explicit FloatValue(double value) : Value(kFloatValue), m_value(value) {} /*! * @brief Constructor. * * @param[in] value FloatValue value. */ - explicit FloatValue(float value) - : Value(kFloatValue) - , m_value(value) - { - } + explicit FloatValue(float value) : Value(kFloatValue), m_value(value) {} /*! * @brief Copy constructor. * * @param[in] other FloatValue to copy. */ - explicit FloatValue(const FloatValue &other) - : Value(kFloatValue) - , m_value(other.m_value) - { - } + explicit FloatValue(const FloatValue &other) : Value(kFloatValue), m_value(other.m_value) {} /*! * @brief Assign operator. @@ -361,44 +332,28 @@ class StringValue : public Value /*! * @brief Constructor. */ - StringValue() - : Value(kStringValue) - , m_value() - { - } + StringValue() : Value(kStringValue), m_value() {} /*! * @brief Constructor. * * @param[in] value StringValue value. */ - explicit StringValue(const std::string &value) - : Value(kStringValue) - , m_value(value) - { - } + explicit StringValue(const std::string &value) : Value(kStringValue), m_value(value) {} /*! * @brief Constructor. * * @param[in] value StringValue value. */ - explicit StringValue(const std::string *value) - : Value(kStringValue) - , m_value(*value) - { - } + explicit StringValue(const std::string *value) : Value(kStringValue), m_value(*value) {} /*! * @brief Copy constructor. * * @param[in] other StringValue to copy. */ - StringValue(const StringValue &other) - : Value(kStringValue) - , m_value(other.m_value) - { - } + StringValue(const StringValue &other) : Value(kStringValue), m_value(other.m_value) {} /*! * @brief Get StringValue type name. diff --git a/erpcgen/src/erpcgen.cpp b/erpcgen/src/erpcgen.cpp index 056a8ec6..2eaf96a9 100644 --- a/erpcgen/src/erpcgen.cpp +++ b/erpcgen/src/erpcgen.cpp @@ -98,19 +98,19 @@ class erpcgenTool { kCLanguage, kPythonLanguage, - }; /*!< Generated outputs format. */ + }; /*!< Generated outputs format. */ typedef vector string_vector_t; /*!< Vector of positional arguments. */ - int m_argc; /*!< Number of command line arguments. */ - char **m_argv; /*!< String value for each command line argument. */ - StdoutLogger *m_logger; /*!< Singleton logger instance. */ - verbose_type_t m_verboseType; /*!< Which type of log is need to set (warning, info, debug). */ - const char *m_outputFilePath; /*!< Path to the output file. */ - const char *m_ErpcFile; /*!< ERPC file. */ - string_vector_t m_positionalArgs; /*!< Positional arguments. */ - languages_t m_outputLanguage; /*!< Output language we're generating. */ - InterfaceDefinition::codec_t m_codec; /*!< Used codec type. */ + int m_argc; /*!< Number of command line arguments. */ + char **m_argv; /*!< String value for each command line argument. */ + StdoutLogger *m_logger; /*!< Singleton logger instance. */ + verbose_type_t m_verboseType; /*!< Which type of log is need to set (warning, info, debug). */ + const char *m_outputFilePath; /*!< Path to the output file. */ + const char *m_ErpcFile; /*!< ERPC file. */ + string_vector_t m_positionalArgs; /*!< Positional arguments. */ + languages_t m_outputLanguage; /*!< Output language we're generating. */ + InterfaceDefinition::codec_t m_codec; /*!< Used codec type. */ public: /*! @@ -121,15 +121,9 @@ class erpcgenTool * * Creates the singleton logger instance. */ - erpcgenTool(int argc, char *argv[]) - : m_argc(argc) - , m_argv(argv) - , m_logger(0) - , m_verboseType(verbose_type_t::kWarning) - , m_outputFilePath(NULL) - , m_ErpcFile(NULL) - , m_outputLanguage(languages_t::kCLanguage) - , m_codec(InterfaceDefinition::codec_t::kNotSpecified) + erpcgenTool(int argc, char *argv[]) : + m_argc(argc), m_argv(argv), m_logger(0), m_verboseType(verbose_type_t::kWarning), m_outputFilePath(NULL), + m_ErpcFile(NULL), m_outputLanguage(languages_t::kCLanguage), m_codec(InterfaceDefinition::codec_t::kNotSpecified) { // create logger instance m_logger = new StdoutLogger(); @@ -193,7 +187,8 @@ class erpcgenTool PathSearcher::getGlobalSearcher().addSearchPath(optarg); break; - case 'g': { + case 'g': + { string lang = optarg; if (lang == "c") { @@ -211,7 +206,8 @@ class erpcgenTool break; } - case 'c': { + case 'c': + { string codec = optarg; if (codec.compare("basic") == 0) { diff --git a/erpcgen/src/options.cpp b/erpcgen/src/options.cpp index 5edea150..db954fbe 100644 --- a/erpcgen/src/options.cpp +++ b/erpcgen/src/options.cpp @@ -74,10 +74,7 @@ static const char endl = '\n'; class ostream { public: - ostream(FILE *fileptr) - : fp(fileptr) - { - } + ostream(FILE *fileptr) : fp(fileptr) {} ostream &operator<<(char ch); @@ -159,12 +156,8 @@ void OptArgvIter::rewind(void) static const char WHITESPACE[] = " \t\n\r\v\f"; const char *OptStrTokIter::default_delims = WHITESPACE; -OptStrTokIter::OptStrTokIter(const char *tokens, const char *arg_delimiters) -: len(unsigned(strlen(tokens))) -, str(tokens) -, seps(arg_delimiters) -, cur(NULLSTR) -, tokstr(NULLSTR) +OptStrTokIter::OptStrTokIter(const char *tokens, const char *arg_delimiters) : +len(unsigned(strlen(tokens))), str(tokens), seps(arg_delimiters), cur(NULLSTR), tokstr(NULLSTR) { if (seps == NULL) seps = default_delims; @@ -220,9 +213,7 @@ enum const unsigned OptIstreamIter::MAX_LINE_LEN = 1024; // Constructor -OptIstreamIter::OptIstreamIter(istream &input) -: is(input) -, tok_iter(NULL) +OptIstreamIter::OptIstreamIter(istream &input) : is(input), tok_iter(NULL) { #ifdef USE_STDIO fprintf(stderr, "%s: Can't use OptIstreamIter class:\n", "OptIstreamIter::OptIstreamIter"); @@ -408,20 +399,14 @@ static kwdmatch_t kwdmatch(const char *src, const char *attempt, int len = 0) class OptionSpec { public: - OptionSpec(const char *decl = NULLSTR) - : hidden(0) - , spec(decl) + OptionSpec(const char *decl = NULLSTR) : hidden(0), spec(decl) { if (spec == NULL) spec = NULL_spec; CheckHidden(); } - OptionSpec(const OptionSpec &cp) - : hidden(cp.hidden) - , spec(cp.spec) - { - } + OptionSpec(const OptionSpec &cp) : hidden(cp.hidden), spec(cp.spec) {} // NOTE: use default destructor! @@ -645,13 +630,9 @@ unsigned OptionSpec::Format(char *buf, unsigned optctrls) const #define DIR_SEP_CHAR '/' #endif -Options::Options(const char *arg_name, const char *const optv[]) -: explicit_end(0) -, optctrls(static_cast(OptCtrl::DEFAULT)) -, optvec(optv) -, nextchar(NULLSTR) -, listopt(NULLSTR) -, cmdname(arg_name) +Options::Options(const char *arg_name, const char *const optv[]) : +explicit_end(0), optctrls(static_cast(OptCtrl::DEFAULT)), optvec(optv), nextchar(NULLSTR), listopt(NULLSTR), +cmdname(arg_name) { const char *basename = ::strrchr(cmdname, DIR_SEP_CHAR); if (basename) diff --git a/erpcgen/src/options.hpp b/erpcgen/src/options.hpp index 0518c29f..9cb83111 100644 --- a/erpcgen/src/options.hpp +++ b/erpcgen/src/options.hpp @@ -102,19 +102,9 @@ class OptArgvIter : public OptIterRwd const char *const *av; // arg vector public: - explicit OptArgvIter(const char *const argv[]) - : ndx(0) - , ac(-1) - , av(argv) - { - } + explicit OptArgvIter(const char *const argv[]) : ndx(0), ac(-1), av(argv) {} - OptArgvIter(int argc, const char *const argv[]) - : ndx(0) - , ac(argc) - , av(argv) - { - } + OptArgvIter(int argc, const char *const argv[]) : ndx(0), ac(argc), av(argv) {} virtual ~OptArgvIter(void); diff --git a/erpcgen/src/smart_ptr.hpp b/erpcgen/src/smart_ptr.hpp index 23149e78..71918e9d 100644 --- a/erpcgen/src/smart_ptr.hpp +++ b/erpcgen/src/smart_ptr.hpp @@ -37,7 +37,7 @@ struct smart_ptr_delete_array * * This class only supports the single-owner paradigm. */ -template > +template > class smart_ptr { public: @@ -48,23 +48,13 @@ class smart_ptr typedef const T &const_ref_type; //! Default constructor. Initializes with no pointer set. - smart_ptr() - : _p(nullptr) - { - } + smart_ptr() : _p(nullptr) {} //! This constructor takes a pointer to the object to be deleted. - smart_ptr(ptr_type p) - : _p(p) - { - } + smart_ptr(ptr_type p) : _p(p) {} //! @brief Move copy constructor. - smart_ptr(smart_ptr &&other) - : _p(other._p) - { - other._p = nullptr; - } + smart_ptr(smart_ptr &&other) : _p(other._p) { other._p = nullptr; } //! @brief Move assignment operator. smart_ptr &operator=(smart_ptr &&other) @@ -159,10 +149,10 @@ class smart_ptr //! @brief Version of smart_ptr that uses delete []. template -using smart_array_ptr = smart_ptr >; +using smart_array_ptr = smart_ptr>; //! @brief Version of smart_ptr that uses free(). template -using smart_free_ptr = smart_ptr >; +using smart_free_ptr = smart_ptr>; #endif // _smart_ptr_h_ diff --git a/erpcgen/src/types/AliasType.hpp b/erpcgen/src/types/AliasType.hpp index b08cffbe..7c912772 100644 --- a/erpcgen/src/types/AliasType.hpp +++ b/erpcgen/src/types/AliasType.hpp @@ -34,9 +34,8 @@ class AliasType : public DataType * @param[in] name Name. * @param[in] elementType Given data type. */ - AliasType(const std::string &name, DataType *elementType) - : DataType(name, data_type_t::kAliasType) - , m_elementType(elementType) + AliasType(const std::string &name, DataType *elementType) : + DataType(name, data_type_t::kAliasType), m_elementType(elementType) { } @@ -48,9 +47,8 @@ class AliasType : public DataType * @param[in] tok Token, which contains name and location. * @param[in] elementType Given data type. */ - AliasType(const Token &tok, DataType *elementType) - : DataType(tok, data_type_t::kAliasType) - , m_elementType(elementType) + AliasType(const Token &tok, DataType *elementType) : + DataType(tok, data_type_t::kAliasType), m_elementType(elementType) { } diff --git a/erpcgen/src/types/Annotation.hpp b/erpcgen/src/types/Annotation.hpp index 6d83154e..969d0460 100644 --- a/erpcgen/src/types/Annotation.hpp +++ b/erpcgen/src/types/Annotation.hpp @@ -44,11 +44,8 @@ class Annotation * @param[in] val Pointer to value. * @param[in] lang Programming language for which is annotation intended. */ - Annotation(const Token &token, Value *val, program_lang_t lang) - : m_name(token.getStringValue()) - , m_value(val) - , m_location(token.getLocation()) - , m_lang(lang) + Annotation(const Token &token, Value *val, program_lang_t lang) : + m_name(token.getStringValue()), m_value(val), m_location(token.getLocation()), m_lang(lang) { } @@ -59,11 +56,8 @@ class Annotation * * @param[in] token Token contains annotation name and location in parsed file. */ - explicit Annotation(const Token &token) - : m_name(token.getStringValue()) - , m_value(nullptr) - , m_location(token.getLocation()) - , m_lang(program_lang_t::kAll) + explicit Annotation(const Token &token) : + m_name(token.getStringValue()), m_value(nullptr), m_location(token.getLocation()), m_lang(program_lang_t::kAll) { } @@ -74,11 +68,8 @@ class Annotation * * @param[in] a Source annotation. */ - explicit Annotation(const Annotation &a) - : m_name(a.m_name) - , m_value(a.m_value) - , m_location(a.m_location) - , m_lang(a.m_lang) + explicit Annotation(const Annotation &a) : + m_name(a.m_name), m_value(a.m_value), m_location(a.m_location), m_lang(a.m_lang) { } diff --git a/erpcgen/src/types/ArrayType.hpp b/erpcgen/src/types/ArrayType.hpp index 2db48edd..16a6014c 100644 --- a/erpcgen/src/types/ArrayType.hpp +++ b/erpcgen/src/types/ArrayType.hpp @@ -34,10 +34,8 @@ class ArrayType : public DataType * @param[in] elementType Given data type. * @param[in] elementCount Given count. */ - ArrayType(DataType *elementType, uint32_t elementCount) - : DataType("(array)", data_type_t::kArrayType) - , m_elementType(elementType) - , m_elementCount(elementCount) + ArrayType(DataType *elementType, uint32_t elementCount) : + DataType("(array)", data_type_t::kArrayType), m_elementType(elementType), m_elementCount(elementCount) { } diff --git a/erpcgen/src/types/BuiltinType.hpp b/erpcgen/src/types/BuiltinType.hpp index 0cdecad5..4cb45aa0 100644 --- a/erpcgen/src/types/BuiltinType.hpp +++ b/erpcgen/src/types/BuiltinType.hpp @@ -55,9 +55,8 @@ class BuiltinType : public DataType * @param[in] name Given name. * @param[in] builtinType Given builtin type. */ - BuiltinType(const std::string &name, builtin_type_t builtinType) - : DataType(name, data_type_t::kBuiltinType) - , m_builtinType(builtinType) + BuiltinType(const std::string &name, builtin_type_t builtinType) : + DataType(name, data_type_t::kBuiltinType), m_builtinType(builtinType) { } diff --git a/erpcgen/src/types/ConstType.hpp b/erpcgen/src/types/ConstType.hpp index 6a845231..4c523aaf 100644 --- a/erpcgen/src/types/ConstType.hpp +++ b/erpcgen/src/types/ConstType.hpp @@ -36,10 +36,8 @@ class ConstType : public Symbol * @param[in] dataType Given data type.. * @param[in] value Given value. */ - ConstType(const Token &tok, DataType *dataType, Value *value) - : Symbol(symbol_type_t::kConstSymbol, tok) - , m_dataType(dataType) - , m_value(value) + ConstType(const Token &tok, DataType *dataType, Value *value) : + Symbol(symbol_type_t::kConstSymbol, tok), m_dataType(dataType), m_value(value) { } diff --git a/erpcgen/src/types/DataType.hpp b/erpcgen/src/types/DataType.hpp index daed4c24..bc646fee 100644 --- a/erpcgen/src/types/DataType.hpp +++ b/erpcgen/src/types/DataType.hpp @@ -49,11 +49,7 @@ class DataType : public Symbol * * @param[in] dataType Given data type. */ - explicit DataType(data_type_t dataType) - : Symbol(symbol_type_t::kTypenameSymbol) - , m_dataType(dataType) - { - } + explicit DataType(data_type_t dataType) : Symbol(symbol_type_t::kTypenameSymbol), m_dataType(dataType) {} /*! * @brief Constructor. @@ -63,9 +59,8 @@ class DataType : public Symbol * @param[in] dataType Given data type. * @param[in] name Given name for symbol. */ - DataType(const std::string &name, data_type_t dataType) - : Symbol(symbol_type_t::kTypenameSymbol, name) - , m_dataType(dataType) + DataType(const std::string &name, data_type_t dataType) : + Symbol(symbol_type_t::kTypenameSymbol, name), m_dataType(dataType) { } /*! @@ -77,9 +72,7 @@ class DataType : public Symbol * @param[in] dataType Given data type. * @param[in] symbolType Given symbol type for symbol. */ - DataType(const Token &tok, data_type_t dataType) - : Symbol(symbol_type_t::kTypenameSymbol, tok) - , m_dataType(dataType) + DataType(const Token &tok, data_type_t dataType) : Symbol(symbol_type_t::kTypenameSymbol, tok), m_dataType(dataType) { } diff --git a/erpcgen/src/types/EnumMember.hpp b/erpcgen/src/types/EnumMember.hpp index f0562ca4..730f5e4d 100644 --- a/erpcgen/src/types/EnumMember.hpp +++ b/erpcgen/src/types/EnumMember.hpp @@ -34,10 +34,8 @@ class EnumMember : public Symbol * @param[in] tok Token, which contains name and location. * @param[in] value Given value. */ - EnumMember(const Token &tok, uint32_t value) - : Symbol(symbol_type_t::kEnumMemberSymbol, tok) - , m_value(value) - , m_valueSet(true) + EnumMember(const Token &tok, uint32_t value) : + Symbol(symbol_type_t::kEnumMemberSymbol, tok), m_value(value), m_valueSet(true) { } @@ -48,10 +46,8 @@ class EnumMember : public Symbol * * @param[in] tok Token, which contains name and location. */ - explicit EnumMember(const Token &tok) - : Symbol(symbol_type_t::kEnumMemberSymbol, tok) - , m_value(-1) - , m_valueSet(false) + explicit EnumMember(const Token &tok) : + Symbol(symbol_type_t::kEnumMemberSymbol, tok), m_value(-1), m_valueSet(false) { } diff --git a/erpcgen/src/types/EnumType.hpp b/erpcgen/src/types/EnumType.hpp index a28e3af5..2f35de26 100644 --- a/erpcgen/src/types/EnumType.hpp +++ b/erpcgen/src/types/EnumType.hpp @@ -37,20 +37,14 @@ class EnumType : public DataType * * @param[in] tok Given token. */ - explicit EnumType(const Token &tok) - : DataType(tok, data_type_t::kEnumType) - { - } + explicit EnumType(const Token &tok) : DataType(tok, data_type_t::kEnumType) {} /*! * @brief Constructor. * * This function set DataType with default name. */ - EnumType() - : DataType("", data_type_t::kEnumType) - { - } + EnumType() : DataType("", data_type_t::kEnumType) {} /*! * @brief This function will add enum member to the enum. diff --git a/erpcgen/src/types/Function.hpp b/erpcgen/src/types/Function.hpp index ad4a3e11..11fda0c7 100644 --- a/erpcgen/src/types/Function.hpp +++ b/erpcgen/src/types/Function.hpp @@ -34,11 +34,8 @@ class FunctionBase /*! * @brief Constructor. */ - FunctionBase(Interface *interface) - : m_parameters("(fn)") - , m_returnType(nullptr) - , m_isOneway(false) - , m_interface(interface) + FunctionBase(Interface *interface) : + m_parameters("(fn)"), m_returnType(nullptr), m_isOneway(false), m_interface(interface) { } @@ -134,11 +131,9 @@ class Function : public FunctionBase, public Symbol * @param[in] tok Given token. * @param[in] interface Parent interface. */ - Function(const Token &tok, Interface *interface) - : FunctionBase(interface) - , Symbol(symbol_type_t::kFunctionSymbol, tok) - , m_uniqueId(++s_idCounter) - , m_functionType(nullptr) + Function(const Token &tok, Interface *interface) : + FunctionBase(interface), Symbol(symbol_type_t::kFunctionSymbol, tok), m_uniqueId(++s_idCounter), + m_functionType(nullptr) { } @@ -151,11 +146,8 @@ class Function : public FunctionBase, public Symbol * @param[in] interface Parent interface. * @param[in] uniqueId Given unique function id. */ - Function(const Token &tok, Interface *interface, uint32_t uniqueId) - : FunctionBase(interface) - , Symbol(symbol_type_t::kFunctionSymbol, tok) - , m_uniqueId(uniqueId) - , m_functionType(nullptr) + Function(const Token &tok, Interface *interface, uint32_t uniqueId) : + FunctionBase(interface), Symbol(symbol_type_t::kFunctionSymbol, tok), m_uniqueId(uniqueId), m_functionType(nullptr) { s_idCounter = uniqueId; } @@ -208,7 +200,7 @@ class Function : public FunctionBase, public Symbol uint32_t m_uniqueId; /*!< Function unique id. */ FunctionType *m_functionType; /*!< Function type. */ - static uint32_t s_idCounter; /*!< Function id counter. Each function will increase this. */ + static uint32_t s_idCounter; /*!< Function id counter. Each function will increase this. */ }; } // namespace erpcgen diff --git a/erpcgen/src/types/FunctionType.hpp b/erpcgen/src/types/FunctionType.hpp index 2c944213..923cbac4 100644 --- a/erpcgen/src/types/FunctionType.hpp +++ b/erpcgen/src/types/FunctionType.hpp @@ -41,10 +41,8 @@ class FunctionType : public FunctionBase, public DataType * @param[in] tok Given token. * @param[in] m_interface Parent interface. */ - FunctionType(const Token &tok, Interface *interface) - : FunctionBase(interface) - , DataType(tok, data_type_t::kFunctionType) - , m_callbackFuns() + FunctionType(const Token &tok, Interface *interface) : + FunctionBase(interface), DataType(tok, data_type_t::kFunctionType), m_callbackFuns() { } diff --git a/erpcgen/src/types/Group.hpp b/erpcgen/src/types/Group.hpp index d2cf95a0..a9399d15 100644 --- a/erpcgen/src/types/Group.hpp +++ b/erpcgen/src/types/Group.hpp @@ -30,7 +30,7 @@ class Group public: typedef std::vector interface_list_t; /*!< Vector of interfaces belongs to group. */ typedef std::vector symbols_list_t; /*!< Vector of symbols belongs to group. */ - typedef std::map > + typedef std::map> symbol_directions_map_t; /*!< Map symbol with direction in which is used in current group. */ /*! @@ -38,11 +38,7 @@ class Group * * @param[in] name Group name. */ - explicit Group(const std::string &name) - : m_name(name) - { - m_template["name"] = name; - } + explicit Group(const std::string &name) : m_name(name) { m_template["name"] = name; } /*! * @brief This function returns the group name. diff --git a/erpcgen/src/types/Interface.hpp b/erpcgen/src/types/Interface.hpp index c4a82a83..0bbe61b0 100644 --- a/erpcgen/src/types/Interface.hpp +++ b/erpcgen/src/types/Interface.hpp @@ -39,10 +39,8 @@ class Interface : public Symbol * * @param[in] tok Given token. */ - explicit Interface(const Token &tok) - : Symbol(symbol_type_t::kInterfaceSymbol, tok) - , m_scope() - , m_uniqueId(s_idCounter++) + explicit Interface(const Token &tok) : + Symbol(symbol_type_t::kInterfaceSymbol, tok), m_scope(), m_uniqueId(s_idCounter++) { } @@ -124,7 +122,7 @@ class Interface : public Symbol function_types_vector_t m_functionTypes; /*!< Vector of interface function types. */ uint32_t m_uniqueId; /*!< Interface unique id. */ - static uint32_t s_idCounter; /*!< Interface id counter. Each interface will increase this. */ + static uint32_t s_idCounter; /*!< Interface id counter. Each interface will increase this. */ }; } // namespace erpcgen diff --git a/erpcgen/src/types/ListType.hpp b/erpcgen/src/types/ListType.hpp index cef44ec9..e9b76cc0 100644 --- a/erpcgen/src/types/ListType.hpp +++ b/erpcgen/src/types/ListType.hpp @@ -33,10 +33,8 @@ class ListType : public DataType * * @param[in] elementType Given data type. */ - explicit ListType(DataType *elementType) - : DataType("(list)", data_type_t::kListType) - , m_elementType(elementType) - , m_lengthVariableName("") + explicit ListType(DataType *elementType) : + DataType("(list)", data_type_t::kListType), m_elementType(elementType), m_lengthVariableName("") { } diff --git a/erpcgen/src/types/Program.hpp b/erpcgen/src/types/Program.hpp index 3d0efd0d..77179016 100644 --- a/erpcgen/src/types/Program.hpp +++ b/erpcgen/src/types/Program.hpp @@ -35,10 +35,7 @@ class Program : public Symbol * * @param[in] tok Given token. */ - explicit Program(const Token &tok) - : Symbol(symbol_type_t::kProgramSymbol, tok) - { - } + explicit Program(const Token &tok) : Symbol(symbol_type_t::kProgramSymbol, tok) {} }; } // namespace erpcgen diff --git a/erpcgen/src/types/StructMember.hpp b/erpcgen/src/types/StructMember.hpp index f3448d57..6c0fb055 100644 --- a/erpcgen/src/types/StructMember.hpp +++ b/erpcgen/src/types/StructMember.hpp @@ -46,13 +46,9 @@ class StructMember : public Symbol * @param[in] name Given name. * @param[in] dataType Given data type. */ - StructMember(const std::string &name, DataType *dataType) - : Symbol(symbol_type_t::kStructMemberSymbol, name) - , m_dataType(dataType) - , m_paramDirection() - , m_containList() - , m_containString() - , m_byref(false) + StructMember(const std::string &name, DataType *dataType) : + Symbol(symbol_type_t::kStructMemberSymbol, name), m_dataType(dataType), m_paramDirection(), m_containList(), + m_containString(), m_byref(false) { } @@ -64,13 +60,9 @@ class StructMember : public Symbol * @param[in] tok Given token. * @param[in] dataType Given data type. */ - StructMember(const Token &tok, DataType *dataType) - : Symbol(symbol_type_t::kStructMemberSymbol, tok) - , m_dataType(dataType) - , m_paramDirection() - , m_containList() - , m_containString() - , m_byref(false) + StructMember(const Token &tok, DataType *dataType) : + Symbol(symbol_type_t::kStructMemberSymbol, tok), m_dataType(dataType), m_paramDirection(), m_containList(), + m_containString(), m_byref(false) { } diff --git a/erpcgen/src/types/StructType.hpp b/erpcgen/src/types/StructType.hpp index 7514ed40..d02d3caf 100644 --- a/erpcgen/src/types/StructType.hpp +++ b/erpcgen/src/types/StructType.hpp @@ -38,10 +38,7 @@ class StructType : public DataType * * @param[in] name Given name. */ - explicit StructType(const std::string &name) - : DataType(name, data_type_t::kStructType) - { - } + explicit StructType(const std::string &name) : DataType(name, data_type_t::kStructType) {} /*! * @brief Constructor. @@ -50,10 +47,7 @@ class StructType : public DataType * * @param[in] tok Given token. */ - explicit StructType(const Token &tok) - : DataType(tok, data_type_t::kStructType) - { - } + explicit StructType(const Token &tok) : DataType(tok, data_type_t::kStructType) {} /*! * @brief This function will add struct member to the struct. diff --git a/erpcgen/src/types/Symbol.hpp b/erpcgen/src/types/Symbol.hpp index 654ed0e6..666a4b3b 100644 --- a/erpcgen/src/types/Symbol.hpp +++ b/erpcgen/src/types/Symbol.hpp @@ -50,13 +50,8 @@ class Symbol * * @param[in] symType Enum symbol type. */ - explicit Symbol(symbol_type_t symType) - : m_symbolType(symType) - , m_name() - , m_location() - , m_annotations() - , m_mlComment("") - , m_ilComment("") + explicit Symbol(symbol_type_t symType) : + m_symbolType(symType), m_name(), m_location(), m_annotations(), m_mlComment(""), m_ilComment("") { } @@ -68,13 +63,8 @@ class Symbol * @param[in] symType Enum symbol type. * @param[in] name Name for symbol. */ - Symbol(symbol_type_t symType, const std::string &name) - : m_symbolType(symType) - , m_name(name) - , m_location() - , m_annotations() - , m_mlComment("") - , m_ilComment("") + Symbol(symbol_type_t symType, const std::string &name) : + m_symbolType(symType), m_name(name), m_location(), m_annotations(), m_mlComment(""), m_ilComment("") { } @@ -86,13 +76,9 @@ class Symbol * @param[in] symType Enum symbol type. * @param[in] tok Token for symbol, which contains name and location. */ - Symbol(symbol_type_t symType, const Token &tok) - : m_symbolType(symType) - , m_name(tok.getStringValue()) - , m_location(tok.getLocation()) - , m_annotations() - , m_mlComment("") - , m_ilComment("") + Symbol(symbol_type_t symType, const Token &tok) : + m_symbolType(symType), m_name(tok.getStringValue()), m_location(tok.getLocation()), m_annotations(), + m_mlComment(""), m_ilComment("") { } diff --git a/erpcgen/src/types/SymbolScope.hpp b/erpcgen/src/types/SymbolScope.hpp index 93b3a145..617d1985 100644 --- a/erpcgen/src/types/SymbolScope.hpp +++ b/erpcgen/src/types/SymbolScope.hpp @@ -69,12 +69,7 @@ class SymbolScope /*! * @brief Constructor. */ - SymbolScope() - : m_symbolMap() - , m_symbolVector() - , m_parent(nullptr) - { - } + SymbolScope() : m_symbolMap(), m_symbolVector(), m_parent(nullptr) {} /*! * @brief Destructor. diff --git a/erpcgen/src/types/Type.cpp b/erpcgen/src/types/Type.cpp index b218760e..78ba49f7 100644 --- a/erpcgen/src/types/Type.cpp +++ b/erpcgen/src/types/Type.cpp @@ -119,10 +119,8 @@ string Symbol::getAnnStringValue(const string &annName, Annotation::program_lang return (annVallue) ? annVallue->toString() : ""; } -SymbolScope::typed_iterator::typed_iterator(const vit &bv, const vit &ev, Symbol::symbol_type_t predicateType) -: m_vec(bv) -, m_endvec(ev) -, m_predicateType(predicateType) +SymbolScope::typed_iterator::typed_iterator(const vit &bv, const vit &ev, Symbol::symbol_type_t predicateType) : +m_vec(bv), m_endvec(ev), m_predicateType(predicateType) { // Advance to the first matching symbol. while (m_vec != m_endvec && (*m_vec)->getSymbolType() != m_predicateType) @@ -477,12 +475,14 @@ DataType *DataType::getTrueContainerDataType() DataType *trueDataType = this->getTrueDataType(); switch (trueDataType->getDataType()) { - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { ListType *l = dynamic_cast(trueDataType); assert(l); return l->getElementType()->getTrueContainerDataType(); } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { ArrayType *a = dynamic_cast(trueDataType); assert(a); return a->getElementType()->getTrueContainerDataType(); diff --git a/erpcgen/src/types/UnionCase.hpp b/erpcgen/src/types/UnionCase.hpp index 752aebea..ea5c010a 100644 --- a/erpcgen/src/types/UnionCase.hpp +++ b/erpcgen/src/types/UnionCase.hpp @@ -35,11 +35,9 @@ class UnionCase : public Symbol * @param[in] caseName Given case name. * @param[in] caseValue Given case value. */ - UnionCase(const std::string &caseName, int32_t caseValue) - : Symbol(symbol_type_t::kUnionCaseMemberSymbol, caseName) - , m_caseName(caseName) - , m_caseValue(caseValue) - , m_containingUnion(nullptr) + UnionCase(const std::string &caseName, int32_t caseValue) : + Symbol(symbol_type_t::kUnionCaseMemberSymbol, caseName), m_caseName(caseName), m_caseValue(caseValue), + m_containingUnion(nullptr) { } @@ -51,11 +49,8 @@ class UnionCase : public Symbol * * @param[in] caseValue Given case value. */ - explicit UnionCase(int32_t caseValue) - : Symbol(symbol_type_t::kUnionCaseMemberSymbol) - , m_caseName("") - , m_caseValue(caseValue) - , m_containingUnion(nullptr) + explicit UnionCase(int32_t caseValue) : + Symbol(symbol_type_t::kUnionCaseMemberSymbol), m_caseName(""), m_caseValue(caseValue), m_containingUnion(nullptr) { } @@ -67,11 +62,8 @@ class UnionCase : public Symbol * * @param[in] caseName Given case name. */ - explicit UnionCase(const std::string &caseName) - : Symbol(symbol_type_t::kUnionCaseMemberSymbol) - , m_caseName(caseName) - , m_caseValue(-1) - , m_containingUnion(nullptr) + explicit UnionCase(const std::string &caseName) : + Symbol(symbol_type_t::kUnionCaseMemberSymbol), m_caseName(caseName), m_caseValue(-1), m_containingUnion(nullptr) { } diff --git a/erpcgen/src/types/UnionType.hpp b/erpcgen/src/types/UnionType.hpp index 3362dbee..20950b75 100644 --- a/erpcgen/src/types/UnionType.hpp +++ b/erpcgen/src/types/UnionType.hpp @@ -39,11 +39,9 @@ class UnionType : public DataType * @param[in] name Given name. * @param[in] discriminatorName Discriminator name. */ - UnionType(const std::string &name, const std::string &discriminatorName) - : DataType(name, data_type_t::kUnionType) - , m_discriminator(discriminatorName) - , m_members("(union)") - , m_parentStruct(nullptr) + UnionType(const std::string &name, const std::string &discriminatorName) : + DataType(name, data_type_t::kUnionType), m_discriminator(discriminatorName), m_members("(union)"), + m_parentStruct(nullptr) { } @@ -56,11 +54,9 @@ class UnionType : public DataType * @param[in] tok Given token.. * @param[in] discriminatorName Discriminator name. */ - UnionType(const Token &tok, const std::string &discriminatorName) - : DataType(tok, data_type_t::kUnionType) - , m_discriminator(discriminatorName) - , m_members("(union)") - , m_parentStruct(nullptr) + UnionType(const Token &tok, const std::string &discriminatorName) : + DataType(tok, data_type_t::kUnionType), m_discriminator(discriminatorName), m_members("(union)"), + m_parentStruct(nullptr) { } diff --git a/erpcgen/src/types/VoidType.hpp b/erpcgen/src/types/VoidType.hpp index 6cb72b61..2621dd92 100644 --- a/erpcgen/src/types/VoidType.hpp +++ b/erpcgen/src/types/VoidType.hpp @@ -31,10 +31,7 @@ class VoidType : public DataType * * This function set name to "(void)". */ - VoidType() - : DataType("(void)", data_type_t::kVoidType) - { - } + VoidType() : DataType("(void)", data_type_t::kVoidType) {} /*! * @brief This function returns description about the void. diff --git a/erpcsniffer/src/Sniffer.cpp b/erpcsniffer/src/Sniffer.cpp index 585aaec5..fd363a92 100644 --- a/erpcsniffer/src/Sniffer.cpp +++ b/erpcsniffer/src/Sniffer.cpp @@ -184,7 +184,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) erpc_status_t err; switch (dataType->getDataType()) { - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { AliasType *aliasType = dynamic_cast(dataType); assert(aliasType); string parseDataInfo; @@ -198,7 +199,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) addSpaces(parsedDataInfo, 2); break; } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { ArrayType *arrayType = dynamic_cast(dataType); assert(arrayType); uint32_t arraySize = arrayType->getElementCount(); @@ -221,13 +223,15 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) } break; } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { parsedDataInfo = " value: "; BuiltinType *builtinType = dynamic_cast(dataType); assert(builtinType); switch (builtinType->getBuiltinType()) { - case BuiltinType::builtin_type_t::kBoolType: { + case BuiltinType::builtin_type_t::kBoolType: + { bool value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -237,7 +241,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "bool" + parsedDataInfo + ((value) ? "true" : "false"); break; } - case BuiltinType::builtin_type_t::kInt8Type: { + case BuiltinType::builtin_type_t::kInt8Type: + { int8_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -247,7 +252,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "int8_t" + parsedDataInfo + format_string("%d", value); break; } - case BuiltinType::builtin_type_t::kInt16Type: { + case BuiltinType::builtin_type_t::kInt16Type: + { int16_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -257,7 +263,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "int16_t" + parsedDataInfo + format_string("%d", value); break; } - case BuiltinType::builtin_type_t::kInt32Type: { + case BuiltinType::builtin_type_t::kInt32Type: + { int32_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -267,7 +274,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "int32_t" + parsedDataInfo + format_string("%d", value); break; } - case BuiltinType::builtin_type_t::kInt64Type: { + case BuiltinType::builtin_type_t::kInt64Type: + { int64_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -277,7 +285,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "int64_t" + parsedDataInfo + format_string("%ld", value); break; } - case BuiltinType::builtin_type_t::kUInt8Type: { + case BuiltinType::builtin_type_t::kUInt8Type: + { uint8_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -287,7 +296,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "uint8_t" + parsedDataInfo + format_string("%u", value); break; } - case BuiltinType::builtin_type_t::kUInt16Type: { + case BuiltinType::builtin_type_t::kUInt16Type: + { uint16_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -297,7 +307,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "uint16_t" + parsedDataInfo + format_string("%u", value); break; } - case BuiltinType::builtin_type_t::kUInt32Type: { + case BuiltinType::builtin_type_t::kUInt32Type: + { uint32_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -307,7 +318,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "uint32_t" + parsedDataInfo + format_string("%u", value); break; } - case BuiltinType::builtin_type_t::kUInt64Type: { + case BuiltinType::builtin_type_t::kUInt64Type: + { uint64_t value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -317,7 +329,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "uint64_t" + parsedDataInfo + format_string("%lu", value); break; } - case BuiltinType::builtin_type_t::kFloatType: { + case BuiltinType::builtin_type_t::kFloatType: + { float value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -327,7 +340,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "float" + parsedDataInfo + format_string("%f", value); break; } - case BuiltinType::builtin_type_t::kDoubleType: { + case BuiltinType::builtin_type_t::kDoubleType: + { double value; m_codec->read(value); if ((err = m_codec->getStatus())) @@ -337,7 +351,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "double" + parsedDataInfo + format_string("%f", value); break; } - case BuiltinType::builtin_type_t::kStringType: { + case BuiltinType::builtin_type_t::kStringType: + { char *value; uint32_t length; m_codec->readString(length, &value); @@ -348,7 +363,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "string" + parsedDataInfo + format_string("%.*s", length, value); break; } - case BuiltinType::builtin_type_t::kBinaryType: { + case BuiltinType::builtin_type_t::kBinaryType: + { uint8_t *value; uint32_t length; m_codec->readBinary(length, &value); @@ -364,13 +380,15 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = "binary" + parsedDataInfo + binaryValue; break; } - default: { + default: + { throw runtime_error("Unrecognized builtin type.\n"); } } break; } - case DataType::data_type_t::kEnumType: { + case DataType::data_type_t::kEnumType: + { EnumType *e = dynamic_cast(dataType); assert(e); uint32_t value; @@ -395,7 +413,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) parsedDataInfo = format_string("%s value: %s", e->getName().c_str(), enumMemberName.c_str()); break; } - case DataType::data_type_t::kFunctionType: { + case DataType::data_type_t::kFunctionType: + { FunctionType *f = dynamic_cast(dataType); assert(f); int32_t value; @@ -415,7 +434,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) } break; } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { ListType *listType = dynamic_cast(dataType); assert(listType); uint32_t listSize; @@ -445,7 +465,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) } break; } - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *structType = dynamic_cast(dataType); assert(structType); parsedDataInfo = "struct " + structType->getName() + ":\n"; @@ -470,7 +491,8 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) addSpaces(parsedDataInfo, 2); break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *unionType = dynamic_cast(dataType); assert(unionType); int32_t discriminator; @@ -520,11 +542,13 @@ erpc_status_t Sniffer::parseDataType(DataType *dataType, string &parsedDataInfo) addSpaces(parsedDataInfo, 2); break; } - case DataType::data_type_t::kVoidType: { + case DataType::data_type_t::kVoidType: + { parsedDataInfo = "void"; break; } - default: { + default: + { throw runtime_error("Unrecognized data type.\n"); } } @@ -643,12 +667,14 @@ string Sniffer::getDataTypeName(DataType *dataType) { switch (dataType->getDataType()) { - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { ListType *listType = dynamic_cast(dataType); assert(listType); return "list<" + getDataTypeName(listType->getElementType()) + ">"; } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { string returnVal; while (dataType->isArray()) { @@ -659,7 +685,8 @@ string Sniffer::getDataTypeName(DataType *dataType) } return getDataTypeName(dataType) + returnVal; } - case DataType::data_type_t::kVoidType: { + case DataType::data_type_t::kVoidType: + { return "void"; } default: diff --git a/erpcsniffer/src/Sniffer.hpp b/erpcsniffer/src/Sniffer.hpp index 70f914eb..0697ad3a 100644 --- a/erpcsniffer/src/Sniffer.hpp +++ b/erpcsniffer/src/Sniffer.hpp @@ -37,12 +37,10 @@ class Sniffer * @param[in] quantity How much messages record. */ Sniffer(erpc::Transport *transport, erpcgen::InterfaceDefinition *def, const char *outputFilePath, - uint64_t quantity) - : m_transport(transport) - , m_interfaces(def->getGlobals().getSymbolsOfType(erpcgen::Symbol::symbol_type_t::kInterfaceSymbol)) - , m_outputFilePath(outputFilePath) - , m_quantity(quantity) - , m_codec(new erpc::BasicCodec()){}; + uint64_t quantity) : + m_transport(transport), + m_interfaces(def->getGlobals().getSymbolsOfType(erpcgen::Symbol::symbol_type_t::kInterfaceSymbol)), + m_outputFilePath(outputFilePath), m_quantity(quantity), m_codec(new erpc::BasicCodec()){}; /*! * @brief This function is destructor of Sniffer class. diff --git a/erpcsniffer/src/erpc_config.h b/erpcsniffer/src/erpc_config.h index f1a68c01..bf256c30 100644 --- a/erpcsniffer/src/erpc_config.h +++ b/erpcsniffer/src/erpc_config.h @@ -1,6 +1,7 @@ /* * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2021 NXP + * Copyright 2016-2020 NXP + * Copyright 2020-2021 ACRIOS Systems s.r.o. * All rights reserved. * * @@ -10,6 +11,12 @@ #ifndef _ERPC_CONFIG_H_ #define _ERPC_CONFIG_H_ +/*! + * @addtogroup config + * @{ + * @file + */ + //////////////////////////////////////////////////////////////////////////////// // Declarations //////////////////////////////////////////////////////////////////////////////// @@ -176,10 +183,27 @@ //! @name Assert function definition //@{ -//! User custom asser defition. Include header file if needed before bellow line. If assert is not enabled, default will be used. +//! User custom asser defition. Include header file if needed before bellow line. If assert is not enabled, default will +//! be used. // #define erpc_assert(condition) //@} +//! @def ENDIANES_HEADER +//! +//! Include header file that controls the communication endianness +//! +//! Uncomment for example behaviour for endianness agnostic with: +//! 1. communication in little endian. +//! 2. current processor is big endian. +//! 3. pointer size is 32 bit. +//! 4. float+double scheme not defined, so throws assert if passes. +//! #define ERPC_PROCESSOR_ENDIANNESS_LITTLE 0 +//! #define ERPC_COMMUNICATION_LITTLE 1 +//! #define ERPC_POINTER_SIZE_16 0 +//! #define ERPC_POINTER_SIZE_32 1 +//! #define ERPC_POINTER_SIZE_64 0 +//! #define ENDIANNESS_HEADER "erpc_endianness_agnostic_example.h" + /*! @} */ #endif // _ERPC_CONFIG_H_ //////////////////////////////////////////////////////////////////////////////// diff --git a/erpcsniffer/src/erpcsniffer.cpp b/erpcsniffer/src/erpcsniffer.cpp index 342e6a12..80b94735 100644 --- a/erpcsniffer/src/erpcsniffer.cpp +++ b/erpcsniffer/src/erpcsniffer.cpp @@ -118,11 +118,11 @@ class erpcsnifferTool const char *m_outputFilePath; /*!< Path to the output file. */ const char *m_ErpcFile; /*!< ERPC file. */ string_vector_t m_positionalArgs; - transports_t m_transport; /*!< Transport used for receiving messages. */ - uint64_t m_quantity; /*!< Quantity of logs to store. */ - uint32_t m_baudrate; /*!< Baudrate rate speed. */ - const char *m_port; /*!< Name or number of port. Based on used transport. */ - const char *m_host; /*!< Host name */ + transports_t m_transport; /*!< Transport used for receiving messages. */ + uint64_t m_quantity; /*!< Quantity of logs to store. */ + uint32_t m_baudrate; /*!< Baudrate rate speed. */ + const char *m_port; /*!< Name or number of port. Based on used transport. */ + const char *m_host; /*!< Host name */ public: /*! @@ -133,18 +133,10 @@ class erpcsnifferTool * * Creates the singleton logger instance. */ - erpcsnifferTool(int argc, char *argv[]) - : m_argc(argc) - , m_argv(argv) - , m_logger(0) - , m_verboseType(verbose_type_t::kWarning) - , m_outputFilePath(NULL) - , m_ErpcFile(NULL) - , m_transport(transports_t::kNoneTransport) - , m_quantity(10) - , m_baudrate(115200) - , m_port(NULL) - , m_host(NULL) + erpcsnifferTool(int argc, char *argv[]) : + m_argc(argc), m_argv(argv), m_logger(0), m_verboseType(verbose_type_t::kWarning), m_outputFilePath(NULL), + m_ErpcFile(NULL), m_transport(transports_t::kNoneTransport), m_quantity(10), m_baudrate(115200), m_port(NULL), + m_host(NULL) { // create logger instance m_logger = new StdoutLogger(); @@ -185,22 +177,26 @@ class erpcsnifferTool { switch (optchar) { - case '?': { + case '?': + { printUsage(options); return 0; } - case 'V': { + case 'V': + { printf("%s %s\n%s\n", k_toolName, k_version, k_copyright); return 0; } - case 'o': { + case 'o': + { m_outputFilePath = optarg; break; } - case 'v': { + case 'v': + { if (m_verboseType != verbose_type_t::kExtraDebug) { m_verboseType = (verbose_type_t)(((int)m_verboseType) + 1); @@ -208,12 +204,14 @@ class erpcsnifferTool break; } - case 'I': { + case 'I': + { PathSearcher::getGlobalSearcher().addSearchPath(optarg); break; } - case 't': { + case 't': + { string transport = optarg; if (transport == "tcp") { @@ -231,27 +229,32 @@ class erpcsnifferTool break; } - case 'q': { + case 'q': + { m_quantity = strtoul(optarg, NULL, 10); break; } - case 'b': { + case 'b': + { m_baudrate = strtoul(optarg, NULL, 10); break; } - case 'p': { + case 'p': + { m_port = optarg; break; } - case 'h': { + case 'h': + { m_host = optarg; break; } - default: { + default: + { Log::error("error: unrecognized option\n\n"); printUsage(options); return 0; @@ -336,7 +339,8 @@ class erpcsnifferTool Transport *_transport; switch (m_transport) { - case transports_t::kTcpTransport: { + case transports_t::kTcpTransport: + { uint16_t portNumber = strtoul(m_port, NULL, 10); TCPTransport *tcpTransport = new TCPTransport(m_host, portNumber, true); if (erpc_status_t err = tcpTransport->open()) @@ -347,14 +351,16 @@ class erpcsnifferTool break; } - case transports_t::kSerialTransport: { + case transports_t::kSerialTransport: + { erpc_transport_t transport = erpc_transport_serial_init(m_port, m_baudrate); _transport = reinterpret_cast(transport); assert(_transport); break; } - default: { + default: + { break; } } diff --git a/run_clang_format.py b/run_clang_format.py index 83ed7dac..b427bbc8 100755 --- a/run_clang_format.py +++ b/run_clang_format.py @@ -19,14 +19,10 @@ "erpcsniffer/src", "test"] -# Files which will be not formatted -exceptions = [ - "test/common/gtest/gtest.h", - "test/common/gtest/gtest.cpp", - "erpcgen/src/cpptemplate/cpptempl.h", - "erpcgen/src/cpptemplate/cpptempl.cpp", - "erpcgen/src/cpptemplate/cpptempl_test.cpp"] +with open(".clang-format-ignore") as f: + exceptionsTmp = f.read().split("\n") +exceptions = [exception for exception in exceptionsTmp if exception != "" and exception[0] != "#"] # For windows use "\\" instead of "/" path separators. if os.environ.get('OS', '') == 'Windows_NT': folders = [os.path.normpath(folder) for folder in folders] @@ -52,8 +48,8 @@ clang_format_stderr.decode('utf-8'))) exit(1) clang_format_stdout = clang_format_stdout.decode("utf-8") -if not clang_format_stdout.startswith("clang-format version 10.0.0"): - print("clang-format is not the required version: 10.0.0") +if "clang-format version 16.0.0" not in clang_format_stdout: + print("clang-format is not the required version: 16.0.0") exit(1) # processing formatting @@ -63,7 +59,7 @@ for path, subdirs, files in os.walk(folder): for name in files: if any(ext in name for ext in extensions): - file = os.path.join(path, name) + file = "./" + os.path.join(path, name) if file in exceptions: print("Ignored: ", file) else: diff --git a/test/common/config/erpc_config.h b/test/common/config/erpc_config.h index 4d35278c..c20f9952 100644 --- a/test/common/config/erpc_config.h +++ b/test/common/config/erpc_config.h @@ -1,6 +1,7 @@ /* * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2021 NXP + * Copyright 2016-2020 NXP + * Copyright 2020-2021 ACRIOS Systems s.r.o. * All rights reserved. * * @@ -65,17 +66,17 @@ //! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. //! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. //! -//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is supported -//! by compiler. Uncomment comment bellow to use static allocation policy. -//! In case of static implementation user need consider another values to set (ERPC_CODEC_COUNT, -//! ERPC_MESSAGE_LOGGERS_COUNT, ERPC_CLIENTS_THREADS_AMOUNT). +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is +//! supported by compiler. Uncomment comment bellow to use static allocation policy. In case of static implementation +//! user need consider another values to set (ERPC_CODEC_COUNT, ERPC_MESSAGE_LOGGERS_COUNT, +//! ERPC_CLIENTS_THREADS_AMOUNT). #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_DYNAMIC) //! @def ERPC_CODEC_COUNT //! //! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to -//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one thread per -//! each then 2, ... Default value 2. +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one +//! thread per each then 2, ... Default value 2. #define ERPC_CODEC_COUNT (2U) //! @def ERPC_MESSAGE_LOGGERS_COUNT @@ -89,8 +90,8 @@ //! @def ERPC_CLIENTS_THREADS_AMOUNT //! -//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to ERPC_ALLOCATION_POLICY_STATIC. -//! Default value 1 (Most of current cases). +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. Default value 1 (Most of current cases). #define ERPC_CLIENTS_THREADS_AMOUNT (1U) //! @def ERPC_THREADS @@ -146,7 +147,7 @@ //! ERPC_MESSAGE_LOGGING_DISABLED. //! //! Uncomment for using logging feature. -// #define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) //! @def ERPC_TRANSPORT_MU_USE_MCMGR //! @@ -182,10 +183,27 @@ //! @name Assert function definition //@{ -//! User custom asser defition. Include header file if needed before bellow line. If assert is not enabled, default will be used. +//! User custom asser defition. Include header file if needed before bellow line. If assert is not enabled, default will +//! be used. // #define erpc_assert(condition) //@} +//! @def ENDIANES_HEADER +//! +//! Include header file that controls the communication endianness +//! +//! Uncomment for example behaviour for endianness agnostic with: +//! 1. communication in little endian. +//! 2. current processor is big endian. +//! 3. pointer size is 32 bit. +//! 4. float+double scheme not defined, so throws assert if passes. +//! #define ERPC_PROCESSOR_ENDIANNESS_LITTLE 0 +//! #define ERPC_COMMUNICATION_LITTLE 1 +//! #define ERPC_POINTER_SIZE_16 0 +//! #define ERPC_POINTER_SIZE_32 1 +//! #define ERPC_POINTER_SIZE_64 0 +//! #define ENDIANNESS_HEADER "erpc_endianness_agnostic_example.h" + /*! @} */ #endif // _ERPC_CONFIG_H_ //////////////////////////////////////////////////////////////////////////////// diff --git a/test/common/unit_test_server.cpp b/test/common/unit_test_server.cpp index 7c54afa8..dae97b3e 100644 --- a/test/common/unit_test_server.cpp +++ b/test/common/unit_test_server.cpp @@ -14,17 +14,21 @@ #if (defined(RPMSG) || defined(UART) || defined(MU)) extern "C" { #if defined(UART) +/* clang-format off */ #include "fsl_lpuart_cmsis.h" #include "app_core0.h" +/* clang-format on */ #else #if defined(RPMSG) #include "rpmsg_lite.h" #endif #define APP_ERPC_READY_EVENT_DATA (1) +/* clang-format off */ #include "mcmgr.h" #include "app_core1.h" +/* clang-format on */ #endif #if defined(__CC_ARM) || defined(__ARMCC_VERSION) int main(void); diff --git a/test/test_arbitrator/config/erpc_config.h b/test/test_arbitrator/config/erpc_config.h index 42bced91..a5c4d552 100644 --- a/test/test_arbitrator/config/erpc_config.h +++ b/test/test_arbitrator/config/erpc_config.h @@ -1,8 +1,10 @@ /* * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2021 NXP + * Copyright 2016-2020 NXP + * Copyright 2020-2021 ACRIOS Systems s.r.o. * All rights reserved. * + * * SPDX-License-Identifier: BSD-3-Clause */ @@ -64,17 +66,17 @@ //! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. //! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. //! -//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is supported -//! by compiler. Uncomment comment bellow to use static allocation policy. -//! In case of static implementation user need consider another values to set (ERPC_CODEC_COUNT, -//! ERPC_MESSAGE_LOGGERS_COUNT, ERPC_CLIENTS_THREADS_AMOUNT). +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is +//! supported by compiler. Uncomment comment bellow to use static allocation policy. In case of static implementation +//! user need consider another values to set (ERPC_CODEC_COUNT, ERPC_MESSAGE_LOGGERS_COUNT, +//! ERPC_CLIENTS_THREADS_AMOUNT). #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_DYNAMIC) //! @def ERPC_CODEC_COUNT //! //! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to -//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one thread per -//! each then 2, ... Default value 2. +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one +//! thread per each then 2, ... Default value 2. #define ERPC_CODEC_COUNT (2U) //! @def ERPC_MESSAGE_LOGGERS_COUNT @@ -88,8 +90,8 @@ //! @def ERPC_CLIENTS_THREADS_AMOUNT //! -//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to ERPC_ALLOCATION_POLICY_STATIC. -//! Default value 1 (Most of current cases). +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. Default value 1 (Most of current cases). #define ERPC_CLIENTS_THREADS_AMOUNT (1U) //! @def ERPC_THREADS @@ -145,7 +147,7 @@ //! ERPC_MESSAGE_LOGGING_DISABLED. //! //! Uncomment for using logging feature. -// #define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) //! @def ERPC_TRANSPORT_MU_USE_MCMGR //! @@ -181,10 +183,27 @@ //! @name Assert function definition //@{ -//! User custom asser defition. Include header file if needed before bellow line. If assert is not enabled, default will be used. +//! User custom asser defition. Include header file if needed before bellow line. If assert is not enabled, default will +//! be used. // #define erpc_assert(condition) //@} +//! @def ENDIANES_HEADER +//! +//! Include header file that controls the communication endianness +//! +//! Uncomment for example behaviour for endianness agnostic with: +//! 1. communication in little endian. +//! 2. current processor is big endian. +//! 3. pointer size is 32 bit. +//! 4. float+double scheme not defined, so throws assert if passes. +//! #define ERPC_PROCESSOR_ENDIANNESS_LITTLE 0 +//! #define ERPC_COMMUNICATION_LITTLE 1 +//! #define ERPC_POINTER_SIZE_16 0 +//! #define ERPC_POINTER_SIZE_32 1 +//! #define ERPC_POINTER_SIZE_64 0 +//! #define ENDIANNESS_HEADER "erpc_endianness_agnostic_example.h" + /*! @} */ #endif // _ERPC_CONFIG_H_ //////////////////////////////////////////////////////////////////////////////// diff --git a/test/test_unions/test_unions_server_impl.cpp b/test/test_unions/test_unions_server_impl.cpp index ea53611b..8c2140d1 100644 --- a/test/test_unions/test_unions_server_impl.cpp +++ b/test/test_unions/test_unions_server_impl.cpp @@ -31,7 +31,8 @@ gapGenericEvent_t *testGenericCallback(const gapGenericEvent_t *event) gapGenericEvent_t *newEvent = (gapGenericEvent_t *)erpc_malloc(sizeof(gapGenericEvent_t)); switch (event->eventType) { - case gInternalError_c: { + case gInternalError_c: + { if (event->eventData.internalError.errorCode == gBleSuccess_c && event->eventData.internalError.errorSource == gHciCommandStatus_c && event->eventData.internalError.hciCommandOpcode == 5) @@ -44,7 +45,8 @@ gapGenericEvent_t *testGenericCallback(const gapGenericEvent_t *event) } break; } - case gRandomAddressReady_c: { + case gRandomAddressReady_c: + { int x = 0xAA; int success = 1; int i = 0; @@ -67,7 +69,8 @@ gapGenericEvent_t *testGenericCallback(const gapGenericEvent_t *event) } break; } - case gWhiteListSizeReady_c: { + case gWhiteListSizeReady_c: + { newEvent->eventType = gTestCaseReturn_c; if (100 == event->eventData.whiteListSize) { @@ -82,7 +85,8 @@ gapGenericEvent_t *testGenericCallback(const gapGenericEvent_t *event) case gPublicAddressRead_c: case gAdvertisingSetupFailed_c: case gAdvTxPowerLevelRead_c: - default: { + default: + { } } return newEvent; @@ -93,7 +97,8 @@ foo *sendMyFoo(const foo *f) foo *newFoo = (foo *)erpc_malloc(sizeof(foo)); switch (f->discriminator) { - case apple: { + case apple: + { for (uint32_t i = 0; i < f->bing.myFoobar.rawString.dataLength; ++i) { if ((i + 1) != f->bing.myFoobar.rawString.data[i]) @@ -108,7 +113,8 @@ foo *sendMyFoo(const foo *f) erpc_free(f->bing.myFoobar.rawString.data); break; } - case banana: { + case banana: + { if ((f->bing.x == 3) && (f->bing.y == 4.0)) { newFoo->discriminator = papaya; @@ -123,7 +129,8 @@ foo *sendMyFoo(const foo *f) } break; } - case orange: { + case orange: + { for (uint32_t i = 1; i <= f->bing.a.elementsCount; ++i) { // If data sent across is incorrect, return 0x55 @@ -140,7 +147,8 @@ foo *sendMyFoo(const foo *f) erpc_free(f->bing.a.elements); break; } - default: { + default: + { break; } } @@ -153,7 +161,8 @@ foo *sendMyUnion(fruit discriminator, const unionType *unionVariable) foo *newFoo = (foo *)erpc_malloc(sizeof(foo)); switch (discriminator) { - case apple: { + case apple: + { for (uint32_t i = 0; i < unionVariable->myFoobar.rawString.dataLength; ++i) { if ((i + 1) != unionVariable->myFoobar.rawString.data[i]) @@ -167,7 +176,8 @@ foo *sendMyUnion(fruit discriminator, const unionType *unionVariable) newFoo->bing.ret = 0xAA; break; } - case banana: { + case banana: + { if ((unionVariable->x == 3) && (unionVariable->y == 4.0)) { newFoo->discriminator = papaya; @@ -182,7 +192,8 @@ foo *sendMyUnion(fruit discriminator, const unionType *unionVariable) } break; } - case orange: { + case orange: + { for (uint32_t i = 1; i <= unionVariable->a.elementsCount; ++i) { // If data sent across is incorrect, return 0x55 @@ -198,7 +209,8 @@ foo *sendMyUnion(fruit discriminator, const unionType *unionVariable) newFoo->bing.ret = 0xAA; break; } - default: { + default: + { break; } } From acd195dc3d2d607383d4813856aa8fff424c6fd9 Mon Sep 17 00:00:00 2001 From: "Michal Princ (nxa17570)" Date: Fri, 19 Jan 2024 12:28:34 +0100 Subject: [PATCH 15/24] Format files that are causing clang format check issues --- .github/workflows/clang-format.yml | 1 + erpc_c/port/erpc_threading.h | 13 ++-- erpcgen/src/JavaGenerator.cpp | 104 +++++++++++++++++------------ erpcgen/src/JavaGenerator.hpp | 29 ++++---- 4 files changed, 86 insertions(+), 61 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index f5be8afe..7f17b14e 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -11,4 +11,5 @@ jobs: - uses: DoozyX/clang-format-lint-action@v0.16.2 with: source: '.' + exclude: 'examples/zephyr/matrix_multiply_rpmsglite/src/service examples/zephyr/matrix_multiply_uart/src/service' clangFormatVersion: 16 diff --git a/erpc_c/port/erpc_threading.h b/erpc_c/port/erpc_threading.h index b8b662ea..7266610f 100644 --- a/erpc_c/port/erpc_threading.h +++ b/erpc_c/port/erpc_threading.h @@ -128,7 +128,8 @@ class Thread * @param[in] stackSize Stack size. * @param[in] stackPtr Mandatory task stack pointer for static api usage. */ - void init(thread_entry_t entry, uint32_t priority = 0, uint32_t stackSize = 0, thread_stack_pointer stackPtr = NULL); + void init(thread_entry_t entry, uint32_t priority = 0, uint32_t stackSize = 0, + thread_stack_pointer stackPtr = NULL); /*! * @brief This function starts thread execution. @@ -231,9 +232,9 @@ class Thread static pthread_key_t s_threadObjectKey; /*!< Thread key. */ pthread_t m_thread; /*!< Current thread. */ #elif ERPC_THREADS_IS(FREERTOS) - TaskHandle_t m_task; /*!< Current task. */ - Thread *m_next; /*!< Pointer to next Thread. */ - static Thread *s_first; /*!< Pointer to first Thread. */ + TaskHandle_t m_task; /*!< Current task. */ + Thread *m_next; /*!< Pointer to next Thread. */ + static Thread *s_first; /*!< Pointer to first Thread. */ #if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC StaticTask_t m_staticTask; /*!< Hold static task data. */ #endif @@ -412,7 +413,7 @@ class Mutex #elif ERPC_THREADS_IS(ZEPHYR) struct k_mutex m_mutex; /*!< Mutex.*/ #elif ERPC_THREADS_IS(MBED) - rtos::Mutex *m_mutex; /*!< Mutex. */ + rtos::Mutex *m_mutex; /*!< Mutex. */ #elif ERPC_THREADS_IS(WIN32) HANDLE m_mutex; #elif ERPC_THREADS_IS(THREADX) @@ -498,7 +499,7 @@ class Semaphore SemaphoreHandle_t m_sem; /*!< Semaphore. */ StaticSemaphore_t m_staticQueue; /*!< Static queue. */ #elif ERPC_THREADS_IS(ZEPHYR) - struct k_sem m_sem; /*!< Semaphore. */ + struct k_sem m_sem; /*!< Semaphore. */ #elif ERPC_THREADS_IS(MBED) rtos::Semaphore *m_sem; /*!< Semaphore. */ int m_count; /*!< Semaphore count number. */ diff --git a/erpcgen/src/JavaGenerator.cpp b/erpcgen/src/JavaGenerator.cpp index 76d20063..8dcb5344 100644 --- a/erpcgen/src/JavaGenerator.cpp +++ b/erpcgen/src/JavaGenerator.cpp @@ -34,11 +34,8 @@ extern const char *const kJavaInterface; // Code //////////////////////////////////////////////////////////////////////////////// -JavaGenerator::JavaGenerator(InterfaceDefinition *def, const std::string javaPackageName) -: Generator(def, generator_type_t::kJava) -, m_javaPackageName(javaPackageName) -, m_suffixStrip("") -, m_suffixStripSize(0) +JavaGenerator::JavaGenerator(InterfaceDefinition *def, const std::string javaPackageName) : +Generator(def, generator_type_t::kJava), m_javaPackageName(javaPackageName), m_suffixStrip(""), m_suffixStripSize(0) { /* Set copyright rules. */ if (m_def->hasProgramSymbol()) @@ -354,7 +351,7 @@ data_map JavaGenerator::getFunctionTemplateData(Group *group, Function *fn) } string JavaGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const string &interfaceName, - const string &name, bool insideInterfaceCall) + const string &name, bool insideInterfaceCall) { FunctionType *functionType = dynamic_cast(fn); if (functionType) @@ -385,20 +382,20 @@ string JavaGenerator::getFunctionPrototype(Group *group, FunctionBase *fn, const // Skip data serialization for variables placed as @length value for lists. if (findParamReferencedFromAnn(params, getOutputName(it), LENGTH_ANNOTATION)) { - continue; + continue; } if (!isFirst) { - proto += ", "; - + proto += ", "; } else { - isFirst = false; + isFirst = false; } - if (it->getDirection() == param_direction_t::kOutDirection || it->getDirection() == param_direction_t::kInoutDirection) + if (it->getDirection() == param_direction_t::kOutDirection || + it->getDirection() == param_direction_t::kInoutDirection) { proto += getTypenameName(it->getDataType(), true, true); } @@ -419,17 +416,17 @@ string JavaGenerator::getTypenameName(DataType *t, bool isReference, bool object { string returnName; - - switch (t->getDataType()) { - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { ArrayType *a = dynamic_cast(t); assert(a); returnName = getTypenameName(a->getElementType(), false, false) + "[]"; break; } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { assert(nullptr != dynamic_cast(t)); if (objectType) { @@ -442,23 +439,27 @@ string JavaGenerator::getTypenameName(DataType *t, bool isReference, bool object break; } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { const ListType *a = dynamic_cast(t); assert(a); returnName = "List<" + getTypenameName(a->getElementType(), false, true) + ">"; break; } - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { AliasType *aliasType = dynamic_cast(t); return getTypenameName(aliasType->getTrueDataType(), isReference, objectType); } - case DataType::data_type_t::kVoidType: { + case DataType::data_type_t::kVoidType: + { returnName = "void"; break; } case DataType::data_type_t::kUnionType: case DataType::data_type_t::kEnumType: - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { returnName = getOutputName(t); break; } @@ -638,7 +639,8 @@ data_map JavaGenerator::makeGroupSymbolsTemplateData(Group *group) switch (dataType->getDataType()) { - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { StructType *structType = dynamic_cast(symbol); if (structType == nullptr) { @@ -662,7 +664,8 @@ data_map JavaGenerator::makeGroupSymbolsTemplateData(Group *group) } break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *unionType = dynamic_cast(symbol); if (unionType == nullptr) { @@ -692,7 +695,8 @@ data_map JavaGenerator::makeGroupSymbolsTemplateData(Group *group) } break; } - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { AliasType *aliasType = dynamic_cast(symbol); if (aliasType == nullptr) break; @@ -791,7 +795,7 @@ data_map JavaGenerator::getEncodeDecodeCall(const string &name, DataType *t, Str { static uint8_t listArrayCounter; // Used for creating nested loops variable names data_map templateData; - bool isReference = (isStructMember && structMember->isByref()) || + bool isReference = (isStructMember && structMember->isByref()) || (isFunctionParam && (structMember->getDirection() == param_direction_t::kOutDirection || structMember->getDirection() == param_direction_t::kInoutDirection)); templateData["type"] = getTypeInfo(t, isReference); // Type info about variable @@ -804,14 +808,16 @@ data_map JavaGenerator::getEncodeDecodeCall(const string &name, DataType *t, Str switch (t->getDataType()) { - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { AliasType *aliasType = dynamic_cast(t); assert(aliasType); templateData = getEncodeDecodeCall(name, aliasType->getElementType(), structType, inDataContainer, false, structMember, true, false); break; } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { ArrayType *arrayType = dynamic_cast(t); assert(arrayType); DataType *elementType = arrayType->getElementType()->getTrueDataType(); @@ -833,20 +839,24 @@ data_map JavaGenerator::getEncodeDecodeCall(const string &name, DataType *t, Str templateData["isElementArrayType"] = elementType->isArray(); break; } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { templateData["decode"] = m_templateData["decodeBuiltinType"]; templateData["encode"] = m_templateData["encodeBuiltinType"]; break; } - case DataType::data_type_t::kEnumType: { + case DataType::data_type_t::kEnumType: + { templateData["decode"] = m_templateData["decodeEnumType"]; templateData["encode"] = m_templateData["encodeEnumType"]; break; } - case DataType::data_type_t::kFunctionType: { + case DataType::data_type_t::kFunctionType: + { throw internal_error("Java does not support functions yet."); } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { ListType *listType = dynamic_cast(t); assert(listType); DataType *elementType = listType->getElementType()->getTrueDataType(); @@ -890,15 +900,18 @@ data_map JavaGenerator::getEncodeDecodeCall(const string &name, DataType *t, Str break; } - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { templateData["decode"] = m_templateData["decodeStructType"]; templateData["encode"] = m_templateData["encodeStructType"]; break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { break; } - default: { + default: + { throw internal_error("unknown member type"); } } @@ -948,40 +961,48 @@ data_map JavaGenerator::getTypeInfo(DataType *t, int isReference, bool inDataCon info["isNonEncapsulatedUnion"] = false; switch (t->getDataType()) { - case DataType::data_type_t::kAliasType: { + case DataType::data_type_t::kAliasType: + { info = getTypeInfo(t->getTrueDataType(), false); break; } - case DataType::data_type_t::kArrayType: { + case DataType::data_type_t::kArrayType: + { // Array type requires the array element count to come after the variable/member name. info["type"] = "array"; break; } - case DataType::data_type_t::kBuiltinType: { + case DataType::data_type_t::kBuiltinType: + { assert(dynamic_cast(t)); info["type"] = getBuiltinTypename(dynamic_cast(t)); info["codecTypeName"] = getBuiltinCodecTypeName(dynamic_cast(t)); break; } - case DataType::data_type_t::kEnumType: { + case DataType::data_type_t::kEnumType: + { info["type"] = "enum"; break; } - case DataType::data_type_t::kFunctionType: { + case DataType::data_type_t::kFunctionType: + { info["type"] = "function"; break; } - case DataType::data_type_t::kListType: { + case DataType::data_type_t::kListType: + { info["type"] = "list"; break; } - case DataType::data_type_t::kStructType: { + case DataType::data_type_t::kStructType: + { info["type"] = "struct"; info["decode"] = m_templateData["decodeStructType"]; info["encode"] = m_templateData["encodeStructType"]; break; } - case DataType::data_type_t::kUnionType: { + case DataType::data_type_t::kUnionType: + { UnionType *unionType = dynamic_cast(t); assert(unionType); info["type"] = "union"; @@ -1102,7 +1123,8 @@ data_map JavaGenerator::getTypeInfo(DataType *t, int isReference, bool inDataCon info["cases"] = unionCases; break; } - case DataType::data_type_t::kVoidType: { + case DataType::data_type_t::kVoidType: + { info["type"] = "void"; break; } diff --git a/erpcgen/src/JavaGenerator.hpp b/erpcgen/src/JavaGenerator.hpp index c07809c5..716399c3 100644 --- a/erpcgen/src/JavaGenerator.hpp +++ b/erpcgen/src/JavaGenerator.hpp @@ -47,9 +47,9 @@ class JavaGenerator : public Generator virtual void generate() override; protected: - std::string m_suffixStrip; //!< String to remove from suffixes of names. - size_t m_suffixStripSize; //!< Length of the suffix filter string. - std::string m_javaPackageName; //!< Used java package. + std::string m_suffixStrip; //!< String to remove from suffixes of names. + size_t m_suffixStripSize; //!< Length of the suffix filter string. + std::string m_javaPackageName; //!< Used java package. /*! * @brief This function prepare helpful functions located in template files. @@ -159,12 +159,12 @@ class JavaGenerator : public Generator std::string getFunctionPrototype(Group *group, FunctionBase *fn, const std::string &interfaceName = "", const std::string &name = "", bool insideInterfaceCall = false) override; - /*! + /*! * @brief This function return typename name base on DataType. If objectType is true, * return builtin object insted of primitive. * * @param[in] t data type. - * @param[in] objectType + * @param[in] objectType * * @return Return data type name. */ @@ -247,7 +247,8 @@ class JavaGenerator : public Generator * TODO */ cpptempl::data_map getEncodeDecodeCall(const std::string &name, DataType *t, StructType *structType, - bool inDataContainer, bool isStructMember, StructMember *structMember, bool needTypeDeclaration, bool isFunctionParam); + bool inDataContainer, bool isStructMember, StructMember *structMember, + bool needTypeDeclaration, bool isFunctionParam); /* * TODO @@ -268,7 +269,7 @@ class JavaGenerator : public Generator /*! * @brief This function return CamelCase string representation for given BuiltinType. - * + * * @param[in] t Builtin type. * * @return String representation for given builtin type. @@ -285,7 +286,7 @@ class JavaGenerator : public Generator */ std::string getBuiltinTypename(const BuiltinType *t); - /*! + /*! * @brief This function return string representation for given BuiltinType as Object type. * * @param[in] t Builtin type. @@ -307,12 +308,12 @@ class JavaGenerator : public Generator }; /*! - * @brief This function creates Group package name. - * - * @param[in] group Group - * - * @return Package name for given group. - */ + * @brief This function creates Group package name. + * + * @param[in] group Group + * + * @return Package name for given group. + */ std::string getGroupPackageName(const Group *group); /*! From 32ce7f270e2bbf06b1babbab9ec6c6f34f53c5b6 Mon Sep 17 00:00:00 2001 From: "Michal Princ (nxa17570)" Date: Fri, 19 Jan 2024 22:43:27 +0100 Subject: [PATCH 16/24] clang-format exclude list correction and erpc_threading.h reformat --- .github/workflows/clang-format.yml | 2 +- erpc_c/port/erpc_threading.h | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index 7f17b14e..95f017fd 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -11,5 +11,5 @@ jobs: - uses: DoozyX/clang-format-lint-action@v0.16.2 with: source: '.' - exclude: 'examples/zephyr/matrix_multiply_rpmsglite/src/service examples/zephyr/matrix_multiply_uart/src/service' + exclude: './examples/zephyr/matrix_multiply_rpmsglite/remote/src/service ./examples/zephyr/matrix_multiply_rpmsglite/src/service ./examples/zephyr/matrix_multiply_uart/src/service' clangFormatVersion: 16 diff --git a/erpc_c/port/erpc_threading.h b/erpc_c/port/erpc_threading.h index 7266610f..5a194674 100644 --- a/erpc_c/port/erpc_threading.h +++ b/erpc_c/port/erpc_threading.h @@ -232,9 +232,9 @@ class Thread static pthread_key_t s_threadObjectKey; /*!< Thread key. */ pthread_t m_thread; /*!< Current thread. */ #elif ERPC_THREADS_IS(FREERTOS) - TaskHandle_t m_task; /*!< Current task. */ - Thread *m_next; /*!< Pointer to next Thread. */ - static Thread *s_first; /*!< Pointer to first Thread. */ + TaskHandle_t m_task; /*!< Current task. */ + Thread *m_next; /*!< Pointer to next Thread. */ + static Thread *s_first; /*!< Pointer to first Thread. */ #if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC StaticTask_t m_staticTask; /*!< Hold static task data. */ #endif @@ -413,7 +413,7 @@ class Mutex #elif ERPC_THREADS_IS(ZEPHYR) struct k_mutex m_mutex; /*!< Mutex.*/ #elif ERPC_THREADS_IS(MBED) - rtos::Mutex *m_mutex; /*!< Mutex. */ + rtos::Mutex *m_mutex; /*!< Mutex. */ #elif ERPC_THREADS_IS(WIN32) HANDLE m_mutex; #elif ERPC_THREADS_IS(THREADX) @@ -499,7 +499,7 @@ class Semaphore SemaphoreHandle_t m_sem; /*!< Semaphore. */ StaticSemaphore_t m_staticQueue; /*!< Static queue. */ #elif ERPC_THREADS_IS(ZEPHYR) - struct k_sem m_sem; /*!< Semaphore. */ + struct k_sem m_sem; /*!< Semaphore. */ #elif ERPC_THREADS_IS(MBED) rtos::Semaphore *m_sem; /*!< Semaphore. */ int m_count; /*!< Semaphore count number. */ From 7b7c55f0cbb3cfd237d3f9ce87ab7c735e12b39d Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Fri, 9 Feb 2024 15:36:20 +0100 Subject: [PATCH 17/24] Fixing/improving markdown files (#395) * Fixing/improving markdown files Signed-off-by: Cervenka Dusan * Update the LICENSE file to allow correct license display on Github landing page --------- Signed-off-by: Cervenka Dusan Co-authored-by: Michal Princ --- .github/ISSUE_TEMPLATE/bug_report.md | 14 +- .github/ISSUE_TEMPLATE/feature_request.md | 10 +- .github/ISSUE_TEMPLATE/question.md | 4 +- .github/PULL_REQUEST_TEMPLATE.md | 16 +- LICENSE | 11 - README.md | 233 +++++++++++++----- doxygen/mainpage_erpc.md | 2 +- erpc_python/readme.md | 16 +- erpcgen/test/readme.md | 28 ++- examples/matrix_multiply_tcp_python/readme.md | 42 ++-- .../styles/VSC/vsc-extension-quickstart.md | 8 +- 11 files changed, 247 insertions(+), 137 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 8091dfb3..911ad255 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -7,37 +7,37 @@ assignees: '' --- -**Describe the bug** +## Describe the bug -**To Reproduce** +## To Reproduce -**Expected behavior** +## Expected behavior -**Screenshots** +## Screenshots -**Desktop (please complete the following information):** +## Desktop (please complete the following information) - OS: - eRPC Version: -**Steps you didn't forgot to do** +## Steps you didn't forgot to do - [ ] I checked if there is no related issue opened/closed. - [ ] I checked that there doesn't exist opened PR which is solving this issue. -**Additional context** +## Additional context diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 430d3d04..b525e537 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -7,27 +7,27 @@ assignees: '' --- -**Is your feature request related to a problem? Please describe.** +## Is your feature request related to a problem? Please describe -**Describe the solution you'd like** +## Describe the solution you'd like -**Describe alternatives you've considered** +## Describe alternatives you've considered -**Steps you didn't forgot to do** +## Steps you didn't forgot to do - [ ] I checked if there is no related issue opened/closed. - [ ] I checked that there doesn't exist opened PR which is solving this issue. -**Additional context** +## Additional context diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index 88ba296b..1f85d3b3 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -7,12 +7,12 @@ assignees: '' --- -**If you didn't find answer in existing open/closed issues you may ask here** +## If you didn't find answer in existing open/closed issues you may ask here -**Steps you didn't forgot to do** +## Steps you didn't forgot to do - [ ] I checked if there is no related issue opened/closed. - [ ] I checked that there doesn't exist opened/closed PR which is solving this issue. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 65e6ffe7..6e792f9d 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,36 +1,36 @@ # Pull request -**Choose Correct** +## Choose Correct - [ ] bug - [ ] feature -**Describe the pull request** +## Describe the pull request -**To Reproduce** +## To Reproduce -**Expected behavior** +## Expected behavior -**Screenshots** +## Screenshots -**Desktop (please complete the following information):** +## Desktop (please complete the following information): - OS: - eRPC Version: -**Steps you didn't forgot to do** +## Steps you didn't forgot to do - [ ] I checked if other PR isn't solving this issue. - [ ] I read Contribution details and did appropriate actions. @@ -38,7 +38,7 @@ If applicable, add screenshots to help explain your problem. - [ ] PR code is formatted. - [ ] Allow edits from maintainers pull request option is set (recommended). -**Additional context** +## Additional context diff --git a/LICENSE b/LICENSE index 062e8f37..76727b55 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,3 @@ -Copyright 2014-2016 Freescale Semiconductor, Inc. -Copyright 2016-2024 NXP -All rights reserved. - The BSD 3 Clause License Redistribution and use in source and binary forms, with or without @@ -28,10 +24,3 @@ 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. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md index eb913c22..ad8aabce 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,57 @@ # eRPC +![GitHub all releases](https://img.shields.io/github/downloads/EmbeddedRPC/erpc/total) +[![GitHub License](https://img.shields.io/github/license/EmbeddedRPC/erpc)](/LICENSE) [![Version](https://img.shields.io/github/v/release/EmbeddedRPC/erpc)](https://github.com/EmbeddedRPC/erpc/releases/latest) +![GitHub language count](https://img.shields.io/github/languages/count/EmbeddedRPC/erpc) +![GitHub top language](https://img.shields.io/github/languages/top/EmbeddedRPC/erpc) +![GitHub repo size](https://img.shields.io/github/repo-size/EmbeddedRPC/erpc) +![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/EmbeddedRPC/erpc) +[![GitHub forks](https://img.shields.io/github/forks/EmbeddedRPC/erpc)](https://github.com/EmbeddedRPC/erpc/forks) +![GitHub Repo stars](https://img.shields.io/github/stars/EmbeddedRPC/erpc) +![GitHub watchers](https://img.shields.io/github/watchers/EmbeddedRPC/erpc) +![GitHub commit activity (branch)](https://img.shields.io/github/commit-activity/t/EmbeddedRPC/erpc) +![GitHub commits difference between two branches/tags/commits](https://img.shields.io/github/commits-difference/EmbeddedRPC/erpc?base=main&head=develop&label=master%20behind%20develop%20commits) [![Contributors](https://img.shields.io/github/contributors/EmbeddedRPC/erpc)](https://github.com/EmbeddedRPC/erpc/graphs/contributors) [![Issues](https://img.shields.io/github/issues/EmbeddedRPC/erpc)](https://github.com/EmbeddedRPC/erpc/issues) -[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/EmbeddedRPC/erpc/pulls) -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/EmbeddedRPC/erpc) - -- [eRPC](#erpc) - - [About](#about) - - [Releases](#releases) - - [Edge releases](#edge-releases) - - [Documentation](#documentation) - - [Examples](#examples) - - [References](#references) - - [Directories](#directories) - - [Building and installing](#building-and-installing) - - [Requirements](#requirements) - - [Windows](#windows) - - [Linux and Cygwin](#linux-and-cygwin) - - [Mac OS X](#mac-os-x) - - [Building](#building) - - [Installing for Python](#installing-for-python) - - [Known issues and limitations](#known-issues-and-limitations) - - [Code providing](#code-providing) +[![PRs Welcome](https://img.shields.io/github/issues-pr/EmbeddedRPC/erpc)](https://github.com/EmbeddedRPC/erpc/pulls) + +* [eRPC](#erpc) + * [About](#about) + * [Releases](#releases) + * [Edge releases](#edge-releases) + * [Documentation](#documentation) + * [Examples](#examples) + * [References](#references) + * [Directories](#directories) + * [Building and installing](#building-and-installing) + * [Requirements](#requirements) + * [Windows](#windows) + * [Linux](#linux) + * [Mac OS X](#mac-os-x) + * [Building](#building) + * [Installing for Python](#installing-for-python) + * [Known issues and limitations](#known-issues-and-limitations) + * [Code providing](#code-providing) ## About +[![Open enhancement issues](https://img.shields.io/github/issues/EmbeddedRPC/erpc/enhancement?labelColor=blue&color=black)](https://github.com/EmbeddedRPC/erpc/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement) +[![Closed enhancement issues](https://img.shields.io/github/issues-closed/EmbeddedRPC/erpc/enhancement?labelColor=blue&color=black)](https://github.com/EmbeddedRPC/erpc/issues?q=is%3Aissue+is%3Aclosed+label%3Aenhancement) +[![Open enhancement PRs](https://img.shields.io/github/issues-pr/EmbeddedRPC/erpc/enhancement?labelColor=blue&color=black)](https://github.com/EmbeddedRPC/erpc/pulls?q=is%3Apr+is%3Aopen+label%3Aenhancement) +[![Closed enhancement PRs](https://img.shields.io/github/issues-pr-closed/EmbeddedRPC/erpc/enhancement?labelColor=blue&color=black)](https://github.com/EmbeddedRPC/erpc/pulls?q=is%3Apr+is%3Aclosed+label%3Aenhancement) + +[![Open bug issues](https://img.shields.io/github/issues/EmbeddedRPC/erpc/bug?labelColor=darkred&color=black)](https://github.com/EmbeddedRPC/erpc/issues?q=is%3Aissue+is%3Aopen+label%3Abug) +[![Closed bug issues](https://img.shields.io/github/issues-closed/EmbeddedRPC/erpc/bug?labelColor=darkred&color=black)](https://github.com/EmbeddedRPC/erpc/issues?q=is%3Aissue+is%3Aclosed+label%3Abug) +[![Open bug PRs](https://img.shields.io/github/issues-pr/EmbeddedRPC/erpc/bug?labelColor=darkred&color=black)](https://github.com/EmbeddedRPC/erpc/pulls?q=is%3Apr+is%3Aopen+label%3Abug) +[![Closed bug PRs](https://img.shields.io/github/issues-pr-closed/EmbeddedRPC/erpc/bug?labelColor=darkred&color=black)](https://github.com/EmbeddedRPC/erpc/pulls?q=is%3Apr+is%3Aclosed+label%3Abug) + +[![Open question issues](https://img.shields.io/github/issues/EmbeddedRPC/erpc/question?labelColor=darkviolet&color=black)](https://github.com/EmbeddedRPC/erpc/issues?q=is%3Aissue+is%3Aopen+label%3Aquestion) +[![Closed question issues](https://img.shields.io/github/issues-closed/EmbeddedRPC/erpc/question?labelColor=darkviolet&color=black)](https://github.com/EmbeddedRPC/erpc/issues?q=is%3Aissue+is%3Aclosed+label%3Aquestion) + +[![Open help-wanted issues](https://img.shields.io/github/issues/EmbeddedRPC/erpc/help%20wanted?labelColor=darkgreen&color=black)](https://github.com/EmbeddedRPC/erpc/issues?q=is%3Aissue+is%3Aopen+label%3A%22help%20wanted%22) +[![Closed help-wanted issues](https://img.shields.io/github/issues-closed/EmbeddedRPC/erpc/help%20wanted?labelColor=darkgreen&color=black)](https://github.com/EmbeddedRPC/erpc/issues?q=is%3Aissue+is%3Aclosed+label%3A%22help%20wanted%22) + eRPC (Embedded RPC) is an open source Remote Procedure Call (RPC) system for multichip embedded systems and heterogeneous multicore SoCs. Unlike other modern RPC systems, such as the excellent [Apache Thrift](http://thrift.apache.org), eRPC distinguishes itself by being designed for tightly coupled systems, using plain C for remote functions, and having a small code size (<5kB). It is not intended for high performance distributed systems over a network. @@ -36,7 +62,7 @@ A code generator tool called `erpcgen` is included. It accepts input IDL files, Example `.erpc` file: -```java +```C++ // Define a data type. enum LEDName { kRed, kGreen, kBlue } @@ -51,13 +77,53 @@ Client side usage: ```C void example_client(void) { - // Initialize client running over UART. - erpc_client_init( - erpc_transport_cmsis_uart_init(Driver_USART0), - erpc_mbf_dynamic_init()); + erpc_transport_t transport; + erpc_mbf_t message_buffer_factory; + erpc_client_t client_manager; + + /* Init eRPC client infrastructure */ + transport = erpc_transport_cmsis_uart_init(Driver_USART0); + message_buffer_factory = erpc_mbf_dynamic_init(); + client_manager = erpc_client_init(transport, message_buffer_factory); + + /* init eRPC client IO service */ + initIO_client(client_manager); // Now we can call the remote function to turn on the green LED. set_led(kGreen, true); + + /* deinit objects */ + deinitIO_client(); + erpc_client_deinit(client_manager); + erpc_mbf_dynamic_deinit(message_buffer_factory); + erpc_transport_tcp_deinit(transport); +} +``` + +```C++ +void example_client(void) { + erpc_transport_t transport; + erpc_mbf_t message_buffer_factory; + erpc_client_t client_manager; + + /* Init eRPC client infrastructure */ + transport = erpc_transport_cmsis_uart_init(Driver_USART0); + message_buffer_factory = erpc_mbf_dynamic_init(); + client_manager = erpc_client_init(transport, message_buffer_factory); + + /* scope for client service */ + { + /* init eRPC client IO service */ + IO_client client(client_manager); + + // Now we can call the remote function to turn on the green LED. + client.set_led(kGreen, true); + } + + /* deinit objects */ + erpc_client_deinit(client_manager); + erpc_mbf_dynamic_deinit(message_buffer_factory); + erpc_transport_tcp_deinit(transport); } ``` @@ -70,22 +136,68 @@ void set_led(LEDName whichLed, bool onOrOff) { } void example_server(void) { - // Initialize server running over UART. - erpc_server_init( - erpc_transport_cmsis_uart_init(Driver_USART0), - erpc_mbf_dynamic_init()); + erpc_transport_t transport; + erpc_mbf_t message_buffer_factory; + erpc_server_t server; + erpc_service_t service = create_IO_service(); + + /* Init eRPC server infrastructure */ + transport = erpc_transport_cmsis_uart_init(Driver_USART0); + message_buffer_factory = erpc_mbf_dynamic_init(); + server = erpc_server_init(transport, message_buffer_factory); - // Add the IO service. - erpc_add_service_to_server(create_IO_service()); + /* add custom service implementation to the server */ + erpc_add_service_to_server(server, service); // Run the server. erpc_server_run(); + + /* deinit objects */ + destroy_IO_service(service); + erpc_server_deinit(server); + erpc_mbf_dynamic_deinit(message_buffer_factory); + erpc_transport_tcp_deinit(transport); +} +``` + +```C++ +// Implement the remote function. +class IO : public IO_interface +{ + /* eRPC call definition */ + void set_led(LEDName whichLed, bool onOrOff) override { + // implementation goes here + } +} + +void example_server(void) { + erpc_transport_t transport; + erpc_mbf_t message_buffer_factory; + erpc_server_t server; + IO IOImpl; + IO_service io(&IOImpl); + + /* Init eRPC server infrastructure */ + transport = erpc_transport_cmsis_uart_init(Driver_USART0); + message_buffer_factory = erpc_mbf_dynamic_init(); + server = erpc_server_init(transport, message_buffer_factory); + + /* add custom service implementation to the server */ + erpc_add_service_to_server(server, &io); + + /* poll for requests */ + erpc_status_t err = server.run(); + + /* deinit objects */ + erpc_server_deinit(server); + erpc_mbf_dynamic_deinit(message_buffer_factory); + erpc_transport_tcp_deinit(transport); } ``` A number of transports are supported, and new transport classes are easy to write. -Supported transports: +Supported transports can be found in [erpc/erpc_c/transport](/erpc_c/transports) folder. E.g: * CMSIS UART * NXP Kinetis SPI and DSPI @@ -114,7 +226,7 @@ Edge releases can by found on [eRPC CircleCI](https://app.circleci.com/pipelines ## Examples -[Example IDL](examples/README.md) is available in the `examples/` folder. +[Example IDL](examples/README.md) is available in the [examples/](/examples/) folder. Plenty of eRPC multicore and multiprocessor examples can be also found in NXP MCUXpressoSDK packages. Visit [https://mcuxpresso.nxp.com](https://mcuxpresso.nxp.com) to configure, build and download these packages. @@ -145,53 +257,48 @@ This section provides links to interesting erpc-based projects, articles, blogs ## Directories -`doc` - Documentation. +[doc](/doc) - Documentation. -`doxygen` - Configuration and support files for running Doxygen over the eRPC C++ infrastructure and erpcgen code. +[doxygen](/doxygen) - Configuration and support files for running Doxygen over the eRPC C++ infrastructure and erpcgen code. -`erpc_c` - Holds C/C++ infrastructure for eRPC. This is the code you will include in your application. +[erpc_c](/erpc_c) - Holds C/C++ infrastructure for eRPC. This is the code you will include in your application. -`erpc_python` - Holds Python version of the eRPC infrastructure. +[erpc_python](/erpc_python) - Holds Python version of the eRPC infrastructure. -`erpcgen` - Holds source code for erpcgen and makefiles or project files to build erpcgen on Windows, Linux, and OS X. +[erpcgen](/erpcgen) - Holds source code for erpcgen and makefiles or project files to build erpcgen on Windows, Linux, and OS X. -`erpcsniffer` - Holds source code for erpcsniffer application. +[erpcsniffer](/erpcsniffer) - Holds source code for erpcsniffer application. -`examples` - Several example IDL files. +[examples](/examples) - Several example IDL files. -`mk` - Contains common makefiles for building eRPC components. +[mk](/mk) - Contains common makefiles for building eRPC components. -`test` - Client/server tests. These tests verify the entire communications path from client to server and back. +[test](/test) - Client/server tests. These tests verify the entire communications path from client to server and back. -`utilities` - Holds utilities which bring additional benefit to eRPC apps developers. +[utilities](/utilities) - Holds utilities which bring additional benefit to eRPC apps developers. ## Building and installing -These build instructions apply to host PCs and embedded Linux. For bare metal or RTOS embedded environments, you should copy the `erpc_c` directory into your application sources. +These build instructions apply to host PCs and embedded Linux. For bare metal or RTOS embedded environments, you should copy the [erpc_c](/erpc_c) directory into your application sources. The primary build system is makefile based. It builds a static library of the eRPC C/C++ infrastructure, the `erpcgen` executable, and optionally the unit tests. The makefiles are compatible with gcc or clang on Linux, OS X, and Cygwin. A Windows build -of erpcgen using Visual Studio is also available in the `erpcgen/VisualStudio_v14/` directory. -There is also an Xcode project file in the `erpcgen/` directory which can be used to build erpcgen -for OS X. +of erpcgen using Visual Studio is also available in the [erpcgen/VisualStudio_v14](erpcgen/VisualStudio_v14) directory. +There is also an Xcode project file in the [erpcgen](/erpcgen) directory, which can be used to build erpcgen for OS X. ### Requirements #### Windows -Steps are described in [`erpcgen/VisualStudio_v14/readme_erpcgen.txt`](erpcgen/VisualStudio_v14/readme_erpcgen.txt). - -#### Linux and Cygwin +* Related to Visual Studio: steps are described in [`erpcgen/VisualStudio_v14/readme_erpcgen.txt`](erpcgen/VisualStudio_v14/readme_erpcgen.txt). +* mingw compilation can be used too -Install these packages: +#### Linux -* bison: GNU yacc-compatible parser generator -* flex: A fast lexical analyzer generator -* make: the GNU version of the 'make' utility -* python: Python language interpreter 3.6+ work -* gcc-7: GNU C compiler (recommended version) -* g++-7: GNU C++ compiler (recommended version) +```bash +./install_dependencies.sh +``` Mandatory for case, when build for different architecture is needed @@ -199,10 +306,9 @@ Mandatory for case, when build for different architecture is needed #### Mac OS X -Install these packages with [homebrew](http://brew.sh/): - -* bison: GNU yacc-compatible parser generator (version 3.7.3 is recommended) -* flex: A fast lexical analyzer generator (version 2.6.4 is recommended) +```bash +./install_dependencies.sh +``` ### Building @@ -230,7 +336,8 @@ List of top level Makefile targets: * `erpc`: build the liberpc.a static library * `erpcgen`: build the erpcgen tool -* `test`: build the unit tests under the `test/` directory +* `erpcsniffer`: build the sniffer tool +* `test`: build the unit tests under the [test](/test) directory * `all`: build all of the above * `install`: install liberpc.a, erpcgen, and include files @@ -238,7 +345,7 @@ eRPC code is validated with respect to the C++ 11 standard. ### Installing for Python -To install the Python infrastructure for eRPC see instructions in the [erpc_python folder readme](erpc_python/readme.md). +To install the Python infrastructure for eRPC see instructions in the [erpc python readme](/erpc_python/readme.md). ## Known issues and limitations diff --git a/doxygen/mainpage_erpc.md b/doxygen/mainpage_erpc.md index a3179645..468cafa5 100644 --- a/doxygen/mainpage_erpc.md +++ b/doxygen/mainpage_erpc.md @@ -9,7 +9,7 @@ When a remote function is called by the client, the function's parameters and an Here is a block diagram of an RPC system: -![](./rpc_block_diagram.png) +![rpc block diagram](./rpc_block_diagram.png) This diagram only shows one direction of communication. It leaves out the reply from the server to send the invoked function's return value. This reply uses basically the same sequence of events, but flows back from the server to the client. diff --git a/erpc_python/readme.md b/erpc_python/readme.md index a8f2b06e..57d09477 100644 --- a/erpc_python/readme.md +++ b/erpc_python/readme.md @@ -7,29 +7,27 @@ protocol level. Also, the classes mirror those in the C++ infrastructure. ## Contents -`erpc` - Python package for eRPC infrastructure. +[erpc](erpc) - Python package for eRPC infrastructure. -`setup.py` - setuptools setup script that installs the erpc package. +[setup.py](setup.py) - setuptools setup script that installs the erpc package. -`setup.cfg, README_Pypi.md` - necessary files for the pypi support. +[setup.cfg](setup.cfg), [README_Pypi.md](README_Pypi.md) - necessary files for the pypi support. ## Installation Pip package installer needs to be installed in your Python version. Use following way for Python3 pip installation: ```sh -sudo apt-get install python3-pip -/usr/bin$ sudo rm python -/usr/bin$ sudo ln -s python3 python +sudo apt-get install python3 python3-pip ``` -To install the eRPC Python infrastructure, run the setup.py script like this (based on your system admin rights are required): +To install the eRPC Python infrastructure from pypi: ```sh -python setup.py install +pip install erpc ``` -Alternatively, you may use pip to install the package, like this: +To install the eRPC Python infrastructure from local folder ([erpc/erpc_python](/erpc_python)): ```sh pip install . diff --git a/erpcgen/test/readme.md b/erpcgen/test/readme.md index c63fa4bf..19033d76 100644 --- a/erpcgen/test/readme.md +++ b/erpcgen/test/readme.md @@ -2,10 +2,7 @@ This file documents the parser and output test system for erpcgen. -This test system is built on py.test using its extensive plugin hooks. To run the tests, just run -py.test in `erpc/erpcgen/test/` directory. It's safer to run py.test with parameter source -directory (from erpcgen directory run: "pytest test"). This prevent on windows to execute -boost test in boost folder. +This test system is built on py.test using its extensive plugin hooks. ## Setup @@ -23,7 +20,19 @@ the VisualStudio project. ## Running Run the tests by running the py.test executable. The tests can be run from either the -`erpc/erpcgen/` or `erpc/erpcgen/test/` directories. +[erpc/erpcgen/](/erpcgen) or [erpc/erpcgen/test/](.) directories. The tests can be also run from root folder defining directory with tests as next parameter. + +Run all tests: + +```bash +$ pytest erpcgen/test +``` + +Run one test + +```bash +$ pytest erpcgen/test/test_union_py.yml +``` Use the `--help` option of py.test to see all available command line options. Useful options are `-s` to turn off output capturing and `-v` to list each test case by name as it runs. The `-k` @@ -35,13 +44,12 @@ such as `--ev=3`. Default verbosity is 0. ## Config -The tests use a config file. The standard config is `erpc/erpcgen/test/config.py`. It tries to -figure out the erpcgen executable location based on the OS. If you need to override this, you can -create a `config_local.py` that defines the config variables listed below. +The tests use a config file. The standard config is [erpc/erpcgen/test/config.py](config.py). It tries to figure out the erpcgen executable location based on the OS. If you need to override this, you can create a `config_local.py` that defines the config variables listed below. Config variables: -- `CC` = C/C++ compiler path, defaults to "gcc" +- `CC` = C compiler path, defaults to "gcc" +- `CXX` = C++ compiler path, defaults to "g++" - `ERPCGEN` = absolute path to the erpcgen executable - `RUN_KEEP_COUNT` = number of historical test runs to retain, not including the most recent run @@ -195,7 +203,7 @@ Here, both not pattern searches range from the last matching character of the po also shows a `not_re` pattern that requires a regular expression to not match within the search range. -## Parametrizatio +## Parametrization If the test spec dictionary has a `params` key, then the spec will be parametrized. The `params` key must have a dictionary value with parameter names for keys. Under each of the parameter names diff --git a/examples/matrix_multiply_tcp_python/readme.md b/examples/matrix_multiply_tcp_python/readme.md index 96f51031..97d34155 100644 --- a/examples/matrix_multiply_tcp_python/readme.md +++ b/examples/matrix_multiply_tcp_python/readme.md @@ -1,38 +1,45 @@ # Overview + This example demonstrates usage of eRPC between two PC's or boards (e.g. i.MX) with Python using TCP transport layer. One side acts like a server and the second as a client. When client starts, it generates two random matrixes and sends them to the server. Server then performs matrix multiplication and sends the result matrix back to the client. Client then prints the result matrix. Example can be ran on Personal computer or on boards with Python installed, e.g. i.MX (i.MX7SD, i.MX6SX, etc.) -# eRPC documentation -eRPC is open-source project stored on github: https://github.com/EmbeddedRPC/erpc -eRPC documentation can be also found in: https://github.com/EmbeddedRPC/erpc/wiki +## eRPC documentation + +- eRPC is open-source project stored on github: [https://github.com/EmbeddedRPC/erpc](https://github.com/EmbeddedRPC/erpc) +- eRPC documentation can be also found in: [https://github.com/EmbeddedRPC/erpc/wiki](https://github.com/EmbeddedRPC/erpc/wiki) + +## Prerequisites -# Prerequisites - Python 3.6+ -# eRPC installation\ -1. run `python setup.py install` in folder `erpc/erpc_python/` +## eRPC installation + +1. run `python setup.py install` in folder [erpc/erpc_python/](/erpc_python) 2. `pip install erpc`: only major eRPC versions are available through pypi -# Example files -- `matrix_multiply.py`: main example file -- `service/erpc_matrix_multiply.erpc`: eRPC IDL file for example -- `service/erpc_matrix_multiply/`: eRPC output shim code generated from IDL file +## Example files + +- [matrix_multiply.py](matrix_multiply.py): main example file +- [service/erpc_matrix_multiply.erpc](service/erpc_matrix_multiply.erpc): eRPC IDL file for example +- [service/erpc_matrix_multiply](service/erpc_matrix_multiply): eRPC output shim code generated from IDL file + +## Running the example -# Running the example -- Run `matrix_multiply.py` with `-s` (or `--server`) parameter to run server -- Run `matrix_multiply.py` with `-c` (or `--client`) parameter to run client +- Run [matrix_multiply.py](matrix_multiply.py) with `-s` (or `--server`) parameter to run server +- Run [matrix_multiply.py](matrix_multiply.py) with `-c` (or `--client`) parameter to run client - Both server and client has to have specified host and port with `-t` (`--host`) and `-p` (`--port`) parameters. By default is host set as localhost and port as 40. -## Example: -``` +### Example + +```bash python matrix_multiply.py --server --host 192.168.1.10 --port 40 python matrix_multiply.py --client --host 192.168.1.10 --port 40 ``` The log below shows the output of the *eRPC Matrix Multiply* example in the terminal window: -``` +```bash $ python matrix_multiply.py --server eRPC Matrix Multiply TCP example Server created on localhost:40 @@ -64,8 +71,9 @@ Result matrix 2055 1290 0680 0721 1848 3147 2226 3742 3531 3585 1147 1988 2731 2047 2535 +``` - +```bash $ python matrix_multiply.py --client eRPC Matrix Multiply TCP example Client connecting to a host on localhost:40 diff --git a/utilities/styles/VSC/vsc-extension-quickstart.md b/utilities/styles/VSC/vsc-extension-quickstart.md index ea360ba6..9e338f3b 100644 --- a/utilities/styles/VSC/vsc-extension-quickstart.md +++ b/utilities/styles/VSC/vsc-extension-quickstart.md @@ -3,13 +3,13 @@ ## What's in the folder * This folder contains all of the files necessary for your extension. -* `package.json` - this is the manifest file in which you declare your language support and define the location of the grammar file that has been copied into your extension. -* `syntaxes/erpc.tmLanguage.json` - this is the Text mate grammar file that is used for tokenization. -* `language-configuration.json` - this is the language configuration, defining the tokens that are used for comments and brackets. +* [package.json](package.json) - this is the manifest file in which you declare your language support and define the location of the grammar file that has been copied into your extension. +* [syntaxes/erpc.tmLanguage.json](syntaxes/erpc.tmLanguage.json) - this is the Text mate grammar file that is used for tokenization. +* [language-configuration.json](language-configuration.json) - this is the language configuration, defining the tokens that are used for comments and brackets. ## Get up and running straight away -* Make sure the language configuration settings in `language-configuration.json` are accurate. +* Make sure the language configuration settings in [language-configuration.json](language-configuration.json) are accurate. * Press `F5` to open a new window with your extension loaded. * Create a new file with a file name suffix matching your language. * Verify that syntax highlighting works and that the language configuration settings are working. From a8a7a0daffdee861ebe752612e792279394a1670 Mon Sep 17 00:00:00 2001 From: Thom747 Date: Fri, 9 Feb 2024 16:27:28 +0100 Subject: [PATCH 18/24] Fix Python client TCPTransports not being able to close (#390) * Fix Python client TCPTransports not being able to close * Shutdown socket before close * Replace unnecessary private import --------- Co-authored-by: Thom van der Steenhoven --- erpc_python/erpc/transport.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/erpc_python/erpc/transport.py b/erpc_python/erpc/transport.py index cc3b33d2..8b98ca45 100644 --- a/erpc_python/erpc/transport.py +++ b/erpc_python/erpc/transport.py @@ -10,6 +10,8 @@ import struct import socket import threading +from socket import SHUT_RDWR + from .crc16 import Crc16 from .client import RequestError import time @@ -166,7 +168,9 @@ def _serve(self): self._serverSockEventStart.set() def close(self): - self._serverSockEventStart.clear() + if self._isServer: + self._serverSockEventStart.clear() + self._sock.shutdown(SHUT_RDWR) self._sock.close() self._sock = None From 61b1b36153f209bc1ac65bb415c725f381cbcb04 Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Fri, 9 Feb 2024 16:33:17 +0100 Subject: [PATCH 19/24] align switch brackets (#396) Signed-off-by: Cervenka Dusan Co-authored-by: Michal Princ --- .../transports/erpc_i2c_slave_transport.cpp | 10 +++ .../transports/erpc_lpi2c_slave_transport.cpp | 8 +++ erpcgen/src/AstNode.cpp | 2 + erpcgen/src/AstWalker.cpp | 34 ++++++++++ erpcgen/src/CGenerator.cpp | 47 ++++++++++++++ erpcgen/src/ErpcLexer.cpp | 22 +++++++ erpcgen/src/HexValues.cpp | 8 +++ erpcgen/src/PythonGenerator.cpp | 43 ++++++++++++- erpcgen/src/SymbolScanner.cpp | 63 ++++++++++++++++++- erpcgen/src/erpcgen.cpp | 26 ++++++++ erpcgen/src/types/Type.cpp | 2 + erpcsniffer/src/Sniffer.cpp | 2 + erpcsniffer/src/erpcsniffer.cpp | 8 +++ test/test_lists/test_lists_client_impl.cpp | 6 ++ test/test_unions/test_unions_server_impl.cpp | 1 + 15 files changed, 280 insertions(+), 2 deletions(-) diff --git a/erpc_c/transports/erpc_i2c_slave_transport.cpp b/erpc_c/transports/erpc_i2c_slave_transport.cpp index b96224f8..d90cb287 100644 --- a/erpc_c/transports/erpc_i2c_slave_transport.cpp +++ b/erpc_c/transports/erpc_i2c_slave_transport.cpp @@ -108,39 +108,49 @@ static void I2C_SlaveUserCallback(I2C_Type *base, volatile i2c_slave_transfer_t { /* Address match event */ case kI2C_SlaveAddressMatchEvent: + { transfer->rxData = NULL; transfer->rxSize = 0; break; + } /* Transmit request */ case kI2C_SlaveTransmitEvent: + { /* Update information for transmit process */ transfer->txData = ((I2C_CLB_USER_DATA *)userData)->tx_buffer; transfer->txSize = ((I2C_CLB_USER_DATA *)userData)->tx_size; transfer->rxData = NULL; transfer->rxSize = 0; break; + } /* Setup the slave receive buffer */ case kI2C_SlaveReceiveEvent: + { /* Update information for received process */ transfer->rxData = ((I2C_CLB_USER_DATA *)userData)->rx_buffer; transfer->rxSize = ((I2C_CLB_USER_DATA *)userData)->rx_size; transfer->txData = NULL; transfer->txSize = 0; break; + } /* The master has sent a stop transition on the bus */ case kI2C_SlaveCompletionEvent: + { transport->transfer_cb(); transfer->rxData = NULL; transfer->rxSize = 0; transfer->txData = NULL; transfer->txSize = 0; break; + } default: + { s_isTransferCompleted = false; break; + } } } diff --git a/erpc_c/transports/erpc_lpi2c_slave_transport.cpp b/erpc_c/transports/erpc_lpi2c_slave_transport.cpp index 6a2a6769..5b618dd2 100644 --- a/erpc_c/transports/erpc_lpi2c_slave_transport.cpp +++ b/erpc_c/transports/erpc_lpi2c_slave_transport.cpp @@ -108,20 +108,25 @@ static void LPI2C_SlaveUserCallback(LPI2C_Type *base, lpi2c_slave_transfer_t *tr { /* Transmit request */ case kLPI2C_SlaveTransmitEvent: + { /* Update information for transmit process */ transfer->data = ((LPI2C_CLB_USER_DATA *)userData)->tx_buffer; transfer->dataSize = ((LPI2C_CLB_USER_DATA *)userData)->tx_size; break; + } /* Setup the slave receive buffer */ case kLPI2C_SlaveReceiveEvent: + { /* Update information for received process */ transfer->data = ((LPI2C_CLB_USER_DATA *)userData)->rx_buffer; transfer->dataSize = ((LPI2C_CLB_USER_DATA *)userData)->rx_size; break; + } /* The master has sent a stop transition on the bus */ case kLPI2C_SlaveCompletionEvent: + { /* Filter out dummy transaction completions (additional dummy recv./transmit) */ if (!(transfer->transferredCount == 0 && transfer->dataSize == 0) && transfer->data != NULL) { @@ -130,10 +135,13 @@ static void LPI2C_SlaveUserCallback(LPI2C_Type *base, lpi2c_slave_transfer_t *tr transfer->dataSize = 0; } break; + } default: + { s_isTransferCompleted = false; break; + } } } diff --git a/erpcgen/src/AstNode.cpp b/erpcgen/src/AstNode.cpp index 05b868b7..278487c2 100644 --- a/erpcgen/src/AstNode.cpp +++ b/erpcgen/src/AstNode.cpp @@ -217,7 +217,9 @@ string AstNode::getDescription() const case TOK_UNARY_NEGATE: case TOK_ARRAY: case TOK_UNION_CASE: + { break; + } default: { output += " " + valToString + " "; diff --git a/erpcgen/src/AstWalker.cpp b/erpcgen/src/AstWalker.cpp index 2d898d6c..a473bb46 100644 --- a/erpcgen/src/AstWalker.cpp +++ b/erpcgen/src/AstWalker.cpp @@ -62,49 +62,79 @@ void AstWalker::dispatch(AstNode *node) switch (tok.getToken()) { case TOK_PROGRAM: + { rewrite = handleProgram(node, dir); break; + } case TOK_CHILDREN: + { break; + } case TOK_TYPE: + { rewrite = handleType(node, dir); break; + } case TOK_ENUM: + { rewrite = handleEnum(node, dir); break; + } case TOK_ENUM_MEMBER: + { rewrite = handleEnumMember(node, dir); break; + } case TOK_STRUCT: + { rewrite = handleStruct(node, dir); break; + } case TOK_STRUCT_MEMBER: + { rewrite = handleStructMember(node, dir); break; + } case TOK_UNION: + { rewrite = handleUnion(node, dir); break; + } case TOK_UNION_CASE: + { rewrite = handleUnionCase(node, dir); break; + } case TOK_INTERFACE: + { rewrite = handleInterface(node, dir); break; + } case TOK_FUNCTION: + { rewrite = handleFunction(node, dir); break; + } case TOK_PARAM: + { rewrite = handleParam(node, dir); break; + } case TOK_CONST: + { rewrite = handleConst(node, dir); break; + } case TOK_EXPR: + { rewrite = handleExpr(node, dir); break; + } case TOK_ANNOTATION: + { rewrite = handleAnnotation(node, dir); break; + } case '+': case '-': case '*': @@ -115,12 +145,16 @@ void AstWalker::dispatch(AstNode *node) case '^': case TOK_LSHIFT: case TOK_RSHIFT: + { rewrite = handleBinaryOp(node, dir); break; + } case TOK_UNARY_NEGATE: case '~': + { rewrite = handleUnaryOp(node, dir); break; + } } if (rewrite) diff --git a/erpcgen/src/CGenerator.cpp b/erpcgen/src/CGenerator.cpp index f891a06a..16b86311 100644 --- a/erpcgen/src/CGenerator.cpp +++ b/erpcgen/src/CGenerator.cpp @@ -821,7 +821,9 @@ void CGenerator::makeAliasesTemplateData() break; } default: + { throw internal_error("Only structs or enums are allowed as unnamed types."); + } } } aliases.push_back(aliasInfo); @@ -2268,8 +2270,11 @@ string CGenerator::getTypenameName(DataType *t, const string &name) break; } default: + { throw internal_error(format_string("In getTypenameName: unknown data type: %s value:%d", t->getName().c_str(), t->getDataType())); + break; + } } return returnName; } @@ -2279,35 +2284,65 @@ string CGenerator::getBuiltinTypename(const BuiltinType *t) switch (t->getBuiltinType()) { case BuiltinType::builtin_type_t::kBoolType: + { return "bool"; + } case BuiltinType::builtin_type_t::kInt8Type: + { return "int8_t"; + } case BuiltinType::builtin_type_t::kInt16Type: + { return "int16_t"; + } case BuiltinType::builtin_type_t::kInt32Type: + { return "int32_t"; + } case BuiltinType::builtin_type_t::kInt64Type: + { return "int64_t"; + } case BuiltinType::builtin_type_t::kUInt8Type: + { return "uint8_t"; + } case BuiltinType::builtin_type_t::kUInt16Type: + { return "uint16_t"; + } case BuiltinType::builtin_type_t::kUInt32Type: + { return "uint32_t"; + } case BuiltinType::builtin_type_t::kUInt64Type: + { return "uint64_t"; + } case BuiltinType::builtin_type_t::kFloatType: + { return "float"; + } case BuiltinType::builtin_type_t::kDoubleType: + { return "double"; + } case BuiltinType::builtin_type_t::kStringType: + { return "char *"; + } case BuiltinType::builtin_type_t::kUStringType: + { return "unsigned char*"; + } case BuiltinType::builtin_type_t::kBinaryType: + { return "uint8_t *"; + } default: + { throw internal_error("unknown builtin type"); + } } } @@ -3039,7 +3074,9 @@ bool CGenerator::isNeedCallFree(DataType *dataType) return false; } default: + { return false; + } } } @@ -3422,15 +3459,25 @@ string CGenerator::getDirection(param_direction_t direction) switch (direction) { case param_direction_t::kInDirection: + { return "kInDirection"; + } case param_direction_t::kOutDirection: + { return "kOutDirection"; + } case param_direction_t::kInoutDirection: + { return "kInoutDirection"; + } case param_direction_t::kReturn: + { return "kReturn"; + } default: + { throw semantic_error("Unsupported direction type"); + } } } diff --git a/erpcgen/src/ErpcLexer.cpp b/erpcgen/src/ErpcLexer.cpp index d3763b86..4883fbf3 100644 --- a/erpcgen/src/ErpcLexer.cpp +++ b/erpcgen/src/ErpcLexer.cpp @@ -82,7 +82,9 @@ int ErpcLexer::processStringEscapes(const char *in, char *out) switch (c) { case 0: // end of the string, bail + { break; + } case 'x': { // start of a hex char escape sequence @@ -90,10 +92,14 @@ int ErpcLexer::processStringEscapes(const char *in, char *out) // read high and low nibbles, checking for end of string char hi = *++in; if (hi == 0) + { break; + } char lo = *++in; if (lo == 0) + { break; + } if (isHexDigit(hi) && isHexDigit(lo)) { @@ -111,41 +117,57 @@ int ErpcLexer::processStringEscapes(const char *in, char *out) break; } case 'n': + { *out++ = '\n'; count++; break; + } case 't': + { *out++ = '\t'; count++; break; + } case 'r': + { *out++ = '\r'; count++; break; + } case 'b': + { *out++ = '\b'; count++; break; + } case 'f': + { *out++ = '\f'; count++; break; + } case '0': + { *out++ = '\0'; count++; break; + } default: + { *out++ = c; count++; break; + } } break; } default: + { // copy all other chars directly *out++ = *in++; count++; + } } } diff --git a/erpcgen/src/HexValues.cpp b/erpcgen/src/HexValues.cpp index a1190993..63e5fb58 100644 --- a/erpcgen/src/HexValues.cpp +++ b/erpcgen/src/HexValues.cpp @@ -21,13 +21,21 @@ bool isHexDigit(char c) uint8_t hexCharToInt(char c) { if (c >= '0' && c <= '9') + { return c - '0'; + } else if (c >= 'a' && c <= 'f') + { return c - 'a' + 10; + } else if (c >= 'A' && c <= 'F') + { return c - 'A' + 10; + } else + { return static_cast(-1); + } } //! \param encodedByte Must point to at least two ASCII hex characters. diff --git a/erpcgen/src/PythonGenerator.cpp b/erpcgen/src/PythonGenerator.cpp index 3c1f581f..680c5e89 100644 --- a/erpcgen/src/PythonGenerator.cpp +++ b/erpcgen/src/PythonGenerator.cpp @@ -237,20 +237,29 @@ data_map PythonGenerator::getFunctionTemplateData(Group *group, Function *fn) switch (dir) { case param_direction_t::kInDirection: + { paramInfo["direction"] = "in"; inParams.push_back(paramInfo); break; + } case param_direction_t::kOutDirection: + { paramInfo["direction"] = "out"; outParams.push_back(paramInfo); break; + } case param_direction_t::kInoutDirection: + { paramInfo["direction"] = "inout"; inParams.push_back(paramInfo); outParams.push_back(paramInfo); break; + } default: + { paramInfo["direction"] = "none"; + break; + } } params.push_back(paramInfo); @@ -516,7 +525,9 @@ data_map PythonGenerator::makeGroupSymbolsTemplateData(Group *group) break; } default: + { break; + } } } } @@ -701,7 +712,7 @@ data_map PythonGenerator::getTypeInfo(DataType *t) { EnumType *enumType = dynamic_cast(it); assert(enumType); - for (auto itMember : enumType->getMembers()) + for (const auto itMember : enumType->getMembers()) { if (unionCase->getCaseName() == itMember->getName()) { @@ -777,7 +788,9 @@ data_map PythonGenerator::getTypeInfo(DataType *t) break; } default: + { throw internal_error("unknown data type"); + } } return info; } @@ -787,33 +800,61 @@ string PythonGenerator::getBuiltinTypename(const BuiltinType *t) switch (t->getBuiltinType()) { case BuiltinType::builtin_type_t::kBoolType: + { return "bool"; + } case BuiltinType::builtin_type_t::kInt8Type: + { return "int8"; + } case BuiltinType::builtin_type_t::kInt16Type: + { return "int16"; + } case BuiltinType::builtin_type_t::kInt32Type: + { return "int32"; + } case BuiltinType::builtin_type_t::kInt64Type: + { return "int64"; + } case BuiltinType::builtin_type_t::kUInt8Type: + { return "uint8"; + } case BuiltinType::builtin_type_t::kUInt16Type: + { return "uint16"; + } case BuiltinType::builtin_type_t::kUInt32Type: + { return "uint32"; + } case BuiltinType::builtin_type_t::kUInt64Type: + { return "uint64"; + } case BuiltinType::builtin_type_t::kFloatType: + { return "float"; + } case BuiltinType::builtin_type_t::kDoubleType: + { return "double"; + } case BuiltinType::builtin_type_t::kStringType: + { return "string"; + } case BuiltinType::builtin_type_t::kBinaryType: + { return "binary"; + } default: + { throw internal_error("unknown builtin type"); + } } } diff --git a/erpcgen/src/SymbolScanner.cpp b/erpcgen/src/SymbolScanner.cpp index c47b5f23..9b752654 100644 --- a/erpcgen/src/SymbolScanner.cpp +++ b/erpcgen/src/SymbolScanner.cpp @@ -406,15 +406,22 @@ AstNode *SymbolScanner::handleBinaryOp(AstNode *node, bottom_up) switch (tok.getToken()) { case '+': + { result = l + r; break; + } case '-': + { result = l - r; break; + } case '*': + { result = l * r; break; + } case '/': + { // Just make the result a zero if div-by-zero. if (r == 0) { @@ -425,7 +432,9 @@ AstNode *SymbolScanner::handleBinaryOp(AstNode *node, bottom_up) result = l / r; } break; + } case '%': + { // Just make the result a zero if div-by-zero. if (r == 0) { @@ -436,23 +445,36 @@ AstNode *SymbolScanner::handleBinaryOp(AstNode *node, bottom_up) result = l % r; } break; + } case '&': + { result = l & r; break; + } case '|': + { result = l | r; break; + } case '^': + { result = l ^ r; break; + } case TOK_LSHIFT: + { result = l << r; break; + } case TOK_RSHIFT: + { result = l >> r; break; + } default: + { throw internal_error("unknown binary operator"); + } } IntegerValue::int_type_t intType; @@ -504,15 +526,22 @@ AstNode *SymbolScanner::handleBinaryOp(AstNode *node, bottom_up) switch (tok.getToken()) { case '+': + { result = l + r; break; + } case '-': + { result = l - r; break; + } case '*': + { result = l * r; break; + } case '/': + { /* Just make the result a zero if div-by-zero. */ if (r == 0) { @@ -523,6 +552,7 @@ AstNode *SymbolScanner::handleBinaryOp(AstNode *node, bottom_up) result = l / r; } break; + } /* Throw semantic error on invalid operators for floats. */ case '%': @@ -531,9 +561,13 @@ AstNode *SymbolScanner::handleBinaryOp(AstNode *node, bottom_up) case '^': case TOK_LSHIFT: case TOK_RSHIFT: + { throw semantic_error(format_string("line %d: invalid operator on float value", tok.getFirstLine())); + } default: + { throw internal_error("unknown binary operator"); + } } resultNode = new AstNode(Token(TOK_FLOAT_LITERAL, new FloatValue(result))); @@ -579,13 +613,19 @@ AstNode *SymbolScanner::handleUnaryOp(AstNode *node, bottom_up) switch (tok.getToken()) { case TOK_UNARY_NEGATE: + { value = (-(int64_t)(value)); break; + } case '~': + { value = ~value; break; + } default: + { throw internal_error("unknown unary operator"); + } } return new AstNode(Token(TOK_INT_LITERAL, new IntegerValue(value, valueInt->getIntType()))); @@ -596,15 +636,21 @@ AstNode *SymbolScanner::handleUnaryOp(AstNode *node, bottom_up) switch (tok.getToken()) { case TOK_UNARY_NEGATE: + { value = -value; return new AstNode(Token(TOK_FLOAT_LITERAL, new FloatValue(value))); + } // It is a semantic error to use the binary invert operator on a float. case '~': + { throw semantic_error(format_string("line %d: invalid operator on float value", tok.getFirstLine())); + } default: + { throw internal_error("unknown unary operator"); + } } } @@ -1116,18 +1162,24 @@ AstNode *SymbolScanner::handleFunction(AstNode *node, top_down) switch (returnTypeToken.getToken()) { case TOK_ONEWAY: + { func->setIsOneway(true); func->setReturnStructMemberType(new StructMember("(return)", new VoidType)); break; + } case TOK_VOID: + { func->setReturnStructMemberType(new StructMember("(return)", new VoidType)); break; + } default: + { DataType *dataType = lookupDataType(returnTypeNode); func->setReturnStructMemberType(new StructMember("(return)", dataType)); break; + } } if (returnTypeToken.getToken() != TOK_ONEWAY) { @@ -1382,19 +1434,26 @@ void SymbolScanner::setParameterDirection(StructMember *param, AstNode *directio switch (directionNode->getToken().getToken()) { case TOK_IN: + { param_direction = param_direction_t::kInDirection; break; + } case TOK_OUT: + { param_direction = param_direction_t::kOutDirection; break; + } case TOK_INOUT: + { param_direction = param_direction_t::kInoutDirection; break; + } default: + { delete param; throw semantic_error(format_string("line %d: expected parameter direction type", directionNode->getToken().getFirstLine())); - break; + } } } else /* if no direction specified, default case is an 'in' variable */ @@ -1474,8 +1533,10 @@ DataType *SymbolScanner::lookupDataType(const AstNode *typeNode) return lookupDataTypeByName(typeNode->getChild(3)->getToken(), &(m_currentStruct->getScope()), false); } default: + { throw internal_error(format_string("unexpected token type %s on line %d", typeToken.getTokenName(), typeToken.getLocation().m_firstLine)); + } } } diff --git a/erpcgen/src/erpcgen.cpp b/erpcgen/src/erpcgen.cpp index e5288c72..fe520d2c 100644 --- a/erpcgen/src/erpcgen.cpp +++ b/erpcgen/src/erpcgen.cpp @@ -171,27 +171,37 @@ class erpcgenTool switch (optchar) { case '?': + { printUsage(options); return 0; + } case 'V': + { printf("%s %s\n%s\n", k_toolName, k_version, k_copyright); return 0; + } case 'o': + { m_outputFilePath = optarg; break; + } case 'v': + { if (m_verboseType != verbose_type_t::kExtraDebug) { m_verboseType = (verbose_type_t)(((int)m_verboseType) + 1); } break; + } case 'I': + { PathSearcher::getGlobalSearcher().addSearchPath(optarg); break; + } case 'g': { @@ -238,9 +248,11 @@ class erpcgenTool } default: + { Log::error("error: unrecognized option\n\n"); printUsage(options); return 0; + } } } @@ -325,15 +337,21 @@ class erpcgenTool switch (m_outputLanguage) { case languages_t::kCLanguage: + { CGenerator(&def).generate(); break; + } case languages_t::kPythonLanguage: + { PythonGenerator(&def).generate(); break; + } case languages_t::kJavaLanguage: + { // TODO: Check java package JavaGenerator(&def, m_javaPackageName).generate(); break; + } } } catch (exception &e) @@ -373,17 +391,25 @@ class erpcgenTool switch (m_verboseType) { case verbose_type_t::kWarning: + { Log::getLogger()->setFilterLevel(Logger::log_level_t::kWarning); break; + } case verbose_type_t::kInfo: + { Log::getLogger()->setFilterLevel(Logger::log_level_t::kInfo); break; + } case verbose_type_t::kDebug: + { Log::getLogger()->setFilterLevel(Logger::log_level_t::kDebug); break; + } case verbose_type_t::kExtraDebug: + { Log::getLogger()->setFilterLevel(Logger::log_level_t::kDebug2); break; + } } } }; diff --git a/erpcgen/src/types/Type.cpp b/erpcgen/src/types/Type.cpp index 78ba49f7..748d6a25 100644 --- a/erpcgen/src/types/Type.cpp +++ b/erpcgen/src/types/Type.cpp @@ -488,7 +488,9 @@ DataType *DataType::getTrueContainerDataType() return a->getElementType()->getTrueContainerDataType(); } default: + { return trueDataType; + } } } diff --git a/erpcsniffer/src/Sniffer.cpp b/erpcsniffer/src/Sniffer.cpp index fd363a92..5e7007b7 100644 --- a/erpcsniffer/src/Sniffer.cpp +++ b/erpcsniffer/src/Sniffer.cpp @@ -690,7 +690,9 @@ string Sniffer::getDataTypeName(DataType *dataType) return "void"; } default: + { return dataType->getName(); + } } } diff --git a/erpcsniffer/src/erpcsniffer.cpp b/erpcsniffer/src/erpcsniffer.cpp index 80b94735..5839084a 100644 --- a/erpcsniffer/src/erpcsniffer.cpp +++ b/erpcsniffer/src/erpcsniffer.cpp @@ -415,17 +415,25 @@ class erpcsnifferTool switch (m_verboseType) { case verbose_type_t::kWarning: + { Log::getLogger()->setFilterLevel(Logger::log_level_t::kWarning); break; + } case verbose_type_t::kInfo: + { Log::getLogger()->setFilterLevel(Logger::log_level_t::kInfo); break; + } case verbose_type_t::kDebug: + { Log::getLogger()->setFilterLevel(Logger::log_level_t::kDebug); break; + } case verbose_type_t::kExtraDebug: + { Log::getLogger()->setFilterLevel(Logger::log_level_t::kDebug2); break; + } } } }; diff --git a/test/test_lists/test_lists_client_impl.cpp b/test/test_lists/test_lists_client_impl.cpp index f648712a..f6706d65 100644 --- a/test/test_lists/test_lists_client_impl.cpp +++ b/test/test_lists/test_lists_client_impl.cpp @@ -205,14 +205,20 @@ TEST(test_list, SendReceived2Enum) switch (j) { case 0: + { *list_s = red; break; + } case 1: + { *list_s = green; break; + } case 2: + { *list_s = blue; break; + } } ++list_s; } diff --git a/test/test_unions/test_unions_server_impl.cpp b/test/test_unions/test_unions_server_impl.cpp index 8c2140d1..55c2d785 100644 --- a/test/test_unions/test_unions_server_impl.cpp +++ b/test/test_unions/test_unions_server_impl.cpp @@ -87,6 +87,7 @@ gapGenericEvent_t *testGenericCallback(const gapGenericEvent_t *event) case gAdvTxPowerLevelRead_c: default: { + break; } } return newEvent; From ddb44676205608507f5606ba2fa065767a6fed0e Mon Sep 17 00:00:00 2001 From: Dusan Cervenka Date: Mon, 12 Feb 2024 07:55:32 +0100 Subject: [PATCH 20/24] Remove cstbool library (#403) https://en.cppreference.com/w/cpp/header/cstdbool Signed-off-by: Cervenka Dusan --- erpc_c/transports/erpc_spi_master_transport.hpp | 1 - erpcgen/src/HexValues.hpp | 1 - erpcgen/src/templates/c_common_header.template | 1 - .../remote/src/service/erpc_matrix_multiply_common.hpp | 1 - .../src/service/erpc_matrix_multiply_common.hpp | 1 - .../src/service/erpc_matrix_multiply_common.hpp | 1 - 6 files changed, 6 deletions(-) diff --git a/erpc_c/transports/erpc_spi_master_transport.hpp b/erpc_c/transports/erpc_spi_master_transport.hpp index e2de9bae..1c81ba63 100644 --- a/erpc_c/transports/erpc_spi_master_transport.hpp +++ b/erpc_c/transports/erpc_spi_master_transport.hpp @@ -12,7 +12,6 @@ #include "erpc_framed_transport.hpp" -#include #include extern "C" { diff --git a/erpcgen/src/HexValues.hpp b/erpcgen/src/HexValues.hpp index 9433504e..63153260 100644 --- a/erpcgen/src/HexValues.hpp +++ b/erpcgen/src/HexValues.hpp @@ -9,7 +9,6 @@ #if !defined(_HexValues_h_) #define _HexValues_h_ -#include #include //! \brief Determines whether \a c is a hex digit character. diff --git a/erpcgen/src/templates/c_common_header.template b/erpcgen/src/templates/c_common_header.template index 2083bbd2..9e203662 100644 --- a/erpcgen/src/templates/c_common_header.template +++ b/erpcgen/src/templates/c_common_header.template @@ -26,7 +26,6 @@ extern "C" #include #include {% else %} -#include #include #include {% endif %} diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.hpp index d1b16374..994cfce5 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.hpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.hpp @@ -17,7 +17,6 @@ #define _erpc_matrix_multiply_common_hpp_ -#include #include #include diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.hpp index d1b16374..994cfce5 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.hpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.hpp @@ -17,7 +17,6 @@ #define _erpc_matrix_multiply_common_hpp_ -#include #include #include diff --git a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.hpp index d1b16374..994cfce5 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.hpp +++ b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.hpp @@ -17,7 +17,6 @@ #define _erpc_matrix_multiply_common_hpp_ -#include #include #include From 8e55ad616a403ca5aee9d9869740655cfb0ec96f Mon Sep 17 00:00:00 2001 From: Gabbla Date: Thu, 22 Feb 2024 17:26:13 +0100 Subject: [PATCH 21/24] transport: fix zephyr uart transport. See #409 --- erpc_c/transports/erpc_uart_zephyr_transport.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/erpc_c/transports/erpc_uart_zephyr_transport.cpp b/erpc_c/transports/erpc_uart_zephyr_transport.cpp index fe08982a..5f50c931 100644 --- a/erpc_c/transports/erpc_uart_zephyr_transport.cpp +++ b/erpc_c/transports/erpc_uart_zephyr_transport.cpp @@ -153,7 +153,7 @@ erpc_status_t UartTransport::init(void) erpc_status_t UartTransport::underlyingReceive(uint8_t *data, uint32_t size) { - erpc_status_t erpcStatus = kErpcStatus_ReceiveFailed; + erpc_status_t erpcStatus = kErpcStatus_Success; if (ring_buf_size_get(&uart_receive_buf) < size) { @@ -168,7 +168,6 @@ erpc_status_t UartTransport::underlyingReceive(uint8_t *data, uint32_t size) { } #endif - erpcStatus = kErpcStatus_Success; } /* read data from buffer */ From f9af0f6e14c5cc9c26333b7ac5915eeb01421529 Mon Sep 17 00:00:00 2001 From: amgross <33063505+amgross@users.noreply.github.com> Date: Tue, 19 Mar 2024 10:06:28 +0200 Subject: [PATCH 22/24] Add BSD-3 license to endianness agnostic files (#417) Co-authored-by: amgross --- erpc_c/port/erpc_endianness_agnostic_example.h | 4 ++++ erpc_c/port/erpc_endianness_undefined.h | 3 +++ 2 files changed, 7 insertions(+) diff --git a/erpc_c/port/erpc_endianness_agnostic_example.h b/erpc_c/port/erpc_endianness_agnostic_example.h index ce4daa89..fe41dafb 100644 --- a/erpc_c/port/erpc_endianness_agnostic_example.h +++ b/erpc_c/port/erpc_endianness_agnostic_example.h @@ -1,3 +1,7 @@ +/* + * SPDX-License-Identifier: BSD-3-Clause + */ + /* * This is example file for endianness agnostic communication based on byteswap.h. * Other approach can be done with htons(), htonl(), ntohs(), ntohl() and such. diff --git a/erpc_c/port/erpc_endianness_undefined.h b/erpc_c/port/erpc_endianness_undefined.h index df35d48a..505243fb 100644 --- a/erpc_c/port/erpc_endianness_undefined.h +++ b/erpc_c/port/erpc_endianness_undefined.h @@ -1,3 +1,6 @@ +/* + * SPDX-License-Identifier: BSD-3-Clause + */ #ifndef _ERPC_ENDIANNESS_UNDEFINED_H_ #define _ERPC_ENDIANNESS_UNDEFINED_H_ From 46308229b33abd650206740eefe729d9dd5d5911 Mon Sep 17 00:00:00 2001 From: Rene Becker <77767676+rene-becker-setec@users.noreply.github.com> Date: Wed, 17 Apr 2024 17:29:28 +1000 Subject: [PATCH 23/24] fix for issue 420: UART ZEPHYR Transport will (most likely) stop to work after a few transactions when using USB-CDC (#421) * fix for issue 420 fixes issue 420. Not yet happy about error handling though .... fixes: https://github.com/EmbeddedRPC/erpc/issues/420 * fix formatting * fixing formatting 2nd attempt this time replacing file with one provided via https://github.com/EmbeddedRPC/erpc/pull/421#issuecomment-2051754199 --- .../transports/erpc_uart_zephyr_transport.cpp | 413 +++++++++--------- 1 file changed, 206 insertions(+), 207 deletions(-) diff --git a/erpc_c/transports/erpc_uart_zephyr_transport.cpp b/erpc_c/transports/erpc_uart_zephyr_transport.cpp index 5f50c931..ee1f3b40 100644 --- a/erpc_c/transports/erpc_uart_zephyr_transport.cpp +++ b/erpc_c/transports/erpc_uart_zephyr_transport.cpp @@ -1,207 +1,206 @@ -/* - * Copyright 2023 NXP - * - * - * SPDX-License-Identifier: BSD-3-Clause - */ - -#include "erpc_uart_zephyr_transport.hpp" -#include -#include -#include - -using namespace erpc; - -//////////////////////////////////////////////////////////////////////////////// -// Variables -//////////////////////////////////////////////////////////////////////////////// - -static volatile bool s_isTransferReceiveCompleted = false; -static volatile bool s_isTransferSendCompleted = false; -static volatile uint32_t s_transferReceiveRequireBytes = 0; -static UartTransport *s_uart_instance = NULL; - -#define UART_BUFFER_SIZE ERPC_DEFAULT_BUFFER_SIZE - -RING_BUF_DECLARE(uart_receive_buf, UART_BUFFER_SIZE); -RING_BUF_DECLARE(uart_send_buf, UART_BUFFER_SIZE); - -//////////////////////////////////////////////////////////////////////////////// -// Code -//////////////////////////////////////////////////////////////////////////////// - -UartTransport::UartTransport(struct device *dev) : -m_dev(dev) -#if !ERPC_THREADS_IS(NONE) -, -m_rxSemaphore(), m_txSemaphore() -#endif -{ - s_uart_instance = this; -} - -UartTransport::~UartTransport(void) {} - -void UartTransport::tx_cb(void) -{ -#if !ERPC_THREADS_IS(NONE) - m_txSemaphore.put(); -#else - s_isTransferSendCompleted = true; -#endif -} - -void UartTransport::rx_cb(void) -{ -#if !ERPC_THREADS_IS(NONE) - m_rxSemaphore.put(); -#else - s_isTransferReceiveCompleted = true; -#endif - s_transferReceiveRequireBytes = UART_BUFFER_SIZE; -} - -/* Transfer callback */ -static void TransferCallback(const struct device *dev, void *user_data) -{ - uint8_t c; - uint32_t size; - uint32_t rx_size; - uint32_t tx_size; - uint8_t *data; - int err; - - if (!uart_irq_update(dev)) - { - return; - } - - if (uart_irq_rx_ready(dev)) - { - size = ring_buf_put_claim(&uart_receive_buf, &data, UART_BUFFER_SIZE); - - /* read until FIFO empty */ - rx_size = uart_fifo_read(dev, data, size); - - if (rx_size < 0) - { - /* Error */ - } - - if (rx_size == size) - { - if (uart_fifo_read(dev, &c, 1) == 1) - { - /* Error - more data in fifo */ - } - } - - err = ring_buf_put_finish(&uart_receive_buf, rx_size); - if (err != 0) - { - /* This shouldn't happen unless rx_size > size */ - } - - /* Enough bytes was received, call receive callback */ - if (ring_buf_size_get(&uart_receive_buf) >= s_transferReceiveRequireBytes) - { - s_uart_instance->rx_cb(); - } - } - - if (uart_irq_tx_ready(dev) && ring_buf_size_get(&uart_send_buf) > 0) - { - /* read one byte from queue */ - size = ring_buf_get_claim(&uart_send_buf, &data, UART_BUFFER_SIZE); - - /* send it thought UART */ - tx_size = uart_fifo_fill(dev, data, size); - if (tx_size < 0) - { - /* Error */ - } - - err = ring_buf_get_finish(&uart_send_buf, tx_size); - if (err != 0) - { - /* bytes_send exceeds amount of valid data in a ring buffer. */ - } - - if (ring_buf_size_get(&uart_send_buf) == 0) - { - /* no more bytes to send; disable tx interrupt */ - uart_irq_tx_disable(dev); - s_uart_instance->tx_cb(); - } - } -} - -erpc_status_t UartTransport::init(void) -{ - erpc_status_t erpcStatus = kErpcStatus_InitFailed; - - int32_t status = uart_irq_callback_user_data_set(m_dev, TransferCallback, this); - - if (status == 0) - { - uart_irq_rx_enable(m_dev); - erpcStatus = kErpcStatus_Success; - } - - return erpcStatus; -} - -erpc_status_t UartTransport::underlyingReceive(uint8_t *data, uint32_t size) -{ - erpc_status_t erpcStatus = kErpcStatus_Success; - - if (ring_buf_size_get(&uart_receive_buf) < size) - { - s_transferReceiveRequireBytes = size; - -/* wait until the receiving is finished */ -#if !ERPC_THREADS_IS(NONE) - (void)m_rxSemaphore.get(); -#else - s_isTransferReceiveCompleted = false; - while (!s_isTransferReceiveCompleted) - { - } -#endif - } - - /* read data from buffer */ - if (ring_buf_get(&uart_receive_buf, data, size) != size) - { - /* reading error, should not happen */ - erpcStatus = kErpcStatus_ReceiveFailed; - } - - return erpcStatus; -} - -erpc_status_t UartTransport::underlyingSend(const uint8_t *data, uint32_t size) -{ - erpc_status_t erpcStatus = kErpcStatus_SendFailed; - - s_isTransferSendCompleted = false; - - /* fill buffer */ - ring_buf_put(&uart_send_buf, data, size); - - /* enable transport */ - uart_irq_tx_enable(m_dev); - -/* wait until the sending is finished */ -#if !ERPC_THREADS_IS(NONE) - (void)m_txSemaphore.get(); -#else - while (!s_isTransferSendCompleted) - { - } -#endif - - erpcStatus = kErpcStatus_Success; - - return erpcStatus; -} +/* + * Copyright 2023 NXP + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_uart_zephyr_transport.hpp" +#include +#include +#include + +using namespace erpc; + +//////////////////////////////////////////////////////////////////////////////// +// Variables +//////////////////////////////////////////////////////////////////////////////// + +static volatile bool s_isTransferReceiveCompleted = false; +static volatile bool s_isTransferSendCompleted = false; +static volatile uint32_t s_transferReceiveRequireBytes = 0; +static UartTransport *s_uart_instance = NULL; + +#define UART_BUFFER_SIZE ERPC_DEFAULT_BUFFER_SIZE + +RING_BUF_DECLARE(uart_receive_buf, UART_BUFFER_SIZE); +RING_BUF_DECLARE(uart_send_buf, UART_BUFFER_SIZE); + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +UartTransport::UartTransport(struct device *dev) : +m_dev(dev) +#if !ERPC_THREADS_IS(NONE) +, +m_rxSemaphore(), m_txSemaphore() +#endif +{ + s_uart_instance = this; +} + +UartTransport::~UartTransport(void) {} + +void UartTransport::tx_cb(void) +{ +#if !ERPC_THREADS_IS(NONE) + m_txSemaphore.put(); +#else + s_isTransferSendCompleted = true; +#endif +} + +void UartTransport::rx_cb(void) +{ +#if !ERPC_THREADS_IS(NONE) + m_rxSemaphore.put(); +#else + s_isTransferReceiveCompleted = true; +#endif + s_transferReceiveRequireBytes = UART_BUFFER_SIZE; +} + +/* Transfer callback */ +static void TransferCallback(const struct device *dev, void *user_data) +{ + uint32_t size; + uint32_t rx_size; + uint32_t tx_size; + uint8_t *data; + int err; + + if (!uart_irq_update(dev)) + { + return; + } + + if (uart_irq_rx_ready(dev)) + { + do + { + if (ring_buf_space_get(&uart_receive_buf) == 0) + { + /* Error - receive buffer is full */ + } + + size = ring_buf_put_claim(&uart_receive_buf, &data, UART_BUFFER_SIZE); + + /* read until FIFO empty */ + rx_size = uart_fifo_read(dev, data, size); + if (rx_size < 0) + { + /* Error */ + } + + err = ring_buf_put_finish(&uart_receive_buf, rx_size); + if (err != 0) + { + /* This shouldn't happen unless rx_size > size */ + } + + } while (rx_size == size); + + /* Enough bytes was received, call receive callback */ + if (ring_buf_size_get(&uart_receive_buf) >= s_transferReceiveRequireBytes) + { + s_uart_instance->rx_cb(); + } + } + + if (uart_irq_tx_ready(dev) && ring_buf_size_get(&uart_send_buf) > 0) + { + /* read one byte from queue */ + size = ring_buf_get_claim(&uart_send_buf, &data, UART_BUFFER_SIZE); + + /* send it thought UART */ + tx_size = uart_fifo_fill(dev, data, size); + if (tx_size < 0) + { + /* Error */ + } + + err = ring_buf_get_finish(&uart_send_buf, tx_size); + if (err != 0) + { + /* bytes_send exceeds amount of valid data in a ring buffer. */ + } + + if (ring_buf_size_get(&uart_send_buf) == 0) + { + /* no more bytes to send; disable tx interrupt */ + uart_irq_tx_disable(dev); + s_uart_instance->tx_cb(); + } + } +} + +erpc_status_t UartTransport::init(void) +{ + erpc_status_t erpcStatus = kErpcStatus_InitFailed; + + int32_t status = uart_irq_callback_user_data_set(m_dev, TransferCallback, this); + + if (status == 0) + { + uart_irq_rx_enable(m_dev); + erpcStatus = kErpcStatus_Success; + } + + return erpcStatus; +} + +erpc_status_t UartTransport::underlyingReceive(uint8_t *data, uint32_t size) +{ + erpc_status_t erpcStatus = kErpcStatus_Success; + + if (ring_buf_size_get(&uart_receive_buf) < size) + { + s_transferReceiveRequireBytes = size; + +/* wait until the receiving is finished */ +#if !ERPC_THREADS_IS(NONE) + (void)m_rxSemaphore.get(); +#else + s_isTransferReceiveCompleted = false; + while (!s_isTransferReceiveCompleted) + { + } +#endif + } + + /* read data from buffer */ + if (ring_buf_get(&uart_receive_buf, data, size) != size) + { + /* reading error, should not happen */ + erpcStatus = kErpcStatus_ReceiveFailed; + } + + return erpcStatus; +} + +erpc_status_t UartTransport::underlyingSend(const uint8_t *data, uint32_t size) +{ + erpc_status_t erpcStatus = kErpcStatus_SendFailed; + + s_isTransferSendCompleted = false; + + /* fill buffer */ + ring_buf_put(&uart_send_buf, data, size); + + /* enable transport */ + uart_irq_tx_enable(m_dev); + +/* wait until the sending is finished */ +#if !ERPC_THREADS_IS(NONE) + (void)m_txSemaphore.get(); +#else + while (!s_isTransferSendCompleted) + { + } +#endif + + erpcStatus = kErpcStatus_Success; + + return erpcStatus; +} From 5c2c6b76cf29ac124aa6a4f4cff6fae89f988983 Mon Sep 17 00:00:00 2001 From: Mcu_sdk Ci Date: Tue, 2 Jul 2024 10:21:17 +0200 Subject: [PATCH 24/24] Apply 1.13.0 release update --- .gitignore | 3 + SW-Content-Register.txt | 37 +++ doxygen/Doxyfile.erpc | 2 +- doxygen/Doxyfile.erpcgen | 2 +- erpc_c/infra/erpc_version.h | 6 +- erpc_c/port/erpc_serial.cpp | 2 +- erpc_c/setup/erpc_setup_mbox_zephyr.cpp | 74 +++++ erpc_c/setup/erpc_setup_uart_zephyr.cpp | 42 ++- erpc_c/setup/erpc_transport_setup.h | 35 ++- .../transports/erpc_mbox_zephyr_transport.cpp | 192 +++++++++++++ .../transports/erpc_mbox_zephyr_transport.hpp | 132 +++++++++ erpc_c/transports/erpc_tcp_transport.cpp | 2 +- erpc_java/deploy.xml | 2 +- erpc_java/pom.xml | 2 +- erpc_python/erpc/erpc_version.py | 4 +- .../client/MatrixMultiplyServiceClient.java | 2 +- .../common/Constants.java | 2 +- .../interfaces/IMatrixMultiplyService.java | 2 +- .../AbstractMatrixMultiplyServiceService.java | 2 +- .../service/__init__.py | 2 +- .../service/erpc_matrix_multiply/__init__.py | 6 +- .../service/erpc_matrix_multiply/client.py | 2 +- .../service/erpc_matrix_multiply/common.py | 2 +- .../service/erpc_matrix_multiply/interface.py | 2 +- .../service/erpc_matrix_multiply/server.py | 2 +- .../matrix_multiply_mbox/CMakeLists.txt | 47 ++++ examples/zephyr/matrix_multiply_mbox/Kconfig | 13 + .../matrix_multiply_mbox/Kconfig.sysbuild | 13 + .../zephyr/matrix_multiply_mbox/README.rst | 97 +++++++ .../boards/mimxrt1160_evk_cm7.conf | 3 + .../boards/mimxrt1160_evk_cm7.overlay | 29 ++ .../boards/mimxrt1170_evk_cm7.conf | 3 + .../boards/mimxrt1170_evk_cm7.overlay | 29 ++ .../boards/mimxrt1170_evkb_cm7.conf | 3 + .../boards/mimxrt1170_evkb_cm7.overlay | 29 ++ .../zephyr/matrix_multiply_mbox/erpc_config.h | 187 ++++++++++++ examples/zephyr/matrix_multiply_mbox/prj.conf | 18 ++ .../remote/CMakeLists.txt | 45 +++ .../remote/boards/mimxrt1160_evk_cm4.conf | 4 + .../remote/boards/mimxrt1160_evk_cm4.overlay | 48 ++++ .../remote/boards/mimxrt1170_evk_cm4.conf | 4 + .../remote/boards/mimxrt1170_evk_cm4.overlay | 48 ++++ .../remote/boards/mimxrt1170_evkb_cm4.conf | 4 + .../remote/boards/mimxrt1170_evkb_cm4.overlay | 49 ++++ .../matrix_multiply_mbox/remote/prj.conf | 19 ++ .../remote/src/erpc_error_handler.cpp | 106 +++++++ .../remote/src/erpc_error_handler.h | 47 ++++ .../matrix_multiply_mbox/remote/src/main.cpp | 134 +++++++++ .../service/c_erpc_matrix_multiply_server.cpp | 78 +++++ .../service/c_erpc_matrix_multiply_server.h | 58 ++++ .../src/service/erpc_matrix_multiply.erpc | 24 ++ .../src/service/erpc_matrix_multiply_common.h | 56 ++++ .../service/erpc_matrix_multiply_common.hpp | 48 ++++ .../erpc_matrix_multiply_interface.cpp | 28 ++ .../erpc_matrix_multiply_interface.hpp | 40 +++ .../service/erpc_matrix_multiply_server.cpp | 147 ++++++++++ .../service/erpc_matrix_multiply_server.hpp | 57 ++++ .../zephyr/matrix_multiply_mbox/sample.yaml | 6 + .../src/erpc_error_handler.cpp | 106 +++++++ .../src/erpc_error_handler.h | 47 ++++ .../zephyr/matrix_multiply_mbox/src/main.cpp | 152 ++++++++++ .../service/c_erpc_matrix_multiply_client.cpp | 58 ++++ .../service/c_erpc_matrix_multiply_client.h | 53 ++++ .../src/service/erpc_matrix_multiply.erpc | 24 ++ .../service/erpc_matrix_multiply_client.cpp | 126 +++++++++ .../service/erpc_matrix_multiply_client.hpp | 42 +++ .../src/service/erpc_matrix_multiply_common.h | 56 ++++ .../service/erpc_matrix_multiply_common.hpp | 48 ++++ .../erpc_matrix_multiply_interface.cpp | 28 ++ .../erpc_matrix_multiply_interface.hpp | 40 +++ .../matrix_multiply_mbox/sysbuild.cmake | 34 +++ .../matrix_multiply_rpmsglite/CMakeLists.txt | 6 +- .../zephyr/matrix_multiply_rpmsglite/Kconfig | 6 +- .../Kconfig.sysbuild | 6 +- .../boards/lpcxpresso54114_m4.overlay | 5 +- .../boards/lpcxpresso55s69_cpu0.overlay | 5 +- .../boards/mimxrt1160_evk_cm7.overlay | 4 +- .../boards/mimxrt1170_evk_cm7.overlay | 4 +- .../boards/mimxrt1170_evkb_cm7.conf | 5 - .../boards/mimxrt1170_evkb_cm7.overlay | 4 +- .../remote/CMakeLists.txt | 6 +- .../remote/boards/lpcxpresso54114_m0.overlay | 5 +- .../boards/lpcxpresso55s69_cpu1.overlay | 5 +- .../remote/boards/mimxrt1160_evk_cm4.overlay | 4 +- .../remote/boards/mimxrt1170_evk_cm4.overlay | 4 +- .../remote/boards/mimxrt1170_evkb_cm4.conf | 5 - .../remote/boards/mimxrt1170_evkb_cm4.overlay | 4 +- .../service/c_erpc_matrix_multiply_server.cpp | 2 +- .../service/c_erpc_matrix_multiply_server.h | 2 +- .../src/service/erpc_matrix_multiply_common.h | 4 +- .../service/erpc_matrix_multiply_common.hpp | 4 +- .../erpc_matrix_multiply_interface.cpp | 4 +- .../erpc_matrix_multiply_interface.hpp | 2 +- .../service/erpc_matrix_multiply_server.cpp | 4 +- .../service/erpc_matrix_multiply_server.hpp | 4 +- .../service/c_erpc_matrix_multiply_client.cpp | 2 +- .../service/c_erpc_matrix_multiply_client.h | 2 +- .../service/erpc_matrix_multiply_client.cpp | 4 +- .../service/erpc_matrix_multiply_client.hpp | 2 +- .../src/service/erpc_matrix_multiply_common.h | 4 +- .../service/erpc_matrix_multiply_common.hpp | 4 +- .../erpc_matrix_multiply_interface.cpp | 4 +- .../erpc_matrix_multiply_interface.hpp | 2 +- .../matrix_multiply_rpmsglite/sysbuild.cmake | 6 +- .../zephyr/matrix_multiply_tcp/CMakeLists.txt | 24 ++ .../zephyr/matrix_multiply_tcp/README.rst | 115 ++++++++ examples/zephyr/matrix_multiply_tcp/prj.conf | 56 ++++ .../zephyr/matrix_multiply_tcp/sample.yaml | 3 + .../matrix_multiply_tcp/src/erpc_config.h | 187 ++++++++++++ .../src/erpc_error_handler.cpp | 106 +++++++ .../src/erpc_error_handler.h | 47 ++++ .../zephyr/matrix_multiply_tcp/src/main.cpp | 119 ++++++++ .../service/c_erpc_matrix_multiply_server.cpp | 78 +++++ .../service/c_erpc_matrix_multiply_server.h | 58 ++++ .../src/service/erpc_matrix_multiply.erpc | 24 ++ .../src/service/erpc_matrix_multiply_common.h | 56 ++++ .../service/erpc_matrix_multiply_common.hpp | 48 ++++ .../erpc_matrix_multiply_interface.cpp | 28 ++ .../erpc_matrix_multiply_interface.hpp | 40 +++ .../service/erpc_matrix_multiply_server.cpp | 147 ++++++++++ .../service/erpc_matrix_multiply_server.hpp | 57 ++++ .../service/c_erpc_matrix_multiply_server.cpp | 2 +- .../service/c_erpc_matrix_multiply_server.h | 2 +- .../src/service/erpc_matrix_multiply_common.h | 4 +- .../service/erpc_matrix_multiply_common.hpp | 4 +- .../erpc_matrix_multiply_interface.cpp | 4 +- .../erpc_matrix_multiply_interface.hpp | 2 +- .../service/erpc_matrix_multiply_server.cpp | 4 +- .../service/erpc_matrix_multiply_server.hpp | 4 +- test/common/gtest/gtest.cpp | 4 +- test/common/gtest/gtest.h | 35 ++- test/common/unit_test_arbitrator_app1.cpp | 9 +- ...st_zephyr_rpmsg_lite_arbitrator_client.cpp | 266 ++++++++++++++++++ ...st_zephyr_rpmsg_lite_arbitrator_server.cpp | 238 ++++++++++++++++ .../unit_test_zephyr_rpmsg_lite_client.cpp | 133 +++++++++ .../unit_test_zephyr_rpmsg_lite_server.cpp | 104 +++++++ ...nit_test_zephyr_uart_arbitrator_server.cpp | 236 ++++++++++++++++ test/common/unit_test_zephyr_uart_server.cpp | 101 +++++++ .../scripts/server/runner.py | 20 +- .../test_arbitrator_client_impl.cpp | 1 + test/zephyr/README.rst | 93 ++++++ test/zephyr/cmake/test.cmake | 88 ++++++ test/zephyr/cmake/variables.cmake | 27 ++ test/zephyr/rpmsglite/cmake/rpmsg_lite.cmake | 29 ++ test/zephyr/rpmsglite/cmake/sysbuild.cmake | 31 ++ test/zephyr/rpmsglite/cmake/unit_test.cmake | 44 +++ test/zephyr/rpmsglite/config/Kconfig | 11 + .../config/boards/lpcxpresso54114_m4.conf | 2 + .../config/boards/lpcxpresso54114_m4.overlay | 20 ++ .../config/boards/lpcxpresso55s69_cpu0.conf | 1 + .../boards/lpcxpresso55s69_cpu0.overlay | 22 ++ .../config/boards/mimxrt1160_evk_cm7.conf | 2 + .../config/boards/mimxrt1160_evk_cm7.overlay | 24 ++ .../config/boards/mimxrt1170_evk_cm7.conf | 2 + .../config/boards/mimxrt1170_evk_cm7.overlay | 24 ++ .../config/boards/mimxrt1170_evkb_cm7.conf | 7 + .../config/boards/mimxrt1170_evkb_cm7.overlay | 24 ++ test/zephyr/rpmsglite/config/erpc_config.h | 187 ++++++++++++ test/zephyr/rpmsglite/config/prj.conf | 37 +++ .../remote/boards/lpcxpresso54114_m0.conf | 2 + .../remote/boards/lpcxpresso54114_m0.overlay | 20 ++ .../remote/boards/lpcxpresso55s69_cpu1.conf | 2 + .../boards/lpcxpresso55s69_cpu1.overlay | 22 ++ .../remote/boards/mimxrt1160_evk_cm4.conf | 3 + .../remote/boards/mimxrt1160_evk_cm4.overlay | 51 ++++ .../remote/boards/mimxrt1170_evk_cm4.conf | 3 + .../remote/boards/mimxrt1170_evk_cm4.overlay | 51 ++++ .../remote/boards/mimxrt1170_evkb_cm4.conf | 8 + .../remote/boards/mimxrt1170_evkb_cm4.overlay | 51 ++++ test/zephyr/rpmsglite/config/remote/prj.conf | 33 +++ test/zephyr/rpmsglite/config/rpmsg_config.h | 38 +++ .../rpmsglite/test_annotations/CMakeLists.txt | 18 ++ .../test_annotations/remote/CMakeLists.txt | 16 ++ .../rpmsglite/test_annotations/sysbuild.cmake | 8 + .../rpmsglite/test_annotations/testcase.yaml | 4 + .../rpmsglite/test_arbitrator/CMakeLists.txt | 21 ++ .../rpmsglite/test_arbitrator/common.cmake | 31 ++ .../config/boards/lpcxpresso54114_m4.conf | 2 + .../config/boards/lpcxpresso54114_m4.overlay | 20 ++ .../config/boards/lpcxpresso55s69_cpu0.conf | 1 + .../boards/lpcxpresso55s69_cpu0.overlay | 22 ++ .../config/boards/mimxrt1160_evk_cm7.conf | 2 + .../config/boards/mimxrt1160_evk_cm7.overlay | 24 ++ .../config/boards/mimxrt1170_evk_cm7.conf | 2 + .../config/boards/mimxrt1170_evk_cm7.overlay | 24 ++ .../config/boards/mimxrt1170_evkb_cm7.conf | 7 + .../config/boards/mimxrt1170_evkb_cm7.overlay | 24 ++ .../test_arbitrator/config/erpc_config.h | 187 ++++++++++++ .../rpmsglite/test_arbitrator/config/prj.conf | 37 +++ .../remote/boards/lpcxpresso54114_m0.conf | 2 + .../remote/boards/lpcxpresso54114_m0.overlay | 20 ++ .../remote/boards/lpcxpresso55s69_cpu1.conf | 2 + .../boards/lpcxpresso55s69_cpu1.overlay | 22 ++ .../remote/boards/mimxrt1160_evk_cm4.conf | 3 + .../remote/boards/mimxrt1160_evk_cm4.overlay | 51 ++++ .../remote/boards/mimxrt1170_evk_cm4.conf | 3 + .../remote/boards/mimxrt1170_evk_cm4.overlay | 51 ++++ .../remote/boards/mimxrt1170_evkb_cm4.conf | 8 + .../remote/boards/mimxrt1170_evkb_cm4.overlay | 51 ++++ .../test_arbitrator/config/remote/prj.conf | 33 +++ .../test_arbitrator/config/rpmsg_config.h | 40 +++ .../test_arbitrator/remote/CMakeLists.txt | 21 ++ .../rpmsglite/test_arbitrator/sysbuild.cmake | 8 + .../rpmsglite/test_arbitrator/testcase.yaml | 7 + .../rpmsglite/test_arrays/CMakeLists.txt | 18 ++ .../test_arrays/remote/CMakeLists.txt | 18 ++ .../rpmsglite/test_arrays/sysbuild.cmake | 8 + .../rpmsglite/test_arrays/testcase.yaml | 4 + .../rpmsglite/test_binary/CMakeLists.txt | 16 ++ .../test_binary/remote/CMakeLists.txt | 16 ++ .../rpmsglite/test_binary/sysbuild.cmake | 6 + .../rpmsglite/test_binary/testcase.yaml | 4 + .../rpmsglite/test_builtin/CMakeLists.txt | 16 ++ .../test_builtin/remote/CMakeLists.txt | 16 ++ .../rpmsglite/test_builtin/sysbuild.cmake | 8 + .../rpmsglite/test_builtin/testcase.yaml | 4 + .../rpmsglite/test_callbacks/CMakeLists.txt | 18 ++ .../rpmsglite/test_callbacks/common.cmake | 27 ++ .../test_callbacks/remote/CMakeLists.txt | 18 ++ .../rpmsglite/test_callbacks/sysbuild.cmake | 8 + .../rpmsglite/test_callbacks/testcase.yaml | 4 + .../rpmsglite/test_const/CMakeLists.txt | 16 ++ .../test_const/remote/CMakeLists.txt | 16 ++ .../rpmsglite/test_const/sysbuild.cmake | 8 + .../zephyr/rpmsglite/test_const/testcase.yaml | 4 + .../rpmsglite/test_enums/CMakeLists.txt | 16 ++ .../test_enums/remote/CMakeLists.txt | 16 ++ .../rpmsglite/test_enums/sysbuild.cmake | 7 + .../zephyr/rpmsglite/test_enums/testcase.yaml | 4 + .../rpmsglite/test_lists/CMakeLists.txt | 16 ++ .../test_lists/remote/CMakeLists.txt | 16 ++ .../rpmsglite/test_lists/sysbuild.cmake | 8 + .../zephyr/rpmsglite/test_lists/testcase.yaml | 4 + .../rpmsglite/test_shared/CMakeLists.txt | 20 ++ .../test_shared/remote/CMakeLists.txt | 16 ++ .../rpmsglite/test_shared/sysbuild.cmake | 8 + .../rpmsglite/test_shared/testcase.yaml | 4 + .../rpmsglite/test_struct/CMakeLists.txt | 18 ++ .../test_struct/remote/CMakeLists.txt | 18 ++ .../rpmsglite/test_struct/sysbuild.cmake | 8 + .../rpmsglite/test_struct/testcase.yaml | 4 + .../rpmsglite/test_typedef/CMakeLists.txt | 16 ++ .../test_typedef/remote/CMakeLists.txt | 16 ++ .../rpmsglite/test_typedef/sysbuild.cmake | 8 + .../rpmsglite/test_typedef/testcase.yaml | 4 + .../rpmsglite/test_unions/CMakeLists.txt | 18 ++ .../test_unions/remote/CMakeLists.txt | 18 ++ .../rpmsglite/test_unions/sysbuild.cmake | 8 + .../rpmsglite/test_unions/testcase.yaml | 4 + test/zephyr/uart/cmake/unit_test.cmake | 29 ++ test/zephyr/uart/config/erpc_config.h | 187 ++++++++++++ test/zephyr/uart/config/prj.conf | 28 ++ .../uart/test_annotations/CMakeLists.txt | 15 + .../uart/test_annotations/testcase.yaml | 8 + .../uart/test_arbitrator/CMakeLists.txt | 35 +++ .../uart/test_arbitrator/config/erpc_config.h | 211 ++++++++++++++ .../uart/test_arbitrator/config/prj.conf | 32 +++ .../zephyr/uart/test_arbitrator/testcase.yaml | 8 + test/zephyr/uart/test_arrays/CMakeLists.txt | 15 + test/zephyr/uart/test_arrays/testcase.yaml | 8 + test/zephyr/uart/test_binary/CMakeLists.txt | 13 + test/zephyr/uart/test_binary/testcase.yaml | 8 + test/zephyr/uart/test_builtin/CMakeLists.txt | 13 + test/zephyr/uart/test_builtin/testcase.yaml | 8 + .../zephyr/uart/test_callbacks/CMakeLists.txt | 39 +++ test/zephyr/uart/test_callbacks/testcase.yaml | 8 + test/zephyr/uart/test_const/CMakeLists.txt | 13 + test/zephyr/uart/test_const/testcase.yaml | 8 + test/zephyr/uart/test_enums/CMakeLists.txt | 13 + test/zephyr/uart/test_enums/testcase.yaml | 8 + test/zephyr/uart/test_lists/CMakeLists.txt | 13 + test/zephyr/uart/test_lists/testcase.yaml | 8 + test/zephyr/uart/test_shared/CMakeLists.txt | 13 + test/zephyr/uart/test_shared/testcase.yaml | 8 + test/zephyr/uart/test_struct/CMakeLists.txt | 15 + test/zephyr/uart/test_struct/testcase.yaml | 8 + test/zephyr/uart/test_typedef/CMakeLists.txt | 13 + test/zephyr/uart/test_typedef/testcase.yaml | 8 + test/zephyr/uart/test_unions/CMakeLists.txt | 15 + test/zephyr/uart/test_unions/testcase.yaml | 8 + zephyr/CMakeLists.txt | 17 +- zephyr/Kconfig | 14 +- 282 files changed, 8374 insertions(+), 128 deletions(-) create mode 100644 SW-Content-Register.txt create mode 100644 erpc_c/setup/erpc_setup_mbox_zephyr.cpp create mode 100644 erpc_c/transports/erpc_mbox_zephyr_transport.cpp create mode 100644 erpc_c/transports/erpc_mbox_zephyr_transport.hpp create mode 100644 examples/zephyr/matrix_multiply_mbox/CMakeLists.txt create mode 100644 examples/zephyr/matrix_multiply_mbox/Kconfig create mode 100644 examples/zephyr/matrix_multiply_mbox/Kconfig.sysbuild create mode 100644 examples/zephyr/matrix_multiply_mbox/README.rst create mode 100644 examples/zephyr/matrix_multiply_mbox/boards/mimxrt1160_evk_cm7.conf create mode 100644 examples/zephyr/matrix_multiply_mbox/boards/mimxrt1160_evk_cm7.overlay create mode 100644 examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evk_cm7.conf create mode 100644 examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evk_cm7.overlay create mode 100644 examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evkb_cm7.conf create mode 100644 examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evkb_cm7.overlay create mode 100644 examples/zephyr/matrix_multiply_mbox/erpc_config.h create mode 100644 examples/zephyr/matrix_multiply_mbox/prj.conf create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/CMakeLists.txt create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1160_evk_cm4.conf create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1160_evk_cm4.overlay create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evk_cm4.conf create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evk_cm4.overlay create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evkb_cm4.conf create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evkb_cm4.overlay create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/prj.conf create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/erpc_error_handler.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/erpc_error_handler.h create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/main.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/c_erpc_matrix_multiply_server.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/c_erpc_matrix_multiply_server.h create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply.erpc create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_common.h create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_common.hpp create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_interface.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_interface.hpp create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_server.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_server.hpp create mode 100644 examples/zephyr/matrix_multiply_mbox/sample.yaml create mode 100644 examples/zephyr/matrix_multiply_mbox/src/erpc_error_handler.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/src/erpc_error_handler.h create mode 100644 examples/zephyr/matrix_multiply_mbox/src/main.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/c_erpc_matrix_multiply_client.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/c_erpc_matrix_multiply_client.h create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply.erpc create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_client.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_client.hpp create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_common.h create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_common.hpp create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_interface.cpp create mode 100644 examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_interface.hpp create mode 100644 examples/zephyr/matrix_multiply_mbox/sysbuild.cmake create mode 100644 examples/zephyr/matrix_multiply_tcp/CMakeLists.txt create mode 100644 examples/zephyr/matrix_multiply_tcp/README.rst create mode 100644 examples/zephyr/matrix_multiply_tcp/prj.conf create mode 100644 examples/zephyr/matrix_multiply_tcp/sample.yaml create mode 100644 examples/zephyr/matrix_multiply_tcp/src/erpc_config.h create mode 100644 examples/zephyr/matrix_multiply_tcp/src/erpc_error_handler.cpp create mode 100644 examples/zephyr/matrix_multiply_tcp/src/erpc_error_handler.h create mode 100644 examples/zephyr/matrix_multiply_tcp/src/main.cpp create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/c_erpc_matrix_multiply_server.cpp create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/c_erpc_matrix_multiply_server.h create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply.erpc create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_common.h create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_common.hpp create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_interface.cpp create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_interface.hpp create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_server.cpp create mode 100644 examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_server.hpp create mode 100644 test/common/unit_test_zephyr_rpmsg_lite_arbitrator_client.cpp create mode 100644 test/common/unit_test_zephyr_rpmsg_lite_arbitrator_server.cpp create mode 100644 test/common/unit_test_zephyr_rpmsg_lite_client.cpp create mode 100644 test/common/unit_test_zephyr_rpmsg_lite_server.cpp create mode 100644 test/common/unit_test_zephyr_uart_arbitrator_server.cpp create mode 100644 test/common/unit_test_zephyr_uart_server.cpp create mode 100644 test/zephyr/README.rst create mode 100644 test/zephyr/cmake/test.cmake create mode 100644 test/zephyr/cmake/variables.cmake create mode 100644 test/zephyr/rpmsglite/cmake/rpmsg_lite.cmake create mode 100644 test/zephyr/rpmsglite/cmake/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/cmake/unit_test.cmake create mode 100644 test/zephyr/rpmsglite/config/Kconfig create mode 100644 test/zephyr/rpmsglite/config/boards/lpcxpresso54114_m4.conf create mode 100644 test/zephyr/rpmsglite/config/boards/lpcxpresso54114_m4.overlay create mode 100644 test/zephyr/rpmsglite/config/boards/lpcxpresso55s69_cpu0.conf create mode 100644 test/zephyr/rpmsglite/config/boards/lpcxpresso55s69_cpu0.overlay create mode 100644 test/zephyr/rpmsglite/config/boards/mimxrt1160_evk_cm7.conf create mode 100644 test/zephyr/rpmsglite/config/boards/mimxrt1160_evk_cm7.overlay create mode 100644 test/zephyr/rpmsglite/config/boards/mimxrt1170_evk_cm7.conf create mode 100644 test/zephyr/rpmsglite/config/boards/mimxrt1170_evk_cm7.overlay create mode 100644 test/zephyr/rpmsglite/config/boards/mimxrt1170_evkb_cm7.conf create mode 100644 test/zephyr/rpmsglite/config/boards/mimxrt1170_evkb_cm7.overlay create mode 100644 test/zephyr/rpmsglite/config/erpc_config.h create mode 100644 test/zephyr/rpmsglite/config/prj.conf create mode 100644 test/zephyr/rpmsglite/config/remote/boards/lpcxpresso54114_m0.conf create mode 100644 test/zephyr/rpmsglite/config/remote/boards/lpcxpresso54114_m0.overlay create mode 100644 test/zephyr/rpmsglite/config/remote/boards/lpcxpresso55s69_cpu1.conf create mode 100644 test/zephyr/rpmsglite/config/remote/boards/lpcxpresso55s69_cpu1.overlay create mode 100644 test/zephyr/rpmsglite/config/remote/boards/mimxrt1160_evk_cm4.conf create mode 100644 test/zephyr/rpmsglite/config/remote/boards/mimxrt1160_evk_cm4.overlay create mode 100644 test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evk_cm4.conf create mode 100644 test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evk_cm4.overlay create mode 100644 test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evkb_cm4.conf create mode 100644 test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evkb_cm4.overlay create mode 100644 test/zephyr/rpmsglite/config/remote/prj.conf create mode 100644 test/zephyr/rpmsglite/config/rpmsg_config.h create mode 100644 test/zephyr/rpmsglite/test_annotations/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_annotations/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_annotations/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_annotations/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_arbitrator/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_arbitrator/common.cmake create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso54114_m4.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso54114_m4.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso55s69_cpu0.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso55s69_cpu0.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1160_evk_cm7.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1160_evk_cm7.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evk_cm7.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evk_cm7.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evkb_cm7.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evkb_cm7.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/erpc_config.h create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/prj.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso54114_m0.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso54114_m0.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso55s69_cpu1.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso55s69_cpu1.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1160_evk_cm4.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1160_evk_cm4.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evk_cm4.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evk_cm4.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evkb_cm4.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evkb_cm4.overlay create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/remote/prj.conf create mode 100644 test/zephyr/rpmsglite/test_arbitrator/config/rpmsg_config.h create mode 100644 test/zephyr/rpmsglite/test_arbitrator/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_arbitrator/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_arbitrator/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_arrays/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_arrays/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_arrays/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_arrays/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_binary/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_binary/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_binary/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_binary/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_builtin/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_builtin/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_builtin/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_builtin/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_callbacks/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_callbacks/common.cmake create mode 100644 test/zephyr/rpmsglite/test_callbacks/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_callbacks/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_callbacks/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_const/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_const/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_const/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_const/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_enums/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_enums/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_enums/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_enums/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_lists/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_lists/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_lists/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_lists/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_shared/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_shared/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_shared/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_shared/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_struct/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_struct/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_struct/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_struct/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_typedef/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_typedef/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_typedef/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_typedef/testcase.yaml create mode 100644 test/zephyr/rpmsglite/test_unions/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_unions/remote/CMakeLists.txt create mode 100644 test/zephyr/rpmsglite/test_unions/sysbuild.cmake create mode 100644 test/zephyr/rpmsglite/test_unions/testcase.yaml create mode 100644 test/zephyr/uart/cmake/unit_test.cmake create mode 100644 test/zephyr/uart/config/erpc_config.h create mode 100644 test/zephyr/uart/config/prj.conf create mode 100644 test/zephyr/uart/test_annotations/CMakeLists.txt create mode 100644 test/zephyr/uart/test_annotations/testcase.yaml create mode 100644 test/zephyr/uart/test_arbitrator/CMakeLists.txt create mode 100644 test/zephyr/uart/test_arbitrator/config/erpc_config.h create mode 100644 test/zephyr/uart/test_arbitrator/config/prj.conf create mode 100644 test/zephyr/uart/test_arbitrator/testcase.yaml create mode 100644 test/zephyr/uart/test_arrays/CMakeLists.txt create mode 100644 test/zephyr/uart/test_arrays/testcase.yaml create mode 100644 test/zephyr/uart/test_binary/CMakeLists.txt create mode 100644 test/zephyr/uart/test_binary/testcase.yaml create mode 100644 test/zephyr/uart/test_builtin/CMakeLists.txt create mode 100644 test/zephyr/uart/test_builtin/testcase.yaml create mode 100644 test/zephyr/uart/test_callbacks/CMakeLists.txt create mode 100644 test/zephyr/uart/test_callbacks/testcase.yaml create mode 100644 test/zephyr/uart/test_const/CMakeLists.txt create mode 100644 test/zephyr/uart/test_const/testcase.yaml create mode 100644 test/zephyr/uart/test_enums/CMakeLists.txt create mode 100644 test/zephyr/uart/test_enums/testcase.yaml create mode 100644 test/zephyr/uart/test_lists/CMakeLists.txt create mode 100644 test/zephyr/uart/test_lists/testcase.yaml create mode 100644 test/zephyr/uart/test_shared/CMakeLists.txt create mode 100644 test/zephyr/uart/test_shared/testcase.yaml create mode 100644 test/zephyr/uart/test_struct/CMakeLists.txt create mode 100644 test/zephyr/uart/test_struct/testcase.yaml create mode 100644 test/zephyr/uart/test_typedef/CMakeLists.txt create mode 100644 test/zephyr/uart/test_typedef/testcase.yaml create mode 100644 test/zephyr/uart/test_unions/CMakeLists.txt create mode 100644 test/zephyr/uart/test_unions/testcase.yaml diff --git a/.gitignore b/.gitignore index 8e4ecc71..09fc8040 100644 --- a/.gitignore +++ b/.gitignore @@ -112,3 +112,6 @@ boost*/ mingw.7z mingw64/ vs_BuildTools* + +# Zephyr's repo link +__repo__/ \ No newline at end of file diff --git a/SW-Content-Register.txt b/SW-Content-Register.txt new file mode 100644 index 00000000..aafc9df8 --- /dev/null +++ b/SW-Content-Register.txt @@ -0,0 +1,37 @@ +Release Name: eRPC +Release Version: 1.12.0 +Package License: BSD-3-Clause + +the_bus_pirate Name: The Bus Pirate + Version: NA + Outgoing License: Open Source - CC0 (Public Domain + Dedication License) + License File: http://code.google.com/p/the-bus-pirate/ + Format: source code + Description: OS independent serial interface + Location: + erpc_c/port/erpc_serial.h, + erpc_c/port/erpc_serial.cpp + Origin: Community + Url: http://code.google.com/p/the-bus-pirate/ + +cpp_template Name: CPP Template + Version: NA + Outgoing License: Open Source - MIT + License File: + erpcgen/src/cpptemplate/LICENSE.txt + Format: source code + Description: CPP Template + Location: erpcgen/src/cpptemplate + Origin: Ryan Ginstrom & Martinho Fernandes + +cpp_option_parser Name: C++ option-parser + Version: NA + Outgoing License: Brad Appleton's license + License File: http://www.bradapp.com/ftp/src/libs/C++/Options.tar.gz + , see README file + Format: Plain Text + Description: C++ option-parser + Location: erpcgen/src/options.cpp + Origin: Brad Appleton bradapp@enteract.com + Url: http://www.bradapp.com/ftp/src/libs/C++/Options.html \ No newline at end of file diff --git a/doxygen/Doxyfile.erpc b/doxygen/Doxyfile.erpc index f56fb310..06af371e 100644 --- a/doxygen/Doxyfile.erpc +++ b/doxygen/Doxyfile.erpc @@ -38,7 +38,7 @@ PROJECT_NAME = "eRPC API Reference" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = "Rev. 1.12.0" +PROJECT_NUMBER = "Rev. 1.13.0" # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/doxygen/Doxyfile.erpcgen b/doxygen/Doxyfile.erpcgen index 77190978..14b11de3 100644 --- a/doxygen/Doxyfile.erpcgen +++ b/doxygen/Doxyfile.erpcgen @@ -38,7 +38,7 @@ PROJECT_NAME = "eRPC Generator (erpcgen)" # could be handy for archiving the generated documentation or if some version # control system is used. -PROJECT_NUMBER = "Rev. 1.12.0" +PROJECT_NUMBER = "Rev. 1.13.0" # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a diff --git a/erpc_c/infra/erpc_version.h b/erpc_c/infra/erpc_version.h index 1f5188f8..2a1270c6 100644 --- a/erpc_c/infra/erpc_version.h +++ b/erpc_c/infra/erpc_version.h @@ -1,6 +1,6 @@ /* * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016-2023 NXP + * Copyright 2016-2024 NXP * All rights reserved. * * @@ -20,9 +20,9 @@ //////////////////////////////////////////////////////////////////////////////// //! @brief String version of eRPC. -#define ERPC_VERSION "1.12.0" +#define ERPC_VERSION "1.13.0" //! @brief Integer version of eRPC. -#define ERPC_VERSION_NUMBER 11200 +#define ERPC_VERSION_NUMBER 11300 /*! @} */ diff --git a/erpc_c/port/erpc_serial.cpp b/erpc_c/port/erpc_serial.cpp index 2423ca8e..3b3fdc8d 100644 --- a/erpc_c/port/erpc_serial.cpp +++ b/erpc_c/port/erpc_serial.cpp @@ -220,7 +220,7 @@ int serial_read(int fd, char *buf, int size) ClearCommError(hCom, &errors, NULL); - if (!ReadFile(hCom, temp, RX_BUF_BYTES - bytesToRead, &bytesRead, &s_readOverlap)) + if (!ReadFile(hCom, temp, size - bytesToRead, &bytesRead, &s_readOverlap)) { if (GetLastError() == ERROR_IO_PENDING) { diff --git a/erpc_c/setup/erpc_setup_mbox_zephyr.cpp b/erpc_c/setup/erpc_setup_mbox_zephyr.cpp new file mode 100644 index 00000000..75543c5e --- /dev/null +++ b/erpc_c/setup/erpc_setup_mbox_zephyr.cpp @@ -0,0 +1,74 @@ +/* + * Copyright 2023 NXP + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_manually_constructed.hpp" +#include "erpc_transport_setup.h" +#include "erpc_mbox_zephyr_transport.hpp" + +using namespace erpc; + +//////////////////////////////////////////////////////////////////////////////// +// Variables +//////////////////////////////////////////////////////////////////////////////// + +ERPC_MANUALLY_CONSTRUCTED_STATIC(MBOXTransport, s_transport); + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +erpc_transport_t erpc_transport_zephyr_mbox_init(void *dev, void *tx_channel, void *rx_channel) +{ + erpc_transport_t transport; + MBOXTransport *mboxTransport; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_transport.isUsed()) + { + mboxTransport = NULL; + } + else + { + s_transport.construct((struct device *)dev, (struct mbox_channel *)tx_channel, + (struct mbox_channel *)rx_channel); + mboxTransport = s_transport.get(); + } + +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + mboxTransport = + new MBOXTransport((struct device *)dev, (struct mbox_channel *)tx_channel, (struct mbox_channel *)rx_channel); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(mboxTransport); + + if (mboxTransport != NULL) + { + if (mboxTransport->init() != kErpcStatus_Success) + { + erpc_transport_zephyr_mbox_deinit(transport); + transport = NULL; + } + } + + return transport; +} + +void erpc_transport_zephyr_mbox_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_transport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + MBOXTransport *mboxTransport = reinterpret_cast(transport); + + delete mboxTransport; +#endif +} diff --git a/erpc_c/setup/erpc_setup_uart_zephyr.cpp b/erpc_c/setup/erpc_setup_uart_zephyr.cpp index 42c7242f..b13abe16 100644 --- a/erpc_c/setup/erpc_setup_uart_zephyr.cpp +++ b/erpc_c/setup/erpc_setup_uart_zephyr.cpp @@ -15,7 +15,7 @@ using namespace erpc; // Variables //////////////////////////////////////////////////////////////////////////////// -ERPC_MANUALLY_CONSTRUCTED(UartTransport, s_transport); +ERPC_MANUALLY_CONSTRUCTED_STATIC(UartTransport, s_transport); //////////////////////////////////////////////////////////////////////////////// // Code @@ -24,16 +24,48 @@ ERPC_MANUALLY_CONSTRUCTED(UartTransport, s_transport); erpc_transport_t erpc_transport_zephyr_uart_init(void *dev) { erpc_transport_t transport; + UartTransport *uartTransport; - s_transport.construct((struct device *)dev); - if (s_transport->init() == kErpcStatus_Success) +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + if (s_transport.isUsed()) { - transport = reinterpret_cast(s_transport.get()); + uartTransport = NULL; } else { - transport = NULL; + s_transport.construct(reinterpret_cast(dev)); + uartTransport = s_transport.get(); + } +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + uartTransport = new UartTransport(reinterpret_cast(dev)); +#else +#error "Unknown eRPC allocation policy!" +#endif + + transport = reinterpret_cast(uartTransport); + + if (uartTransport != NULL) + { + if (uartTransport->init() != kErpcStatus_Success) + { + erpc_transport_zephyr_uart_deinit(transport); + transport = NULL; + } } return transport; } + +void erpc_transport_zephyr_uart_deinit(erpc_transport_t transport) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_STATIC + (void)transport; + s_transport.destroy(); +#elif ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(transport != NULL); + + UartTransport *uartTransport = reinterpret_cast(transport); + + delete uartTransport; +#endif +} \ No newline at end of file diff --git a/erpc_c/setup/erpc_transport_setup.h b/erpc_c/setup/erpc_transport_setup.h index fa90a6af..65c3d4be 100644 --- a/erpc_c/setup/erpc_transport_setup.h +++ b/erpc_c/setup/erpc_transport_setup.h @@ -1,6 +1,6 @@ /* * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. - * Copyright 2016-2022 NXP + * Copyright 2016-2024 NXP * Copyright 2019 ACRIOS Systems s.r.o. * All rights reserved. * @@ -508,6 +508,11 @@ erpc_transport_t erpc_transport_cmsis_uart_init(void *uartDrv); */ void erpc_transport_cmsis_uart_deinit(erpc_transport_t transport); +//@} + +//! @name Zephyr transports setup +//@{ + /*! * @brief Create a Zephyr UART transport. * @@ -520,6 +525,34 @@ void erpc_transport_cmsis_uart_deinit(erpc_transport_t transport); */ erpc_transport_t erpc_transport_zephyr_uart_init(void *dev); +/*! + * @brief Deinitialize Zephyr UART transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_zephyr_uart_deinit(erpc_transport_t transport); + +/*! + * @brief Create a Zephyr MBOX transport. + * + * Create a Zephyr MBOX transport instance, to be used on both the server + * and the client side. + * + * @param[in] dev Zephyr MBOX device address. + * @param[in] tx_channel Zephyr MBOX transmit channel. + * @param[in] rx_channel Zephyr MBOX receive channel. + * + * @return Return NULL or erpc_transport_t instance pointer. + */ +erpc_transport_t erpc_transport_zephyr_mbox_init(void *dev, void *tx_channel, void *rx_channel); + +/*! + * @brief Deinitialize Zephyr MBOX transport. + * + * @param[in] transport Transport which was initialized with init function. + */ +void erpc_transport_zephyr_mbox_deinit(erpc_transport_t transport); + //@} //! @name USB CDC transport setup diff --git a/erpc_c/transports/erpc_mbox_zephyr_transport.cpp b/erpc_c/transports/erpc_mbox_zephyr_transport.cpp new file mode 100644 index 00000000..cf29bd6c --- /dev/null +++ b/erpc_c/transports/erpc_mbox_zephyr_transport.cpp @@ -0,0 +1,192 @@ +/* + * Copyright 2023 NXP + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_mbox_zephyr_transport.hpp" +#include "erpc_port.h" +#include +#include + +using namespace erpc; + +//////////////////////////////////////////////////////////////////////////////// +// Variables +//////////////////////////////////////////////////////////////////////////////// +static MBOXTransport *s_mbox_instance = NULL; + +RING_BUF_DECLARE(s_rxRingBuffer, MBOX_BUFFER_SIZE); + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +MBOXTransport::MBOXTransport(struct device *dev, struct mbox_channel *tx_channel, struct mbox_channel *rx_channel) : +m_dev(dev), m_tx_channel(tx_channel), m_rx_channel(rx_channel) +#if !ERPC_THREADS_IS(NONE) +, +m_rxSemaphore(), m_txSemaphore() +#endif +{ + s_mbox_instance = this; +} + +MBOXTransport::~MBOXTransport(void) {} + +void MBOXTransport::rx_cb(struct mbox_msg *data) +{ + // Read data to ring buffer + ring_buf_put(&s_rxRingBuffer, static_cast(data->data), data->size); + + // message is complete, unblock caller of the receive function + if (ring_buf_size_get(&s_rxRingBuffer) >= m_transferReceiveRequireBytes) + { + m_isTransferReceiveCompleted = true; +#if !ERPC_THREADS_IS(NONE) + // disable MU rx full interrupt in rtos-based blocking implementation + m_rxSemaphore.put(); +#endif + m_transferReceiveRequireBytes = MBOX_BUFFER_SIZE; + } +} + +/* Transfer callback */ +static void mbox_callback(const struct device *dev, uint32_t channel, void *user_data, struct mbox_msg *data) +{ + s_mbox_instance->rx_cb(data); +} + +erpc_status_t MBOXTransport::init(void) +{ + if (mbox_register_callback(m_rx_channel, mbox_callback, NULL)) + { + printk("mbox_register_callback() error\n"); + return kErpcStatus_InitFailed; + } + + if (mbox_set_enabled(m_rx_channel, 1)) + { + printk("mbox_set_enable() error\n"); + return kErpcStatus_InitFailed; + } + + return kErpcStatus_Success; +} + +erpc_status_t MBOXTransport::receive(MessageBuffer *message) +{ + erpc_status_t status = kErpcStatus_Success; + uint8_t tmp[4]; + uint32_t rxMsgSize = 0; + + if (message == NULL) + { + status = kErpcStatus_ReceiveFailed; + } + else + { +#if !ERPC_THREADS_IS(NONE) + Mutex::Guard lock(m_receiveLock); +#endif + + // Wait for size of the message + waitForBytes(sizeof(uint32_t)); + ring_buf_get(&s_rxRingBuffer, (uint8_t *)&rxMsgSize, sizeof(uint32_t)); + + // Wait for message to be transmitted + waitForBytes(rxMsgSize); + message->setUsed((uint16_t)rxMsgSize); + + if (ring_buf_get(&s_rxRingBuffer, reinterpret_cast(message->get()), rxMsgSize) != rxMsgSize) + { + status = kErpcStatus_ReceiveFailed; + }; + + // Read remaining bytes from ring buffer + ring_buf_get(&s_rxRingBuffer, tmp, 4 - (rxMsgSize % 4)); + + rxMsgSize = 0; + } + + return status; +} + +void MBOXTransport::waitForBytes(uint32_t numOfBytes) +{ + if (ring_buf_size_get(&s_rxRingBuffer) < numOfBytes) + { + m_transferReceiveRequireBytes = numOfBytes; + +/* wait until the receiving is finished */ +#if !ERPC_THREADS_IS(NONE) + (void)m_rxSemaphore.get(); +#else + m_isTransferReceiveCompleted = false; + while (!m_isTransferReceiveCompleted) + { + } +#endif + } +} + +erpc_status_t MBOXTransport::send(MessageBuffer *message) +{ + erpc_status_t status = kErpcStatus_Success; + struct mbox_msg txMsg; + uint32_t txMsgSize = 0; + uint32_t txCntBytes = 0; + uint8_t *txBuffer; + + if (message == NULL) + { + status = kErpcStatus_SendFailed; + } + else + { +#if !ERPC_THREADS_IS(NONE) + Mutex::Guard lock(m_sendLock); +#endif + + txMsgSize = message->getUsed(); + txCntBytes = 0; + txBuffer = message->get(); + + txMsg.data = &txMsgSize; + txMsg.size = sizeof(uint32_t); + + mbox_send(m_tx_channel, &txMsg); + + while (txCntBytes < txMsgSize) + { + txMsg.data = &txBuffer[txCntBytes]; + txMsg.size = sizeof(uint32_t); + + int mboxStatus = mbox_send(m_tx_channel, &txMsg); + + if (mboxStatus == -EBUSY) + { + continue; + } + + if (mboxStatus < 0) + { + return kErpcStatus_SendFailed; + } + + txCntBytes += sizeof(uint32_t); + } + + txMsgSize = 0; + txCntBytes = 0; + txBuffer = NULL; + } + + return status; +} + +bool MBOXTransport::hasMessage(void) +{ + return !ring_buf_is_empty(&s_rxRingBuffer); +} diff --git a/erpc_c/transports/erpc_mbox_zephyr_transport.hpp b/erpc_c/transports/erpc_mbox_zephyr_transport.hpp new file mode 100644 index 00000000..fef8289e --- /dev/null +++ b/erpc_c/transports/erpc_mbox_zephyr_transport.hpp @@ -0,0 +1,132 @@ +/* + * Copyright 2023 NXP + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC_ZEPHYR_MBOX_TRANSPORT_H_ +#define _EMBEDDED_RPC_ZEPHYR_MBOX_TRANSPORT_H_ + +#include "erpc_config_internal.h" +#if !ERPC_THREADS_IS(NONE) +#include "erpc_threading.h" +#endif +#include "erpc_transport.hpp" + +extern "C" { +#include +#include +#include +} + +#define MBOX_BUFFER_SIZE ERPC_DEFAULT_BUFFER_SIZE + +/*! + * @addtogroup mbox_transport + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +namespace erpc { +/*! + * @brief Transport to send/receive messages via MBOX. + * + * @ingroup mbox_transport + */ +class MBOXTransport : public Transport +{ +public: + /*! + * @brief Constructor. + * + * @param[in] dev Zephyr MBOX device. + * @param[in] tx_channel Zephyr MBOX tx channel. + * @param[in] rx_channel Zephyr MBOX rx channel. + */ + MBOXTransport(struct device *dev, struct mbox_channel *tx_channel, struct mbox_channel *rx_channel); + + /*! + * @brief Destructor. + */ + virtual ~MBOXTransport(void); + + /*! + * @brief Initialize Zephyr MBOX peripheral configuration structure with values specified in MBOXTransport + * constructor. + * + * @retval kErpcStatus_InitFailed When MBOC init function failed. + * @retval kErpcStatus_Success When MBOX init function was executed successfully. + */ + virtual erpc_status_t init(void); + + /*! + * @brief Start receiving data and stores it to passed message buffer + * + * Initialize receiving of message, it is blocking until doesn't receive complete message. + * + * @param[in] message Message buffer, which will be filled by incoming message. + * + * @return kErpcStatus_Success + */ + virtual erpc_status_t receive(MessageBuffer *message) override; + + /*! + * @brief Function to send prepared message. + * + * @param[in] message Pass message buffer to send. + * + * @retval kErpcStatus_SendFailed Failed to send message buffer. + * @retval kErpcStatus_Success Successfully sent all data. + */ + virtual erpc_status_t send(MessageBuffer *message) override; + + /*! + * @brief Function to check if is new message to receive. + * + * This function should be called before blocking function receive() to avoid waiting for new message. + * + * @return True if exist new message, else false. + */ + virtual bool hasMessage(void) override; + + /*! + * @brief Function called from ISR + * + * Unblocks the receive function. + */ + void rx_cb(struct mbox_msg *data); + +protected: + struct device *m_dev; /*!< Access structure of the MBOX device */ + struct mbox_channel *m_tx_channel; + struct mbox_channel *m_rx_channel; + + volatile bool m_isTransferReceiveCompleted = false; + volatile uint32_t m_transferReceiveRequireBytes = 0; + + /*! + * @brief Function waits for given amount of bytes to be in ring buffer. + * + * @param[in] numOfBytes Required number of bytes in ring buffer + */ + void waitForBytes(uint32_t numOfBytes); + +#if !ERPC_THREADS_IS(NONE) + Semaphore m_rxSemaphore; /*!< Semaphore used by RTOS to block task until the receiving is not complete */ + Semaphore m_txSemaphore; /*!< Semaphore used by RTOS to block task until the sending is not complete */ + + Mutex m_sendLock; /*!< Mutex protecting send. */ + Mutex m_receiveLock; /*!< Mutex protecting receive. */ +#endif +}; + +} // namespace erpc + +/*! @} */ + +#endif // _EMBEDDED_RPC_ZEPHYR_MBOX_TRANSPORT_H_ diff --git a/erpc_c/transports/erpc_tcp_transport.cpp b/erpc_c/transports/erpc_tcp_transport.cpp index 9712ce6c..c910ec49 100644 --- a/erpc_c/transports/erpc_tcp_transport.cpp +++ b/erpc_c/transports/erpc_tcp_transport.cpp @@ -268,7 +268,7 @@ erpc_status_t TCPTransport::connectClient(void) { #else // globally disable the SIGPIPE signal -#if !defined(__MINGW32__) +#if !defined(__MINGW32__) && !defined(__ZEPHYR__) signal(SIGPIPE, SIG_IGN); #endif #endif // defined(SO_NOSIGPIPE) diff --git a/erpc_java/deploy.xml b/erpc_java/deploy.xml index 1adf2193..2d496677 100644 --- a/erpc_java/deploy.xml +++ b/erpc_java/deploy.xml @@ -6,7 +6,7 @@ io.github.embeddedrpc.erpc erpc - 0.1.0 + 1.13.0 eRPC eRPC (Embedded RPC) is an open source Remote Procedure Call (RPC) system for multichip embedded systems diff --git a/erpc_java/pom.xml b/erpc_java/pom.xml index 934b688f..5173cdba 100644 --- a/erpc_java/pom.xml +++ b/erpc_java/pom.xml @@ -6,7 +6,7 @@ io.github.embeddedrpc.erpc erpc - 0.1.0 + 1.13.0 eRPC eRPC (Embedded RPC) is an open source Remote Procedure Call (RPC) system for multichip embedded systems diff --git a/erpc_python/erpc/erpc_version.py b/erpc_python/erpc/erpc_version.py index 3efec812..3e702641 100644 --- a/erpc_python/erpc/erpc_version.py +++ b/erpc_python/erpc/erpc_version.py @@ -1,9 +1,9 @@ #!/usr/bin/env python -# Copyright 2017-2023 NXP +# Copyright 2017-2024 NXP # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # Should be same as in erpc_version.h -ERPC_VERSION = "1.12.0" +ERPC_VERSION = "1.13.0" diff --git a/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/client/MatrixMultiplyServiceClient.java b/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/client/MatrixMultiplyServiceClient.java index 15b4d35f..edaa54e0 100644 --- a/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/client/MatrixMultiplyServiceClient.java +++ b/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/client/MatrixMultiplyServiceClient.java @@ -1,5 +1,5 @@ /** - * Generated by erpcgen 1.12.0 on Mon Jan 8 09:33:04 2024. + * Generated by erpcgen 1.13.0 on Mon Apr 22 10:58:07 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/common/Constants.java b/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/common/Constants.java index 6543b0f8..dbdf1e08 100644 --- a/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/common/Constants.java +++ b/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/common/Constants.java @@ -1,5 +1,5 @@ /** - * Generated by erpcgen 1.12.0 on Mon Jan 8 09:33:04 2024. + * Generated by erpcgen 1.13.0 on Mon Apr 22 10:58:07 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/interfaces/IMatrixMultiplyService.java b/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/interfaces/IMatrixMultiplyService.java index 3599a81a..364027c6 100644 --- a/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/interfaces/IMatrixMultiplyService.java +++ b/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/interfaces/IMatrixMultiplyService.java @@ -1,5 +1,5 @@ /** - * Generated by erpcgen 1.12.0 on Mon Jan 8 09:33:04 2024. + * Generated by erpcgen 1.13.0 on Mon Apr 22 10:58:07 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/server/AbstractMatrixMultiplyServiceService.java b/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/server/AbstractMatrixMultiplyServiceService.java index 2312c609..c77dbd1c 100644 --- a/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/server/AbstractMatrixMultiplyServiceService.java +++ b/examples/matrix_multiply_java/src/main/java/io/github/embeddedrpc/erpc/example/erpc_matrix_multiply/server/AbstractMatrixMultiplyServiceService.java @@ -1,5 +1,5 @@ /** - * Generated by erpcgen 1.12.0 on Mon Jan 8 09:33:04 2024. + * Generated by erpcgen 1.13.0 on Mon Apr 22 10:58:07 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/matrix_multiply_tcp_python/service/__init__.py b/examples/matrix_multiply_tcp_python/service/__init__.py index b3fea60e..3fd87830 100644 --- a/examples/matrix_multiply_tcp_python/service/__init__.py +++ b/examples/matrix_multiply_tcp_python/service/__init__.py @@ -5,7 +5,7 @@ # SPDX-License-Identifier: BSD-3-Clause # -# Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. +# Generated by erpcgen 1.13.0 on Thu Apr 18 09:56:46 2024. # # AUTOGENERATED - DO NOT EDIT # diff --git a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/__init__.py b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/__init__.py index 360de229..54db5dbd 100644 --- a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/__init__.py +++ b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/__init__.py @@ -5,7 +5,7 @@ # SPDX-License-Identifier: BSD-3-Clause # -# Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. +# Generated by erpcgen 1.13.0 on Thu Apr 18 09:56:46 2024. # # AUTOGENERATED - DO NOT EDIT # @@ -15,8 +15,8 @@ version = erpc_version.ERPC_VERSION except ImportError: version = "unknown" -if version != "1.12.0": - raise ValueError("The generated shim code version (1.12.0) is different to the rest of eRPC code (%s). \ +if version != "1.13.0": + raise ValueError("The generated shim code version (1.13.0) is different to the rest of eRPC code (%s). \ Install newer version by running \"python setup.py install\" in folder erpc/erpc_python/." % repr(version)) from . import common diff --git a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/client.py b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/client.py index 098618db..1d8ae6f7 100644 --- a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/client.py +++ b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/client.py @@ -5,7 +5,7 @@ # SPDX-License-Identifier: BSD-3-Clause # -# Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. +# Generated by erpcgen 1.13.0 on Thu Apr 18 09:56:46 2024. # # AUTOGENERATED - DO NOT EDIT # diff --git a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/common.py b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/common.py index a4ede601..16e235fb 100644 --- a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/common.py +++ b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/common.py @@ -5,7 +5,7 @@ # SPDX-License-Identifier: BSD-3-Clause # -# Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. +# Generated by erpcgen 1.13.0 on Thu Apr 18 09:56:46 2024. # # AUTOGENERATED - DO NOT EDIT # diff --git a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/interface.py b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/interface.py index b0d25311..04ea34e5 100644 --- a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/interface.py +++ b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/interface.py @@ -5,7 +5,7 @@ # SPDX-License-Identifier: BSD-3-Clause # -# Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. +# Generated by erpcgen 1.13.0 on Thu Apr 18 09:56:46 2024. # # AUTOGENERATED - DO NOT EDIT # diff --git a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/server.py b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/server.py index 7fa1adc6..b8c807de 100644 --- a/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/server.py +++ b/examples/matrix_multiply_tcp_python/service/erpc_matrix_multiply/server.py @@ -5,7 +5,7 @@ # SPDX-License-Identifier: BSD-3-Clause # -# Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. +# Generated by erpcgen 1.13.0 on Thu Apr 18 09:56:46 2024. # # AUTOGENERATED - DO NOT EDIT # diff --git a/examples/zephyr/matrix_multiply_mbox/CMakeLists.txt b/examples/zephyr/matrix_multiply_mbox/CMakeLists.txt new file mode 100644 index 00000000..d8aed058 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/CMakeLists.txt @@ -0,0 +1,47 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) + +set(REMOTE_ZEPHYR_DIR ${CMAKE_CURRENT_BINARY_DIR}/../remote/zephyr) + +if(("${BOARD}" STREQUAL "mimxrt1170_evkb_cm7") OR + ("${BOARD}" STREQUAL "mimxrt1170_evk_cm7") OR + ("${BOARD}" STREQUAL "mimxrt1160_evk_cm7")) + message(STATUS "${BOARD} compile as Main in this sample") +else() + message(FATAL_ERROR "${BOARD} is not supported for this sample") +endif() + +project(matrix_multiply_mbox) + +enable_language(C CXX) + +if(CONFIG_INCLUDE_REMOTE_DIR) + target_include_directories(zephyr_interface + INTERFACE ${REMOTE_ZEPHYR_DIR}/include/public) +endif() + +target_include_directories(app PRIVATE + ${PROJECT_SOURCE_DIR}/ + ${PROJECT_SOURCE_DIR}/src + ${PROJECT_SOURCE_DIR}/src/service +) + +target_sources(app PRIVATE + ${PROJECT_SOURCE_DIR}/src/main.cpp + ${PROJECT_SOURCE_DIR}/src/erpc_error_handler.cpp + + # Generated shim code + ${PROJECT_SOURCE_DIR}/src/service/c_erpc_matrix_multiply_client.cpp + ${PROJECT_SOURCE_DIR}/src/service/erpc_matrix_multiply_client.cpp + ${PROJECT_SOURCE_DIR}/src/service/erpc_matrix_multiply_interface.cpp +) + +# Same for erpc library and erpc_config.h +target_include_directories(erpc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/examples/zephyr/matrix_multiply_mbox/Kconfig b/examples/zephyr/matrix_multiply_mbox/Kconfig new file mode 100644 index 00000000..8f708489 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/Kconfig @@ -0,0 +1,13 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +source "Kconfig.zephyr" + +config INCLUDE_REMOTE_DIR + bool "Include remote core header directory" + help + Include remote build header files. Can be used if primary image + needs to be aware of size or base address of secondary image diff --git a/examples/zephyr/matrix_multiply_mbox/Kconfig.sysbuild b/examples/zephyr/matrix_multiply_mbox/Kconfig.sysbuild new file mode 100644 index 00000000..6ae8dbda --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/Kconfig.sysbuild @@ -0,0 +1,13 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +source "share/sysbuild/Kconfig" + +config REMOTE_BOARD +string + default "mimxrt1170_evkb_cm4" if $(BOARD) = "mimxrt1170_evkb_cm7" + default "mimxrt1170_evk_cm4" if $(BOARD) = "mimxrt1170_evk_cm7" + default "mimxrt1160_evk_cm4" if $(BOARD) = "mimxrt1160_evk_cm7" diff --git a/examples/zephyr/matrix_multiply_mbox/README.rst b/examples/zephyr/matrix_multiply_mbox/README.rst new file mode 100644 index 00000000..6f06a59a --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/README.rst @@ -0,0 +1,97 @@ +.. _matrix_multiply_mbox: + +Matrix multiply MBOX +########### + +The eRPC Matrix multiply MBOX sample that can be used with: :ref:`supported board `. + + +The Multicore eRPC Matrix Multiply project is a simple demonstration program that uses Zephyr OS and +the Multicore SDK to show how to implement the Remote Procedure Call between cores of the multicore +system. The primary core (eRPC client) releases the secondary core (eRPC server) from the reset and +then the erpcMatrixMultiply() eRPC call is issued to let the secondary core to perform the +multiplication of two randomly generated matrices. The original matrices and the result matrix is +printed out to the serial console by the primary core. MBOX eRPC transport layer is used in +this example application. + +Shared memory usage +This multicore example uses the MBOX for data exchange.The MBOX chanells are defined in `board/.overlay`. + +eRPC documentation +eRPC specific files are stored in: middleware\multicore\erpc +eRPC documentation is stored in: middleware\multicore\erpc\doc +eRPC is open-source project stored on github: https://github.com/EmbeddedRPC/erpc +eRPC documentation can be also found in: http://embeddedrpc.github.io + +Building and Running +******************** + +This application can be built and executed on Supported Multi Core boards as follows: + +Building the application for mimxrt1160_evk_cm7 +*********************************************** + +.. zephyr-app-commands:: + :zephyr-app: samples/matrix_multiply_rpmsglite + :board: mimxrt1160_evk_cm7 + :goals: debug + :west-args: --sysbuild + +Building the application for mimxrt1170_evk_cm7 +*********************************************** + +.. zephyr-app-commands:: + :zephyr-app: samples/matrix_multiply_rpmsglite + :board: mimxrt1170_evk_cm7 + :goals: debug + :west-args: --sysbuild + +Building the application for mimxrt1170_evkb_cm7 +*********************************************** + +.. zephyr-app-commands:: + :zephyr-app: samples/matrix_multiply_rpmsglite + :board: mimxrt1170_evkb_cm7 + :goals: debug + :west-args: --sysbuild + +Sample Output +============= + +Open a serial terminal (minicom, putty, etc.) and connect the board with the +following settings: + +- Speed: 115200 +- Data: 8 bits +- Parity: None +- Stop bits: 1 + +Reset the board and the following message will appear on the corresponding +serial port: + +.. code-block:: console + + Matrix #1 + 21 33 37 37 9 + 23 45 43 0 32 + 38 44 8 15 36 + 18 18 38 44 16 + 22 23 0 38 7 + + Matrix #2 + 11 23 27 45 11 + 7 19 23 24 6 + 32 26 49 43 16 + 22 48 36 34 41 + 27 20 32 31 11 + + eRPC request is sent to the server + + Result matrix + 2703 4028 4759 4865 2637 + 2808 3142 4787 4956 1563 + 2284 3358 4122 4736 1821 + 2940 4176 4858 4868 2894 + 1428 2907 2715 3051 2015 + + ... \ No newline at end of file diff --git a/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1160_evk_cm7.conf b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1160_evk_cm7.conf new file mode 100644 index 00000000..78b67f1f --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1160_evk_cm7.conf @@ -0,0 +1,3 @@ +CONFIG_MBOX_NXP_IMX_MU=y +CONFIG_INCLUDE_REMOTE_DIR=y +CONFIG_SECOND_CORE_MCUX=y \ No newline at end of file diff --git a/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1160_evk_cm7.overlay b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1160_evk_cm7.overlay new file mode 100644 index 00000000..01c6edf4 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1160_evk_cm7.overlay @@ -0,0 +1,29 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* Delete ipc chosen property where old IPM mailbox driver bellow is + * configured. + */ + /delete-property/ zephyr,ipc; + }; + + soc { + /* Delete IPM Driver node nxp,imx-mu */ + /delete-node/ mailbox@40c48000; + + /* Attach MBOX driver to MU Unit */ + mbox:mbox@40c48000 { + compatible = "nxp,mbox-imx-mu"; + reg = <0x40c48000 0x4000>; + interrupts = <118 0>; + rx-channels = <4>; + #mbox-cells = <1>; + status = "okay"; + }; + }; +}; \ No newline at end of file diff --git a/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evk_cm7.conf b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evk_cm7.conf new file mode 100644 index 00000000..583b4950 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evk_cm7.conf @@ -0,0 +1,3 @@ +CONFIG_MBOX_NXP_IMX_MU=y +CONFIG_INCLUDE_REMOTE_DIR=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evk_cm7.overlay b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evk_cm7.overlay new file mode 100644 index 00000000..f6388ee7 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evk_cm7.overlay @@ -0,0 +1,29 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* Delete ipc chosen property where old IPM mailbox driver bellow is + * configured. + */ + /delete-property/ zephyr,ipc; + }; + + soc { + /* Delete IPM Driver node nxp,imx-mu */ + /delete-node/ mailbox@40c48000; + + /* Attach MBOX driver to MU Unit */ + mbox:mbox@40c48000 { + compatible = "nxp,mbox-imx-mu"; + reg = <0x40c48000 0x4000>; + interrupts = <118 0>; + rx-channels = <4>; + #mbox-cells = <1>; + status = "okay"; + }; + }; +}; diff --git a/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evkb_cm7.conf b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evkb_cm7.conf new file mode 100644 index 00000000..0dfb100e --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evkb_cm7.conf @@ -0,0 +1,3 @@ +CONFIG_MBOX_NXP_IMX_MU=y +CONFIG_SECOND_CORE_MCUX=y +CONFIG_INCLUDE_REMOTE_DIR=y diff --git a/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evkb_cm7.overlay b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evkb_cm7.overlay new file mode 100644 index 00000000..f6388ee7 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/boards/mimxrt1170_evkb_cm7.overlay @@ -0,0 +1,29 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* Delete ipc chosen property where old IPM mailbox driver bellow is + * configured. + */ + /delete-property/ zephyr,ipc; + }; + + soc { + /* Delete IPM Driver node nxp,imx-mu */ + /delete-node/ mailbox@40c48000; + + /* Attach MBOX driver to MU Unit */ + mbox:mbox@40c48000 { + compatible = "nxp,mbox-imx-mu"; + reg = <0x40c48000 0x4000>; + interrupts = <118 0>; + rx-channels = <4>; + #mbox-cells = <1>; + status = "okay"; + }; + }; +}; diff --git a/examples/zephyr/matrix_multiply_mbox/erpc_config.h b/examples/zephyr/matrix_multiply_mbox/erpc_config.h new file mode 100644 index 00000000..6076fd48 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/erpc_config.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2021 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_CONFIG_H_ +#define _ERPC_CONFIG_H_ + +/*! + * @addtogroup config + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +//! @name Threading model options +//@{ +#define ERPC_ALLOCATION_POLICY_DYNAMIC (0U) //!< Dynamic allocation policy +#define ERPC_ALLOCATION_POLICY_STATIC (1U) //!< Static allocation policy + +#define ERPC_THREADS_NONE (0U) //!< No threads. +#define ERPC_THREADS_PTHREADS (1U) //!< POSIX pthreads. +#define ERPC_THREADS_FREERTOS (2U) //!< FreeRTOS. +#define ERPC_THREADS_ZEPHYR (3U) //!< ZEPHYR. +#define ERPC_THREADS_MBED (4U) //!< Mbed OS +#define ERPC_THREADS_WIN32 (5U) //!< WIN32 +#define ERPC_THREADS_THREADX (6U) //!< THREADX + +#define ERPC_NOEXCEPT_DISABLED (0U) //!< Disabling noexcept feature. +#define ERPC_NOEXCEPT_ENABLED (1U) //!< Enabling noexcept feature. + +#define ERPC_NESTED_CALLS_DISABLED (0U) //!< No nested calls support. +#define ERPC_NESTED_CALLS_ENABLED (1U) //!< Nested calls support. + +#define ERPC_NESTED_CALLS_DETECTION_DISABLED (0U) //!< Nested calls detection disabled. +#define ERPC_NESTED_CALLS_DETECTION_ENABLED (1U) //!< Nested calls detection enabled. + +#define ERPC_MESSAGE_LOGGING_DISABLED (0U) //!< Trace functions disabled. +#define ERPC_MESSAGE_LOGGING_ENABLED (1U) //!< Trace functions enabled. + +#define ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED (0U) //!< Do not use MCMGR for MU ISR management. +#define ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED (1U) //!< Use MCMGR for MU ISR management. + +#define ERPC_PRE_POST_ACTION_DISABLED (0U) //!< Pre post shim callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_ENABLED (1U) //!< Pre post shim callback functions enabled. + +#define ERPC_PRE_POST_ACTION_DEFAULT_DISABLED (0U) //!< Pre post shim default callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_DEFAULT_ENABLED (1U) //!< Pre post shim default callback functions enabled. +//@} + +//! @name Configuration options +//@{ + +//! @def ERPC_ALLOCATION_POLICY +//! +//! @brief Choose which allocation policy should be used. +//! +//! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. +//! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. +//! +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is +//! supported by compiler. Uncomment comment bellow to use static allocation policy. In case of static implementation +//! user need consider another values to set (ERPC_CODEC_COUNT, ERPC_MESSAGE_LOGGERS_COUNT, +//! ERPC_CLIENTS_THREADS_AMOUNT). +// #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_STATIC) + +//! @def ERPC_CODEC_COUNT +//! +//! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one +//! thread per each then 2, ... Default value 2. +// #define ERPC_CODEC_COUNT (2U) + +//! @def ERPC_MESSAGE_LOGGERS_COUNT +//! +//! @brief Set amount of message loggers objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. +//! For example if client or server is used in one thread then 1. If both are used in one thread per each then 2, ... +//! For arbitrated client 1 is enough. +//! Default value 0 (May not be used). +// #define ERPC_MESSAGE_LOGGERS_COUNT (0U) + +//! @def ERPC_CLIENTS_THREADS_AMOUNT +//! +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. Default value 1 (Most of current cases). +// #define ERPC_CLIENTS_THREADS_AMOUNT (1U) + +//! @def ERPC_THREADS +//! +//! @brief Select threading model. +//! +//! Set to one of the @c ERPC_THREADS_x macros to specify the threading model used by eRPC. +//! +//! Leave commented out to attempt to auto-detect. Auto-detection works well for pthreads. +//! FreeRTOS can be detected when building with compilers that support __has_include(). +//! Otherwise, the default is no threading. +#define ERPC_THREADS (ERPC_THREADS_NONE) + +//! @def ERPC_DEFAULT_BUFFER_SIZE +//! +//! Uncomment to change the size of buffers allocated by one of MessageBufferFactory. +//! (@ref client_setup and @ref server_setup). The default size is set to 256. +//! For RPMsg transport layer, ERPC_DEFAULT_BUFFER_SIZE must be 2^n - 16. +#define ERPC_DEFAULT_BUFFER_SIZE (4096U) + +//! @def ERPC_DEFAULT_BUFFERS_COUNT +//! +//! Uncomment to change the count of buffers allocated by one of statically allocated messages. +//! Default value is set to 2. +//#define ERPC_DEFAULT_BUFFERS_COUNT (2U) + +//! @def ERPC_NOEXCEPT +//! +//! @brief Disable/enable noexcept support. +//! +//! Uncomment for using noexcept feature. +//#define ERPC_NOEXCEPT (ERPC_NOEXCEPT_ENABLED) + +//! @def ERPC_NESTED_CALLS +//! +//! Default set to ERPC_NESTED_CALLS_DISABLED. Uncomment when callbacks, or other eRPC +//! functions are called from server implementation of another eRPC call. Nested functions +//! need to be marked as @nested in IDL. +//#define ERPC_NESTED_CALLS (ERPC_NESTED_CALLS_ENABLED) + +//! @def ERPC_NESTED_CALLS_DETECTION +//! +//! Default set to ERPC_NESTED_CALLS_DETECTION_ENABLED when NDEBUG macro is presented. +//! This serve for locating nested calls in code. Nested calls are calls where inside eRPC function +//! on server side is called another eRPC function (like callbacks). Code need be a bit changed +//! to support nested calls. See ERPC_NESTED_CALLS macro. +//#define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_DISABLED) + +//! @def ERPC_MESSAGE_LOGGING +//! +//! Enable eRPC message logging code through the eRPC. Take look into "erpc_message_loggers.h". Can be used for base +//! printing messages, or sending data to another system for data analysis. Default set to +//! ERPC_MESSAGE_LOGGING_DISABLED. +//! +//! Uncomment for using logging feature. +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) + +//! @def ERPC_TRANSPORT_MU_USE_MCMGR +//! +//! @brief MU transport layer configuration. +//! +//! Set to one of the @c ERPC_TRANSPORT_MU_USE_MCMGR_x macros to configure the MCMGR usage in MU transport layer. +//! +//! MU transport layer could leverage the Multicore Manager (MCMGR) component for Inter-Core +//! interrupts / MU interrupts management or the Inter-Core interrupts can be managed by itself (MUX_IRQHandler +//! overloading). By default, ERPC_TRANSPORT_MU_USE_MCMGR is set to ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED when mcmgr.h +//! is part of the project, otherwise the ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED option is used. This settings can be +//! overwritten from the erpc_config.h by uncommenting the ERPC_TRANSPORT_MU_USE_MCMGR macro definition. Do not forget +//! to add the MCMGR library into your project when ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED option is used! See the +//! erpc_mu_transport.h for additional MU settings. +//#define ERPC_TRANSPORT_MU_USE_MCMGR ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED +//@} + +//! @def ERPC_PRE_POST_ACTION +//! +//! Enable eRPC pre and post callback functions shim code. Take look into "erpc_pre_post_action.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DISABLED. +//! +//! Uncomment for using pre post callback feature. +//#define ERPC_PRE_POST_ACTION (ERPC_PRE_POST_ACTION_ENABLED) + +//! @def ERPC_PRE_POST_ACTION_DEFAULT +//! +//! Enable eRPC pre and post default callback functions. Take look into "erpc_setup_extensions.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DEFAULT_DISABLED. +//! +//! Uncomment for using pre post default callback feature. +//#define ERPC_PRE_POST_ACTION_DEFAULT (ERPC_PRE_POST_ACTION_DEFAULT_ENABLED) + +/*! @} */ +#endif // _ERPC_CONFIG_H_ +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/examples/zephyr/matrix_multiply_mbox/prj.conf b/examples/zephyr/matrix_multiply_mbox/prj.conf new file mode 100644 index 00000000..c42a45e0 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/prj.conf @@ -0,0 +1,18 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP20=y +CONFIG_NEWLIB_LIBC=y +CONFIG_GLIBCXX_LIBCPP=y + +# Compiler +CONFIG_MAIN_STACK_SIZE=4096 +CONFIG_HEAP_MEM_POOL_SIZE=8192 +CONFIG_NO_OPTIMIZATIONS=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_MBOX=y + +# MBOX +CONFIG_MBOX=y + diff --git a/examples/zephyr/matrix_multiply_mbox/remote/CMakeLists.txt b/examples/zephyr/matrix_multiply_mbox/remote/CMakeLists.txt new file mode 100644 index 00000000..35d431a0 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/CMakeLists.txt @@ -0,0 +1,45 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) + +if(("${BOARD}" STREQUAL "mimxrt1170_evkb_cm4") OR + ("${BOARD}" STREQUAL "mimxrt1170_evk_cm4") OR + ("${BOARD}" STREQUAL "mimxrt1160_evk_cm4")) + message(STATUS "${BOARD} compile as remote in this sample") +else() + message(FATAL_ERROR "${BOARD} is not supported for this sample") +endif() + +project(remote) + +message(STATUS "${BOARD} compiles as remote in this sample") + +target_include_directories(app PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/..) + +enable_language(C CXX) + +target_include_directories(app PRIVATE + ${PROJECT_SOURCE_DIR}/.. + ${PROJECT_SOURCE_DIR}/src + ${PROJECT_SOURCE_DIR}/src/service +) + +target_sources(app PRIVATE + # Main files + ${PROJECT_SOURCE_DIR}/src/main.cpp + ${PROJECT_SOURCE_DIR}/src/erpc_error_handler.cpp + + # Generated shim code + ${PROJECT_SOURCE_DIR}/src/service/c_erpc_matrix_multiply_server.cpp + ${PROJECT_SOURCE_DIR}/src/service/erpc_matrix_multiply_server.cpp + ${PROJECT_SOURCE_DIR}/src/service/erpc_matrix_multiply_interface.cpp +) + +# Same for erpc library and erpc_config.h +target_include_directories(erpc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/..) \ No newline at end of file diff --git a/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1160_evk_cm4.conf b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1160_evk_cm4.conf new file mode 100644 index 00000000..af787c38 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1160_evk_cm4.conf @@ -0,0 +1,4 @@ +CONFIG_MBOX_NXP_IMX_MU=y +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y \ No newline at end of file diff --git a/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1160_evk_cm4.overlay b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1160_evk_cm4.overlay new file mode 100644 index 00000000..3b0e39f8 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1160_evk_cm4.overlay @@ -0,0 +1,48 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart1; + zephyr,shell-uart = &lpuart1; + + /* Delete ipc chosen property where old IPM mailbox driver bellow is + * configured. + */ + /delete-property/ zephyr,ipc; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + + /* Delete IPM Driver node nxp,imx-mu */ + /delete-node/ mailbox@40c4c000; + + /* Attach MBOX driver to MU Unit */ + mbox:mbox@40c4c000 { + compatible = "nxp,mbox-imx-mu"; + reg = <0x40c4c000 0x4000>; + interrupts = <118 0>; + rx-channels = <4>; + #mbox-cells = <1>; + status = "okay"; + }; + }; +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; \ No newline at end of file diff --git a/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evk_cm4.conf b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evk_cm4.conf new file mode 100644 index 00000000..0d36a72a --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evk_cm4.conf @@ -0,0 +1,4 @@ +CONFIG_MBOX_NXP_IMX_MU=y +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evk_cm4.overlay b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evk_cm4.overlay new file mode 100644 index 00000000..9cf09274 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evk_cm4.overlay @@ -0,0 +1,48 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart1; + zephyr,shell-uart = &lpuart1; + + /* Delete ipc chosen property where old IPM mailbox driver bellow is + * configured. + */ + /delete-property/ zephyr,ipc; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + + /* Delete IPM Driver node nxp,imx-mu */ + /delete-node/ mailbox@40c4c000; + + /* Attach MBOX driver to MU Unit */ + mbox:mbox@40c4c000 { + compatible = "nxp,mbox-imx-mu"; + reg = <0x40c4c000 0x4000>; + interrupts = <118 0>; + rx-channels = <4>; + #mbox-cells = <1>; + status = "okay"; + }; + }; +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; diff --git a/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evkb_cm4.conf b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evkb_cm4.conf new file mode 100644 index 00000000..0d36a72a --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evkb_cm4.conf @@ -0,0 +1,4 @@ +CONFIG_MBOX_NXP_IMX_MU=y +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evkb_cm4.overlay b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evkb_cm4.overlay new file mode 100644 index 00000000..56337d14 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/boards/mimxrt1170_evkb_cm4.overlay @@ -0,0 +1,49 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart1; + zephyr,shell-uart = &lpuart1; + + /* Delete ipc chosen property where old IPM mailbox driver bellow is + * configured. + */ + /delete-property/ zephyr,ipc; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + + /* Delete IPM Driver node nxp,imx-mu */ + /delete-node/ mailbox@40c4c000; + + /* Attach MBOX driver to MU Unit */ + mbox:mbox@40c4c000 { + compatible = "nxp,mbox-imx-mu"; + reg = <0x40c4c000 0x4000>; + interrupts = <118 0>; + rx-channels = <4>; + #mbox-cells = <1>; + status = "okay"; + }; + }; + +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; diff --git a/examples/zephyr/matrix_multiply_mbox/remote/prj.conf b/examples/zephyr/matrix_multiply_mbox/remote/prj.conf new file mode 100644 index 00000000..705181c7 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/prj.conf @@ -0,0 +1,19 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP20=y +CONFIG_NEWLIB_LIBC=y +CONFIG_GLIBCXX_LIBCPP=y + +# Compiler +CONFIG_MAIN_STACK_SIZE=4096 +CONFIG_HEAP_MEM_POOL_SIZE=8192 +CONFIG_NO_OPTIMIZATIONS=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_MBOX=y + +# MBOX +CONFIG_MBOX=y + +CONFIG_STDOUT_CONSOLE=n diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/erpc_error_handler.cpp b/examples/zephyr/matrix_multiply_mbox/remote/src/erpc_error_handler.cpp new file mode 100644 index 00000000..8be36267 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/erpc_error_handler.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_error_handler.h" +#include + +//////////////////////////////////////////////////////////////////////////////// +// Variables +//////////////////////////////////////////////////////////////////////////////// + +extern bool g_erpc_error_occurred; +bool g_erpc_error_occurred = false; + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +void erpc_error_handler(erpc_status_t err, uint32_t functionID) +{ + switch (err) + { + case kErpcStatus_Fail: + printk("\r\nGeneric failure."); + break; + + case kErpcStatus_InvalidArgument: + printk("\r\nArgument is an invalid value."); + break; + + case kErpcStatus_Timeout: + printk("\r\nOperated timed out."); + break; + + case kErpcStatus_InvalidMessageVersion: + printk("\r\nMessage header contains an unknown version."); + break; + + case kErpcStatus_ExpectedReply: + printk("\r\nExpected a reply message but got another message type."); + break; + + case kErpcStatus_CrcCheckFailed: + printk("\r\nMessage is corrupted."); + break; + + case kErpcStatus_BufferOverrun: + printk("\r\nAttempt to read or write past the end of a buffer."); + break; + + case kErpcStatus_UnknownName: + printk("\r\nCould not find host with given name."); + break; + + case kErpcStatus_ConnectionFailure: + printk("\r\nFailed to connect to host."); + break; + + case kErpcStatus_ConnectionClosed: + printk("\r\nConnected closed by peer."); + break; + + case kErpcStatus_MemoryError: + printk("\r\nMemory allocation error."); + break; + + case kErpcStatus_ServerIsDown: + printk("\r\nServer is stopped."); + break; + + case kErpcStatus_InitFailed: + printk("\r\nTransport layer initialization failed."); + break; + + case kErpcStatus_ReceiveFailed: + printk("\r\nFailed to receive data."); + break; + + case kErpcStatus_SendFailed: + printk("\r\nFailed to send data."); + break; + + /* no error occurred */ + case kErpcStatus_Success: + return; + + /* unhandled error */ + default: + printk("\r\nUnhandled error occurred."); + break; + } + + /* When error occurred on client side. */ + if (functionID != 0) + { + printk("Function id '%u'.", (unsigned int)functionID); + } + printk("\r\n"); + + /* error occurred */ + g_erpc_error_occurred = true; +} diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/erpc_error_handler.h b/examples/zephyr/matrix_multiply_mbox/remote/src/erpc_error_handler.h new file mode 100644 index 00000000..faf32559 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/erpc_error_handler.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2022 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__ERROR_HANDLER_H_ +#define _EMBEDDED_RPC__ERROR_HANDLER_H_ + +#include "erpc_common.h" +#include + +/*! + * @addtogroup error_handler + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// API +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +//! @name Error handler +//@{ + +/*! + * @brief This function handles eRPC errors. + * + * This function prints a description of occurred error and sets bool variable g_erpc_error_occurred which is used for + * determining if error occurred in user application on client side. + */ +void erpc_error_handler(erpc_status_t err, uint32_t functionID); + +//@} + +#ifdef __cplusplus +} +#endif + +/*! @} */ +#endif // _EMBEDDED_RPC__ERROR_HANDLER_H_ diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/main.cpp b/examples/zephyr/matrix_multiply_mbox/remote/src/main.cpp new file mode 100644 index 00000000..270ea40b --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/main.cpp @@ -0,0 +1,134 @@ +/* + * Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include + +#include "erpc_server_setup.h" +#include "erpc_mbox_zephyr_transport.hpp" +#include "erpc_error_handler.h" + + +#include "erpc_matrix_multiply_common.h" +#include "c_erpc_matrix_multiply_server.h" + +/******************************************************************************* + * Definitions + ******************************************************************************/ +#define TX_ID (0) +#define RX_ID (1) + +/******************************************************************************* + * Prototypes + ******************************************************************************/ + +/******************************************************************************* + * Code + ******************************************************************************/ + +/*! + * @brief erpcMatrixMultiply function implementation. + * + * This is the implementation of the erpcMatrixMultiply function called by the primary core. + * + * @param matrix1 First matrix + * @param matrix2 Second matrix + * @param result_matrix Result matrix + */ +void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) +{ + int32_t i, j, k; + + /* Clear the result matrix */ + for (i = 0; i < matrix_size; ++i) + { + for (j = 0; j < matrix_size; ++j) + { + result_matrix[i][j] = 0; + } + } + + /* Multiply two matrices */ + for (i = 0; i < matrix_size; ++i) + { + for (j = 0; j < matrix_size; ++j) + { + for (k = 0; k < matrix_size; ++k) + { + result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]; + } + } + } +} + +/*! + * @brief Main function + */ +int main(void) +{ + struct mbox_channel tx_channel; + struct mbox_channel rx_channel; + const struct device *dev; + + erpc_transport_t transport; + erpc_server_t server; + + dev = DEVICE_DT_GET(DT_NODELABEL(mbox)); + printk("REMOTE: MTU %d\n", mbox_mtu_get(dev)); + + + /* MBOX transport layer initialization */ + mbox_init_channel(&tx_channel, dev, TX_ID); + mbox_init_channel(&rx_channel, dev, RX_ID); + + transport = erpc_transport_zephyr_mbox_init((void *)dev, (void *)&tx_channel, (void *)&rx_channel); + + /* MessageBufferFactory initialization */ + erpc_mbf_t message_buffer_factory; + message_buffer_factory = erpc_mbf_dynamic_init(); + + /* eRPC server side initialization */ + server = erpc_server_init(transport, message_buffer_factory); + + /* adding the service to the server */ + erpc_service_t service = create_MatrixMultiplyService_service(); + erpc_add_service_to_server(server, service); + + for (;;) + { + /* process message */ + erpc_status_t status = erpc_server_poll(server); + + /* handle error status */ + if (status != (erpc_status_t)kErpcStatus_Success) + { + /* print error description */ + erpc_error_handler(status, 0); + + /* removing the service from the server */ + erpc_remove_service_from_server(server, service); + destroy_MatrixMultiplyService_service(service); + + /* stop erpc server */ + erpc_server_stop(server); + + /* print error description */ + erpc_server_deinit(server); + + /* exit program loop */ + break; + } + + /* do other tasks */ + int32_t i; + for (i = 0; i < 10000; i++) + { + } + } + for (;;) + { + } +} diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/c_erpc_matrix_multiply_server.cpp b/examples/zephyr/matrix_multiply_mbox/remote/src/service/c_erpc_matrix_multiply_server.cpp new file mode 100644 index 00000000..d65660ce --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/c_erpc_matrix_multiply_server.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#include +#include "c_erpc_matrix_multiply_server.h" +#include "erpc_matrix_multiply_server.hpp" +#include "erpc_manually_constructed.hpp" + +using namespace erpc; +using namespace std; +using namespace erpcShim; + + +class MatrixMultiplyService_server: public MatrixMultiplyService_interface +{ + public: + virtual ~MatrixMultiplyService_server() {}; + + + void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) + { + ::erpcMatrixMultiply(matrix1, matrix2, result_matrix); + } +}; + +ERPC_MANUALLY_CONSTRUCTED_STATIC(MatrixMultiplyService_service, s_MatrixMultiplyService_service); +ERPC_MANUALLY_CONSTRUCTED_STATIC(MatrixMultiplyService_server, s_MatrixMultiplyService_server); + +erpc_service_t create_MatrixMultiplyService_service(void) +{ + erpc_service_t service; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + service = new (nothrow) MatrixMultiplyService_service(new (nothrow)MatrixMultiplyService_server()); +#else + if (s_MatrixMultiplyService_service.isUsed()) + { + service = NULL; + } + else + { + s_MatrixMultiplyService_server.construct(); + s_MatrixMultiplyService_service.construct(s_MatrixMultiplyService_server.get()); + service = s_MatrixMultiplyService_service.get(); + } +#endif + + return service; +} + +void destroy_MatrixMultiplyService_service(erpc_service_t service) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + if (service) + { + delete (MatrixMultiplyService_server *)(((MatrixMultiplyService_service *)service)->getHandler()); + delete (MatrixMultiplyService_service *)service; + } +#else + (void)service; + erpc_assert(service == s_MatrixMultiplyService_service.get()); + s_MatrixMultiplyService_service.destroy(); + s_MatrixMultiplyService_server.destroy(); +#endif +} + diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/c_erpc_matrix_multiply_server.h b/examples/zephyr/matrix_multiply_mbox/remote/src/service/c_erpc_matrix_multiply_server.h new file mode 100644 index 00000000..b7e7815d --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/c_erpc_matrix_multiply_server.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_c_erpc_matrix_multiply_server_h_) +#define _c_erpc_matrix_multiply_server_h_ + +#include "erpc_matrix_multiply_common.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +typedef void * erpc_service_t; + +#if !defined(ERPC_FUNCTIONS_DEFINITIONS) +#define ERPC_FUNCTIONS_DEFINITIONS + + +/*! @brief MatrixMultiplyService identifiers */ +enum _MatrixMultiplyService_ids +{ + kMatrixMultiplyService_service_id = 1, + kMatrixMultiplyService_erpcMatrixMultiply_id = 1, +}; + +//! @name MatrixMultiplyService +//@{ +void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix); +//@} + + +#endif // ERPC_FUNCTIONS_DEFINITIONS + +/*! @brief Return MatrixMultiplyService_service service object. */ +erpc_service_t create_MatrixMultiplyService_service(void); + +/*! @brief Destroy MatrixMultiplyService_service service object. */ +void destroy_MatrixMultiplyService_service(erpc_service_t service); + + +#if defined(__cplusplus) +} +#endif + +#endif // _c_erpc_matrix_multiply_server_h_ diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply.erpc b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply.erpc new file mode 100644 index 00000000..bfcece34 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply.erpc @@ -0,0 +1,24 @@ +//Copyright below will be added into all generated files. +/*! + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +program erpc_matrix_multiply + +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +const int32 matrix_size = 5; + +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +type Matrix = int32[matrix_size][matrix_size]; + +interface MatrixMultiplyService { + erpcMatrixMultiply(in Matrix matrix1, in Matrix matrix2, out Matrix result_matrix) -> void +} diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_common.h b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_common.h new file mode 100644 index 00000000..5015f99a --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_common.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_common_h_) +#define _erpc_matrix_multiply_common_h_ + + +#if defined(__cplusplus) +extern "C" +{ +#endif +#include +#include +#include + +#include "erpc_version.h" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +#if !defined(ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY) +#define ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +// Aliases data types declarations +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +typedef int32_t Matrix[5][5]; + +// Constant variable declarations +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +extern const int32_t matrix_size; + +#endif // ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +#if defined(__cplusplus) +} +#endif + +#endif // _erpc_matrix_multiply_common_h_ diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_common.hpp new file mode 100644 index 00000000..56efc4ad --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_common.hpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_common_hpp_) +#define _erpc_matrix_multiply_common_hpp_ + + +#include +#include + +#include "erpc_version.h" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +#if !defined(ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY) +#define ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +// Aliases data types declarations +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +typedef int32_t Matrix[5][5]; + +// Constant variable declarations +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +extern const int32_t matrix_size; + +#endif // ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + + +#endif // _erpc_matrix_multiply_common_hpp_ diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_interface.cpp b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_interface.cpp new file mode 100644 index 00000000..ceb050fe --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_interface.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#include "erpc_matrix_multiply_interface.hpp" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +using namespace std; +using namespace erpcShim; + +MatrixMultiplyService_interface::~MatrixMultiplyService_interface(void) +{ +} diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_interface.hpp b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_interface.hpp new file mode 100644 index 00000000..e4426378 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_interface.hpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_interface_hpp_) +#define _erpc_matrix_multiply_interface_hpp_ + +#include "erpc_matrix_multiply_common.hpp" + +namespace erpcShim +{ + + +// Abstract base class for MatrixMultiplyService +class MatrixMultiplyService_interface +{ + public: + static const uint8_t m_serviceId = 1; + static const uint8_t m_erpcMatrixMultiplyId = 1; + + virtual ~MatrixMultiplyService_interface(void); + + virtual void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) = 0; +private: +}; +} // erpcShim + + +#endif // _erpc_matrix_multiply_interface_hpp_ diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_server.cpp b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_server.cpp new file mode 100644 index 00000000..a190dcfa --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_server.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#include "erpc_matrix_multiply_server.hpp" +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC +#include +#include "erpc_port.h" +#endif +#include "erpc_manually_constructed.hpp" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + +using namespace erpc; +using namespace std; +using namespace erpcShim; + +#if ERPC_NESTED_CALLS_DETECTION +extern bool nestingDetection; +#endif + + + +// Constant variable definitions +#if defined(__MINGW32__) +__declspec( selectany ) +#else +#pragma weak matrix_size +#endif +extern const int32_t matrix_size = 5; + + +MatrixMultiplyService_service::MatrixMultiplyService_service(MatrixMultiplyService_interface *_MatrixMultiplyService_interface) + : erpc::Service(MatrixMultiplyService_interface::m_serviceId) + , m_handler(_MatrixMultiplyService_interface) +{ +} + +MatrixMultiplyService_service::~MatrixMultiplyService_service() +{ +} + +// return service interface handler. +MatrixMultiplyService_interface* MatrixMultiplyService_service::getHandler(void) +{ + return m_handler; +} + +// Call the correct server shim based on method unique ID. +erpc_status_t MatrixMultiplyService_service::handleInvocation(uint32_t methodId, uint32_t sequence, Codec * codec, MessageBufferFactory *messageFactory, Transport * transport) +{ + erpc_status_t erpcStatus; + switch (methodId) + { + case MatrixMultiplyService_interface::m_erpcMatrixMultiplyId: + { + erpcStatus = erpcMatrixMultiply_shim(codec, messageFactory, transport, sequence); + break; + } + + default: + { + erpcStatus = kErpcStatus_InvalidArgument; + break; + } + } + + return erpcStatus; +} + +// Server shim for erpcMatrixMultiply of MatrixMultiplyService interface. +erpc_status_t MatrixMultiplyService_service::erpcMatrixMultiply_shim(Codec * codec, MessageBufferFactory *messageFactory, Transport * transport, uint32_t sequence) +{ + erpc_status_t err = kErpcStatus_Success; + + Matrix matrix1; + Matrix matrix2; + Matrix result_matrix; + + // startReadMessage() was already called before this shim was invoked. + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->read(matrix1[arrayCount0][arrayCount1]); + } + } + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->read(matrix2[arrayCount0][arrayCount1]); + } + } + + err = codec->getStatus(); + if (err == kErpcStatus_Success) + { + // Invoke the actual served function. +#if ERPC_NESTED_CALLS_DETECTION + nestingDetection = true; +#endif + m_handler->erpcMatrixMultiply(matrix1, matrix2, result_matrix); +#if ERPC_NESTED_CALLS_DETECTION + nestingDetection = false; +#endif + + // preparing MessageBuffer for serializing data + err = messageFactory->prepareServerBufferForSend(codec->getBufferRef(), transport->reserveHeaderSize()); + } + + if (err == kErpcStatus_Success) + { + // preparing codec for serializing data + codec->reset(transport->reserveHeaderSize()); + + // Build response message. + codec->startWriteMessage(message_type_t::kReplyMessage, MatrixMultiplyService_interface::m_serviceId, MatrixMultiplyService_interface::m_erpcMatrixMultiplyId, sequence); + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->write(result_matrix[arrayCount0][arrayCount1]); + } + } + + err = codec->getStatus(); + } + + return err; +} diff --git a/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_server.hpp b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_server.hpp new file mode 100644 index 00000000..9a5efd0a --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/remote/src/service/erpc_matrix_multiply_server.hpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_server_hpp_) +#define _erpc_matrix_multiply_server_hpp_ + +#include "erpc_matrix_multiply_interface.hpp" + +#include "erpc_server.hpp" +#include "erpc_codec.hpp" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +namespace erpcShim +{ + +/*! + * @brief Service subclass for MatrixMultiplyService. + */ +class MatrixMultiplyService_service : public erpc::Service +{ +public: + MatrixMultiplyService_service(MatrixMultiplyService_interface *_MatrixMultiplyService_interface); + + virtual ~MatrixMultiplyService_service(); + + /*! @brief return service interface handler. */ + MatrixMultiplyService_interface* getHandler(void); + + /*! @brief Call the correct server shim based on method unique ID. */ + virtual erpc_status_t handleInvocation(uint32_t methodId, uint32_t sequence, erpc::Codec * codec, erpc::MessageBufferFactory *messageFactory, erpc::Transport * transport); + +private: + MatrixMultiplyService_interface *m_handler; + /*! @brief Server shim for erpcMatrixMultiply of MatrixMultiplyService interface. */ + erpc_status_t erpcMatrixMultiply_shim(erpc::Codec * codec, erpc::MessageBufferFactory *messageFactory, erpc::Transport * transport, uint32_t sequence); +}; + +} // erpcShim + + +#endif // _erpc_matrix_multiply_server_hpp_ diff --git a/examples/zephyr/matrix_multiply_mbox/sample.yaml b/examples/zephyr/matrix_multiply_mbox/sample.yaml new file mode 100644 index 00000000..10e90eb7 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/sample.yaml @@ -0,0 +1,6 @@ +sample: + description: eRPC Matrix multiplication using MBOX transport layer + name: eRPC MBOX Matrix multiplication +common: + sysbuild: true + tags: mbox diff --git a/examples/zephyr/matrix_multiply_mbox/src/erpc_error_handler.cpp b/examples/zephyr/matrix_multiply_mbox/src/erpc_error_handler.cpp new file mode 100644 index 00000000..8be36267 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/erpc_error_handler.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_error_handler.h" +#include + +//////////////////////////////////////////////////////////////////////////////// +// Variables +//////////////////////////////////////////////////////////////////////////////// + +extern bool g_erpc_error_occurred; +bool g_erpc_error_occurred = false; + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +void erpc_error_handler(erpc_status_t err, uint32_t functionID) +{ + switch (err) + { + case kErpcStatus_Fail: + printk("\r\nGeneric failure."); + break; + + case kErpcStatus_InvalidArgument: + printk("\r\nArgument is an invalid value."); + break; + + case kErpcStatus_Timeout: + printk("\r\nOperated timed out."); + break; + + case kErpcStatus_InvalidMessageVersion: + printk("\r\nMessage header contains an unknown version."); + break; + + case kErpcStatus_ExpectedReply: + printk("\r\nExpected a reply message but got another message type."); + break; + + case kErpcStatus_CrcCheckFailed: + printk("\r\nMessage is corrupted."); + break; + + case kErpcStatus_BufferOverrun: + printk("\r\nAttempt to read or write past the end of a buffer."); + break; + + case kErpcStatus_UnknownName: + printk("\r\nCould not find host with given name."); + break; + + case kErpcStatus_ConnectionFailure: + printk("\r\nFailed to connect to host."); + break; + + case kErpcStatus_ConnectionClosed: + printk("\r\nConnected closed by peer."); + break; + + case kErpcStatus_MemoryError: + printk("\r\nMemory allocation error."); + break; + + case kErpcStatus_ServerIsDown: + printk("\r\nServer is stopped."); + break; + + case kErpcStatus_InitFailed: + printk("\r\nTransport layer initialization failed."); + break; + + case kErpcStatus_ReceiveFailed: + printk("\r\nFailed to receive data."); + break; + + case kErpcStatus_SendFailed: + printk("\r\nFailed to send data."); + break; + + /* no error occurred */ + case kErpcStatus_Success: + return; + + /* unhandled error */ + default: + printk("\r\nUnhandled error occurred."); + break; + } + + /* When error occurred on client side. */ + if (functionID != 0) + { + printk("Function id '%u'.", (unsigned int)functionID); + } + printk("\r\n"); + + /* error occurred */ + g_erpc_error_occurred = true; +} diff --git a/examples/zephyr/matrix_multiply_mbox/src/erpc_error_handler.h b/examples/zephyr/matrix_multiply_mbox/src/erpc_error_handler.h new file mode 100644 index 00000000..faf32559 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/erpc_error_handler.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2022 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__ERROR_HANDLER_H_ +#define _EMBEDDED_RPC__ERROR_HANDLER_H_ + +#include "erpc_common.h" +#include + +/*! + * @addtogroup error_handler + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// API +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +//! @name Error handler +//@{ + +/*! + * @brief This function handles eRPC errors. + * + * This function prints a description of occurred error and sets bool variable g_erpc_error_occurred which is used for + * determining if error occurred in user application on client side. + */ +void erpc_error_handler(erpc_status_t err, uint32_t functionID); + +//@} + +#ifdef __cplusplus +} +#endif + +/*! @} */ +#endif // _EMBEDDED_RPC__ERROR_HANDLER_H_ diff --git a/examples/zephyr/matrix_multiply_mbox/src/main.cpp b/examples/zephyr/matrix_multiply_mbox/src/main.cpp new file mode 100644 index 00000000..4c267d46 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/main.cpp @@ -0,0 +1,152 @@ +/* + * Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ +#include +#include + +#include "erpc_client_setup.h" +#include "erpc_mbox_zephyr_transport.hpp" +#include "erpc_error_handler.h" + +#include "c_erpc_matrix_multiply_client.h" +#include "erpc_matrix_multiply_common.h" + + + +/******************************************************************************* + * Definitions + ******************************************************************************/ +#define MATRIX_ITEM_MAX_VALUE (50) +#define APP_ERPC_READY_EVENT_DATA (1U) + +#define TX_ID (1) +#define RX_ID (0) + +/******************************************************************************* + * Variables + ******************************************************************************/ +extern bool g_erpc_error_occurred; + +/******************************************************************************* + * Prototypes + ******************************************************************************/ + +/******************************************************************************* + * Code + ******************************************************************************/ + +/*! + * @brief Fill matrices by random values + */ +static void fill_matrices(Matrix matrix1_ptr, Matrix matrix2_ptr) +{ + int32_t a, b; + + /* Fill both matrices by random values */ + for (a = 0; a < matrix_size; ++a) + { + for (b = 0; b < matrix_size; ++b) + { + matrix1_ptr[a][b] = rand() % MATRIX_ITEM_MAX_VALUE; + matrix2_ptr[a][b] = rand() % MATRIX_ITEM_MAX_VALUE; + } + } +} + +/*! + * @brief Printing a matrix to the console + */ +static void print_matrix(Matrix matrix_ptr) +{ + int32_t a, b; + + for (a = 0; a < matrix_size; ++a) + { + for (b = 0; b < matrix_size; ++b) + { + printk("%4i ", matrix_ptr[a][b]); + } + printk("\r\n"); + } +} + +int main(void) +{ + struct mbox_channel tx_channel; + struct mbox_channel rx_channel; + const struct device *dev; + + erpc_transport_t transport; + erpc_client_t client; + + Matrix matrix1 = { 0 }, matrix2 = { 0 }, result_matrix = { 0 }; + + dev = DEVICE_DT_GET(DT_NODELABEL(mbox)); + + /* MBOX transport layer initialization */ + + mbox_init_channel(&tx_channel, dev, TX_ID); + mbox_init_channel(&rx_channel, dev, RX_ID); + + transport = erpc_transport_zephyr_mbox_init((void *)dev, (void *)&tx_channel, (void *)&rx_channel); + + /* MessageBufferFactory initialization */ + erpc_mbf_t message_buffer_factory; + message_buffer_factory = erpc_mbf_dynamic_init(); + + /* eRPC client side initialization */ + client = erpc_client_init(transport, message_buffer_factory); + initMatrixMultiplyService_client(client); + + /* Set default error handler */ + erpc_client_set_error_handler(client, erpc_error_handler); + + /* Fill both matrices by random values */ + fill_matrices(matrix1, matrix2); + + /* Print both matrices on the console */ + printk("\r\nMatrix #1"); + printk("\r\n=========\r\n"); + print_matrix(matrix1); + + printk("\r\nMatrix #2"); + printk("\r\n=========\r\n"); + print_matrix(matrix2); + + for (;;) + { + printk("\r\neRPC request is sent to the server\r\n"); + + erpcMatrixMultiply(matrix1, matrix2, result_matrix); + + /* Check if some error occurred in eRPC */ + if (g_erpc_error_occurred) + { + /* Exit program loop */ + break; + } + + printk("\r\nResult matrix"); + printk("\r\n=============\r\n"); + print_matrix(result_matrix); + + k_sleep(K_MSEC(1000)); + + /* Fill both matrices by random values */ + fill_matrices(matrix1, matrix2); + + /* Print both matrices on the console */ + printk("\r\nMatrix #1"); + printk("\r\n=========\r\n"); + print_matrix(matrix1); + + printk("\r\nMatrix #2"); + printk("\r\n=========\r\n"); + print_matrix(matrix2); + } + for (;;) + { + } +} diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/c_erpc_matrix_multiply_client.cpp b/examples/zephyr/matrix_multiply_mbox/src/service/c_erpc_matrix_multiply_client.cpp new file mode 100644 index 00000000..a20696f5 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/c_erpc_matrix_multiply_client.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#include "c_erpc_matrix_multiply_client.h" +#include "erpc_matrix_multiply_client.hpp" +#include "erpc_manually_constructed.hpp" + +using namespace erpc; +using namespace std; +using namespace erpcShim; + + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC +MatrixMultiplyService_client *s_MatrixMultiplyService_client = nullptr; +#else +ERPC_MANUALLY_CONSTRUCTED_STATIC(MatrixMultiplyService_client, s_MatrixMultiplyService_client); +#endif + +void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) +{ + s_MatrixMultiplyService_client->erpcMatrixMultiply(matrix1, matrix2, result_matrix); +} + +void initMatrixMultiplyService_client(erpc_client_t client) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + erpc_assert(s_MatrixMultiplyService_client == nullptr); + s_MatrixMultiplyService_client = new MatrixMultiplyService_client(reinterpret_cast(client)); +#else + erpc_assert(!s_MatrixMultiplyService_client.isUsed()); + s_MatrixMultiplyService_client.construct(reinterpret_cast(client)); +#endif +} + +void deinitMatrixMultiplyService_client(void) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + if (s_MatrixMultiplyService_client != nullptr) + { + delete s_MatrixMultiplyService_client; + s_MatrixMultiplyService_client = nullptr; + } +#else + s_MatrixMultiplyService_client.destroy(); +#endif +} diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/c_erpc_matrix_multiply_client.h b/examples/zephyr/matrix_multiply_mbox/src/service/c_erpc_matrix_multiply_client.h new file mode 100644 index 00000000..7fc9a163 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/c_erpc_matrix_multiply_client.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_c_erpc_matrix_multiply_client_h_) +#define _c_erpc_matrix_multiply_client_h_ + +#include "erpc_matrix_multiply_common.h" +#include "erpc_client_manager.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#if !defined(ERPC_FUNCTIONS_DEFINITIONS) +#define ERPC_FUNCTIONS_DEFINITIONS + + +/*! @brief MatrixMultiplyService identifiers */ +enum _MatrixMultiplyService_ids +{ + kMatrixMultiplyService_service_id = 1, + kMatrixMultiplyService_erpcMatrixMultiply_id = 1, +}; + +//! @name MatrixMultiplyService +//@{ +void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix); +//@} + +#endif // ERPC_FUNCTIONS_DEFINITIONS + +void initMatrixMultiplyService_client(erpc_client_t client); + +void deinitMatrixMultiplyService_client(void); + +#if defined(__cplusplus) +} +#endif + +#endif // _c_erpc_matrix_multiply_client_h_ diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply.erpc b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply.erpc new file mode 100644 index 00000000..bfcece34 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply.erpc @@ -0,0 +1,24 @@ +//Copyright below will be added into all generated files. +/*! + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +program erpc_matrix_multiply + +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +const int32 matrix_size = 5; + +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +type Matrix = int32[matrix_size][matrix_size]; + +interface MatrixMultiplyService { + erpcMatrixMultiply(in Matrix matrix1, in Matrix matrix2, out Matrix result_matrix) -> void +} diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_client.cpp b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_client.cpp new file mode 100644 index 00000000..bc890132 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_client.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC +#include "erpc_port.h" +#endif +#include "erpc_codec.hpp" +#include "erpc_matrix_multiply_client.hpp" +#include "erpc_manually_constructed.hpp" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + +using namespace erpc; +using namespace std; +using namespace erpcShim; + + +// Constant variable definitions +#if defined(__MINGW32__) +__declspec( selectany ) +#else +#pragma weak matrix_size +#endif +extern const int32_t matrix_size = 5; + + + +MatrixMultiplyService_client::MatrixMultiplyService_client(ClientManager *manager) +:m_clientManager(manager) +{ +} + +MatrixMultiplyService_client::~MatrixMultiplyService_client() +{ +} + +// MatrixMultiplyService interface erpcMatrixMultiply function client shim. +void MatrixMultiplyService_client::erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) +{ + erpc_status_t err = kErpcStatus_Success; + + +#if ERPC_PRE_POST_ACTION + pre_post_action_cb preCB = m_clientManager->getPreCB(); + if (preCB) + { + preCB(); + } +#endif + + // Get a new request. + RequestContext request = m_clientManager->createRequest(false); + + // Encode the request. + Codec * codec = request.getCodec(); + + if (codec == NULL) + { + err = kErpcStatus_MemoryError; + } + else + { + codec->startWriteMessage(message_type_t::kInvocationMessage, m_serviceId, m_erpcMatrixMultiplyId, request.getSequence()); + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->write(matrix1[arrayCount0][arrayCount1]); + } + } + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->write(matrix2[arrayCount0][arrayCount1]); + } + } + + // Send message to server + // Codec status is checked inside this function. + m_clientManager->performRequest(request); + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->read(result_matrix[arrayCount0][arrayCount1]); + } + } + + err = codec->getStatus(); + } + + // Dispose of the request. + m_clientManager->releaseRequest(request); + + // Invoke error handler callback function + m_clientManager->callErrorHandler(err, m_erpcMatrixMultiplyId); + +#if ERPC_PRE_POST_ACTION + pre_post_action_cb postCB = m_clientManager->getPostCB(); + if (postCB) + { + postCB(); + } +#endif + + + return; +} diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_client.hpp b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_client.hpp new file mode 100644 index 00000000..9f9b7bb5 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_client.hpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_client_hpp_) +#define _erpc_matrix_multiply_client_hpp_ + +#include "erpc_matrix_multiply_interface.hpp" + +#include "erpc_client_manager.h" + +namespace erpcShim +{ + +class MatrixMultiplyService_client: public MatrixMultiplyService_interface +{ + public: + MatrixMultiplyService_client(erpc::ClientManager *manager); + + virtual ~MatrixMultiplyService_client(); + + virtual void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix); + + protected: + erpc::ClientManager *m_clientManager; +}; + +} // erpcShim + + +#endif // _erpc_matrix_multiply_client_hpp_ diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_common.h b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_common.h new file mode 100644 index 00000000..5015f99a --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_common.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_common_h_) +#define _erpc_matrix_multiply_common_h_ + + +#if defined(__cplusplus) +extern "C" +{ +#endif +#include +#include +#include + +#include "erpc_version.h" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +#if !defined(ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY) +#define ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +// Aliases data types declarations +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +typedef int32_t Matrix[5][5]; + +// Constant variable declarations +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +extern const int32_t matrix_size; + +#endif // ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +#if defined(__cplusplus) +} +#endif + +#endif // _erpc_matrix_multiply_common_h_ diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_common.hpp new file mode 100644 index 00000000..56efc4ad --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_common.hpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_common_hpp_) +#define _erpc_matrix_multiply_common_hpp_ + + +#include +#include + +#include "erpc_version.h" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +#if !defined(ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY) +#define ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +// Aliases data types declarations +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +typedef int32_t Matrix[5][5]; + +// Constant variable declarations +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +extern const int32_t matrix_size; + +#endif // ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + + +#endif // _erpc_matrix_multiply_common_hpp_ diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_interface.cpp b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_interface.cpp new file mode 100644 index 00000000..ceb050fe --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_interface.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#include "erpc_matrix_multiply_interface.hpp" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +using namespace std; +using namespace erpcShim; + +MatrixMultiplyService_interface::~MatrixMultiplyService_interface(void) +{ +} diff --git a/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_interface.hpp b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_interface.hpp new file mode 100644 index 00000000..e4426378 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/src/service/erpc_matrix_multiply_interface.hpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_interface_hpp_) +#define _erpc_matrix_multiply_interface_hpp_ + +#include "erpc_matrix_multiply_common.hpp" + +namespace erpcShim +{ + + +// Abstract base class for MatrixMultiplyService +class MatrixMultiplyService_interface +{ + public: + static const uint8_t m_serviceId = 1; + static const uint8_t m_erpcMatrixMultiplyId = 1; + + virtual ~MatrixMultiplyService_interface(void); + + virtual void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) = 0; +private: +}; +} // erpcShim + + +#endif // _erpc_matrix_multiply_interface_hpp_ diff --git a/examples/zephyr/matrix_multiply_mbox/sysbuild.cmake b/examples/zephyr/matrix_multiply_mbox/sysbuild.cmake new file mode 100644 index 00000000..f6fb8146 --- /dev/null +++ b/examples/zephyr/matrix_multiply_mbox/sysbuild.cmake @@ -0,0 +1,34 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +if("${SB_CONFIG_REMOTE_BOARD}" STREQUAL "") + message(FATAL_ERROR + "Target ${BOARD} not supported for this sample. " + "There is no remote board selected in Kconfig.sysbuild") +endif() + +set(REMOTE_APP remote) + +ExternalZephyrProject_Add( + APPLICATION ${REMOTE_APP} + SOURCE_DIR ${APP_DIR}/${REMOTE_APP} + BOARD ${SB_CONFIG_REMOTE_BOARD} +) + +native_simulator_set_child_images(${DEFAULT_IMAGE} ${REMOTE_APP}) + +native_simulator_set_final_executable(${DEFAULT_IMAGE}) + +if ("${BOARD}" STREQUAL "mimxrt1170_evkb_cm7" OR + "${BOARD}" STREQUAL "mimxrt1170_evk_cm7" OR + "${BOARD}" STREQUAL "mimxrt1160_evk_cm7" + ) + # For these NXP boards the main core application is dependent on + # 'zephyr_image_info.h' generated by remote application. + + # Let's build the remote application first + add_dependencies(${DEFAULT_IMAGE} ${REMOTE_APP}) +endif() \ No newline at end of file diff --git a/examples/zephyr/matrix_multiply_rpmsglite/CMakeLists.txt b/examples/zephyr/matrix_multiply_rpmsglite/CMakeLists.txt index ef3edcef..62b2971f 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/CMakeLists.txt +++ b/examples/zephyr/matrix_multiply_rpmsglite/CMakeLists.txt @@ -1,4 +1,8 @@ -# SPDX-License-Identifier: Apache-2.0 +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# cmake_minimum_required(VERSION 3.20.0) diff --git a/examples/zephyr/matrix_multiply_rpmsglite/Kconfig b/examples/zephyr/matrix_multiply_rpmsglite/Kconfig index 3837c49b..8f708489 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/Kconfig +++ b/examples/zephyr/matrix_multiply_rpmsglite/Kconfig @@ -1,6 +1,8 @@ -# Copyright 2023 NXP # -# SPDX-License-Identifier: Apache-2.0 +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# source "Kconfig.zephyr" diff --git a/examples/zephyr/matrix_multiply_rpmsglite/Kconfig.sysbuild b/examples/zephyr/matrix_multiply_rpmsglite/Kconfig.sysbuild index 0ff689dd..150379c2 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/Kconfig.sysbuild +++ b/examples/zephyr/matrix_multiply_rpmsglite/Kconfig.sysbuild @@ -1,6 +1,8 @@ -# Copyright 2023 NXP # -# SPDX-License-Identifier: Apache-2.0 +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# source "share/sysbuild/Kconfig" diff --git a/examples/zephyr/matrix_multiply_rpmsglite/boards/lpcxpresso54114_m4.overlay b/examples/zephyr/matrix_multiply_rpmsglite/boards/lpcxpresso54114_m4.overlay index e061dcc4..9b1024d6 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/boards/lpcxpresso54114_m4.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/boards/lpcxpresso54114_m4.overlay @@ -1,8 +1,7 @@ /* - * Copyright (c) 2019 Linaro Limited - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ / { diff --git a/examples/zephyr/matrix_multiply_rpmsglite/boards/lpcxpresso55s69_cpu0.overlay b/examples/zephyr/matrix_multiply_rpmsglite/boards/lpcxpresso55s69_cpu0.overlay index 270eb0e7..c0696468 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/boards/lpcxpresso55s69_cpu0.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/boards/lpcxpresso55s69_cpu0.overlay @@ -1,8 +1,7 @@ /* - * Copyright (c) 2019 Linaro Limited - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ / { diff --git a/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1160_evk_cm7.overlay b/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1160_evk_cm7.overlay index 584538a1..3bf2b0dc 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1160_evk_cm7.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1160_evk_cm7.overlay @@ -1,7 +1,7 @@ /* - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ #include diff --git a/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evk_cm7.overlay b/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evk_cm7.overlay index 584538a1..3bf2b0dc 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evk_cm7.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evk_cm7.overlay @@ -1,7 +1,7 @@ /* - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ #include diff --git a/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evkb_cm7.conf b/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evkb_cm7.conf index ae8dba8c..630a1933 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evkb_cm7.conf +++ b/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evkb_cm7.conf @@ -1,7 +1,2 @@ -# -# Copyright 2023, NXP -# -# SPDX-License-Identifier: Apache-2.0 -# CONFIG_INCLUDE_REMOTE_DIR=y CONFIG_SECOND_CORE_MCUX=y diff --git a/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evkb_cm7.overlay b/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evkb_cm7.overlay index 584538a1..3bf2b0dc 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evkb_cm7.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/boards/mimxrt1170_evkb_cm7.overlay @@ -1,7 +1,7 @@ /* - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ #include diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/CMakeLists.txt b/examples/zephyr/matrix_multiply_rpmsglite/remote/CMakeLists.txt index 16ed61d7..6793ca58 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/CMakeLists.txt +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/CMakeLists.txt @@ -1,4 +1,8 @@ -# SPDX-License-Identifier: Apache-2.0 +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# cmake_minimum_required(VERSION 3.20.0) diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/lpcxpresso54114_m0.overlay b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/lpcxpresso54114_m0.overlay index e061dcc4..9b1024d6 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/lpcxpresso54114_m0.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/lpcxpresso54114_m0.overlay @@ -1,8 +1,7 @@ /* - * Copyright (c) 2019 Linaro Limited - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ / { diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/lpcxpresso55s69_cpu1.overlay b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/lpcxpresso55s69_cpu1.overlay index 270eb0e7..c0696468 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/lpcxpresso55s69_cpu1.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/lpcxpresso55s69_cpu1.overlay @@ -1,8 +1,7 @@ /* - * Copyright (c) 2019 Linaro Limited - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ / { diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1160_evk_cm4.overlay b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1160_evk_cm4.overlay index 83589d7e..ab57a613 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1160_evk_cm4.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1160_evk_cm4.overlay @@ -1,7 +1,7 @@ /* - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ #include diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evk_cm4.overlay b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evk_cm4.overlay index 83589d7e..ab57a613 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evk_cm4.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evk_cm4.overlay @@ -1,7 +1,7 @@ /* - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ #include diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evkb_cm4.conf b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evkb_cm4.conf index 7b43b448..4dfc4a60 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evkb_cm4.conf +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evkb_cm4.conf @@ -1,8 +1,3 @@ -# -# Copyright 2023, NXP -# -# SPDX-License-Identifier: Apache-2.0 -# CONFIG_BUILD_OUTPUT_INFO_HEADER=y CONFIG_BUILD_OUTPUT_HEX=y CONFIG_SECOND_CORE_MCUX=y diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evkb_cm4.overlay b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evkb_cm4.overlay index b9c0439c..65fb71ff 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evkb_cm4.overlay +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/boards/mimxrt1170_evkb_cm4.overlay @@ -1,7 +1,7 @@ /* - * Copyright 2023 NXP + * Copyright 2023-2024 NXP * - * SPDX-License-Identifier: Apache-2.0 + * SPDX-License-Identifier: BSD-3-Clause */ #include diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/c_erpc_matrix_multiply_server.cpp b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/c_erpc_matrix_multiply_server.cpp index afb98cb3..d65660ce 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/c_erpc_matrix_multiply_server.cpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/c_erpc_matrix_multiply_server.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/c_erpc_matrix_multiply_server.h b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/c_erpc_matrix_multiply_server.h index d312e8d3..b7e7815d 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/c_erpc_matrix_multiply_server.h +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/c_erpc_matrix_multiply_server.h @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.h b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.h index fdbd0c7a..5015f99a 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.h +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.h @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -27,7 +27,7 @@ extern "C" #include "erpc_version.h" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.hpp index 994cfce5..56efc4ad 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.hpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_common.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -22,7 +22,7 @@ #include "erpc_version.h" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_interface.cpp b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_interface.cpp index e50f033c..ceb050fe 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_interface.cpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_interface.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -15,7 +15,7 @@ #include "erpc_matrix_multiply_interface.hpp" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_interface.hpp b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_interface.hpp index b2be5a90..e4426378 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_interface.hpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_interface.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_server.cpp b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_server.cpp index d6c97a33..a190dcfa 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_server.cpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_server.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -20,7 +20,7 @@ #endif #include "erpc_manually_constructed.hpp" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_server.hpp b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_server.hpp index ad1f17f2..9a5efd0a 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_server.hpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/remote/src/service/erpc_matrix_multiply_server.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -21,7 +21,7 @@ #include "erpc_server.hpp" #include "erpc_codec.hpp" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/c_erpc_matrix_multiply_client.cpp b/examples/zephyr/matrix_multiply_rpmsglite/src/service/c_erpc_matrix_multiply_client.cpp index af77c961..a20696f5 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/c_erpc_matrix_multiply_client.cpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/c_erpc_matrix_multiply_client.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/c_erpc_matrix_multiply_client.h b/examples/zephyr/matrix_multiply_rpmsglite/src/service/c_erpc_matrix_multiply_client.h index 8966a5c4..7fc9a163 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/c_erpc_matrix_multiply_client.h +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/c_erpc_matrix_multiply_client.h @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_client.cpp b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_client.cpp index 329c4b43..bc890132 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_client.cpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_client.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -20,7 +20,7 @@ #include "erpc_matrix_multiply_client.hpp" #include "erpc_manually_constructed.hpp" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_client.hpp b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_client.hpp index b8b81101..9f9b7bb5 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_client.hpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_client.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.h b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.h index fdbd0c7a..5015f99a 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.h +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.h @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -27,7 +27,7 @@ extern "C" #include "erpc_version.h" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.hpp index 994cfce5..56efc4ad 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.hpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_common.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -22,7 +22,7 @@ #include "erpc_version.h" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_interface.cpp b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_interface.cpp index e50f033c..ceb050fe 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_interface.cpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_interface.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -15,7 +15,7 @@ #include "erpc_matrix_multiply_interface.hpp" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_interface.hpp b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_interface.hpp index b2be5a90..e4426378 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_interface.hpp +++ b/examples/zephyr/matrix_multiply_rpmsglite/src/service/erpc_matrix_multiply_interface.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:39 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_rpmsglite/sysbuild.cmake b/examples/zephyr/matrix_multiply_rpmsglite/sysbuild.cmake index 255b8358..573177b7 100644 --- a/examples/zephyr/matrix_multiply_rpmsglite/sysbuild.cmake +++ b/examples/zephyr/matrix_multiply_rpmsglite/sysbuild.cmake @@ -1,6 +1,8 @@ -# Copyright 2023 NXP # -# SPDX-License-Identifier: Apache-2.0 +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# # Add external project ExternalZephyrProject_Add( diff --git a/examples/zephyr/matrix_multiply_tcp/CMakeLists.txt b/examples/zephyr/matrix_multiply_tcp/CMakeLists.txt new file mode 100644 index 00000000..87eb5813 --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/CMakeLists.txt @@ -0,0 +1,24 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) + +project(erpc_matrix_multiply_example C CXX) + +target_sources(app PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/erpc_error_handler.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/service/c_erpc_matrix_multiply_server.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/service/erpc_matrix_multiply_interface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/service/erpc_matrix_multiply_server.cpp + ) + +target_include_directories(app PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) +target_include_directories(app PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/service) + +target_include_directories(erpc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) diff --git a/examples/zephyr/matrix_multiply_tcp/README.rst b/examples/zephyr/matrix_multiply_tcp/README.rst new file mode 100644 index 00000000..749b7afe --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/README.rst @@ -0,0 +1,115 @@ +.. _matrix_multiply_tcp: + +Matrix multiply TCP +################### + +This example demonstrates usage of eRPC between PC and board using the Zephyr OS and the TCP +transport layer. Board acts like a server and the PC as client. When client starts, it generates +two random matrixes and sends them to server. Server then performs matrix multiplication and sends +result data back to client. Result matrix is then printed on the PC side. + +eRPC documentation +eRPC specific files are stored in: middleware\\multicore\\erpc +eRPC documentation is stored in: middleware\\multicore\\erpc\\doc +eRPC is open-source project stored on github: https://github.com/EmbeddedRPC/erpc +eRPC documentation can be also found in: http://embeddedrpc.github.io + +PC Side Setup (Python) +********************** + +1. Make sure you have Python installed on your PC +2. Install serial module by executing following command in command line: "python -m pip install pyserial" +3. Install eRPC module to Python by executing setup.py located in: middleware\\multicore\\erpc\\erpc_python - "python setup.py install" + +Run erpc\\examples\\matrix_multiply_tcp_python\\matrix_multiply.py as client + +usage: matrix_multiply.py [-h] [-c] [-s] [-t HOST] [-p PORT] [-S SERIAL] [-B BAUD] + +eRPC Matrix Multiply example + +options: + -h, --help show this help message and exit + -c, --client Run client + -s, --server Run server + -t HOST, --host HOST Host IP address (default value is localhost) + -p PORT, --port PORT Port (default value is 40) + -S SERIAL, --serial SERIAL + Serial device (default value is None) + -B BAUD, --baud BAUD Baud (default value is 115200) + +Example: +======== +To run PC side as a client with a board connected as a server to COM3 execute: + +.. code-block:: bash + + matrix_multiply.py --client --host 192.0.2.1 --port 12345 + + +Building and Running +******************** + +This application can be built and executed as follows: + + +Building the application for mimxrt1060_evk +******************************************* + +.. zephyr-app-commands:: + :zephyr-app: samples/matrix_multiply_tcp + :board: mimxrt1060_evk + :goals: debug + +Building the application for mimxrt1160_evk_cm7 +*********************************************** + +.. zephyr-app-commands:: + :zephyr-app: samples/matrix_multiply_uart + :board: mimxrt1160_evk_cm7 + :goals: debug + +Sample Output +============= + +Open a serial terminal (minicom, putty, etc.) and connect the board with the +following settings: + +- Speed: 115200 +- Data: 8 bits +- Parity: None +- Stop bits: 1 + +Reset the board and the following message will appear on the corresponding +serial port: + +.. code-block:: console + + eRPC Matrix Multiply TCP example + Transport: serial=COM14 baudrate=115200 + Matrix #1 + ========= + 8 2 1 3 1 + 9 4 7 6 0 + 3 8 5 9 8 + 2 8 7 3 7 + 7 8 3 6 3 + + Matrix #1 + ========= + 1 9 5 7 8 + 2 4 8 3 9 + 9 1 8 3 0 + 7 6 3 4 2 + 4 4 8 7 8 + + eRPC request is sent to the server + + Matrix result + ========= + 46 103 81 84 96 + 122 140 151 120 120 + 159 150 210 152 178 + 130 103 195 120 150 + 104 146 165 127 164 + + Press Enter to initiate the next matrix multiplication or 'q' to quit diff --git a/examples/zephyr/matrix_multiply_tcp/prj.conf b/examples/zephyr/matrix_multiply_tcp/prj.conf new file mode 100644 index 00000000..c0cb6aef --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/prj.conf @@ -0,0 +1,56 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP20=y +CONFIG_GLIBCXX_LIBCPP=y +CONFIG_NEWLIB_LIBC=y + +# POSIX +CONFIG_POSIX_API=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_TCP=y + +# Networking config +CONFIG_NETWORKING=y +CONFIG_NET_TCP=y +CONFIG_NET_SOCKETS=y + +# Network address config +CONFIG_NET_CONFIG_SETTINGS=y +CONFIG_NET_CONFIG_NEED_IPV4=y +CONFIG_NET_CONFIG_NEED_IPV6=n +CONFIG_NET_CONFIG_MY_IPV4_ADDR="192.0.2.1" + +# Threads +CONFIG_THREAD_CUSTOM_DATA=y +CONFIG_DYNAMIC_THREAD=y +CONFIG_DYNAMIC_THREAD_POOL_SIZE=1 +CONFIG_DYNAMIC_THREAD_STACK_SIZE=8192 + +# Compiler +CONFIG_HEAP_MEM_POOL_SIZE=16384 + +#CONFIG_NO_OPTIMIZATIONS=y + +# reguired only if CONFIG_NO_OPTIMIZATIONS is enabled +#CONFIG_MAIN_STACK_SIZE=16384 +#CONFIG_ISR_STACK_SIZE=4096 +#CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=8192 +#CONFIG_NET_MGMT_EVENT_STACK_SIZE=4096 +#CONFIG_NET_TCP_WORKQ_STACK_SIZE=1024 + +# does not work - eth_mcux.c:90 +CONFIG_NET_RX_STACK_SIZE=16384 + +# Debug +#CONFIG_LOG=y +#CONFIG_LOG_MODE_IMMEDIATE=y +#CONFIG_LOG_OVERRIDE_LEVEL=3 +#CONFIG_NET_LOG=y + +#CONFIG_THREAD_ANALYZER=y +#CONFIG_THREAD_ANALYZER_USE_PRINTK=y +#CONFIG_THREAD_ANALYZER_AUTO=y +#CONFIG_THREAD_ANALYZER_AUTO_INTERVAL=5 +#CONFIG_THREAD_NAME=y diff --git a/examples/zephyr/matrix_multiply_tcp/sample.yaml b/examples/zephyr/matrix_multiply_tcp/sample.yaml new file mode 100644 index 00000000..49859405 --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/sample.yaml @@ -0,0 +1,3 @@ +sample: + description: eRPC TCP Matrix multiplication + name: eRPC Matrix TCP multiplication diff --git a/examples/zephyr/matrix_multiply_tcp/src/erpc_config.h b/examples/zephyr/matrix_multiply_tcp/src/erpc_config.h new file mode 100644 index 00000000..3f03735a --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/erpc_config.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2021 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_CONFIG_H_ +#define _ERPC_CONFIG_H_ + +/*! + * @addtogroup config + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +//! @name Threading model options +//@{ +#define ERPC_ALLOCATION_POLICY_DYNAMIC (0U) //!< Dynamic allocation policy +#define ERPC_ALLOCATION_POLICY_STATIC (1U) //!< Static allocation policy + +#define ERPC_THREADS_NONE (0U) //!< No threads. +#define ERPC_THREADS_PTHREADS (1U) //!< POSIX pthreads. +#define ERPC_THREADS_FREERTOS (2U) //!< FreeRTOS. +#define ERPC_THREADS_ZEPHYR (3U) //!< ZEPHYR. +#define ERPC_THREADS_MBED (4U) //!< Mbed OS +#define ERPC_THREADS_WIN32 (5U) //!< WIN32 +#define ERPC_THREADS_THREADX (6U) //!< THREADX + +#define ERPC_NOEXCEPT_DISABLED (0U) //!< Disabling noexcept feature. +#define ERPC_NOEXCEPT_ENABLED (1U) //!< Enabling noexcept feature. + +#define ERPC_NESTED_CALLS_DISABLED (0U) //!< No nested calls support. +#define ERPC_NESTED_CALLS_ENABLED (1U) //!< Nested calls support. + +#define ERPC_NESTED_CALLS_DETECTION_DISABLED (0U) //!< Nested calls detection disabled. +#define ERPC_NESTED_CALLS_DETECTION_ENABLED (1U) //!< Nested calls detection enabled. + +#define ERPC_MESSAGE_LOGGING_DISABLED (0U) //!< Trace functions disabled. +#define ERPC_MESSAGE_LOGGING_ENABLED (1U) //!< Trace functions enabled. + +#define ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED (0U) //!< Do not use MCMGR for MU ISR management. +#define ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED (1U) //!< Use MCMGR for MU ISR management. + +#define ERPC_PRE_POST_ACTION_DISABLED (0U) //!< Pre post shim callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_ENABLED (1U) //!< Pre post shim callback functions enabled. + +#define ERPC_PRE_POST_ACTION_DEFAULT_DISABLED (0U) //!< Pre post shim default callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_DEFAULT_ENABLED (1U) //!< Pre post shim default callback functions enabled. +//@} + +//! @name Configuration options +//@{ + +//! @def ERPC_ALLOCATION_POLICY +//! +//! @brief Choose which allocation policy should be used. +//! +//! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. +//! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. +//! +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is +//! supported by compiler. Uncomment comment bellow to use static allocation policy. In case of static implementation +//! user need consider another values to set (ERPC_CODEC_COUNT, ERPC_MESSAGE_LOGGERS_COUNT, +//! ERPC_CLIENTS_THREADS_AMOUNT). +// #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_STATIC) + +//! @def ERPC_CODEC_COUNT +//! +//! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one +//! thread per each then 2, ... Default value 2. +// #define ERPC_CODEC_COUNT (2U) + +//! @def ERPC_MESSAGE_LOGGERS_COUNT +//! +//! @brief Set amount of message loggers objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. +//! For example if client or server is used in one thread then 1. If both are used in one thread per each then 2, ... +//! For arbitrated client 1 is enough. +//! Default value 0 (May not be used). +// #define ERPC_MESSAGE_LOGGERS_COUNT (0U) + +//! @def ERPC_CLIENTS_THREADS_AMOUNT +//! +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. Default value 1 (Most of current cases). +// #define ERPC_CLIENTS_THREADS_AMOUNT (1U) + +//! @def ERPC_THREADS +//! +//! @brief Select threading model. +//! +//! Set to one of the @c ERPC_THREADS_x macros to specify the threading model used by eRPC. +//! +//! Leave commented out to attempt to auto-detect. Auto-detection works well for pthreads. +//! FreeRTOS can be detected when building with compilers that support __has_include(). +//! Otherwise, the default is no threading. +#define ERPC_THREADS (ERPC_THREADS_PTHREADS) + +//! @def ERPC_DEFAULT_BUFFER_SIZE +//! +//! Uncomment to change the size of buffers allocated by one of MessageBufferFactory. +//! (@ref client_setup and @ref server_setup). The default size is set to 256. +//! For RPMsg transport layer, ERPC_DEFAULT_BUFFER_SIZE must be 2^n - 16. +#define ERPC_DEFAULT_BUFFER_SIZE (4096U) + +//! @def ERPC_DEFAULT_BUFFERS_COUNT +//! +//! Uncomment to change the count of buffers allocated by one of statically allocated messages. +//! Default value is set to 2. +//#define ERPC_DEFAULT_BUFFERS_COUNT (2U) + +//! @def ERPC_NOEXCEPT +//! +//! @brief Disable/enable noexcept support. +//! +//! Uncomment for using noexcept feature. +//#define ERPC_NOEXCEPT (ERPC_NOEXCEPT_ENABLED) + +//! @def ERPC_NESTED_CALLS +//! +//! Default set to ERPC_NESTED_CALLS_DISABLED. Uncomment when callbacks, or other eRPC +//! functions are called from server implementation of another eRPC call. Nested functions +//! need to be marked as @nested in IDL. +//#define ERPC_NESTED_CALLS (ERPC_NESTED_CALLS_ENABLED) + +//! @def ERPC_NESTED_CALLS_DETECTION +//! +//! Default set to ERPC_NESTED_CALLS_DETECTION_ENABLED when NDEBUG macro is presented. +//! This serve for locating nested calls in code. Nested calls are calls where inside eRPC function +//! on server side is called another eRPC function (like callbacks). Code need be a bit changed +//! to support nested calls. See ERPC_NESTED_CALLS macro. +//#define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_DISABLED) + +//! @def ERPC_MESSAGE_LOGGING +//! +//! Enable eRPC message logging code through the eRPC. Take look into "erpc_message_loggers.h". Can be used for base +//! printing messages, or sending data to another system for data analysis. Default set to +//! ERPC_MESSAGE_LOGGING_DISABLED. +//! +//! Uncomment for using logging feature. +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) + +//! @def ERPC_TRANSPORT_MU_USE_MCMGR +//! +//! @brief MU transport layer configuration. +//! +//! Set to one of the @c ERPC_TRANSPORT_MU_USE_MCMGR_x macros to configure the MCMGR usage in MU transport layer. +//! +//! MU transport layer could leverage the Multicore Manager (MCMGR) component for Inter-Core +//! interrupts / MU interrupts management or the Inter-Core interrupts can be managed by itself (MUX_IRQHandler +//! overloading). By default, ERPC_TRANSPORT_MU_USE_MCMGR is set to ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED when mcmgr.h +//! is part of the project, otherwise the ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED option is used. This settings can be +//! overwritten from the erpc_config.h by uncommenting the ERPC_TRANSPORT_MU_USE_MCMGR macro definition. Do not forget +//! to add the MCMGR library into your project when ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED option is used! See the +//! erpc_mu_transport.h for additional MU settings. +//#define ERPC_TRANSPORT_MU_USE_MCMGR ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED +//@} + +//! @def ERPC_PRE_POST_ACTION +//! +//! Enable eRPC pre and post callback functions shim code. Take look into "erpc_pre_post_action.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DISABLED. +//! +//! Uncomment for using pre post callback feature. +//#define ERPC_PRE_POST_ACTION (ERPC_PRE_POST_ACTION_ENABLED) + +//! @def ERPC_PRE_POST_ACTION_DEFAULT +//! +//! Enable eRPC pre and post default callback functions. Take look into "erpc_setup_extensions.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DEFAULT_DISABLED. +//! +//! Uncomment for using pre post default callback feature. +//#define ERPC_PRE_POST_ACTION_DEFAULT (ERPC_PRE_POST_ACTION_DEFAULT_ENABLED) + +/*! @} */ +#endif // _ERPC_CONFIG_H_ +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/examples/zephyr/matrix_multiply_tcp/src/erpc_error_handler.cpp b/examples/zephyr/matrix_multiply_tcp/src/erpc_error_handler.cpp new file mode 100644 index 00000000..8be36267 --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/erpc_error_handler.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_error_handler.h" +#include + +//////////////////////////////////////////////////////////////////////////////// +// Variables +//////////////////////////////////////////////////////////////////////////////// + +extern bool g_erpc_error_occurred; +bool g_erpc_error_occurred = false; + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +void erpc_error_handler(erpc_status_t err, uint32_t functionID) +{ + switch (err) + { + case kErpcStatus_Fail: + printk("\r\nGeneric failure."); + break; + + case kErpcStatus_InvalidArgument: + printk("\r\nArgument is an invalid value."); + break; + + case kErpcStatus_Timeout: + printk("\r\nOperated timed out."); + break; + + case kErpcStatus_InvalidMessageVersion: + printk("\r\nMessage header contains an unknown version."); + break; + + case kErpcStatus_ExpectedReply: + printk("\r\nExpected a reply message but got another message type."); + break; + + case kErpcStatus_CrcCheckFailed: + printk("\r\nMessage is corrupted."); + break; + + case kErpcStatus_BufferOverrun: + printk("\r\nAttempt to read or write past the end of a buffer."); + break; + + case kErpcStatus_UnknownName: + printk("\r\nCould not find host with given name."); + break; + + case kErpcStatus_ConnectionFailure: + printk("\r\nFailed to connect to host."); + break; + + case kErpcStatus_ConnectionClosed: + printk("\r\nConnected closed by peer."); + break; + + case kErpcStatus_MemoryError: + printk("\r\nMemory allocation error."); + break; + + case kErpcStatus_ServerIsDown: + printk("\r\nServer is stopped."); + break; + + case kErpcStatus_InitFailed: + printk("\r\nTransport layer initialization failed."); + break; + + case kErpcStatus_ReceiveFailed: + printk("\r\nFailed to receive data."); + break; + + case kErpcStatus_SendFailed: + printk("\r\nFailed to send data."); + break; + + /* no error occurred */ + case kErpcStatus_Success: + return; + + /* unhandled error */ + default: + printk("\r\nUnhandled error occurred."); + break; + } + + /* When error occurred on client side. */ + if (functionID != 0) + { + printk("Function id '%u'.", (unsigned int)functionID); + } + printk("\r\n"); + + /* error occurred */ + g_erpc_error_occurred = true; +} diff --git a/examples/zephyr/matrix_multiply_tcp/src/erpc_error_handler.h b/examples/zephyr/matrix_multiply_tcp/src/erpc_error_handler.h new file mode 100644 index 00000000..faf32559 --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/erpc_error_handler.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2022 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _EMBEDDED_RPC__ERROR_HANDLER_H_ +#define _EMBEDDED_RPC__ERROR_HANDLER_H_ + +#include "erpc_common.h" +#include + +/*! + * @addtogroup error_handler + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// API +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +//! @name Error handler +//@{ + +/*! + * @brief This function handles eRPC errors. + * + * This function prints a description of occurred error and sets bool variable g_erpc_error_occurred which is used for + * determining if error occurred in user application on client side. + */ +void erpc_error_handler(erpc_status_t err, uint32_t functionID); + +//@} + +#ifdef __cplusplus +} +#endif + +/*! @} */ +#endif // _EMBEDDED_RPC__ERROR_HANDLER_H_ diff --git a/examples/zephyr/matrix_multiply_tcp/src/main.cpp b/examples/zephyr/matrix_multiply_tcp/src/main.cpp new file mode 100644 index 00000000..3a53e7ee --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/main.cpp @@ -0,0 +1,119 @@ +/* + * Copyright 2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +#include "erpc_server_setup.h" +#include "c_erpc_matrix_multiply_server.h" +#include "erpc_matrix_multiply_common.h" +#include "erpc_error_handler.h" +#include "erpc_transport_setup.h" + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/******************************************************************************* + * Variables + ******************************************************************************/ +erpc_server_t server; + +/******************************************************************************* + * Prototypes + ******************************************************************************/ + +/******************************************************************************* + * Code + ******************************************************************************/ + +/*! + * @brief erpcMatrixMultiply function implementation. + * + * This is the implementation of the erpcMatrixMultiply function called by the primary core. + * + * @param matrix1 First matrix + * @param matrix2 Second matrix + * @param result_matrix Result matrix + */ +void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) +{ + int32_t i, j, k; + + /* Clear the result matrix */ + for (i = 0; i < matrix_size; ++i) + { + for (j = 0; j < matrix_size; ++j) + { + result_matrix[i][j] = 0; + } + } + + /* Multiply two matrices */ + for (i = 0; i < matrix_size; ++i) + { + for (j = 0; j < matrix_size; ++j) + { + for (k = 0; k < matrix_size; ++k) + { + result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]; + } + } + } +} + +int main(void) +{ + /* TCP transport layer initialization */ + erpc_transport_t transport; + transport = erpc_transport_tcp_init("localhost", 12345, true); + + /* MessageBufferFactory initialization */ + erpc_mbf_t message_buffer_factory; + message_buffer_factory = erpc_mbf_dynamic_init(); + + /* eRPC server side initialization */ + server = erpc_server_init(transport, message_buffer_factory); + + /* adding the service to the server */ + erpc_service_t service = create_MatrixMultiplyService_service(); + erpc_add_service_to_server(server, service); + + for (;;) + { + /* process message */ + erpc_status_t status = erpc_server_poll(server); + + /* handle error status */ + if (status != (erpc_status_t)kErpcStatus_Success) + { + /* print error description */ + erpc_error_handler(status, 0); + + /* removing the service from the server */ + erpc_remove_service_from_server(server, service); + destroy_MatrixMultiplyService_service(service); + + /* stop erpc server */ + erpc_server_stop(server); + + /* print error description */ + erpc_server_deinit(server); + + /* exit program loop */ + break; + } + + /* do other tasks */ + int32_t i; + for (i = 0; i < 10000; i++) + { + } + } + + for (;;) + { + } +} diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/c_erpc_matrix_multiply_server.cpp b/examples/zephyr/matrix_multiply_tcp/src/service/c_erpc_matrix_multiply_server.cpp new file mode 100644 index 00000000..d19c4a8b --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/c_erpc_matrix_multiply_server.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#include +#include "c_erpc_matrix_multiply_server.h" +#include "erpc_matrix_multiply_server.hpp" +#include "erpc_manually_constructed.hpp" + +using namespace erpc; +using namespace std; +using namespace erpcShim; + + +class MatrixMultiplyService_server: public MatrixMultiplyService_interface +{ + public: + virtual ~MatrixMultiplyService_server() {}; + + + void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) + { + ::erpcMatrixMultiply(matrix1, matrix2, result_matrix); + } +}; + +ERPC_MANUALLY_CONSTRUCTED_STATIC(MatrixMultiplyService_service, s_MatrixMultiplyService_service); +ERPC_MANUALLY_CONSTRUCTED_STATIC(MatrixMultiplyService_server, s_MatrixMultiplyService_server); + +erpc_service_t create_MatrixMultiplyService_service(void) +{ + erpc_service_t service; + +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + service = new (nothrow) MatrixMultiplyService_service(new (nothrow)MatrixMultiplyService_server()); +#else + if (s_MatrixMultiplyService_service.isUsed()) + { + service = NULL; + } + else + { + s_MatrixMultiplyService_server.construct(); + s_MatrixMultiplyService_service.construct(s_MatrixMultiplyService_server.get()); + service = s_MatrixMultiplyService_service.get(); + } +#endif + + return service; +} + +void destroy_MatrixMultiplyService_service(erpc_service_t service) +{ +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC + if (service) + { + delete (MatrixMultiplyService_server *)(((MatrixMultiplyService_service *)service)->getHandler()); + delete (MatrixMultiplyService_service *)service; + } +#else + (void)service; + erpc_assert(service == s_MatrixMultiplyService_service.get()); + s_MatrixMultiplyService_service.destroy(); + s_MatrixMultiplyService_server.destroy(); +#endif +} + diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/c_erpc_matrix_multiply_server.h b/examples/zephyr/matrix_multiply_tcp/src/service/c_erpc_matrix_multiply_server.h new file mode 100644 index 00000000..e1f168bf --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/c_erpc_matrix_multiply_server.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_c_erpc_matrix_multiply_server_h_) +#define _c_erpc_matrix_multiply_server_h_ + +#include "erpc_matrix_multiply_common.h" + +#if defined(__cplusplus) +extern "C" +{ +#endif + +typedef void * erpc_service_t; + +#if !defined(ERPC_FUNCTIONS_DEFINITIONS) +#define ERPC_FUNCTIONS_DEFINITIONS + + +/*! @brief MatrixMultiplyService identifiers */ +enum _MatrixMultiplyService_ids +{ + kMatrixMultiplyService_service_id = 1, + kMatrixMultiplyService_erpcMatrixMultiply_id = 1, +}; + +//! @name MatrixMultiplyService +//@{ +void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix); +//@} + + +#endif // ERPC_FUNCTIONS_DEFINITIONS + +/*! @brief Return MatrixMultiplyService_service service object. */ +erpc_service_t create_MatrixMultiplyService_service(void); + +/*! @brief Destroy MatrixMultiplyService_service service object. */ +void destroy_MatrixMultiplyService_service(erpc_service_t service); + + +#if defined(__cplusplus) +} +#endif + +#endif // _c_erpc_matrix_multiply_server_h_ diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply.erpc b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply.erpc new file mode 100644 index 00000000..bfcece34 --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply.erpc @@ -0,0 +1,24 @@ +//Copyright below will be added into all generated files. +/*! + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +program erpc_matrix_multiply + +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +const int32 matrix_size = 5; + +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +type Matrix = int32[matrix_size][matrix_size]; + +interface MatrixMultiplyService { + erpcMatrixMultiply(in Matrix matrix1, in Matrix matrix2, out Matrix result_matrix) -> void +} diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_common.h b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_common.h new file mode 100644 index 00000000..6050df24 --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_common.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_common_h_) +#define _erpc_matrix_multiply_common_h_ + + +#if defined(__cplusplus) +extern "C" +{ +#endif +#include +#include +#include + +#include "erpc_version.h" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +#if !defined(ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY) +#define ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +// Aliases data types declarations +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +typedef int32_t Matrix[5][5]; + +// Constant variable declarations +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +extern const int32_t matrix_size; + +#endif // ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +#if defined(__cplusplus) +} +#endif + +#endif // _erpc_matrix_multiply_common_h_ diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_common.hpp new file mode 100644 index 00000000..3dfef510 --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_common.hpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_common_hpp_) +#define _erpc_matrix_multiply_common_hpp_ + + +#include +#include + +#include "erpc_version.h" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +#if !defined(ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY) +#define ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + +// Aliases data types declarations +/*! This is the matrix array type. The dimension has to be the same as the + matrix size const. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +typedef int32_t Matrix[5][5]; + +// Constant variable declarations +/*! This const defines the matrix size. The value has to be the same as the + Matrix array dimension. Do not forget to re-generate the erpc code once the + matrix size is changed in the erpc file */ +extern const int32_t matrix_size; + +#endif // ERPC_TYPE_DEFINITIONS_ERPC_MATRIX_MULTIPLY + + +#endif // _erpc_matrix_multiply_common_hpp_ diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_interface.cpp b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_interface.cpp new file mode 100644 index 00000000..0aa9af0a --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_interface.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#include "erpc_matrix_multiply_interface.hpp" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +using namespace std; +using namespace erpcShim; + +MatrixMultiplyService_interface::~MatrixMultiplyService_interface(void) +{ +} diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_interface.hpp b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_interface.hpp new file mode 100644 index 00000000..99b264cf --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_interface.hpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_interface_hpp_) +#define _erpc_matrix_multiply_interface_hpp_ + +#include "erpc_matrix_multiply_common.hpp" + +namespace erpcShim +{ + + +// Abstract base class for MatrixMultiplyService +class MatrixMultiplyService_interface +{ + public: + static const uint8_t m_serviceId = 1; + static const uint8_t m_erpcMatrixMultiplyId = 1; + + virtual ~MatrixMultiplyService_interface(void); + + virtual void erpcMatrixMultiply(Matrix matrix1, Matrix matrix2, Matrix result_matrix) = 0; +private: +}; +} // erpcShim + + +#endif // _erpc_matrix_multiply_interface_hpp_ diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_server.cpp b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_server.cpp new file mode 100644 index 00000000..a76721da --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_server.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#include "erpc_matrix_multiply_server.hpp" +#if ERPC_ALLOCATION_POLICY == ERPC_ALLOCATION_POLICY_DYNAMIC +#include +#include "erpc_port.h" +#endif +#include "erpc_manually_constructed.hpp" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + +using namespace erpc; +using namespace std; +using namespace erpcShim; + +#if ERPC_NESTED_CALLS_DETECTION +extern bool nestingDetection; +#endif + + + +// Constant variable definitions +#if defined(__MINGW32__) +__declspec( selectany ) +#else +#pragma weak matrix_size +#endif +extern const int32_t matrix_size = 5; + + +MatrixMultiplyService_service::MatrixMultiplyService_service(MatrixMultiplyService_interface *_MatrixMultiplyService_interface) + : erpc::Service(MatrixMultiplyService_interface::m_serviceId) + , m_handler(_MatrixMultiplyService_interface) +{ +} + +MatrixMultiplyService_service::~MatrixMultiplyService_service() +{ +} + +// return service interface handler. +MatrixMultiplyService_interface* MatrixMultiplyService_service::getHandler(void) +{ + return m_handler; +} + +// Call the correct server shim based on method unique ID. +erpc_status_t MatrixMultiplyService_service::handleInvocation(uint32_t methodId, uint32_t sequence, Codec * codec, MessageBufferFactory *messageFactory, Transport * transport) +{ + erpc_status_t erpcStatus; + switch (methodId) + { + case MatrixMultiplyService_interface::m_erpcMatrixMultiplyId: + { + erpcStatus = erpcMatrixMultiply_shim(codec, messageFactory, transport, sequence); + break; + } + + default: + { + erpcStatus = kErpcStatus_InvalidArgument; + break; + } + } + + return erpcStatus; +} + +// Server shim for erpcMatrixMultiply of MatrixMultiplyService interface. +erpc_status_t MatrixMultiplyService_service::erpcMatrixMultiply_shim(Codec * codec, MessageBufferFactory *messageFactory, Transport * transport, uint32_t sequence) +{ + erpc_status_t err = kErpcStatus_Success; + + Matrix matrix1; + Matrix matrix2; + Matrix result_matrix; + + // startReadMessage() was already called before this shim was invoked. + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->read(matrix1[arrayCount0][arrayCount1]); + } + } + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->read(matrix2[arrayCount0][arrayCount1]); + } + } + + err = codec->getStatus(); + if (err == kErpcStatus_Success) + { + // Invoke the actual served function. +#if ERPC_NESTED_CALLS_DETECTION + nestingDetection = true; +#endif + m_handler->erpcMatrixMultiply(matrix1, matrix2, result_matrix); +#if ERPC_NESTED_CALLS_DETECTION + nestingDetection = false; +#endif + + // preparing MessageBuffer for serializing data + err = messageFactory->prepareServerBufferForSend(codec->getBufferRef(), transport->reserveHeaderSize()); + } + + if (err == kErpcStatus_Success) + { + // preparing codec for serializing data + codec->reset(transport->reserveHeaderSize()); + + // Build response message. + codec->startWriteMessage(message_type_t::kReplyMessage, MatrixMultiplyService_interface::m_serviceId, MatrixMultiplyService_interface::m_erpcMatrixMultiplyId, sequence); + + for (uint32_t arrayCount0 = 0U; arrayCount0 < 5U; ++arrayCount0) + { + for (uint32_t arrayCount1 = 0U; arrayCount1 < 5U; ++arrayCount1) + { + codec->write(result_matrix[arrayCount0][arrayCount1]); + } + } + + err = codec->getStatus(); + } + + return err; +} diff --git a/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_server.hpp b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_server.hpp new file mode 100644 index 00000000..c8e5a724 --- /dev/null +++ b/examples/zephyr/matrix_multiply_tcp/src/service/erpc_matrix_multiply_server.hpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. + * Copyright 2016 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. + * + * AUTOGENERATED - DO NOT EDIT + */ + + +#if !defined(_erpc_matrix_multiply_server_hpp_) +#define _erpc_matrix_multiply_server_hpp_ + +#include "erpc_matrix_multiply_interface.hpp" + +#include "erpc_server.hpp" +#include "erpc_codec.hpp" + +#if 11300 != ERPC_VERSION_NUMBER +#error "The generated shim code version is different to the rest of eRPC code." +#endif + + +namespace erpcShim +{ + +/*! + * @brief Service subclass for MatrixMultiplyService. + */ +class MatrixMultiplyService_service : public erpc::Service +{ +public: + MatrixMultiplyService_service(MatrixMultiplyService_interface *_MatrixMultiplyService_interface); + + virtual ~MatrixMultiplyService_service(); + + /*! @brief return service interface handler. */ + MatrixMultiplyService_interface* getHandler(void); + + /*! @brief Call the correct server shim based on method unique ID. */ + virtual erpc_status_t handleInvocation(uint32_t methodId, uint32_t sequence, erpc::Codec * codec, erpc::MessageBufferFactory *messageFactory, erpc::Transport * transport); + +private: + MatrixMultiplyService_interface *m_handler; + /*! @brief Server shim for erpcMatrixMultiply of MatrixMultiplyService interface. */ + erpc_status_t erpcMatrixMultiply_shim(erpc::Codec * codec, erpc::MessageBufferFactory *messageFactory, erpc::Transport * transport, uint32_t sequence); +}; + +} // erpcShim + + +#endif // _erpc_matrix_multiply_server_hpp_ diff --git a/examples/zephyr/matrix_multiply_uart/src/service/c_erpc_matrix_multiply_server.cpp b/examples/zephyr/matrix_multiply_uart/src/service/c_erpc_matrix_multiply_server.cpp index afb98cb3..d19c4a8b 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/c_erpc_matrix_multiply_server.cpp +++ b/examples/zephyr/matrix_multiply_uart/src/service/c_erpc_matrix_multiply_server.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_uart/src/service/c_erpc_matrix_multiply_server.h b/examples/zephyr/matrix_multiply_uart/src/service/c_erpc_matrix_multiply_server.h index d312e8d3..e1f168bf 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/c_erpc_matrix_multiply_server.h +++ b/examples/zephyr/matrix_multiply_uart/src/service/c_erpc_matrix_multiply_server.h @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.h b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.h index fdbd0c7a..6050df24 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.h +++ b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.h @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -27,7 +27,7 @@ extern "C" #include "erpc_version.h" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.hpp b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.hpp index 994cfce5..3dfef510 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.hpp +++ b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_common.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -22,7 +22,7 @@ #include "erpc_version.h" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_interface.cpp b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_interface.cpp index e50f033c..0aa9af0a 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_interface.cpp +++ b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_interface.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -15,7 +15,7 @@ #include "erpc_matrix_multiply_interface.hpp" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_interface.hpp b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_interface.hpp index b2be5a90..99b264cf 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_interface.hpp +++ b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_interface.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. * * AUTOGENERATED - DO NOT EDIT */ diff --git a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_server.cpp b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_server.cpp index d6c97a33..a76721da 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_server.cpp +++ b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_server.cpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -20,7 +20,7 @@ #endif #include "erpc_manually_constructed.hpp" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_server.hpp b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_server.hpp index ad1f17f2..c8e5a724 100644 --- a/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_server.hpp +++ b/examples/zephyr/matrix_multiply_uart/src/service/erpc_matrix_multiply_server.hpp @@ -7,7 +7,7 @@ */ /* - * Generated by erpcgen 1.12.0 on Wed Oct 25 10:00:57 2023. + * Generated by erpcgen 1.13.0 on Thu Apr 18 09:59:40 2024. * * AUTOGENERATED - DO NOT EDIT */ @@ -21,7 +21,7 @@ #include "erpc_server.hpp" #include "erpc_codec.hpp" -#if 11200 != ERPC_VERSION_NUMBER +#if 11300 != ERPC_VERSION_NUMBER #error "The generated shim code version is different to the rest of eRPC code." #endif diff --git a/test/common/gtest/gtest.cpp b/test/common/gtest/gtest.cpp index 4a7fc663..d6aed525 100644 --- a/test/common/gtest/gtest.cpp +++ b/test/common/gtest/gtest.cpp @@ -5390,7 +5390,7 @@ class ScopedPrematureExitFile { ~ScopedPrematureExitFile() { if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') { - remove(premature_exit_filepath_); + // remove(premature_exit_filepath_); } } @@ -9600,7 +9600,7 @@ class CapturedStream { } ~CapturedStream() { - remove(filename_.c_str()); + // remove(filename_.c_str()); } std::string GetCapturedString() { diff --git a/test/common/gtest/gtest.h b/test/common/gtest/gtest.h index ef9a6231..df1bd334 100644 --- a/test/common/gtest/gtest.h +++ b/test/common/gtest/gtest.h @@ -3393,29 +3393,54 @@ inline bool IsDir(const StatStruct& st) { # endif // GTEST_OS_WINDOWS_MOBILE #elif GTEST_OS_BARE_METAL - typedef struct { int x; } StatStruct; -#if not defined(__ARMCC_VERSION) +#if not defined(__ARMCC_VERSION) && not defined(__ZEPHYR__) inline int FileNo(FILE* file) { return fileno(file); } #else inline int FileNo(FILE* file) { return -1; } #endif inline int IsATTY(int fd) { return 0; } inline int Stat(const char* path, StatStruct* buf) { return -1; } +#if not defined(__ZEPHYR__) inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } -#if not defined(__ARMCC_VERSION) +#else +inline int StrCaseCmp(const char* s1, const char* s2) +{ + const char *ch1 = (const char *)s1; + const char *ch2 = (const char *)s2; + + while (tolower(*ch1) == tolower(*ch2++)) { + if (*ch1++ == '\0') { + return (0); + } + } + + return (tolower(*ch1) - tolower(*--ch2)); +} +#endif +#if not defined(__ARMCC_VERSION) && not defined(__ZEPHYR__) inline char* StrDup(const char* src) { return strdup(src); } #else -inline char* StrDup(const char* src) { return (NULL); } +inline char* StrDup(const char* src) { + size_t len; + char *copy; + + len = strlen(src) + 1; + if ((copy = (char *)malloc(len)) == NULL) { + return (NULL); + } + + memcpy(copy, src, len); + return (copy); +} #endif inline int RmDir(const char* dir) { return -1; } inline bool IsDir(const StatStruct& st) { return false; } #else - typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } diff --git a/test/common/unit_test_arbitrator_app1.cpp b/test/common/unit_test_arbitrator_app1.cpp index 9b85268b..9577aedc 100644 --- a/test/common/unit_test_arbitrator_app1.cpp +++ b/test/common/unit_test_arbitrator_app1.cpp @@ -1,6 +1,6 @@ /* * Copyright (c) 2016, Freescale Semiconductor, Inc. - * Copyright 2016 - 2023 NXP + * Copyright 2016 - 2024 NXP * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause @@ -90,7 +90,7 @@ void runClient(void *arg) // wait until ERPC first (client) app will announce that it is ready. while (waitClient == 0) { - Thread::sleep(10); + Thread::sleep(10000); } // wait until ERPC first (client) app will announce ready to quit state @@ -98,7 +98,7 @@ void runClient(void *arg) { isTestPassing = testClient(); { - Thread::sleep(10); + Thread::sleep(10000); Mutex::Guard lock(waitQuitMutex); if (waitQuit != 0 || isTestPassing != 0 || stopTest != 0) { @@ -110,7 +110,7 @@ void runClient(void *arg) while (true) { - Thread::sleep(10); + Thread::sleep(100000); Mutex::Guard lock(waitQuitMutex); if (waitQuit != 0) { @@ -253,4 +253,3 @@ int testClient() } return 0; } -} diff --git a/test/common/unit_test_zephyr_rpmsg_lite_arbitrator_client.cpp b/test/common/unit_test_zephyr_rpmsg_lite_arbitrator_client.cpp new file mode 100644 index 00000000..876fae6d --- /dev/null +++ b/test/common/unit_test_zephyr_rpmsg_lite_arbitrator_client.cpp @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016 - 2023 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ +#include + +#include "erpc_arbitrated_client_setup.h" +#include "erpc_mbf_setup.h" +#include "erpc_server_setup.h" +#include "erpc_transport_setup.h" +#include "erpc_threading.h" + +// #include "FreeRTOS.h" +// #include "semphr.h" +// #include "task.h" + +#include "c_test_firstInterface_client.h" +#include "c_test_secondInterface_server.h" +#include "gtest.h" +#include "unit_test.h" +#include "unit_test_wrapped.h" + +#include "rpmsg_lite.h" + +// #ifdef UNITY_DUMP_RESULTS +// #include "corn_g_test.h" +// #endif + +using namespace erpc; +using namespace std; + +#define APP_ERPC_READY_EVENT_DATA (1) +#define RPMSG_LITE_LINK_ID (0) + +Mutex waitQuitMutex; +Thread g_initThread("runInit"); +Thread g_serverThread("runServer"); +Thread g_clientThread("runClient"); + +K_THREAD_STACK_DEFINE(stack_init, 256 * 4); +K_THREAD_STACK_DEFINE(stack_server, 1536 * 8); +K_THREAD_STACK_DEFINE(stack_client, 1536 * 8); + +volatile int waitQuit = 0; +volatile uint16_t eRPCReadyEventData = 0; +extern const uint32_t erpc_generated_crc; +erpc_service_t service = NULL; +erpc_server_t server; + +struct k_poll_signal signalClient; +struct k_poll_signal signalServer; + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// +/*! + * @brief eRPC server side ready event handler + */ +static void eRPCReadyEventHandler(uint16_t eventData, void *context) +{ + eRPCReadyEventData = eventData; +} + +void increaseWaitQuit() +{ + Mutex::Guard lock(waitQuitMutex); + waitQuit++; +} + +void runServer(void *arg) +{ + struct k_poll_event events[1] = { + K_POLL_EVENT_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &signalServer) + }; + k_poll(events, 1, K_FOREVER); + + erpc_status_t err; + err = erpc_server_run(server); + increaseWaitQuit(); + + if (err != kErpcStatus_Success) + { + printk("Server error: %d\r\n", err); + } + + k_thread_suspend(k_current_get()); +} + +void runClient(void *arg) +{ + struct k_poll_event events[1] = { + K_POLL_EVENT_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &signalClient), + }; + k_poll(events, 1, K_FOREVER); + + // send to ERPC second (server) app message that this app is ready. + whenReady(); + + __attribute__((unused)) int i; + i = RUN_ALL_TESTS(); + + // wait until ERPC second (server) app will announce ready to quit state. + while (true) + { + Mutex::Guard lock(waitQuitMutex); + if (waitQuit != 0) + { + break; + } + } + + // send to ERPC second (server) app ready to quit state + quitFirstInterfaceServer(); + + increaseWaitQuit(); + + k_thread_suspend(k_current_get()); +} + +void runInit(void *arg) +{ + erpc_transport_t transportClient; + erpc_transport_t transportServer; + + // RPMsg-Lite transport layer initialization + transportClient = erpc_transport_rpmsg_lite_rtos_master_init(100, 101, RPMSG_LITE_LINK_ID); + + if (transportClient == NULL) + { + // error in initialization of transport layer + printk("Transport layer initialization failed\r\n"); + while (1) + { + } + } + + // MessageBufferFactory initialization + erpc_mbf_t message_buffer_factory; + erpc_client_t client; + + message_buffer_factory = erpc_mbf_rpmsg_init(transportClient); + + // eRPC client side initialization + client = erpc_arbitrated_client_init(transportClient, message_buffer_factory, &transportServer); + initInterfaces(client); + + // eRPC server side initialization + server = erpc_server_init(transportServer, message_buffer_factory); + + erpc_arbitrated_client_set_crc(client, erpc_generated_crc); + + // adding server to client for nested calls. + erpc_arbitrated_client_set_server(client, server); + erpc_arbitrated_client_set_server_thread_id(client, (void *)g_serverThread.getThreadId()); + + // adding the service to the server + service = create_SecondInterface_service(); + erpc_add_service_to_server(server, service); + + // unblock server and client task + + k_poll_signal_raise(&signalClient, 0); + k_poll_signal_raise(&signalServer, 0); + + k_thread_suspend(k_current_get()); +} + +class ZephyrPrinter : public ::testing::EmptyTestEventListener +{ + virtual void OnTestCaseStart(const ::testing::TestCase &test_case) + { + printk("[----------] %d %s from %s\n", test_case.test_to_run_count(), + (test_case.test_to_run_count() == 1 ? "test" : "tests"), test_case.name()); + } + + virtual void OnTestStart(const ::testing::TestInfo &test_info) + { + printk("[ RUN ] %s.%s\n", test_info.test_case_name(), test_info.name()); + } + + virtual void OnTestDisabled(const ::testing::TestInfo &test_info) + { + printk("[ DISABLED ] %s.%s\n", test_info.test_case_name(), test_info.name()); + } + + virtual void OnTestPartResult(const ::testing::TestPartResult &test_part_result) + { + if (test_part_result.type() == ::testing::TestPartResult::kSuccess) + { + return; + } + else + { + printk("%s (%d) %s\n%s\n", test_part_result.file_name(), test_part_result.line_number(), + test_part_result.failed() ? "error" : "Success", test_part_result.summary()); + } + } + + virtual void OnTestEnd(const ::testing::TestInfo &test_info) + { + if (test_info.result()->Passed()) + { + printk("[ OK ] "); + } + else + { + printk("[ FAILED ] "); + } + printk("%s.%s\n", test_info.test_case_name(), test_info.name()); + } + + virtual void OnTestCaseEnd(const ::testing::TestCase &test_case) + { + printk("%d %s from %s\n", test_case.test_to_run_count(), + (test_case.test_to_run_count() == 1 ? "test" : "tests"), test_case.name()); + } + + virtual void OnTestProgramEnd(const ::testing::UnitTest &) { printk("[==========] Done running all tests.\r\n"); } +}; + +int main(void) +{ + env_sleep_msec(1000); + int fake_argc = 1; + const auto fake_arg0 = "dummy"; + char *fake_argv0 = const_cast(fake_arg0); + char **fake_argv = &fake_argv0; + ::testing::InitGoogleTest(&fake_argc, fake_argv); + + ::testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners(); + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new ZephyrPrinter); + + k_poll_signal_init(&signalClient); + k_poll_signal_init(&signalServer); + + g_initThread.init(&runInit, 1, 256 * 4); + g_serverThread.init(&runServer, 2, 1536 * 4); + g_clientThread.init(&runClient, 1, 1536 * 4); + + g_initThread.setStackPointer(stack_init); + g_serverThread.setStackPointer(stack_server); + g_clientThread.setStackPointer(stack_client); + + g_initThread.start(); + g_serverThread.start(); + g_clientThread.start(); + + k_thread_suspend(k_current_get()); +} + +extern "C" { +void quitSecondInterfaceServer() +{ + /* removing the service from the server */ + erpc_remove_service_from_server(server, service); + destroy_SecondInterface_service(service); + + // Stop server part + erpc_server_stop(server); + increaseWaitQuit(); +} +} diff --git a/test/common/unit_test_zephyr_rpmsg_lite_arbitrator_server.cpp b/test/common/unit_test_zephyr_rpmsg_lite_arbitrator_server.cpp new file mode 100644 index 00000000..477e1656 --- /dev/null +++ b/test/common/unit_test_zephyr_rpmsg_lite_arbitrator_server.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016 - 2024 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +#include "erpc_arbitrated_client_setup.h" +#include "erpc_mbf_setup.h" +#include "erpc_server_setup.h" +#include "erpc_transport_setup.h" +#include "erpc_threading.h" + +#include "c_test_firstInterface_server.h" +#include "c_test_secondInterface_client.h" +#include "unit_test.h" +#include "unit_test_wrapped.h" + +#include "rpmsg_lite.h" + +using namespace erpc; + +int testClient(); + +#define APP_ERPC_READY_EVENT_DATA (1) +#define RPMSG_LITE_LINK_ID (0) + +#define SHM_MEM_ADDR DT_REG_ADDR(DT_CHOSEN(zephyr_ipc_shm)) +#define SHM_MEM_SIZE DT_REG_SIZE(DT_CHOSEN(zephyr_ipc_shm)) + +Mutex waitQuitMutex; +Thread g_initThread("runInit"); +Thread g_serverThread("runServer"); +Thread g_clientThread("runClient"); + +volatile int waitQuit = 0; +volatile int waitClient = 0; +volatile int isTestPassing = 0; +uint32_t startupData; +volatile int stopTest = 0; +extern const uint32_t erpc_generated_crc; +erpc_service_t service = NULL; +erpc_server_t server; + +K_THREAD_STACK_DEFINE(stack_init, 256 * 4); +K_THREAD_STACK_DEFINE(stack_server, 1536 * 4); +K_THREAD_STACK_DEFINE(stack_client, 1536 * 4); + +struct k_poll_signal signalClient; +struct k_poll_signal signalServer; + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// +void increaseWaitQuit() +{ + Mutex::Guard lock(waitQuitMutex); + waitQuit++; +} + +void runServer(void *arg) +{ + struct k_poll_event events[1] = { + K_POLL_EVENT_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &signalServer), + }; + k_poll(events, 1, K_FOREVER); + + erpc_status_t err; + err = erpc_server_run(server); + increaseWaitQuit(); + + if (err != kErpcStatus_Success) + { + // server error + while (1) + { + } + } + k_thread_suspend(k_current_get()); +} + +void runClient(void *arg) +{ + struct k_poll_event events[1] = { + K_POLL_EVENT_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &signalClient), + }; + k_poll(events, 1, K_FOREVER); + + // wait until ERPC first (client) app will announce that it is ready. + while (waitClient == 0) + { + Thread::sleep(10000); + } + + // wait until ERPC first (client) app will announce ready to quit state + while (true) + { + isTestPassing = testClient(); + { + Thread::sleep(10000); + Mutex::Guard lock(waitQuitMutex); + if (waitQuit != 0 || isTestPassing != 0 || stopTest != 0) + { + enableFirstSide(); + break; + } + } + } + + while (true) + { + Thread::sleep(100000); + Mutex::Guard lock(waitQuitMutex); + if (waitQuit != 0) + { + break; + } + } + + // send to ERPC first (client) app ready to quit state + quitSecondInterfaceServer(); + increaseWaitQuit(); + k_thread_suspend(k_current_get()); +} + +static void SignalReady(void) {} + +void runInit(void *arg) +{ + uint32_t *shared_memory = (uint32_t *)SHM_MEM_ADDR; + + erpc_transport_t transportClient; + erpc_transport_t transportServer; + erpc_mbf_t message_buffer_factory; + erpc_client_t client; + + transportClient = erpc_transport_rpmsg_lite_rtos_remote_init(101U, 100U, (void *)(char *)shared_memory, + RPMSG_LITE_LINK_ID, SignalReady, NULL); + // MessageBufferFactory initialization + message_buffer_factory = erpc_mbf_rpmsg_init(transportClient); + + // eRPC client side initialization + client = erpc_arbitrated_client_init(transportClient, message_buffer_factory, &transportServer); + initInterfaces(client); + + // eRPC server side initialization + server = erpc_server_init(transportServer, message_buffer_factory); + + erpc_arbitrated_client_set_crc(client, erpc_generated_crc); + + // adding server to client for nested calls. + erpc_arbitrated_client_set_server(client, server); + erpc_arbitrated_client_set_server_thread_id(client, (void *)g_serverThread.getThreadId()); + + // adding the service to the server + service = create_FirstInterface_service(); + erpc_add_service_to_server(server, service); + + // unblock server and client task + k_poll_signal_raise(&signalClient, 0); + k_poll_signal_raise(&signalServer, 0); + + k_thread_suspend(k_current_get()); +} + +int main(void) +{ + env_sleep_msec(0); + k_poll_signal_init(&signalClient); + k_poll_signal_init(&signalServer); + + g_initThread.init(&runInit, 1, 256 * 4); + g_serverThread.init(&runServer, 3, 1536 * 4); + g_clientThread.init(&runClient, 2, 1536 * 4); + + g_initThread.setStackPointer(stack_init); + g_serverThread.setStackPointer(stack_server); + g_clientThread.setStackPointer(stack_client); + + + g_initThread.start(); + g_serverThread.start(); + g_clientThread.start(); + + k_thread_suspend(k_current_get()); +} + +extern "C" { +void stopSecondSide() +{ + ++stopTest; +} + +int32_t getResultFromSecondSide() +{ + return isTestPassing; +} + +void testCasesAreDone(void) +{ + increaseWaitQuit(); +} + +void quitFirstInterfaceServer() +{ + /* removing the service from the server */ + erpc_remove_service_from_server(server, service); + destroy_FirstInterface_service(service); + + // Stop server part + erpc_server_stop(server); +} + +void whenReady() +{ + waitClient++; +} +} + +int testClient() +{ + int number = 15; + for (int i = 0; i < number; i++) + { + secondSendInt(i + number); + } + for (int i = number - 1; i >= 0; i--) + { + if (i + number != secondReceiveInt()) + { + return -1; + } + } + return 0; +} diff --git a/test/common/unit_test_zephyr_rpmsg_lite_client.cpp b/test/common/unit_test_zephyr_rpmsg_lite_client.cpp new file mode 100644 index 00000000..8b95b9fa --- /dev/null +++ b/test/common/unit_test_zephyr_rpmsg_lite_client.cpp @@ -0,0 +1,133 @@ +/* + * Copyright 2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +#include "rpmsg_lite.h" +#include "erpc_client_setup.h" + +#include "c_test_unit_test_common_client.h" +#include "gtest.h" +#include "gtestListener.hpp" +#include "myAlloc.hpp" +#include "unit_test_wrapped.h" + +// #ifdef UNITY_DUMP_RESULTS +// #include "corn_g_test.h" +// #endif + +using namespace std; + +//////////////////////////////////////////////////////////////////////////////// +// Classes +//////////////////////////////////////////////////////////////////////////////// + +class ZephyrPrinter : public ::testing::EmptyTestEventListener +{ + virtual void OnTestCaseStart(const ::testing::TestCase &test_case) + { + printk("[----------] %d %s from %s\n", test_case.test_to_run_count(), + (test_case.test_to_run_count() == 1 ? "test" : "tests"), test_case.name()); + } + + virtual void OnTestStart(const ::testing::TestInfo &test_info) + { + printk("[ RUN ] %s.%s\n", test_info.test_case_name(), test_info.name()); + } + + virtual void OnTestDisabled(const ::testing::TestInfo &test_info) + { + printk("[ DISABLED ] %s.%s\n", test_info.test_case_name(), test_info.name()); + } + + virtual void OnTestPartResult(const ::testing::TestPartResult &test_part_result) + { + if (test_part_result.type() == ::testing::TestPartResult::kSuccess) + { + return; + } + else + { + printk("%s (%d) %s\n%s\n", test_part_result.file_name(), test_part_result.line_number(), + test_part_result.failed() ? "error" : "Success", test_part_result.summary()); + } + } + + virtual void OnTestEnd(const ::testing::TestInfo &test_info) + { + if (test_info.result()->Passed()) + { + printk("[ OK ] "); + } + else + { + printk("[ FAILED ] "); + } + printk("%s.%s\n", test_info.test_case_name(), test_info.name()); + } + + virtual void OnTestCaseEnd(const ::testing::TestCase &test_case) + { + printk("%d %s from %s\n", test_case.test_to_run_count(), + (test_case.test_to_run_count() == 1 ? "test" : "tests"), test_case.name()); + } + + virtual void OnTestProgramEnd(const ::testing::UnitTest &) { printk("[==========] Done running all tests.\r\n"); } +}; + +using namespace std; + +//////////////////////////////////////////////////////////////////////////////// +// Definitions +//////////////////////////////////////////////////////////////////////////////// + +#define RPMSG_LITE_LINK_ID (0) +int ::MyAlloc::allocated_ = 0; +extern char rpmsg_lite_base[]; + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +int main(void) +{ + env_sleep_msec(4000); + + int fake_argc = 1; + const auto fake_arg0 = "dummy"; + char *fake_argv0 = const_cast(fake_arg0); + char **fake_argv = &fake_argv0; + ::testing::InitGoogleTest(&fake_argc, fake_argv); + + ::testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners(); + listeners.Append(new LeakChecker); + + delete listeners.Release(listeners.default_result_printer()); + listeners.Append(new ZephyrPrinter); + + erpc_transport_t transport; + erpc_mbf_t message_buffer_factory; + erpc_client_t client; + + transport = erpc_transport_rpmsg_lite_rtos_master_init(100, 101, RPMSG_LITE_LINK_ID); + message_buffer_factory = erpc_mbf_rpmsg_init(transport); + + client = erpc_client_init(transport, message_buffer_factory); + initInterfaces_common(client); + initInterfaces(client); + + int i = RUN_ALL_TESTS(); + quit(); + + erpc_client_deinit(client); + + return i; +} + +void initInterfaces_common(erpc_client_t client) +{ + initCommon_client(client); +} diff --git a/test/common/unit_test_zephyr_rpmsg_lite_server.cpp b/test/common/unit_test_zephyr_rpmsg_lite_server.cpp new file mode 100644 index 00000000..82f53722 --- /dev/null +++ b/test/common/unit_test_zephyr_rpmsg_lite_server.cpp @@ -0,0 +1,104 @@ +/* + * Copyright 2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_mbf_setup.h" +#include "erpc_server_setup.h" +#include "erpc_simple_server.hpp" +#include "erpc_transport_setup.h" + +#include "rpmsg_lite.h" + +#include "c_test_unit_test_common_server.h" +#include "myAlloc.hpp" +#include "unit_test_wrapped.h" + +//////////////////////////////////////////////////////////////////////////////// +// Variables +//////////////////////////////////////////////////////////////////////////////// +#define RPMSG_LITE_LINK_ID (0) + +#define SHM_MEM_ADDR DT_REG_ADDR(DT_CHOSEN(zephyr_ipc_shm)) +#define SHM_MEM_SIZE DT_REG_SIZE(DT_CHOSEN(zephyr_ipc_shm)) + +int ::MyAlloc::allocated_ = 0; +extern char rpmsg_lite_base[]; +erpc_service_t service_common = NULL; +erpc_server_t server; + + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +static void SignalReady(void) {} + +int main(void) +{ + env_sleep_msec(1000); + uint32_t *shared_memory = (uint32_t *)SHM_MEM_ADDR; + + erpc_transport_t transport; + erpc_mbf_t message_buffer_factory; + + transport = erpc_transport_rpmsg_lite_rtos_remote_init(101U, 100U, (void *)(char *)shared_memory, + RPMSG_LITE_LINK_ID, SignalReady, NULL); + message_buffer_factory = erpc_mbf_rpmsg_init(transport); + + /* Init server */ + server = erpc_server_init(transport, message_buffer_factory); + + /* Add test services. This function call erpc_add_service_to_server for all necessary services. */ + add_services_to_server(server); + + /* Add common service */ + add_common_service(server); + + /* Add run server */ + erpc_server_run(server); + + /* Deinit server */ + erpc_server_deinit(server); + + return 0; +} + +//////////////////////////////////////////////////////////////////////////////// +// Server helper functions +//////////////////////////////////////////////////////////////////////////////// + +void add_common_service(erpc_server_t server) +{ + service_common = create_Common_service(); + erpc_add_service_to_server(server, service_common); +} + +void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) +{ + erpc_remove_service_from_server(server, service); + destroy_Common_service(service); +} + +//////////////////////////////////////////////////////////////////////////////// +// Common service implementations here +//////////////////////////////////////////////////////////////////////////////// + +void quit() +{ + /* removing common services from the server */ + remove_common_services_from_server(server, service_common); + + /* removing individual test services from the server */ + remove_services_from_server(server); + + erpc_server_stop(server); +} + +int32_t getServerAllocated() +{ + int result = ::MyAlloc::allocated(); + ::MyAlloc::allocated(0); + return result; +} diff --git a/test/common/unit_test_zephyr_uart_arbitrator_server.cpp b/test/common/unit_test_zephyr_uart_arbitrator_server.cpp new file mode 100644 index 00000000..cae93ef3 --- /dev/null +++ b/test/common/unit_test_zephyr_uart_arbitrator_server.cpp @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016 - 2024 NXP + * All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +#include "erpc_arbitrated_client_setup.h" +#include "erpc_mbf_setup.h" +#include "erpc_server_setup.h" +#include "erpc_transport_setup.h" +#include "erpc_threading.h" + +#include "c_test_firstInterface_server.h" +#include "c_test_secondInterface_client.h" +#include "unit_test.h" +#include "unit_test_wrapped.h" + +using namespace erpc; + +#define UART_DEVICE_NODE DT_CHOSEN(zephyr_console) +static const struct device *const uart_dev = DEVICE_DT_GET(UART_DEVICE_NODE); + +int testClient(); + +Mutex waitQuitMutex; +Thread g_initThread("runInit"); +Thread g_serverThread("runServer"); +Thread g_clientThread("runClient"); + +volatile int waitQuit = 0; +volatile int waitClient = 0; +volatile int isTestPassing = 0; +uint32_t startupData; +volatile int stopTest = 0; +extern const uint32_t erpc_generated_crc; +erpc_service_t service = NULL; +erpc_server_t server; + +K_THREAD_STACK_DEFINE(stack_init, 256 * 4); +K_THREAD_STACK_DEFINE(stack_server, 1536 * 4); +K_THREAD_STACK_DEFINE(stack_client, 1536 * 4); + +struct k_poll_signal signalClient; +struct k_poll_signal signalServer; + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// +void increaseWaitQuit() +{ + Mutex::Guard lock(waitQuitMutex); + waitQuit++; +} + +void runServer(void *arg) +{ + struct k_poll_event events[1] = { + K_POLL_EVENT_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &signalServer), + }; + k_poll(events, 1, K_FOREVER); + + erpc_status_t err; + err = erpc_server_run(server); + increaseWaitQuit(); + + if (err != kErpcStatus_Success) + { + // server error + while (1) + { + } + } + k_thread_suspend(k_current_get()); +} + +void runClient(void *arg) +{ + struct k_poll_event events[1] = { + K_POLL_EVENT_INITIALIZER(K_POLL_TYPE_SIGNAL, K_POLL_MODE_NOTIFY_ONLY, &signalClient), + }; + k_poll(events, 1, K_FOREVER); + + // wait until ERPC first (client) app will announce that it is ready. + while (waitClient == 0) + { + Thread::sleep(10000); + } + + // wait until ERPC first (client) app will announce ready to quit state + while (true) + { + isTestPassing = testClient(); + { + Thread::sleep(10000); + Mutex::Guard lock(waitQuitMutex); + if (waitQuit != 0 || isTestPassing != 0 || stopTest != 0) + { + enableFirstSide(); + break; + } + } + } + + while (true) + { + Thread::sleep(100000); + Mutex::Guard lock(waitQuitMutex); + if (waitQuit != 0) + { + break; + } + } + + // send to ERPC first (client) app ready to quit state + quitSecondInterfaceServer(); + increaseWaitQuit(); + k_thread_suspend(k_current_get()); +} + +static void SignalReady(void) {} + +void runInit(void *arg) +{ + if (!device_is_ready(uart_dev)) + { + printk("UART device not found!"); + return; + } + + erpc_transport_t transportClient; + erpc_transport_t transportServer; + erpc_mbf_t message_buffer_factory; + erpc_client_t client; + + transportClient = erpc_transport_zephyr_uart_init((void *)uart_dev); + + // MessageBufferFactory initialization + message_buffer_factory = erpc_mbf_dynamic_init(); + + // eRPC client side initialization + client = erpc_arbitrated_client_init(transportClient, message_buffer_factory, &transportServer); + initInterfaces(client); + + // eRPC server side initialization + server = erpc_server_init(transportServer, message_buffer_factory); + + erpc_arbitrated_client_set_crc(client, erpc_generated_crc); + + // adding server to client for nested calls. + erpc_arbitrated_client_set_server(client, server); + erpc_arbitrated_client_set_server_thread_id(client, (void *)g_serverThread.getThreadId()); + + // adding the service to the server + service = create_FirstInterface_service(); + erpc_add_service_to_server(server, service); + + // unblock server and client task + k_poll_signal_raise(&signalClient, 0); + k_poll_signal_raise(&signalServer, 0); + + k_thread_suspend(k_current_get()); +} + +int main(void) +{ + k_poll_signal_init(&signalClient); + k_poll_signal_init(&signalServer); + + g_initThread.init(&runInit, 1, 256 * 4); + g_serverThread.init(&runServer, 3, 1536 * 4); + g_clientThread.init(&runClient, 2, 1536 * 4); + + g_initThread.setStackPointer(stack_init); + g_serverThread.setStackPointer(stack_server); + g_clientThread.setStackPointer(stack_client); + + + g_initThread.start(); + g_serverThread.start(); + g_clientThread.start(); + + k_thread_suspend(k_current_get()); +} + +extern "C" { +void stopSecondSide() +{ + ++stopTest; +} + +int32_t getResultFromSecondSide() +{ + return isTestPassing; +} + +void testCasesAreDone(void) +{ + increaseWaitQuit(); +} + +void quitFirstInterfaceServer() +{ + /* removing the service from the server */ + erpc_remove_service_from_server(server, service); + destroy_FirstInterface_service(service); + + // Stop server part + erpc_server_stop(server); +} + +void whenReady() +{ + waitClient++; +} +} + +int testClient() +{ + int number = 15; + for (int i = 0; i < number; i++) + { + secondSendInt(i + number); + } + for (int i = number - 1; i >= 0; i--) + { + if (i + number != secondReceiveInt()) + { + return -1; + } + } + return 0; +} diff --git a/test/common/unit_test_zephyr_uart_server.cpp b/test/common/unit_test_zephyr_uart_server.cpp new file mode 100644 index 00000000..2521b0e3 --- /dev/null +++ b/test/common/unit_test_zephyr_uart_server.cpp @@ -0,0 +1,101 @@ +/* + * Copyright 2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include "erpc_mbf_setup.h" +#include "erpc_server_setup.h" +#include "erpc_simple_server.hpp" +#include "erpc_transport_setup.h" +#include "erpc_uart_zephyr_transport.hpp" + +#include "c_test_unit_test_common_server.h" +#include "myAlloc.hpp" +#include "unit_test_wrapped.h" + +//////////////////////////////////////////////////////////////////////////////// +// Variables +//////////////////////////////////////////////////////////////////////////////// +#define UART_DEVICE_NODE DT_CHOSEN(zephyr_console) + +static const struct device *const uart_dev = DEVICE_DT_GET(UART_DEVICE_NODE); + +int ::MyAlloc::allocated_ = 0; +erpc_service_t service_common = NULL; +erpc_server_t server; + + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +int main(void) +{ + if (!device_is_ready(uart_dev)) + { + printk("UART device not found!"); + return -1; + } + + erpc_transport_t transport; + erpc_mbf_t message_buffer_factory; + + transport = erpc_transport_zephyr_uart_init((void *)uart_dev); + message_buffer_factory = erpc_mbf_dynamic_init(); + + /* Init server */ + server = erpc_server_init(transport, message_buffer_factory); + + /* Add test services. This function call erpc_add_service_to_server for all necessary services. */ + add_services_to_server(server); + + /* Add common service */ + add_common_service(server); + + /* Add run server */ + erpc_server_run(server); + + /* Deinit server */ + erpc_server_deinit(server); + + return 0; +} + +//////////////////////////////////////////////////////////////////////////////// +// Server helper functions +//////////////////////////////////////////////////////////////////////////////// + +void add_common_service(erpc_server_t server) +{ + service_common = create_Common_service(); + erpc_add_service_to_server(server, service_common); +} + +void remove_common_services_from_server(erpc_server_t server, erpc_service_t service) +{ + erpc_remove_service_from_server(server, service); + destroy_Common_service(service); +} + +//////////////////////////////////////////////////////////////////////////////// +// Common service implementations here +//////////////////////////////////////////////////////////////////////////////// + +void quit() +{ + /* removing common services from the server */ + remove_common_services_from_server(server, service_common); + + /* removing individual test services from the server */ + remove_services_from_server(server); + + erpc_server_stop(server); +} + +int32_t getServerAllocated() +{ + int result = ::MyAlloc::allocated(); + ::MyAlloc::allocated(0); + return result; +} diff --git a/test/python_impl_tests/scripts/server/runner.py b/test/python_impl_tests/scripts/server/runner.py index b3582696..cd5ce026 100644 --- a/test/python_impl_tests/scripts/server/runner.py +++ b/test/python_impl_tests/scripts/server/runner.py @@ -20,12 +20,19 @@ def __init__(self, name, params, services, constructors): self.client = None self.proc = None self.argParser = self.initParser() - try: - self.args = self.argParser.parse_args() - except: - args = [item for item in sys.argv if (item in ['-c', '-s', '--server', '--client']) or ('=' in item)] + + if '--twister-harness' in sys.argv: + # Filter all unnecessary arguments from Twister + args = [item for item in sys.argv if ('--device-serial' in item or '--device-serial-baud' in item)] + args.append('-c') self.args = self.argParser.parse_args(args) - self.initTest(name, params) + else: + try: + self.args = self.argParser.parse_args() + except: + args = [item for item in sys.argv if (item in ['-c', '-s', '--server', '--client']) or ('=' in item)] + self.args = self.argParser.parse_args(args) + self.initTest(name, params) def initParser(self): # parse cmd parameters @@ -36,6 +43,9 @@ def initParser(self): argParser.add_argument('-p', '--port', default='12345', help='Port (default value is 12345)') argParser.add_argument('-S', '--serial', default=None, help='Serial device (default value is None)') argParser.add_argument('-B', '--baud', default='115200', help='Baud (default value is 115200)') + # Zephyr Twister arguments + argParser.add_argument('--device-serial', default=None, dest='serial') + argParser.add_argument('--device-serial-baud', default='115200', dest='baud', ) return argParser def initTest(self, name, params): diff --git a/test/test_arbitrator/test_arbitrator_client_impl.cpp b/test/test_arbitrator/test_arbitrator_client_impl.cpp index 22839f2b..b4157ae7 100644 --- a/test/test_arbitrator/test_arbitrator_client_impl.cpp +++ b/test/test_arbitrator/test_arbitrator_client_impl.cpp @@ -64,6 +64,7 @@ TEST(test_arbitrator, NestedCallTest) stopSecondSide(); while (!enabled) { + Thread::sleep(1000); }; EXPECT_EQ(nestedCallTest(), nestedCallsCount * 2 - 1); } diff --git a/test/zephyr/README.rst b/test/zephyr/README.rst new file mode 100644 index 00000000..6450fd8a --- /dev/null +++ b/test/zephyr/README.rst @@ -0,0 +1,93 @@ +Zephyr eRPC tests +################# + +This folder contains all the necessary files to test eRPC with Zephyr. +The folder contains two folders for dual core testing - `rpmsglite/` and PC-Board testing via UART - `uart/`. + +To build images for the primary and secondary core, Zephyr requires the use of `sysbuild`. The primary `CMakeLists.txt` is +located in the unit test folder, while the `CMakeLists.txt` for the secondary core is +located in the nested `remote` folder. The `sysbuild.cmake` directs the Zephyr build system to +first build the secondary core and then link it to the primary image. + +Directory structure +******************* + +* **cmake/** CMake files used for building tests +* **rpmsglite/cmake/** CMake files for sysbuild and tests +* **uart/cmake/** CMake files for tests +* **rpmsglite/config/** Configuration files for both cores +* **uart/config/** Configuration files for UART tests +* **rpmsglite/test\_xxx/** Directories with tests. Contains primary and remote CMakeLists.txt, sysbuild.cmake and testcase.yaml +* **uart/test\_xxx/** Directories with tests. Contains CMakeLists.txt and testcase.yaml + +Running tests +************* + +Note: To generate eRPC code, CMake requires `erpcgen` executable to be in Path. +If you have already builded `erpcgen`, add it to the path. Windows: + +.. code-block:: console + + $env:PATH = $env:PATH + ';C:\path\to\erpc\erpcgen\' # Windows + +All tests (RPMSG-Lite and UART) can be executed with Zephyr's Twister: + +.. code-block:: console + + west twister --device-testing --device-serial COM8 -T .\erpc\test\zephyr -p mimxrt1160_evk_cm7 --west-flash --west-runner=jlink + +For executing tests on one core boards (mimxrt1060_evk): + +.. code-block:: console + + west twister --device-testing --device-serial COM8 -T .\erpc\test\zephyr\uart -p mimxrt1060_evkb + +* `--device-testing` Run tests on device +* `--device-serial` Select port where is the device connected +* `-T` Path where Twister looks for test cases (testcase.yaml) +* `-p` Name of the device +* `--west-flash` is required to be able build sysbuild tests. +* `--west-runner` Runner used to flash board + +Test's structure notes +###################### + +Each test suite has it's own `cmake/unit_test.cmake`. Each test has its own folder with a CMakeLists files that include `cmake/unit_test.cmake`, which includes +Zephyr and all necessary variables. These variables can be overridden in the test's CMakeLists file. Finally, the `zephyr/cmake/test.cmake`` file is included. +Ensure that all sources and includes are added to the test when included. If the client is involved, add the gtest as well. + +`cmake/unit_test.cmake` has to define `ERPC_ROOT_DIR`, `ZEPHYR_TEST_CMAKE_DIR` and `ERPC_ROOT_DIR`. +Additionally `TRANSPORT` and `APP_TYPE` has to be specified in test's `CMakeLists.txt` or in `unit_test.cmake` before including `zephyr/cmake/variables.cmake`. + +Variable +******** + +* **RPMSG_LITE_REMOTE_BOARD** Remote board selected based on build board +* **APP_TYPE** CLIENT/SERVER, specified in projects's CMakeLists +* **TRANSPORT** In this case always `zephyr_uart` or `zephyr_rpmsg_lite` +* **TEST_NAME** Name of the test - test_binary, ... +* **TEST_SOURCE_DIR** Source dir of the test implementation +* **TEST_COMMON_DIR** Common dir of the erpc test (`erpc/test/common``) +* **ERPC_NAME** Default `test`, can be overridden +* **ERPC_NAME_APP** Default ERPC_NAME, overridden +* **TEST_OUT_DIR** The binary directory where the test is builded +* **ERPC_OUT_ROOT_DIR** The root directory for the erpc shim code is generation +* **ERPC_OUT_DIR** Name of the directory where shim code is generated (Default: erpc_outputs) +* **TEST_ERPC_OUT_DIR** The directory where the erpc shim code is generated +* **GENERATE_ERPC_IDL_FILES** If FALSE, test.cmake file will not generate the shim code +* **IDL_FILE** IDL file that is used for generating +* **TEST_EXT_SOURCES** External sources that are added to the app +* **TEST_EXT_INCLUDES** External includes that are added to the app + +Files +***** + +* **cmake/test.cmake** Generate shim code, add sources and includes to the target, link Configuration files to erpc and rpmsg_lite +* **cmake/variables.cmake** Set default variables +* **{rpmsglite,uart}/cmake/unit_test.cmake** Main cmake for server and client, includes Zephyr package and variables.cmake +* **rpmsglite/cmake/sysbuild.cmake** Common sysbuild for all test. Has to be included from test's folder in file named **sysbuild.cmake** +* **rpmsglite/cmake/rpmsg_lite.cmake** Used in sysbuild.cmake to determinate remote board +* **{rpmsglite,uart}/test_xxx/testcase.yaml** Define test, so it can be discoverd by Twister +* **{rpmsglite,uart}/test_xxx/CMakeLists.cmake** CMake for the test +* **rpmsglite/test_xxx/sysbuild.cmake** Includes cmake/sysbuild.cmake. Used by Zephyr's sysbuild system +* **rpmsglite/test_xxx/remote/CMakeLists.cmake** CMake for the server \ No newline at end of file diff --git a/test/zephyr/cmake/test.cmake b/test/zephyr/cmake/test.cmake new file mode 100644 index 00000000..b1cda6a7 --- /dev/null +++ b/test/zephyr/cmake/test.cmake @@ -0,0 +1,88 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Generate ERPC shim code and add sources and includes to app target. +# If APP_TYPE is client, also add gtest. Link the config directory to erpc a rpmsg_lite. + +set_ifndef(TEST_ERPC_FILES + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME_APP}_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_unit_test_common_interface.cpp + + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME_APP}_${APP_TYPE}.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_unit_test_common_${APP_TYPE}.cpp + + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME_APP}_${APP_TYPE}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME}_unit_test_common_${APP_TYPE}.cpp +) + +if(GENERATE_ERPC_IDL_FILES) + add_custom_command( + OUTPUT ${TEST_ERPC_FILES} + COMMAND erpcgen -g c -o ${ERPC_OUT_ROOT_DIR} ${IDL_FILE} # TODO: add builded erpcgen if not found in path + WORKING_DIRECTORY ${TEST_SOURCE_DIR} + DEPENDS ${IDL_FILE} + COMMENT "Generating eRPC files from: ${IDL_FILE} to ${ERPC_OUT_ROOT_DIR}" + ) +endif() + +set_ifndef(TEST_SOURCES + ${TEST_COMMON_DIR}/unit_test_${TRANSPORT}_${APP_TYPE}.cpp + ${TEST_SOURCE_DIR}/${TEST_NAME}_${APP_TYPE}_impl.cpp + + ${TEST_ERPC_FILES} + ${TEST_EXT_SOURCES} +) + +set_ifndef(TEST_INCLUDES + ${TEST_ERPC_OUT_DIR} + ${TEST_COMMON_DIR} + ${TEST_SOURCE_DIR} + ${CONFIG_DIR}/ + ${TEST_EXT_INCLUDES} +) + +target_include_directories(app PRIVATE ${TEST_INCLUDES}) +target_sources(app PRIVATE ${TEST_SOURCES}) + +# Include gtest +if(APP_TYPE STREQUAL "client") + target_sources(app + PRIVATE ${TEST_COMMON_DIR}/gtest/gtest.cpp + PRIVATE ${TEST_COMMON_DIR}/gtest/gtimer.c + ) + + target_include_directories(app PUBLIC ${TEST_COMMON_DIR}/gtest/) + + target_compile_definitions(app PUBLIC + GTEST_OS_BARE_METAL=1 + GTEST_HAS_CLONE=0 + GTEST_HAS_EXCEPTIONS=0 + GTEST_HAS_GLOBAL_STRING=0 + GTEST_HAS_GLOBAL_WSTRING=0 + GTEST_HAS_POSIX_RE=0 + GTEST_HAS_PTHREAD=0 + GTEST_HAS_RTTI=0 + GTEST_HAS_STD_WSTRING=1 + GTEST_HAS_TR1_TUPLE=0 + GTEST_HAS_SEH=0 + GTEST_HAS_STREAM_REDIRECTION=0 + GTEST_USE_OWN_TR1_TUPLE=1 + GTEST_LANG_CXX11=1 + GTEST_LINKED_AS_SHARED_LIBRARY=0 + GTEST_CREATE_SHARED_LIBRARY=0 + UNITY_DUMP_RESULTS=1 + ) +endif() + +# Also include this directory into rpmsg_lite library because of project specific include rpsmg_config.h +if(CONFIG_RPMSGLITE) + target_include_directories(rpmsg_lite PRIVATE ${CONFIG_DIR}) +endif() + +# Same for erpc library and erpc_config.h +if(CONFIG_ERPC) + target_include_directories(erpc PRIVATE ${CONFIG_DIR}) +endif() \ No newline at end of file diff --git a/test/zephyr/cmake/variables.cmake b/test/zephyr/cmake/variables.cmake new file mode 100644 index 00000000..70d174ec --- /dev/null +++ b/test/zephyr/cmake/variables.cmake @@ -0,0 +1,27 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Set test implementation directory +set(TEST_SOURCE_DIR ${ERPC_ROOT_DIR}/test/${TEST_NAME}) +set(TEST_COMMON_DIR ${ERPC_ROOT_DIR}/test/common) + +# Set test name +set(ERPC_NAME "test") +set(ERPC_NAME_APP ${ERPC_NAME}) + +# Directory where test is generated +set(TEST_OUT_DIR ${CMAKE_CURRENT_BINARY_DIR}) + +# Directory where eRPC shim is generated +set(ERPC_OUT_ROOT_DIR ${TEST_OUT_DIR}) +set(ERPC_OUT_DIR erpc_outputs) +set(TEST_ERPC_OUT_DIR ${ERPC_OUT_ROOT_DIR}/${ERPC_OUT_DIR}) + +# Disable/Enable ERPC Shim generation; Source code has to be added to TEST_CLIENT_SOURCES/TEST_SERVER_SOURCES +set(GENERATE_ERPC_IDL_FILES TRUE) + +# IDL file +set(IDL_FILE ${TEST_SOURCE_DIR}/${TEST_NAME}.erpc) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/cmake/rpmsg_lite.cmake b/test/zephyr/rpmsglite/cmake/rpmsg_lite.cmake new file mode 100644 index 00000000..001aaf31 --- /dev/null +++ b/test/zephyr/rpmsglite/cmake/rpmsg_lite.cmake @@ -0,0 +1,29 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Selects the secondary board based on the board set during build. + +message(STATUS "BOARD: ${BOARD}") + +if(BOARD STREQUAL "lpcxpresso54114_m4") + set(RPMSG_LITE_REMOTE_BOARD "lpcxpresso54114_m0") +elseif(BOARD STREQUAL "lpcxpresso55s69_cpu0") + set(RPMSG_LITE_REMOTE_BOARD "lpcxpresso55s69_cpu1") +elseif(BOARD STREQUAL "mps2_an521") + set(RPMSG_LITE_REMOTE_BOARD "mps2_an521_remote") +elseif(BOARD STREQUAL "v2m_musca_b1") + set(RPMSG_LITE_REMOTE_BOARD "v2m_musca_b1_ns") +elseif(BOARD STREQUAL "mimxrt1170_evk_cm7") + set(RPMSG_LITE_REMOTE_BOARD "mimxrt1170_evk_cm4") +elseif(BOARD STREQUAL "mimxrt1160_evk_cm7") + set(RPMSG_LITE_REMOTE_BOARD "mimxrt1160_evk_cm4") +elseif(BOARD STREQUAL "mimxrt1170_evkb_cm7") + set(RPMSG_LITE_REMOTE_BOARD "mimxrt1170_evkb_cm4") +else() + message(FATAL "RMPSG-Lite: Unsupported board.") +endif() + + diff --git a/test/zephyr/rpmsglite/cmake/sysbuild.cmake b/test/zephyr/rpmsglite/cmake/sysbuild.cmake new file mode 100644 index 00000000..4095b9af --- /dev/null +++ b/test/zephyr/rpmsglite/cmake/sysbuild.cmake @@ -0,0 +1,31 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +get_filename_component(CURRENT_DIR_NAME ${APP_DIR} NAME) +set(SERVER ${CURRENT_DIR_NAME}_remote) +set(CLIENT ${CURRENT_DIR_NAME}) + +# Include RPMSG_LITE_REMOTE_BOARD variable base on BOARD +include(${APP_DIR}/../cmake/rpmsg_lite.cmake) + +# Add external project +ExternalZephyrProject_Add( + APPLICATION ${SERVER} + SOURCE_DIR ${APP_DIR}/remote + BOARD ${RPMSG_LITE_REMOTE_BOARD} + ) + +# Add dependencies so that the remote sample will be built first +# This is required because some primary cores need information from the +# remote core's build, such as the output image's LMA +add_dependencies(${CLIENT} ${SERVER}) +sysbuild_add_dependencies(FLASH ${CLIENT} ${SERVER}) +sysbuild_add_dependencies(CONFIGURE ${CLIENT} ${SERVER}) + +if(SB_CONFIG_BOOTLOADER_MCUBOOT) + # Make sure MCUboot is flashed first + sysbuild_add_dependencies(FLASH ${CLIENT} mcuboot) +endif() diff --git a/test/zephyr/rpmsglite/cmake/unit_test.cmake b/test/zephyr/rpmsglite/cmake/unit_test.cmake new file mode 100644 index 00000000..d48888a8 --- /dev/null +++ b/test/zephyr/rpmsglite/cmake/unit_test.cmake @@ -0,0 +1,44 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +set(TRANSPORT "zephyr_rpmsg_lite") + +if((NOT APP_TYPE STREQUAL "client") AND (NOT APP_TYPE STREQUAL "server")) + message(FATAL_ERROR "Unmown APP_TYPE. Set it to the 'client' or 'server'.") +endif() + +if (APP_TYPE STREQUAL "client") + set(KCONFIG_ROOT ${CMAKE_CURRENT_LIST_DIR}/../config/Kconfig) +endif() + +if(NOT DEFINED APPLICATION_CONFIG_DIR) + if (APP_TYPE STREQUAL "client") + set(APPLICATION_CONFIG_DIR ${CMAKE_CURRENT_LIST_DIR}/../config/) + elseif(APP_TYPE STREQUAL "server") + set(APPLICATION_CONFIG_DIR ${CMAKE_CURRENT_LIST_DIR}/../config/remote) + endif() +endif() + +if(NOT DEFINED CONFIG_DIR) + set(CONFIG_DIR ${CMAKE_CURRENT_LIST_DIR}/../config/) +endif() + +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) + +zephyr_get(APP_DIR SYSBUILD GLOBAL) +get_filename_component(TEST_NAME ${APP_DIR} NAME) +set(ERPC_ROOT_DIR ${ZEPHYR_ERPC_MODULE_DIR}) +set(ZEPHYR_TEST_CMAKE_DIR ${CMAKE_CURRENT_LIST_DIR}/../../cmake) + +# Include test's variables +include(${ZEPHYR_TEST_CMAKE_DIR}/variables.cmake) + +if(CONFIG_INCLUDE_REMOTE_DIR) + target_include_directories(zephyr_interface + INTERFACE + ${CMAKE_CURRENT_BINARY_DIR}/../${TEST_NAME}_remote/zephyr/include/public) +endif() + diff --git a/test/zephyr/rpmsglite/config/Kconfig b/test/zephyr/rpmsglite/config/Kconfig new file mode 100644 index 00000000..defc13a8 --- /dev/null +++ b/test/zephyr/rpmsglite/config/Kconfig @@ -0,0 +1,11 @@ +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause + +source "Kconfig.zephyr" + +config INCLUDE_REMOTE_DIR + bool "Include remote core header directory" + help + Include remote build header files. Can be used if primary image + needs to be aware of size or base address of secondary image diff --git a/test/zephyr/rpmsglite/config/boards/lpcxpresso54114_m4.conf b/test/zephyr/rpmsglite/config/boards/lpcxpresso54114_m4.conf new file mode 100644 index 00000000..60eead5a --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/lpcxpresso54114_m4.conf @@ -0,0 +1,2 @@ +CONFIG_SECOND_CORE_MCUX=y +CONFIG_INCLUDE_REMOTE_DIR=y diff --git a/test/zephyr/rpmsglite/config/boards/lpcxpresso54114_m4.overlay b/test/zephyr/rpmsglite/config/boards/lpcxpresso54114_m4.overlay new file mode 100644 index 00000000..95f16760 --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/lpcxpresso54114_m4.overlay @@ -0,0 +1,20 @@ +/* + * Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* + * shared memory reserved for the inter-processor communication + */ + zephyr,ipc_shm = &sramx1; + zephyr,ipc = &mailbox0; + }; + + sramx1:memory@4000000{ + compatible = "mmio-sram"; + reg = <0x4000000 0x8000>; + }; +}; diff --git a/test/zephyr/rpmsglite/config/boards/lpcxpresso55s69_cpu0.conf b/test/zephyr/rpmsglite/config/boards/lpcxpresso55s69_cpu0.conf new file mode 100644 index 00000000..7e6904d5 --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/lpcxpresso55s69_cpu0.conf @@ -0,0 +1 @@ +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/config/boards/lpcxpresso55s69_cpu0.overlay b/test/zephyr/rpmsglite/config/boards/lpcxpresso55s69_cpu0.overlay new file mode 100644 index 00000000..98df6d93 --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/lpcxpresso55s69_cpu0.overlay @@ -0,0 +1,22 @@ +/* + * Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* + * shared memory reserved for the inter-processor communication + */ + + zephyr,ipc_shm = &sram4duplicate; + zephyr,ipc = &mailbox0; + }; + + /* This is a duplication of sram4, workaround */ + sram4duplicate: memory@20040000 { + compatible = "mmio-sram"; + reg = <0x20040000 DT_SIZE_K(16)>; + }; +}; diff --git a/test/zephyr/rpmsglite/config/boards/mimxrt1160_evk_cm7.conf b/test/zephyr/rpmsglite/config/boards/mimxrt1160_evk_cm7.conf new file mode 100644 index 00000000..630a1933 --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/mimxrt1160_evk_cm7.conf @@ -0,0 +1,2 @@ +CONFIG_INCLUDE_REMOTE_DIR=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/config/boards/mimxrt1160_evk_cm7.overlay b/test/zephyr/rpmsglite/config/boards/mimxrt1160_evk_cm7.overlay new file mode 100644 index 00000000..3bf2b0dc --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/mimxrt1160_evk_cm7.overlay @@ -0,0 +1,24 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + chosen { + zephyr,ipc_shm = &ocram2_overlay; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set. + */ + ocram2_overlay: memory@202c0000{ + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; diff --git a/test/zephyr/rpmsglite/config/boards/mimxrt1170_evk_cm7.conf b/test/zephyr/rpmsglite/config/boards/mimxrt1170_evk_cm7.conf new file mode 100644 index 00000000..630a1933 --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/mimxrt1170_evk_cm7.conf @@ -0,0 +1,2 @@ +CONFIG_INCLUDE_REMOTE_DIR=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/config/boards/mimxrt1170_evk_cm7.overlay b/test/zephyr/rpmsglite/config/boards/mimxrt1170_evk_cm7.overlay new file mode 100644 index 00000000..3bf2b0dc --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/mimxrt1170_evk_cm7.overlay @@ -0,0 +1,24 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + chosen { + zephyr,ipc_shm = &ocram2_overlay; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set. + */ + ocram2_overlay: memory@202c0000{ + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; diff --git a/test/zephyr/rpmsglite/config/boards/mimxrt1170_evkb_cm7.conf b/test/zephyr/rpmsglite/config/boards/mimxrt1170_evkb_cm7.conf new file mode 100644 index 00000000..ffd841cb --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/mimxrt1170_evkb_cm7.conf @@ -0,0 +1,7 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# +CONFIG_INCLUDE_REMOTE_DIR=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/config/boards/mimxrt1170_evkb_cm7.overlay b/test/zephyr/rpmsglite/config/boards/mimxrt1170_evkb_cm7.overlay new file mode 100644 index 00000000..3bf2b0dc --- /dev/null +++ b/test/zephyr/rpmsglite/config/boards/mimxrt1170_evkb_cm7.overlay @@ -0,0 +1,24 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + chosen { + zephyr,ipc_shm = &ocram2_overlay; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set. + */ + ocram2_overlay: memory@202c0000{ + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; diff --git a/test/zephyr/rpmsglite/config/erpc_config.h b/test/zephyr/rpmsglite/config/erpc_config.h new file mode 100644 index 00000000..20721f71 --- /dev/null +++ b/test/zephyr/rpmsglite/config/erpc_config.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2021 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_CONFIG_H_ +#define _ERPC_CONFIG_H_ + +/*! + * @addtogroup config + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +//! @name Threading model options +//@{ +#define ERPC_ALLOCATION_POLICY_DYNAMIC (0U) //!< Dynamic allocation policy +#define ERPC_ALLOCATION_POLICY_STATIC (1U) //!< Static allocation policy + +#define ERPC_THREADS_NONE (0U) //!< No threads. +#define ERPC_THREADS_PTHREADS (1U) //!< POSIX pthreads. +#define ERPC_THREADS_FREERTOS (2U) //!< FreeRTOS. +#define ERPC_THREADS_ZEPHYR (3U) //!< ZEPHYR. +#define ERPC_THREADS_MBED (4U) //!< Mbed OS +#define ERPC_THREADS_WIN32 (5U) //!< WIN32 +#define ERPC_THREADS_THREADX (6U) //!< THREADX + +#define ERPC_NOEXCEPT_DISABLED (0U) //!< Disabling noexcept feature. +#define ERPC_NOEXCEPT_ENABLED (1U) //!< Enabling noexcept feature. + +#define ERPC_NESTED_CALLS_DISABLED (0U) //!< No nested calls support. +#define ERPC_NESTED_CALLS_ENABLED (1U) //!< Nested calls support. + +#define ERPC_NESTED_CALLS_DETECTION_DISABLED (0U) //!< Nested calls detection disabled. +#define ERPC_NESTED_CALLS_DETECTION_ENABLED (1U) //!< Nested calls detection enabled. + +#define ERPC_MESSAGE_LOGGING_DISABLED (0U) //!< Trace functions disabled. +#define ERPC_MESSAGE_LOGGING_ENABLED (1U) //!< Trace functions enabled. + +#define ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED (0U) //!< Do not use MCMGR for MU ISR management. +#define ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED (1U) //!< Use MCMGR for MU ISR management. + +#define ERPC_PRE_POST_ACTION_DISABLED (0U) //!< Pre post shim callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_ENABLED (1U) //!< Pre post shim callback functions enabled. + +#define ERPC_PRE_POST_ACTION_DEFAULT_DISABLED (0U) //!< Pre post shim default callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_DEFAULT_ENABLED (1U) //!< Pre post shim default callback functions enabled. +//@} + +//! @name Configuration options +//@{ + +//! @def ERPC_ALLOCATION_POLICY +//! +//! @brief Choose which allocation policy should be used. +//! +//! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. +//! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. +//! +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is supported +//! by compiler. Uncomment comment bellow to use static allocation policy. +//! In case of static implementation user need consider another values to set (ERPC_CODEC_COUNT, +//! ERPC_MESSAGE_LOGGERS_COUNT, ERPC_CLIENTS_THREADS_AMOUNT). +// #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_STATIC) + +//! @def ERPC_CODEC_COUNT +//! +//! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one thread per +//! each then 2, ... Default value 2. +// #define ERPC_CODEC_COUNT (2U) + +//! @def ERPC_MESSAGE_LOGGERS_COUNT +//! +//! @brief Set amount of message loggers objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. +//! For example if client or server is used in one thread then 1. If both are used in one thread per each then 2, ... +//! For arbitrated client 1 is enough. +//! Default value 0 (May not be used). +// #define ERPC_MESSAGE_LOGGERS_COUNT (0U) + +//! @def ERPC_CLIENTS_THREADS_AMOUNT +//! +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to ERPC_ALLOCATION_POLICY_STATIC. +//! Default value 1 (Most of current cases). +// #define ERPC_CLIENTS_THREADS_AMOUNT (1U) + +//! @def ERPC_THREADS +//! +//! @brief Select threading model. +//! +//! Set to one of the @c ERPC_THREADS_x macros to specify the threading model used by eRPC. +//! +//! Leave commented out to attempt to auto-detect. Auto-detection works well for pthreads. +//! FreeRTOS can be detected when building with compilers that support __has_include(). +//! Otherwise, the default is no threading. +#define ERPC_THREADS (ERPC_THREADS_ZEPHYR) + +//! @def ERPC_DEFAULT_BUFFER_SIZE +//! +//! Uncomment to change the size of buffers allocated by one of MessageBufferFactory. +//! (@ref client_setup and @ref server_setup). The default size is set to 256. +//! For RPMsg transport layer, ERPC_DEFAULT_BUFFER_SIZE must be 2^n - 16. +#define ERPC_DEFAULT_BUFFER_SIZE (496U) + +//! @def ERPC_DEFAULT_BUFFERS_COUNT +//! +//! Uncomment to change the count of buffers allocated by one of statically allocated messages. +//! Default value is set to 2. +//#define ERPC_DEFAULT_BUFFERS_COUNT (2U) + +//! @def ERPC_NOEXCEPT +//! +//! @brief Disable/enable noexcept support. +//! +//! Uncomment for using noexcept feature. +//#define ERPC_NOEXCEPT (ERPC_NOEXCEPT_ENABLED) + +//! @def ERPC_NESTED_CALLS +//! +//! Default set to ERPC_NESTED_CALLS_DISABLED. Uncomment when callbacks, or other eRPC +//! functions are called from server implementation of another eRPC call. Nested functions +//! need to be marked as @nested in IDL. +//#define ERPC_NESTED_CALLS (ERPC_NESTED_CALLS_ENABLED) + +//! @def ERPC_NESTED_CALLS_DETECTION +//! +//! Default set to ERPC_NESTED_CALLS_DETECTION_ENABLED when NDEBUG macro is presented. +//! This serve for locating nested calls in code. Nested calls are calls where inside eRPC function +//! on server side is called another eRPC function (like callbacks). Code need be a bit changed +//! to support nested calls. See ERPC_NESTED_CALLS macro. +//#define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_DISABLED) + +//! @def ERPC_MESSAGE_LOGGING +//! +//! Enable eRPC message logging code through the eRPC. Take look into "erpc_message_loggers.h". Can be used for base +//! printing messages, or sending data to another system for data analysis. Default set to +//! ERPC_MESSAGE_LOGGING_DISABLED. +//! +//! Uncomment for using logging feature. +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) + +//! @def ERPC_TRANSPORT_MU_USE_MCMGR +//! +//! @brief MU transport layer configuration. +//! +//! Set to one of the @c ERPC_TRANSPORT_MU_USE_MCMGR_x macros to configure the MCMGR usage in MU transport layer. +//! +//! MU transport layer could leverage the Multicore Manager (MCMGR) component for Inter-Core +//! interrupts / MU interrupts management or the Inter-Core interrupts can be managed by itself (MUX_IRQHandler +//! overloading). By default, ERPC_TRANSPORT_MU_USE_MCMGR is set to ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED when mcmgr.h +//! is part of the project, otherwise the ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED option is used. This settings can be +//! overwritten from the erpc_config.h by uncommenting the ERPC_TRANSPORT_MU_USE_MCMGR macro definition. Do not forget +//! to add the MCMGR library into your project when ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED option is used! See the +//! erpc_mu_transport.h for additional MU settings. +//#define ERPC_TRANSPORT_MU_USE_MCMGR ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED +//@} + +//! @def ERPC_PRE_POST_ACTION +//! +//! Enable eRPC pre and post callback functions shim code. Take look into "erpc_pre_post_action.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DISABLED. +//! +//! Uncomment for using pre post callback feature. +//#define ERPC_PRE_POST_ACTION (ERPC_PRE_POST_ACTION_ENABLED) + +//! @def ERPC_PRE_POST_ACTION_DEFAULT +//! +//! Enable eRPC pre and post default callback functions. Take look into "erpc_setup_extensions.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DEFAULT_DISABLED. +//! +//! Uncomment for using pre post default callback feature. +//#define ERPC_PRE_POST_ACTION_DEFAULT (ERPC_PRE_POST_ACTION_DEFAULT_ENABLED) + +/*! @} */ +#endif // _ERPC_CONFIG_H_ +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/test/zephyr/rpmsglite/config/prj.conf b/test/zephyr/rpmsglite/config/prj.conf new file mode 100644 index 00000000..e9735977 --- /dev/null +++ b/test/zephyr/rpmsglite/config/prj.conf @@ -0,0 +1,37 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP17=y +CONFIG_GLIBCXX_LIBCPP=y + +CONFIG_NEWLIB_LIBC=y +CONFIG_NEWLIB_LIBC_NANO=y + +# Compiler +CONFIG_MAIN_STACK_SIZE=4096 +CONFIG_HEAP_MEM_POOL_SIZE=8192 +CONFIG_NO_OPTIMIZATIONS=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_RPMSG_LITE=y + +# RPMSG Lite +CONFIG_IPM=y +CONFIG_EVENTS=y +CONFIG_PRINTK=y +CONFIG_RPMSGLITE=y +CONFIG_RPMSGLITE_QUEUE=y +CONFIG_RPMSGLITE_NS=y +CONFIG_TIMESLICE_SIZE=1 + +CONFIG_THREAD_CUSTOM_DATA=y +CONFIG_ERPC_ARBITRATED_CLIENT=y +CONFIG_POLL=y + +CONFIG_THREAD_NAME=y +CONFIG_SCHED_CPU_MASK=y +CONFIG_THREAD_ANALYZER=y + +CONFIG_LOG=y +CONFIG_LOG_MODE_IMMEDIATE=y +CONFIG_LOG_OVERRIDE_LEVEL=3 \ No newline at end of file diff --git a/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso54114_m0.conf b/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso54114_m0.conf new file mode 100644 index 00000000..b9e2b072 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso54114_m0.conf @@ -0,0 +1,2 @@ +CONFIG_SECOND_CORE_MCUX=y +CONFIG_BUILD_OUTPUT_HEX=y diff --git a/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso54114_m0.overlay b/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso54114_m0.overlay new file mode 100644 index 00000000..95f16760 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso54114_m0.overlay @@ -0,0 +1,20 @@ +/* + * Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* + * shared memory reserved for the inter-processor communication + */ + zephyr,ipc_shm = &sramx1; + zephyr,ipc = &mailbox0; + }; + + sramx1:memory@4000000{ + compatible = "mmio-sram"; + reg = <0x4000000 0x8000>; + }; +}; diff --git a/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso55s69_cpu1.conf b/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso55s69_cpu1.conf new file mode 100644 index 00000000..b9e2b072 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso55s69_cpu1.conf @@ -0,0 +1,2 @@ +CONFIG_SECOND_CORE_MCUX=y +CONFIG_BUILD_OUTPUT_HEX=y diff --git a/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso55s69_cpu1.overlay b/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso55s69_cpu1.overlay new file mode 100644 index 00000000..98df6d93 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/lpcxpresso55s69_cpu1.overlay @@ -0,0 +1,22 @@ +/* + * Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* + * shared memory reserved for the inter-processor communication + */ + + zephyr,ipc_shm = &sram4duplicate; + zephyr,ipc = &mailbox0; + }; + + /* This is a duplication of sram4, workaround */ + sram4duplicate: memory@20040000 { + compatible = "mmio-sram"; + reg = <0x20040000 DT_SIZE_K(16)>; + }; +}; diff --git a/test/zephyr/rpmsglite/config/remote/boards/mimxrt1160_evk_cm4.conf b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1160_evk_cm4.conf new file mode 100644 index 00000000..4dfc4a60 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1160_evk_cm4.conf @@ -0,0 +1,3 @@ +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/config/remote/boards/mimxrt1160_evk_cm4.overlay b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1160_evk_cm4.overlay new file mode 100644 index 00000000..ab57a613 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1160_evk_cm4.overlay @@ -0,0 +1,51 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + /* Switch to lpuart2, since primary core uses lpuart1 */ + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart2; + zephyr,shell-uart = &lpuart2; + zephyr,ipc_shm = &ocram2_overlay; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set + */ + ocram2_overlay: memory@202c0000 { + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; + +/* Enable secondary LPUART */ +&lpuart2 { + status = "okay"; + current-speed = <115200>; +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; diff --git a/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evk_cm4.conf b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evk_cm4.conf new file mode 100644 index 00000000..4dfc4a60 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evk_cm4.conf @@ -0,0 +1,3 @@ +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evk_cm4.overlay b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evk_cm4.overlay new file mode 100644 index 00000000..ab57a613 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evk_cm4.overlay @@ -0,0 +1,51 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + /* Switch to lpuart2, since primary core uses lpuart1 */ + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart2; + zephyr,shell-uart = &lpuart2; + zephyr,ipc_shm = &ocram2_overlay; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set + */ + ocram2_overlay: memory@202c0000 { + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; + +/* Enable secondary LPUART */ +&lpuart2 { + status = "okay"; + current-speed = <115200>; +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; diff --git a/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evkb_cm4.conf b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evkb_cm4.conf new file mode 100644 index 00000000..ef7b0f83 --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evkb_cm4.conf @@ -0,0 +1,8 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evkb_cm4.overlay b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evkb_cm4.overlay new file mode 100644 index 00000000..65fb71ff --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/boards/mimxrt1170_evkb_cm4.overlay @@ -0,0 +1,51 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + /* Switch to lpuart2, since primary core uses lpuart1 */ + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart1; + zephyr,shell-uart = &lpuart1; + zephyr,ipc_shm = &ocram2_overlay; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set + */ + ocram2_overlay: memory@202c0000 { + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; + +/* Enable secondary LPUART */ +&lpuart2 { + status = "okay"; + current-speed = <115200>; +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; diff --git a/test/zephyr/rpmsglite/config/remote/prj.conf b/test/zephyr/rpmsglite/config/remote/prj.conf new file mode 100644 index 00000000..5581523e --- /dev/null +++ b/test/zephyr/rpmsglite/config/remote/prj.conf @@ -0,0 +1,33 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP17=y +CONFIG_GLIBCXX_LIBCPP=y + +CONFIG_NEWLIB_LIBC=y +CONFIG_NEWLIB_LIBC_NANO=y + +# Compiler +CONFIG_MAIN_STACK_SIZE=4096 +CONFIG_HEAP_MEM_POOL_SIZE=8192 +CONFIG_NO_OPTIMIZATIONS=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_RPMSG_LITE=y + +# RPMSG Lite +CONFIG_IPM=y +CONFIG_EVENTS=y +CONFIG_PRINTK=y +CONFIG_RPMSGLITE=y +CONFIG_RPMSGLITE_QUEUE=y +CONFIG_RPMSGLITE_NS=y +CONFIG_TIMESLICE_SIZE=1 + +CONFIG_THREAD_CUSTOM_DATA=y +CONFIG_ERPC_ARBITRATED_CLIENT=y +CONFIG_POLL=y + +CONFIG_THREAD_NAME=y +CONFIG_SCHED_CPU_MASK=y +CONFIG_THREAD_ANALYZER=y \ No newline at end of file diff --git a/test/zephyr/rpmsglite/config/rpmsg_config.h b/test/zephyr/rpmsglite/config/rpmsg_config.h new file mode 100644 index 00000000..8d519b6c --- /dev/null +++ b/test/zephyr/rpmsglite/config/rpmsg_config.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2014, Mentor Graphics Corporation + * All rights reserved. + * Copyright (c) 2015 Xilinx, Inc. All rights reserved. + * Copyright 2016 Freescale Semiconductor, Inc. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef RPMSG_CONFIG_H_ +#define RPMSG_CONFIG_H_ + +#include "erpc_config_internal.h" + +/* RPMsg config values */ +/* START { */ +#define RL_MS_PER_INTERVAL (1) + +#define RL_BUFFER_PAYLOAD_SIZE (ERPC_DEFAULT_BUFFER_SIZE) + +#define RL_BUFFER_COUNT (ERPC_DEFAULT_BUFFERS_COUNT) + +#define RL_API_HAS_ZEROCOPY (1) + +#define RL_USE_STATIC_API (1) + +#define RL_USE_MCMGR_IPC_ISR_HANDLER (1) + +#define RL_ASSERT(x) \ + do \ + { \ + if (!(x)) \ + while (1) \ + ; \ + } while (0); +/* } END */ + +#endif /* RPMSG_CONFIG_H_ */ diff --git a/test/zephyr/rpmsglite/test_annotations/CMakeLists.txt b/test/zephyr/rpmsglite/test_annotations/CMakeLists.txt new file mode 100644 index 00000000..44c466af --- /dev/null +++ b/test/zephyr/rpmsglite/test_annotations/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(TEST_EXT_SOURCES ${TEST_COMMON_DIR}/addOne.cpp) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_annotations/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_annotations/remote/CMakeLists.txt new file mode 100644 index 00000000..cf2b14f6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_annotations/remote/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_annotations/sysbuild.cmake b/test/zephyr/rpmsglite/test_annotations/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_annotations/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_annotations/testcase.yaml b/test/zephyr/rpmsglite/test_annotations/testcase.yaml new file mode 100644 index 00000000..05a74273 --- /dev/null +++ b/test/zephyr/rpmsglite/test_annotations/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.annotations: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_arbitrator/CMakeLists.txt b/test/zephyr/rpmsglite/test_arbitrator/CMakeLists.txt new file mode 100644 index 00000000..0184d6e0 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/CMakeLists.txt @@ -0,0 +1,21 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +set(APPLICATION_CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/config) +set(CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/config) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +include(${APP_DIR}/common.cmake) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_arbitrator/common.cmake b/test/zephyr/rpmsglite/test_arbitrator/common.cmake new file mode 100644 index 00000000..faad2b46 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/common.cmake @@ -0,0 +1,31 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +if (APP_TYPE STREQUAL "client") + set(APP_TYPE_SECOND "server") +elseif(APP_TYPE STREQUAL "server") +set(APP_TYPE_SECOND "client") +else() + message(FATAL "Unmown APP_TYPE. Set it to the 'client' or 'server'.") +endif() + + +set(TEST_ERPC_FILES + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_firstInterface_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_firstInterface_${APP_TYPE}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME}_firstInterface_${APP_TYPE}.cpp + + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_secondInterface_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_secondInterface_${APP_TYPE_SECOND}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME}_secondInterface_${APP_TYPE_SECOND}.cpp +) + +set(TEST_SOURCES + ${TEST_ERPC_FILES} + + ${TEST_SOURCE_DIR}/${TEST_NAME}_${APP_TYPE}_impl.cpp + ${TEST_COMMON_DIR}/unit_test_${TRANSPORT}_arbitrator_${APP_TYPE}.cpp +) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso54114_m4.conf b/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso54114_m4.conf new file mode 100644 index 00000000..60eead5a --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso54114_m4.conf @@ -0,0 +1,2 @@ +CONFIG_SECOND_CORE_MCUX=y +CONFIG_INCLUDE_REMOTE_DIR=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso54114_m4.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso54114_m4.overlay new file mode 100644 index 00000000..95f16760 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso54114_m4.overlay @@ -0,0 +1,20 @@ +/* + * Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* + * shared memory reserved for the inter-processor communication + */ + zephyr,ipc_shm = &sramx1; + zephyr,ipc = &mailbox0; + }; + + sramx1:memory@4000000{ + compatible = "mmio-sram"; + reg = <0x4000000 0x8000>; + }; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso55s69_cpu0.conf b/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso55s69_cpu0.conf new file mode 100644 index 00000000..7e6904d5 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso55s69_cpu0.conf @@ -0,0 +1 @@ +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso55s69_cpu0.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso55s69_cpu0.overlay new file mode 100644 index 00000000..6a2568e2 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/lpcxpresso55s69_cpu0.overlay @@ -0,0 +1,22 @@ +/* +* Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* + * shared memory reserved for the inter-processor communication + */ + + zephyr,ipc_shm = &sram4duplicate; + zephyr,ipc = &mailbox0; + }; + + /* This is a duplication of sram4, workaround */ + sram4duplicate: memory@20040000 { + compatible = "mmio-sram"; + reg = <0x20040000 DT_SIZE_K(16)>; + }; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1160_evk_cm7.conf b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1160_evk_cm7.conf new file mode 100644 index 00000000..630a1933 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1160_evk_cm7.conf @@ -0,0 +1,2 @@ +CONFIG_INCLUDE_REMOTE_DIR=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1160_evk_cm7.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1160_evk_cm7.overlay new file mode 100644 index 00000000..d160db3e --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1160_evk_cm7.overlay @@ -0,0 +1,24 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + chosen { + zephyr,ipc_shm = &ocram2_overlay; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set. + */ + ocram2_overlay: memory@202c0000{ + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(23)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evk_cm7.conf b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evk_cm7.conf new file mode 100644 index 00000000..630a1933 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evk_cm7.conf @@ -0,0 +1,2 @@ +CONFIG_INCLUDE_REMOTE_DIR=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evk_cm7.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evk_cm7.overlay new file mode 100644 index 00000000..d160db3e --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evk_cm7.overlay @@ -0,0 +1,24 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + chosen { + zephyr,ipc_shm = &ocram2_overlay; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set. + */ + ocram2_overlay: memory@202c0000{ + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(23)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evkb_cm7.conf b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evkb_cm7.conf new file mode 100644 index 00000000..ffd841cb --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evkb_cm7.conf @@ -0,0 +1,7 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# +CONFIG_INCLUDE_REMOTE_DIR=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evkb_cm7.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evkb_cm7.overlay new file mode 100644 index 00000000..3bf2b0dc --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/boards/mimxrt1170_evkb_cm7.overlay @@ -0,0 +1,24 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + chosen { + zephyr,ipc_shm = &ocram2_overlay; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set. + */ + ocram2_overlay: memory@202c0000{ + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/erpc_config.h b/test/zephyr/rpmsglite/test_arbitrator/config/erpc_config.h new file mode 100644 index 00000000..89abda4e --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/erpc_config.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2021 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_CONFIG_H_ +#define _ERPC_CONFIG_H_ + +/*! + * @addtogroup config + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +//! @name Threading model options +//@{ +#define ERPC_ALLOCATION_POLICY_DYNAMIC (0U) //!< Dynamic allocation policy +#define ERPC_ALLOCATION_POLICY_STATIC (1U) //!< Static allocation policy + +#define ERPC_THREADS_NONE (0U) //!< No threads. +#define ERPC_THREADS_PTHREADS (1U) //!< POSIX pthreads. +#define ERPC_THREADS_FREERTOS (2U) //!< FreeRTOS. +#define ERPC_THREADS_ZEPHYR (3U) //!< ZEPHYR. +#define ERPC_THREADS_MBED (4U) //!< Mbed OS +#define ERPC_THREADS_WIN32 (5U) //!< WIN32 +#define ERPC_THREADS_THREADX (6U) //!< THREADX + +#define ERPC_NOEXCEPT_DISABLED (0U) //!< Disabling noexcept feature. +#define ERPC_NOEXCEPT_ENABLED (1U) //!< Enabling noexcept feature. + +#define ERPC_NESTED_CALLS_DISABLED (0U) //!< No nested calls support. +#define ERPC_NESTED_CALLS_ENABLED (1U) //!< Nested calls support. + +#define ERPC_NESTED_CALLS_DETECTION_DISABLED (0U) //!< Nested calls detection disabled. +#define ERPC_NESTED_CALLS_DETECTION_ENABLED (1U) //!< Nested calls detection enabled. + +#define ERPC_MESSAGE_LOGGING_DISABLED (0U) //!< Trace functions disabled. +#define ERPC_MESSAGE_LOGGING_ENABLED (1U) //!< Trace functions enabled. + +#define ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED (0U) //!< Do not use MCMGR for MU ISR management. +#define ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED (1U) //!< Use MCMGR for MU ISR management. + +#define ERPC_PRE_POST_ACTION_DISABLED (0U) //!< Pre post shim callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_ENABLED (1U) //!< Pre post shim callback functions enabled. + +#define ERPC_PRE_POST_ACTION_DEFAULT_DISABLED (0U) //!< Pre post shim default callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_DEFAULT_ENABLED (1U) //!< Pre post shim default callback functions enabled. +//@} + +//! @name Configuration options +//@{ + +//! @def ERPC_ALLOCATION_POLICY +//! +//! @brief Choose which allocation policy should be used. +//! +//! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. +//! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. +//! +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is supported +//! by compiler. Uncomment comment bellow to use static allocation policy. +//! In case of static implementation user need consider another values to set (ERPC_CODEC_COUNT, +//! ERPC_MESSAGE_LOGGERS_COUNT, ERPC_CLIENTS_THREADS_AMOUNT). +// #define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_STATIC) + +//! @def ERPC_CODEC_COUNT +//! +//! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one thread per +//! each then 2, ... Default value 2. +// #define ERPC_CODEC_COUNT (2U) + +//! @def ERPC_MESSAGE_LOGGERS_COUNT +//! +//! @brief Set amount of message loggers objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. +//! For example if client or server is used in one thread then 1. If both are used in one thread per each then 2, ... +//! For arbitrated client 1 is enough. +//! Default value 0 (May not be used). +// #define ERPC_MESSAGE_LOGGERS_COUNT (0U) + +//! @def ERPC_CLIENTS_THREADS_AMOUNT +//! +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to ERPC_ALLOCATION_POLICY_STATIC. +//! Default value 1 (Most of current cases). +// #define ERPC_CLIENTS_THREADS_AMOUNT (1U) + +//! @def ERPC_THREADS +//! +//! @brief Select threading model. +//! +//! Set to one of the @c ERPC_THREADS_x macros to specify the threading model used by eRPC. +//! +//! Leave commented out to attempt to auto-detect. Auto-detection works well for pthreads. +//! FreeRTOS can be detected when building with compilers that support __has_include(). +//! Otherwise, the default is no threading. +#define ERPC_THREADS (ERPC_THREADS_ZEPHYR) + +//! @def ERPC_DEFAULT_BUFFER_SIZE +//! +//! Uncomment to change the size of buffers allocated by one of MessageBufferFactory. +//! (@ref client_setup and @ref server_setup). The default size is set to 256. +//! For RPMsg transport layer, ERPC_DEFAULT_BUFFER_SIZE must be 2^n - 16. +#define ERPC_DEFAULT_BUFFER_SIZE (496U) + +//! @def ERPC_DEFAULT_BUFFERS_COUNT +//! +//! Uncomment to change the count of buffers allocated by one of statically allocated messages. +//! Default value is set to 2. +#define ERPC_DEFAULT_BUFFERS_COUNT (16U) + +//! @def ERPC_NOEXCEPT +//! +//! @brief Disable/enable noexcept support. +//! +//! Uncomment for using noexcept feature. +//#define ERPC_NOEXCEPT (ERPC_NOEXCEPT_ENABLED) + +//! @def ERPC_NESTED_CALLS +//! +//! Default set to ERPC_NESTED_CALLS_DISABLED. Uncomment when callbacks, or other eRPC +//! functions are called from server implementation of another eRPC call. Nested functions +//! need to be marked as @nested in IDL. +#define ERPC_NESTED_CALLS (ERPC_NESTED_CALLS_ENABLED) + +//! @def ERPC_NESTED_CALLS_DETECTION +//! +//! Default set to ERPC_NESTED_CALLS_DETECTION_ENABLED when NDEBUG macro is presented. +//! This serve for locating nested calls in code. Nested calls are calls where inside eRPC function +//! on server side is called another eRPC function (like callbacks). Code need be a bit changed +//! to support nested calls. See ERPC_NESTED_CALLS macro. +#define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_DISABLED) + +//! @def ERPC_MESSAGE_LOGGING +//! +//! Enable eRPC message logging code through the eRPC. Take look into "erpc_message_loggers.h". Can be used for base +//! printing messages, or sending data to another system for data analysis. Default set to +//! ERPC_MESSAGE_LOGGING_DISABLED. +//! +//! Uncomment for using logging feature. +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) + +//! @def ERPC_TRANSPORT_MU_USE_MCMGR +//! +//! @brief MU transport layer configuration. +//! +//! Set to one of the @c ERPC_TRANSPORT_MU_USE_MCMGR_x macros to configure the MCMGR usage in MU transport layer. +//! +//! MU transport layer could leverage the Multicore Manager (MCMGR) component for Inter-Core +//! interrupts / MU interrupts management or the Inter-Core interrupts can be managed by itself (MUX_IRQHandler +//! overloading). By default, ERPC_TRANSPORT_MU_USE_MCMGR is set to ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED when mcmgr.h +//! is part of the project, otherwise the ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED option is used. This settings can be +//! overwritten from the erpc_config.h by uncommenting the ERPC_TRANSPORT_MU_USE_MCMGR macro definition. Do not forget +//! to add the MCMGR library into your project when ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED option is used! See the +//! erpc_mu_transport.h for additional MU settings. +//#define ERPC_TRANSPORT_MU_USE_MCMGR ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED +//@} + +//! @def ERPC_PRE_POST_ACTION +//! +//! Enable eRPC pre and post callback functions shim code. Take look into "erpc_pre_post_action.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DISABLED. +//! +//! Uncomment for using pre post callback feature. +//#define ERPC_PRE_POST_ACTION (ERPC_PRE_POST_ACTION_ENABLED) + +//! @def ERPC_PRE_POST_ACTION_DEFAULT +//! +//! Enable eRPC pre and post default callback functions. Take look into "erpc_setup_extensions.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DEFAULT_DISABLED. +//! +//! Uncomment for using pre post default callback feature. +//#define ERPC_PRE_POST_ACTION_DEFAULT (ERPC_PRE_POST_ACTION_DEFAULT_ENABLED) + +/*! @} */ +#endif // _ERPC_CONFIG_H_ +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/prj.conf b/test/zephyr/rpmsglite/test_arbitrator/config/prj.conf new file mode 100644 index 00000000..8ddb841a --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/prj.conf @@ -0,0 +1,37 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP17=y +CONFIG_GLIBCXX_LIBCPP=y + +CONFIG_NEWLIB_LIBC=y +CONFIG_NEWLIB_LIBC_NANO=y + +# Compiler +CONFIG_MAIN_STACK_SIZE=4096 +CONFIG_HEAP_MEM_POOL_SIZE=32000 +CONFIG_NO_OPTIMIZATIONS=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_RPMSG_LITE=y + +# RPMSG Lite +CONFIG_IPM=y +CONFIG_EVENTS=y +CONFIG_PRINTK=y +CONFIG_RPMSGLITE=y +CONFIG_RPMSGLITE_QUEUE=y +CONFIG_RPMSGLITE_NS=y +CONFIG_TIMESLICE_SIZE=1 + +CONFIG_THREAD_CUSTOM_DATA=y +CONFIG_ERPC_ARBITRATED_CLIENT=y +CONFIG_POLL=y + +CONFIG_THREAD_NAME=y +CONFIG_SCHED_CPU_MASK=y +CONFIG_THREAD_ANALYZER=y + +CONFIG_LOG=y +CONFIG_LOG_MODE_IMMEDIATE=y +CONFIG_LOG_OVERRIDE_LEVEL=3 \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso54114_m0.conf b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso54114_m0.conf new file mode 100644 index 00000000..b9e2b072 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso54114_m0.conf @@ -0,0 +1,2 @@ +CONFIG_SECOND_CORE_MCUX=y +CONFIG_BUILD_OUTPUT_HEX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso54114_m0.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso54114_m0.overlay new file mode 100644 index 00000000..a5515378 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso54114_m0.overlay @@ -0,0 +1,20 @@ +/* +* Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* + * shared memory reserved for the inter-processor communication + */ + zephyr,ipc_shm = &sramx1; + zephyr,ipc = &mailbox0; + }; + + sramx1:memory@4000000{ + compatible = "mmio-sram"; + reg = <0x4000000 0x8000>; + }; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso55s69_cpu1.conf b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso55s69_cpu1.conf new file mode 100644 index 00000000..b9e2b072 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso55s69_cpu1.conf @@ -0,0 +1,2 @@ +CONFIG_SECOND_CORE_MCUX=y +CONFIG_BUILD_OUTPUT_HEX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso55s69_cpu1.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso55s69_cpu1.overlay new file mode 100644 index 00000000..6a2568e2 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/lpcxpresso55s69_cpu1.overlay @@ -0,0 +1,22 @@ +/* +* Copyright 2023 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/ { + chosen { + /* + * shared memory reserved for the inter-processor communication + */ + + zephyr,ipc_shm = &sram4duplicate; + zephyr,ipc = &mailbox0; + }; + + /* This is a duplication of sram4, workaround */ + sram4duplicate: memory@20040000 { + compatible = "mmio-sram"; + reg = <0x20040000 DT_SIZE_K(16)>; + }; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1160_evk_cm4.conf b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1160_evk_cm4.conf new file mode 100644 index 00000000..4dfc4a60 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1160_evk_cm4.conf @@ -0,0 +1,3 @@ +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1160_evk_cm4.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1160_evk_cm4.overlay new file mode 100644 index 00000000..9cb7c67a --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1160_evk_cm4.overlay @@ -0,0 +1,51 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + /* Switch to lpuart2, since primary core uses lpuart1 */ + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart2; + zephyr,shell-uart = &lpuart2; + zephyr,ipc_shm = &ocram2_overlay; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set + */ + ocram2_overlay: memory@202c0000 { + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(23)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; + +/* Enable secondary LPUART */ +&lpuart2 { + status = "okay"; + current-speed = <115200>; +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evk_cm4.conf b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evk_cm4.conf new file mode 100644 index 00000000..4dfc4a60 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evk_cm4.conf @@ -0,0 +1,3 @@ +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evk_cm4.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evk_cm4.overlay new file mode 100644 index 00000000..ab57a613 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evk_cm4.overlay @@ -0,0 +1,51 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + /* Switch to lpuart2, since primary core uses lpuart1 */ + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart2; + zephyr,shell-uart = &lpuart2; + zephyr,ipc_shm = &ocram2_overlay; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set + */ + ocram2_overlay: memory@202c0000 { + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; + +/* Enable secondary LPUART */ +&lpuart2 { + status = "okay"; + current-speed = <115200>; +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evkb_cm4.conf b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evkb_cm4.conf new file mode 100644 index 00000000..ef7b0f83 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evkb_cm4.conf @@ -0,0 +1,8 @@ +# +# Copyright 2023-2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# +CONFIG_BUILD_OUTPUT_INFO_HEADER=y +CONFIG_BUILD_OUTPUT_HEX=y +CONFIG_SECOND_CORE_MCUX=y diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evkb_cm4.overlay b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evkb_cm4.overlay new file mode 100644 index 00000000..65fb71ff --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/boards/mimxrt1170_evkb_cm4.overlay @@ -0,0 +1,51 @@ +/* + * Copyright 2023-2024 NXP + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include + +/ { + /* Switch to lpuart2, since primary core uses lpuart1 */ + chosen { + zephyr,flash = &ocram; + zephyr,console = &lpuart1; + zephyr,shell-uart = &lpuart1; + zephyr,ipc_shm = &ocram2_overlay; + }; + + soc { + /delete-node/ gpt@400f0000; + + /* Replace GPT2 with another GPT kernel timer */ + gpt2_hw_timer:gpt@400f0000 { + compatible = "nxp,gpt-hw-timer"; + reg = <0x400f0000 0x4000>; + interrupts = <120 0>; + status = "okay"; + }; + }; + + /* OpenAMP fails with full 512K OCRAM2 memory region as shared memory. + * Define a subset of the OCRAM2 region for demo to use + * Note that shared memory must have specific MPU attributes set + */ + ocram2_overlay: memory@202c0000 { + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x202c0000 DT_SIZE_K(16)>; + zephyr,memory-region="OCRAM2_OVERLAY"; + zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_IO) )>; + }; +}; + +/* Enable secondary LPUART */ +&lpuart2 { + status = "okay"; + current-speed = <115200>; +}; + +/* Disable primary GPT timer */ +&gpt_hw_timer { + status = "disabled"; +}; diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/remote/prj.conf b/test/zephyr/rpmsglite/test_arbitrator/config/remote/prj.conf new file mode 100644 index 00000000..5581523e --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/remote/prj.conf @@ -0,0 +1,33 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP17=y +CONFIG_GLIBCXX_LIBCPP=y + +CONFIG_NEWLIB_LIBC=y +CONFIG_NEWLIB_LIBC_NANO=y + +# Compiler +CONFIG_MAIN_STACK_SIZE=4096 +CONFIG_HEAP_MEM_POOL_SIZE=8192 +CONFIG_NO_OPTIMIZATIONS=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_RPMSG_LITE=y + +# RPMSG Lite +CONFIG_IPM=y +CONFIG_EVENTS=y +CONFIG_PRINTK=y +CONFIG_RPMSGLITE=y +CONFIG_RPMSGLITE_QUEUE=y +CONFIG_RPMSGLITE_NS=y +CONFIG_TIMESLICE_SIZE=1 + +CONFIG_THREAD_CUSTOM_DATA=y +CONFIG_ERPC_ARBITRATED_CLIENT=y +CONFIG_POLL=y + +CONFIG_THREAD_NAME=y +CONFIG_SCHED_CPU_MASK=y +CONFIG_THREAD_ANALYZER=y \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_arbitrator/config/rpmsg_config.h b/test/zephyr/rpmsglite/test_arbitrator/config/rpmsg_config.h new file mode 100644 index 00000000..f5f0f565 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/config/rpmsg_config.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014, Mentor Graphics Corporation + * All rights reserved. + * Copyright (c) 2015 Xilinx, Inc. All rights reserved. + * Copyright 2016 Freescale Semiconductor, Inc. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef RPMSG_CONFIG_H_ +#define RPMSG_CONFIG_H_ + +#include "erpc_config_internal.h" + +/* RPMsg config values */ +/* START { */ +#define RL_MS_PER_INTERVAL (1) + +#define RL_BUFFER_PAYLOAD_SIZE (ERPC_DEFAULT_BUFFER_SIZE) + +#define RL_BUFFER_COUNT (ERPC_DEFAULT_BUFFERS_COUNT) + +#define RL_API_HAS_ZEROCOPY (1) + +#define RL_USE_STATIC_API (0) + +#define RL_USE_MCMGR_IPC_ISR_HANDLER (1) + +// #define SH_MEM_TOTAL_SIZE (22527) + +#define RL_ASSERT(x) \ + do \ + { \ + if (!(x)) \ + while (1) \ + ; \ + } while (0); +/* } END */ + +#endif /* RPMSG_CONFIG_H_ */ diff --git a/test/zephyr/rpmsglite/test_arbitrator/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_arbitrator/remote/CMakeLists.txt new file mode 100644 index 00000000..ea4ac692 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/remote/CMakeLists.txt @@ -0,0 +1,21 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +set(APPLICATION_CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../config/remote) +set(CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../config) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +include(${APP_DIR}/common.cmake) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_arbitrator/sysbuild.cmake b/test/zephyr/rpmsglite/test_arbitrator/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_arbitrator/testcase.yaml b/test/zephyr/rpmsglite/test_arbitrator/testcase.yaml new file mode 100644 index 00000000..333a18f0 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arbitrator/testcase.yaml @@ -0,0 +1,7 @@ +tests: + erpc.rpmsglite.arbitrator: + sysbuild: true + harness: gtest + timeout: 60 + extra_configs: + - CONFIG_THREAD_CUSTOM_DATA=y \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_arrays/CMakeLists.txt b/test/zephyr/rpmsglite/test_arrays/CMakeLists.txt new file mode 100644 index 00000000..e34d1b16 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arrays/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(TEST_ERPC_OUT_DIR ${ERPC_OUT_ROOT_DIR}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_arrays/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_arrays/remote/CMakeLists.txt new file mode 100644 index 00000000..5d6ced00 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arrays/remote/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(TEST_ERPC_OUT_DIR ${ERPC_OUT_ROOT_DIR}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_arrays/sysbuild.cmake b/test/zephyr/rpmsglite/test_arrays/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_arrays/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_arrays/testcase.yaml b/test/zephyr/rpmsglite/test_arrays/testcase.yaml new file mode 100644 index 00000000..ab0e77dd --- /dev/null +++ b/test/zephyr/rpmsglite/test_arrays/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.arrays: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_binary/CMakeLists.txt b/test/zephyr/rpmsglite/test_binary/CMakeLists.txt new file mode 100644 index 00000000..bbe6011e --- /dev/null +++ b/test/zephyr/rpmsglite/test_binary/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_binary/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_binary/remote/CMakeLists.txt new file mode 100644 index 00000000..cf2b14f6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_binary/remote/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_binary/sysbuild.cmake b/test/zephyr/rpmsglite/test_binary/sysbuild.cmake new file mode 100644 index 00000000..2dd3cfbf --- /dev/null +++ b/test/zephyr/rpmsglite/test_binary/sysbuild.cmake @@ -0,0 +1,6 @@ +# Copyright 2023 NXP +# +# SPDX-License-Identifier: BSD-3-Clause + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_binary/testcase.yaml b/test/zephyr/rpmsglite/test_binary/testcase.yaml new file mode 100644 index 00000000..13be47b3 --- /dev/null +++ b/test/zephyr/rpmsglite/test_binary/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.binary: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_builtin/CMakeLists.txt b/test/zephyr/rpmsglite/test_builtin/CMakeLists.txt new file mode 100644 index 00000000..bbe6011e --- /dev/null +++ b/test/zephyr/rpmsglite/test_builtin/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_builtin/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_builtin/remote/CMakeLists.txt new file mode 100644 index 00000000..cf2b14f6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_builtin/remote/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_builtin/sysbuild.cmake b/test/zephyr/rpmsglite/test_builtin/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_builtin/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_builtin/testcase.yaml b/test/zephyr/rpmsglite/test_builtin/testcase.yaml new file mode 100644 index 00000000..7843ee55 --- /dev/null +++ b/test/zephyr/rpmsglite/test_builtin/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.builtin: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_callbacks/CMakeLists.txt b/test/zephyr/rpmsglite/test_callbacks/CMakeLists.txt new file mode 100644 index 00000000..459e1532 --- /dev/null +++ b/test/zephyr/rpmsglite/test_callbacks/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +include(${APP_DIR}/common.cmake) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_callbacks/common.cmake b/test/zephyr/rpmsglite/test_callbacks/common.cmake new file mode 100644 index 00000000..357e1424 --- /dev/null +++ b/test/zephyr/rpmsglite/test_callbacks/common.cmake @@ -0,0 +1,27 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +set(ERPC_NAME_APP test_core0) + +# Define required IDL files +set(TEST_ERPC_FILES + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME_APP}_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME_APP}_${APP_TYPE}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME_APP}_${APP_TYPE}.cpp + + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_core1_interface.cpp + + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_unit_test_common_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_unit_test_common_${APP_TYPE}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME}_unit_test_common_${APP_TYPE}.cpp +) + +set(TEST_SOURCES + ${TEST_ERPC_FILES} + + ${TEST_SOURCE_DIR}/${TEST_NAME}_${APP_TYPE}_impl.cpp + ${TEST_COMMON_DIR}/unit_test_${TRANSPORT}_${APP_TYPE}.cpp +) diff --git a/test/zephyr/rpmsglite/test_callbacks/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_callbacks/remote/CMakeLists.txt new file mode 100644 index 00000000..3eb433bc --- /dev/null +++ b/test/zephyr/rpmsglite/test_callbacks/remote/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +include(${APP_DIR}/common.cmake) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_callbacks/sysbuild.cmake b/test/zephyr/rpmsglite/test_callbacks/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_callbacks/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_callbacks/testcase.yaml b/test/zephyr/rpmsglite/test_callbacks/testcase.yaml new file mode 100644 index 00000000..0d380c4b --- /dev/null +++ b/test/zephyr/rpmsglite/test_callbacks/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.callbacks: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_const/CMakeLists.txt b/test/zephyr/rpmsglite/test_const/CMakeLists.txt new file mode 100644 index 00000000..bbe6011e --- /dev/null +++ b/test/zephyr/rpmsglite/test_const/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_const/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_const/remote/CMakeLists.txt new file mode 100644 index 00000000..cf2b14f6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_const/remote/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_const/sysbuild.cmake b/test/zephyr/rpmsglite/test_const/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_const/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_const/testcase.yaml b/test/zephyr/rpmsglite/test_const/testcase.yaml new file mode 100644 index 00000000..635452f1 --- /dev/null +++ b/test/zephyr/rpmsglite/test_const/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.const: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_enums/CMakeLists.txt b/test/zephyr/rpmsglite/test_enums/CMakeLists.txt new file mode 100644 index 00000000..bbe6011e --- /dev/null +++ b/test/zephyr/rpmsglite/test_enums/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_enums/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_enums/remote/CMakeLists.txt new file mode 100644 index 00000000..cf2b14f6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_enums/remote/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_enums/sysbuild.cmake b/test/zephyr/rpmsglite/test_enums/sysbuild.cmake new file mode 100644 index 00000000..d368ee08 --- /dev/null +++ b/test/zephyr/rpmsglite/test_enums/sysbuild.cmake @@ -0,0 +1,7 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_enums/testcase.yaml b/test/zephyr/rpmsglite/test_enums/testcase.yaml new file mode 100644 index 00000000..2722cbd6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_enums/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.enums: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_lists/CMakeLists.txt b/test/zephyr/rpmsglite/test_lists/CMakeLists.txt new file mode 100644 index 00000000..bbe6011e --- /dev/null +++ b/test/zephyr/rpmsglite/test_lists/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_lists/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_lists/remote/CMakeLists.txt new file mode 100644 index 00000000..cf2b14f6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_lists/remote/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_lists/sysbuild.cmake b/test/zephyr/rpmsglite/test_lists/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_lists/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_lists/testcase.yaml b/test/zephyr/rpmsglite/test_lists/testcase.yaml new file mode 100644 index 00000000..a00b9900 --- /dev/null +++ b/test/zephyr/rpmsglite/test_lists/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.lists: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_shared/CMakeLists.txt b/test/zephyr/rpmsglite/test_shared/CMakeLists.txt new file mode 100644 index 00000000..7139fa3f --- /dev/null +++ b/test/zephyr/rpmsglite/test_shared/CMakeLists.txt @@ -0,0 +1,20 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_shared/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_shared/remote/CMakeLists.txt new file mode 100644 index 00000000..cf2b14f6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_shared/remote/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_shared/sysbuild.cmake b/test/zephyr/rpmsglite/test_shared/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_shared/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_shared/testcase.yaml b/test/zephyr/rpmsglite/test_shared/testcase.yaml new file mode 100644 index 00000000..08652f12 --- /dev/null +++ b/test/zephyr/rpmsglite/test_shared/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.shared: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_struct/CMakeLists.txt b/test/zephyr/rpmsglite/test_struct/CMakeLists.txt new file mode 100644 index 00000000..913b04c6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_struct/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(ERPC_NAME_APP test_ArithmeticService) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_struct/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_struct/remote/CMakeLists.txt new file mode 100644 index 00000000..fec4abe0 --- /dev/null +++ b/test/zephyr/rpmsglite/test_struct/remote/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(ERPC_NAME_APP test_ArithmeticService) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_struct/sysbuild.cmake b/test/zephyr/rpmsglite/test_struct/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_struct/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_struct/testcase.yaml b/test/zephyr/rpmsglite/test_struct/testcase.yaml new file mode 100644 index 00000000..01420599 --- /dev/null +++ b/test/zephyr/rpmsglite/test_struct/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.struct: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_typedef/CMakeLists.txt b/test/zephyr/rpmsglite/test_typedef/CMakeLists.txt new file mode 100644 index 00000000..bbe6011e --- /dev/null +++ b/test/zephyr/rpmsglite/test_typedef/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_typedef/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_typedef/remote/CMakeLists.txt new file mode 100644 index 00000000..cf2b14f6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_typedef/remote/CMakeLists.txt @@ -0,0 +1,16 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_typedef/sysbuild.cmake b/test/zephyr/rpmsglite/test_typedef/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_typedef/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_typedef/testcase.yaml b/test/zephyr/rpmsglite/test_typedef/testcase.yaml new file mode 100644 index 00000000..4c2a7225 --- /dev/null +++ b/test/zephyr/rpmsglite/test_typedef/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.typedef: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_unions/CMakeLists.txt b/test/zephyr/rpmsglite/test_unions/CMakeLists.txt new file mode 100644 index 00000000..1ae87bd6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_unions/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "client") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(ERPC_NAME test) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_unions/remote/CMakeLists.txt b/test/zephyr/rpmsglite/test_unions/remote/CMakeLists.txt new file mode 100644 index 00000000..9b36f6b6 --- /dev/null +++ b/test/zephyr/rpmsglite/test_unions/remote/CMakeLists.txt @@ -0,0 +1,18 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +# Zephyr +set(APP_TYPE "server") + +include(${CMAKE_CURRENT_SOURCE_DIR}/../../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(ERPC_NAME test) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/rpmsglite/test_unions/sysbuild.cmake b/test/zephyr/rpmsglite/test_unions/sysbuild.cmake new file mode 100644 index 00000000..e140b251 --- /dev/null +++ b/test/zephyr/rpmsglite/test_unions/sysbuild.cmake @@ -0,0 +1,8 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# Include sysbuild cmake, that is same for all tests +include(${APP_DIR}/../cmake/sysbuild.cmake) \ No newline at end of file diff --git a/test/zephyr/rpmsglite/test_unions/testcase.yaml b/test/zephyr/rpmsglite/test_unions/testcase.yaml new file mode 100644 index 00000000..5da3cdb0 --- /dev/null +++ b/test/zephyr/rpmsglite/test_unions/testcase.yaml @@ -0,0 +1,4 @@ +tests: + erpc.rpmsglite.unions: + sysbuild: true + harness: gtest \ No newline at end of file diff --git a/test/zephyr/uart/cmake/unit_test.cmake b/test/zephyr/uart/cmake/unit_test.cmake new file mode 100644 index 00000000..17f62aed --- /dev/null +++ b/test/zephyr/uart/cmake/unit_test.cmake @@ -0,0 +1,29 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +# App type and transport +set(APP_TYPE "server") +set(TRANSPORT "zephyr_uart") + +# Zephyr APPLICATION_CONFIG_DIR and CONFIG_DIR +if(NOT DEFINED APPLICATION_CONFIG_DIR) + set(APPLICATION_CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../config) +endif() + +if(NOT DEFINED CONFIG_DIR) + set(CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../config) +endif() + +# Include zephyr +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) + +# Common variables +get_filename_component(TEST_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(ERPC_ROOT_DIR ${ZEPHYR_ERPC_MODULE_DIR}) +set(ZEPHYR_TEST_CMAKE_DIR ${CMAKE_CURRENT_LIST_DIR}/../../cmake) + +# Include test's variables +include(${ZEPHYR_TEST_CMAKE_DIR}/variables.cmake) \ No newline at end of file diff --git a/test/zephyr/uart/config/erpc_config.h b/test/zephyr/uart/config/erpc_config.h new file mode 100644 index 00000000..9b3417ce --- /dev/null +++ b/test/zephyr/uart/config/erpc_config.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2021 NXP + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_CONFIG_H_ +#define _ERPC_CONFIG_H_ + +/*! + * @addtogroup config + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +//! @name Threading model options +//@{ +#define ERPC_ALLOCATION_POLICY_DYNAMIC (0U) //!< Dynamic allocation policy +#define ERPC_ALLOCATION_POLICY_STATIC (1U) //!< Static allocation policy + +#define ERPC_THREADS_NONE (0U) //!< No threads. +#define ERPC_THREADS_PTHREADS (1U) //!< POSIX pthreads. +#define ERPC_THREADS_FREERTOS (2U) //!< FreeRTOS. +#define ERPC_THREADS_ZEPHYR (3U) //!< ZEPHYR. +#define ERPC_THREADS_MBED (4U) //!< Mbed OS +#define ERPC_THREADS_WIN32 (5U) //!< WIN32 +#define ERPC_THREADS_THREADX (6U) //!< THREADX + +#define ERPC_NOEXCEPT_DISABLED (0U) //!< Disabling noexcept feature. +#define ERPC_NOEXCEPT_ENABLED (1U) //!< Enabling noexcept feature. + +#define ERPC_NESTED_CALLS_DISABLED (0U) //!< No nested calls support. +#define ERPC_NESTED_CALLS_ENABLED (1U) //!< Nested calls support. + +#define ERPC_NESTED_CALLS_DETECTION_DISABLED (0U) //!< Nested calls detection disabled. +#define ERPC_NESTED_CALLS_DETECTION_ENABLED (1U) //!< Nested calls detection enabled. + +#define ERPC_MESSAGE_LOGGING_DISABLED (0U) //!< Trace functions disabled. +#define ERPC_MESSAGE_LOGGING_ENABLED (1U) //!< Trace functions enabled. + +#define ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED (0U) //!< Do not use MCMGR for MU ISR management. +#define ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED (1U) //!< Use MCMGR for MU ISR management. + +#define ERPC_PRE_POST_ACTION_DISABLED (0U) //!< Pre post shim callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_ENABLED (1U) //!< Pre post shim callback functions enabled. + +#define ERPC_PRE_POST_ACTION_DEFAULT_DISABLED (0U) //!< Pre post shim default callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_DEFAULT_ENABLED (1U) //!< Pre post shim default callback functions enabled. +//@} + +//! @name Configuration options +//@{ + +//! @def ERPC_ALLOCATION_POLICY +//! +//! @brief Choose which allocation policy should be used. +//! +//! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. +//! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. +//! +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is supported +//! by compiler. Uncomment comment bellow to use static allocation policy. +//! In case of static implementation user need consider another values to set (ERPC_CODEC_COUNT, +//! ERPC_MESSAGE_LOGGERS_COUNT, ERPC_CLIENTS_THREADS_AMOUNT). +#define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_DYNAMIC) + +//! @def ERPC_CODEC_COUNT +//! +//! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one thread per +//! each then 2, ... Default value 2. +#define ERPC_CODEC_COUNT (2U) + +//! @def ERPC_MESSAGE_LOGGERS_COUNT +//! +//! @brief Set amount of message loggers objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. +//! For example if client or server is used in one thread then 1. If both are used in one thread per each then 2, ... +//! For arbitrated client 1 is enough. +//! Default value 0 (May not be used). +#define ERPC_MESSAGE_LOGGERS_COUNT (0U) + +//! @def ERPC_CLIENTS_THREADS_AMOUNT +//! +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to ERPC_ALLOCATION_POLICY_STATIC. +//! Default value 1 (Most of current cases). +#define ERPC_CLIENTS_THREADS_AMOUNT (1U) + +//! @def ERPC_THREADS +//! +//! @brief Select threading model. +//! +//! Set to one of the @c ERPC_THREADS_x macros to specify the threading model used by eRPC. +//! +//! Leave commented out to attempt to auto-detect. Auto-detection works well for pthreads. +//! FreeRTOS can be detected when building with compilers that support __has_include(). +//! Otherwise, the default is no threading. +#define ERPC_THREADS (ERPC_THREADS_ZEPHYR) + +//! @def ERPC_DEFAULT_BUFFER_SIZE +//! +//! Uncomment to change the size of buffers allocated by one of MessageBufferFactory. +//! (@ref client_setup and @ref server_setup). The default size is set to 256. +//! For RPMsg transport layer, ERPC_DEFAULT_BUFFER_SIZE must be 2^n - 16. +#define ERPC_DEFAULT_BUFFER_SIZE (512U) + +//! @def ERPC_DEFAULT_BUFFERS_COUNT +//! +//! Uncomment to change the count of buffers allocated by one of statically allocated messages. +//! Default value is set to 2. +//#define ERPC_DEFAULT_BUFFERS_COUNT (2U) + +//! @def ERPC_NOEXCEPT +//! +//! @brief Disable/enable noexcept support. +//! +//! Uncomment for using noexcept feature. +//#define ERPC_NOEXCEPT (ERPC_NOEXCEPT_ENABLED) + +//! @def ERPC_NESTED_CALLS +//! +//! Default set to ERPC_NESTED_CALLS_DISABLED. Uncomment when callbacks, or other eRPC +//! functions are called from server implementation of another eRPC call. Nested functions +//! need to be marked as @nested in IDL. +//#define ERPC_NESTED_CALLS (ERPC_NESTED_CALLS_ENABLED) + +//! @def ERPC_NESTED_CALLS_DETECTION +//! +//! Default set to ERPC_NESTED_CALLS_DETECTION_ENABLED when NDEBUG macro is presented. +//! This serve for locating nested calls in code. Nested calls are calls where inside eRPC function +//! on server side is called another eRPC function (like callbacks). Code need be a bit changed +//! to support nested calls. See ERPC_NESTED_CALLS macro. +//#define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_DISABLED) + +//! @def ERPC_MESSAGE_LOGGING +//! +//! Enable eRPC message logging code through the eRPC. Take look into "erpc_message_loggers.h". Can be used for base +//! printing messages, or sending data to another system for data analysis. Default set to +//! ERPC_MESSAGE_LOGGING_DISABLED. +//! +//! Uncomment for using logging feature. +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) + +//! @def ERPC_TRANSPORT_MU_USE_MCMGR +//! +//! @brief MU transport layer configuration. +//! +//! Set to one of the @c ERPC_TRANSPORT_MU_USE_MCMGR_x macros to configure the MCMGR usage in MU transport layer. +//! +//! MU transport layer could leverage the Multicore Manager (MCMGR) component for Inter-Core +//! interrupts / MU interrupts management or the Inter-Core interrupts can be managed by itself (MUX_IRQHandler +//! overloading). By default, ERPC_TRANSPORT_MU_USE_MCMGR is set to ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED when mcmgr.h +//! is part of the project, otherwise the ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED option is used. This settings can be +//! overwritten from the erpc_config.h by uncommenting the ERPC_TRANSPORT_MU_USE_MCMGR macro definition. Do not forget +//! to add the MCMGR library into your project when ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED option is used! See the +//! erpc_mu_transport.h for additional MU settings. +//#define ERPC_TRANSPORT_MU_USE_MCMGR ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED +//@} + +//! @def ERPC_PRE_POST_ACTION +//! +//! Enable eRPC pre and post callback functions shim code. Take look into "erpc_pre_post_action.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DISABLED. +//! +//! Uncomment for using pre post callback feature. +//#define ERPC_PRE_POST_ACTION (ERPC_PRE_POST_ACTION_ENABLED) + +//! @def ERPC_PRE_POST_ACTION_DEFAULT +//! +//! Enable eRPC pre and post default callback functions. Take look into "erpc_setup_extensions.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DEFAULT_DISABLED. +//! +//! Uncomment for using pre post default callback feature. +//#define ERPC_PRE_POST_ACTION_DEFAULT (ERPC_PRE_POST_ACTION_DEFAULT_ENABLED) + +/*! @} */ +#endif // _ERPC_CONFIG_H_ +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/test/zephyr/uart/config/prj.conf b/test/zephyr/uart/config/prj.conf new file mode 100644 index 00000000..1b222af7 --- /dev/null +++ b/test/zephyr/uart/config/prj.conf @@ -0,0 +1,28 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP17=y +CONFIG_GLIBCXX_LIBCPP=y + +CONFIG_NEWLIB_LIBC=y +CONFIG_NEWLIB_LIBC_NANO=y + +# Compiler +CONFIG_MAIN_STACK_SIZE=4096 +CONFIG_HEAP_MEM_POOL_SIZE=8192 +CONFIG_NO_OPTIMIZATIONS=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_UART=y + +# UART +CONFIG_CONSOLE=n +CONFIG_UART_CONSOLE=n + +CONFIG_THREAD_NAME=y +CONFIG_SCHED_CPU_MASK=y +CONFIG_THREAD_ANALYZER=y + +CONFIG_LOG=y +CONFIG_LOG_MODE_IMMEDIATE=y +CONFIG_LOG_OVERRIDE_LEVEL=3 \ No newline at end of file diff --git a/test/zephyr/uart/test_annotations/CMakeLists.txt b/test/zephyr/uart/test_annotations/CMakeLists.txt new file mode 100644 index 00000000..6d25c45d --- /dev/null +++ b/test/zephyr/uart/test_annotations/CMakeLists.txt @@ -0,0 +1,15 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(TEST_EXT_SOURCES ${TEST_COMMON_DIR}/addOne.cpp) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_annotations/testcase.yaml b/test/zephyr/uart/test_annotations/testcase.yaml new file mode 100644 index 00000000..7605e0a7 --- /dev/null +++ b/test/zephyr/uart/test_annotations/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.annotations: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_annotations/test_annotations.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_arbitrator/CMakeLists.txt b/test/zephyr/uart/test_arbitrator/CMakeLists.txt new file mode 100644 index 00000000..4b148562 --- /dev/null +++ b/test/zephyr/uart/test_arbitrator/CMakeLists.txt @@ -0,0 +1,35 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +set(APPLICATION_CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/config) +set(CONFIG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/config) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(APP_TYPE_SECOND "client") + +set(TEST_ERPC_FILES + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_firstInterface_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_firstInterface_${APP_TYPE}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME}_firstInterface_${APP_TYPE}.cpp + + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_secondInterface_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_secondInterface_${APP_TYPE_SECOND}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME}_secondInterface_${APP_TYPE_SECOND}.cpp +) + +set(TEST_SOURCES + ${TEST_ERPC_FILES} + + ${TEST_SOURCE_DIR}/${TEST_NAME}_${APP_TYPE}_impl.cpp + ${TEST_COMMON_DIR}/unit_test_${TRANSPORT}_arbitrator_${APP_TYPE}.cpp +) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_arbitrator/config/erpc_config.h b/test/zephyr/uart/test_arbitrator/config/erpc_config.h new file mode 100644 index 00000000..ef8a0073 --- /dev/null +++ b/test/zephyr/uart/test_arbitrator/config/erpc_config.h @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2016, Freescale Semiconductor, Inc. + * Copyright 2016-2020 NXP + * Copyright 2020-2021 ACRIOS Systems s.r.o. + * All rights reserved. + * + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _ERPC_CONFIG_H_ +#define _ERPC_CONFIG_H_ + +/*! + * @addtogroup config + * @{ + * @file + */ + +//////////////////////////////////////////////////////////////////////////////// +// Declarations +//////////////////////////////////////////////////////////////////////////////// + +//! @name Threading model options +//@{ +#define ERPC_ALLOCATION_POLICY_DYNAMIC (0U) //!< Dynamic allocation policy +#define ERPC_ALLOCATION_POLICY_STATIC (1U) //!< Static allocation policy + +#define ERPC_THREADS_NONE (0U) //!< No threads. +#define ERPC_THREADS_PTHREADS (1U) //!< POSIX pthreads. +#define ERPC_THREADS_FREERTOS (2U) //!< FreeRTOS. +#define ERPC_THREADS_ZEPHYR (3U) //!< ZEPHYR. +#define ERPC_THREADS_MBED (4U) //!< Mbed OS +#define ERPC_THREADS_WIN32 (5U) //!< WIN32 +#define ERPC_THREADS_THREADX (6U) //!< THREADX + +#define ERPC_NOEXCEPT_DISABLED (0U) //!< Disabling noexcept feature. +#define ERPC_NOEXCEPT_ENABLED (1U) //!< Enabling noexcept feature. + +#define ERPC_NESTED_CALLS_DISABLED (0U) //!< No nested calls support. +#define ERPC_NESTED_CALLS_ENABLED (1U) //!< Nested calls support. + +#define ERPC_NESTED_CALLS_DETECTION_DISABLED (0U) //!< Nested calls detection disabled. +#define ERPC_NESTED_CALLS_DETECTION_ENABLED (1U) //!< Nested calls detection enabled. + +#define ERPC_MESSAGE_LOGGING_DISABLED (0U) //!< Trace functions disabled. +#define ERPC_MESSAGE_LOGGING_ENABLED (1U) //!< Trace functions enabled. + +#define ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED (0U) //!< Do not use MCMGR for MU ISR management. +#define ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED (1U) //!< Use MCMGR for MU ISR management. + +#define ERPC_PRE_POST_ACTION_DISABLED (0U) //!< Pre post shim callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_ENABLED (1U) //!< Pre post shim callback functions enabled. + +#define ERPC_PRE_POST_ACTION_DEFAULT_DISABLED (0U) //!< Pre post shim default callbacks functions disabled. +#define ERPC_PRE_POST_ACTION_DEFAULT_ENABLED (1U) //!< Pre post shim default callback functions enabled. +//@} + +//! @name Configuration options +//@{ + +//! @def ERPC_ALLOCATION_POLICY +//! +//! @brief Choose which allocation policy should be used. +//! +//! Set ERPC_ALLOCATION_POLICY_DYNAMIC if dynamic allocations should be used. +//! Set ERPC_ALLOCATION_POLICY_STATIC if static allocations should be used. +//! +//! Default value is ERPC_ALLOCATION_POLICY_DYNAMIC or in case of FreeRTOS it can be auto-detected if __has_include() is +//! supported by compiler. Uncomment comment bellow to use static allocation policy. In case of static implementation +//! user need consider another values to set (ERPC_CODEC_COUNT, ERPC_MESSAGE_LOGGERS_COUNT, +//! ERPC_CLIENTS_THREADS_AMOUNT). +#define ERPC_ALLOCATION_POLICY (ERPC_ALLOCATION_POLICY_DYNAMIC) + +//! @def ERPC_CODEC_COUNT +//! +//! @brief Set amount of codecs objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. For example if client or server is used in one thread then 1. If both are used in one +//! thread per each then 2, ... Default value 2. +#define ERPC_CODEC_COUNT (2U) + +//! @def ERPC_MESSAGE_LOGGERS_COUNT +//! +//! @brief Set amount of message loggers objects used simultaneously in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. +//! For example if client or server is used in one thread then 1. If both are used in one thread per each then 2, ... +//! For arbitrated client 1 is enough. +//! Default value 0 (May not be used). +#define ERPC_MESSAGE_LOGGERS_COUNT (0U) + +//! @def ERPC_CLIENTS_THREADS_AMOUNT +//! +//! @brief Set amount of client threads objects used in case of ERPC_ALLOCATION_POLICY is set to +//! ERPC_ALLOCATION_POLICY_STATIC. Default value 1 (Most of current cases). +#define ERPC_CLIENTS_THREADS_AMOUNT (1U) + +//! @def ERPC_THREADS +//! +//! @brief Select threading model. +//! +//! Set to one of the @c ERPC_THREADS_x macros to specify the threading model used by eRPC. +//! +//! Leave commented out to attempt to auto-detect. Auto-detection works well for pthreads. +//! FreeRTOS can be detected when building with compilers that support __has_include(). +//! Otherwise, the default is no threading. +#define ERPC_THREADS (ERPC_THREADS_ZEPHYR) + +//! @def ERPC_DEFAULT_BUFFER_SIZE +//! +//! Uncomment to change the size of buffers allocated by one of MessageBufferFactory. +//! (@ref client_setup and @ref server_setup). The default size is set to 256. +//! For RPMsg transport layer, ERPC_DEFAULT_BUFFER_SIZE must be 2^n - 16. +#define ERPC_DEFAULT_BUFFER_SIZE (512U) + +//! @def ERPC_DEFAULT_BUFFERS_COUNT +//! +//! Uncomment to change the count of buffers allocated by one of statically allocated messages. +//! Default value is set to 2. +//#define ERPC_DEFAULT_BUFFERS_COUNT (2U) + +//! @def ERPC_NOEXCEPT +//! +//! @brief Disable/enable noexcept support. +//! +//! Uncomment for using noexcept feature. +//#define ERPC_NOEXCEPT (ERPC_NOEXCEPT_ENABLED) + +//! @def ERPC_NESTED_CALLS +//! +//! Default set to ERPC_NESTED_CALLS_DISABLED. Uncomment when callbacks, or other eRPC +//! functions are called from server implementation of another eRPC call. Nested functions +//! need to be marked as @nested in IDL. +#define ERPC_NESTED_CALLS (ERPC_NESTED_CALLS_ENABLED) + +//! @def ERPC_NESTED_CALLS_DETECTION +//! +//! Default set to ERPC_NESTED_CALLS_DETECTION_ENABLED when NDEBUG macro is presented. +//! This serve for locating nested calls in code. Nested calls are calls where inside eRPC function +//! on server side is called another eRPC function (like callbacks). Code need be a bit changed +//! to support nested calls. See ERPC_NESTED_CALLS macro. +//#define ERPC_NESTED_CALLS_DETECTION (ERPC_NESTED_CALLS_DETECTION_DISABLED) + +//! @def ERPC_MESSAGE_LOGGING +//! +//! Enable eRPC message logging code through the eRPC. Take look into "erpc_message_loggers.h". Can be used for base +//! printing messages, or sending data to another system for data analysis. Default set to +//! ERPC_MESSAGE_LOGGING_DISABLED. +//! +//! Uncomment for using logging feature. +//#define ERPC_MESSAGE_LOGGING (ERPC_MESSAGE_LOGGING_ENABLED) + +//! @def ERPC_TRANSPORT_MU_USE_MCMGR +//! +//! @brief MU transport layer configuration. +//! +//! Set to one of the @c ERPC_TRANSPORT_MU_USE_MCMGR_x macros to configure the MCMGR usage in MU transport layer. +//! +//! MU transport layer could leverage the Multicore Manager (MCMGR) component for Inter-Core +//! interrupts / MU interrupts management or the Inter-Core interrupts can be managed by itself (MUX_IRQHandler +//! overloading). By default, ERPC_TRANSPORT_MU_USE_MCMGR is set to ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED when mcmgr.h +//! is part of the project, otherwise the ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED option is used. This settings can be +//! overwritten from the erpc_config.h by uncommenting the ERPC_TRANSPORT_MU_USE_MCMGR macro definition. Do not forget +//! to add the MCMGR library into your project when ERPC_TRANSPORT_MU_USE_MCMGR_ENABLED option is used! See the +//! erpc_mu_transport.h for additional MU settings. +//#define ERPC_TRANSPORT_MU_USE_MCMGR ERPC_TRANSPORT_MU_USE_MCMGR_DISABLED +//@} + +//! @def ERPC_PRE_POST_ACTION +//! +//! Enable eRPC pre and post callback functions shim code. Take look into "erpc_pre_post_action.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DISABLED. +//! +//! Uncomment for using pre post callback feature. +//#define ERPC_PRE_POST_ACTION (ERPC_PRE_POST_ACTION_ENABLED) + +//! @def ERPC_PRE_POST_ACTION_DEFAULT +//! +//! Enable eRPC pre and post default callback functions. Take look into "erpc_setup_extensions.h". Can be used for +//! detection of eRPC call freeze, ... Default set to ERPC_PRE_POST_ACTION_DEFAULT_DISABLED. +//! +//! Uncomment for using pre post default callback feature. +//#define ERPC_PRE_POST_ACTION_DEFAULT (ERPC_PRE_POST_ACTION_DEFAULT_ENABLED) + +//! @name Assert function definition +//@{ +//! User custom asser defition. Include header file if needed before bellow line. If assert is not enabled, default will +//! be used. +// #define erpc_assert(condition) +//@} + +//! @def ENDIANES_HEADER +//! +//! Include header file that controls the communication endianness +//! +//! Uncomment for example behaviour for endianness agnostic with: +//! 1. communication in little endian. +//! 2. current processor is big endian. +//! 3. pointer size is 32 bit. +//! 4. float+double scheme not defined, so throws assert if passes. +//! #define ERPC_PROCESSOR_ENDIANNESS_LITTLE 0 +//! #define ERPC_COMMUNICATION_LITTLE 1 +//! #define ERPC_POINTER_SIZE_16 0 +//! #define ERPC_POINTER_SIZE_32 1 +//! #define ERPC_POINTER_SIZE_64 0 +//! #define ENDIANNESS_HEADER "erpc_endianness_agnostic_example.h" + +/*! @} */ +#endif // _ERPC_CONFIG_H_ +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/test/zephyr/uart/test_arbitrator/config/prj.conf b/test/zephyr/uart/test_arbitrator/config/prj.conf new file mode 100644 index 00000000..d27a67b3 --- /dev/null +++ b/test/zephyr/uart/test_arbitrator/config/prj.conf @@ -0,0 +1,32 @@ +# C++ Language Support +CONFIG_CPP=y +CONFIG_STD_CPP17=y +CONFIG_GLIBCXX_LIBCPP=y + +CONFIG_NEWLIB_LIBC=y +CONFIG_NEWLIB_LIBC_NANO=y + +# Compiler +CONFIG_MAIN_STACK_SIZE=4096 +CONFIG_HEAP_MEM_POOL_SIZE=8192 +CONFIG_NO_OPTIMIZATIONS=y + +# eRPC +CONFIG_ERPC=y +CONFIG_ERPC_TRANSPORT_UART=y + +# UART +CONFIG_CONSOLE=n +CONFIG_UART_CONSOLE=n + +CONFIG_THREAD_CUSTOM_DATA=y +CONFIG_ERPC_ARBITRATED_CLIENT=y +CONFIG_POLL=y + +CONFIG_THREAD_NAME=y +CONFIG_SCHED_CPU_MASK=y +CONFIG_THREAD_ANALYZER=y + +CONFIG_LOG=y +CONFIG_LOG_MODE_IMMEDIATE=y +CONFIG_LOG_OVERRIDE_LEVEL=3 \ No newline at end of file diff --git a/test/zephyr/uart/test_arbitrator/testcase.yaml b/test/zephyr/uart/test_arbitrator/testcase.yaml new file mode 100644 index 00000000..dda0c3b9 --- /dev/null +++ b/test/zephyr/uart/test_arbitrator/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.arbitrator: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_arbitrator/test_arbitrator.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_arrays/CMakeLists.txt b/test/zephyr/uart/test_arrays/CMakeLists.txt new file mode 100644 index 00000000..5e072377 --- /dev/null +++ b/test/zephyr/uart/test_arrays/CMakeLists.txt @@ -0,0 +1,15 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(TEST_ERPC_OUT_DIR ${ERPC_OUT_ROOT_DIR}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_arrays/testcase.yaml b/test/zephyr/uart/test_arrays/testcase.yaml new file mode 100644 index 00000000..585c5610 --- /dev/null +++ b/test/zephyr/uart/test_arrays/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.arrays: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_arrays/test_arrays.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_binary/CMakeLists.txt b/test/zephyr/uart/test_binary/CMakeLists.txt new file mode 100644 index 00000000..c6297d38 --- /dev/null +++ b/test/zephyr/uart/test_binary/CMakeLists.txt @@ -0,0 +1,13 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_binary/testcase.yaml b/test/zephyr/uart/test_binary/testcase.yaml new file mode 100644 index 00000000..f8771ff1 --- /dev/null +++ b/test/zephyr/uart/test_binary/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.binary: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_binary/test_binary.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_builtin/CMakeLists.txt b/test/zephyr/uart/test_builtin/CMakeLists.txt new file mode 100644 index 00000000..c6297d38 --- /dev/null +++ b/test/zephyr/uart/test_builtin/CMakeLists.txt @@ -0,0 +1,13 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_builtin/testcase.yaml b/test/zephyr/uart/test_builtin/testcase.yaml new file mode 100644 index 00000000..6d37074e --- /dev/null +++ b/test/zephyr/uart/test_builtin/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.builtin: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_builtin/test_builtin.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_callbacks/CMakeLists.txt b/test/zephyr/uart/test_callbacks/CMakeLists.txt new file mode 100644 index 00000000..a8fdb43a --- /dev/null +++ b/test/zephyr/uart/test_callbacks/CMakeLists.txt @@ -0,0 +1,39 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(ERPC_NAME_APP test_core0) + +# Define required IDL files +set(TEST_ERPC_FILES + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME_APP}_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME_APP}_${APP_TYPE}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME_APP}_${APP_TYPE}.cpp + + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_core1_interface.cpp + + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_unit_test_common_interface.cpp + ${TEST_ERPC_OUT_DIR}/${ERPC_NAME}_unit_test_common_${APP_TYPE}.cpp + ${TEST_ERPC_OUT_DIR}/c_${ERPC_NAME}_unit_test_common_${APP_TYPE}.cpp +) + +set(TEST_SOURCES + ${TEST_ERPC_FILES} + + ${TEST_SOURCE_DIR}/${TEST_NAME}_${APP_TYPE}_impl.cpp + ${TEST_COMMON_DIR}/unit_test_${TRANSPORT}_${APP_TYPE}.cpp +) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_callbacks/testcase.yaml b/test/zephyr/uart/test_callbacks/testcase.yaml new file mode 100644 index 00000000..bd5e1765 --- /dev/null +++ b/test/zephyr/uart/test_callbacks/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.callbacks: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_callbacks/test_callbacks.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_const/CMakeLists.txt b/test/zephyr/uart/test_const/CMakeLists.txt new file mode 100644 index 00000000..c6297d38 --- /dev/null +++ b/test/zephyr/uart/test_const/CMakeLists.txt @@ -0,0 +1,13 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_const/testcase.yaml b/test/zephyr/uart/test_const/testcase.yaml new file mode 100644 index 00000000..e2f1498f --- /dev/null +++ b/test/zephyr/uart/test_const/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.const: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_const/test_const.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_enums/CMakeLists.txt b/test/zephyr/uart/test_enums/CMakeLists.txt new file mode 100644 index 00000000..c6297d38 --- /dev/null +++ b/test/zephyr/uart/test_enums/CMakeLists.txt @@ -0,0 +1,13 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_enums/testcase.yaml b/test/zephyr/uart/test_enums/testcase.yaml new file mode 100644 index 00000000..bd953912 --- /dev/null +++ b/test/zephyr/uart/test_enums/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.enums: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_enums/test_enums.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_lists/CMakeLists.txt b/test/zephyr/uart/test_lists/CMakeLists.txt new file mode 100644 index 00000000..c6297d38 --- /dev/null +++ b/test/zephyr/uart/test_lists/CMakeLists.txt @@ -0,0 +1,13 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_lists/testcase.yaml b/test/zephyr/uart/test_lists/testcase.yaml new file mode 100644 index 00000000..c53f86fc --- /dev/null +++ b/test/zephyr/uart/test_lists/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.lists: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_lists/test_lists.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_shared/CMakeLists.txt b/test/zephyr/uart/test_shared/CMakeLists.txt new file mode 100644 index 00000000..c6297d38 --- /dev/null +++ b/test/zephyr/uart/test_shared/CMakeLists.txt @@ -0,0 +1,13 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_shared/testcase.yaml b/test/zephyr/uart/test_shared/testcase.yaml new file mode 100644 index 00000000..00e2227f --- /dev/null +++ b/test/zephyr/uart/test_shared/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.shared: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_shared/test_shared.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_struct/CMakeLists.txt b/test/zephyr/uart/test_struct/CMakeLists.txt new file mode 100644 index 00000000..5584b67d --- /dev/null +++ b/test/zephyr/uart/test_struct/CMakeLists.txt @@ -0,0 +1,15 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(ERPC_NAME_APP test_ArithmeticService) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_struct/testcase.yaml b/test/zephyr/uart/test_struct/testcase.yaml new file mode 100644 index 00000000..f944b548 --- /dev/null +++ b/test/zephyr/uart/test_struct/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.struct: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_struct/test_atest_structrrays.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_typedef/CMakeLists.txt b/test/zephyr/uart/test_typedef/CMakeLists.txt new file mode 100644 index 00000000..c6297d38 --- /dev/null +++ b/test/zephyr/uart/test_typedef/CMakeLists.txt @@ -0,0 +1,13 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_typedef/testcase.yaml b/test/zephyr/uart/test_typedef/testcase.yaml new file mode 100644 index 00000000..aed6d2bf --- /dev/null +++ b/test/zephyr/uart/test_typedef/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.typedef: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_typedef/test_typedef.py" \ No newline at end of file diff --git a/test/zephyr/uart/test_unions/CMakeLists.txt b/test/zephyr/uart/test_unions/CMakeLists.txt new file mode 100644 index 00000000..53266d3e --- /dev/null +++ b/test/zephyr/uart/test_unions/CMakeLists.txt @@ -0,0 +1,15 @@ +# +# Copyright 2024 NXP +# +# SPDX-License-Identifier: BSD-3-Clause +# + +cmake_minimum_required(VERSION 3.20.0) + +include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/unit_test.cmake) +project(${APP_TYPE}) + +set(ERPC_NAME test) + +# Include test +include(${ZEPHYR_TEST_CMAKE_DIR}/test.cmake) diff --git a/test/zephyr/uart/test_unions/testcase.yaml b/test/zephyr/uart/test_unions/testcase.yaml new file mode 100644 index 00000000..a847573c --- /dev/null +++ b/test/zephyr/uart/test_unions/testcase.yaml @@ -0,0 +1,8 @@ +tests: + erpc.uart.unions: + harness: pytest + tags: + - pytest + harness_config: + pytest_root: + - "../../../python_impl_tests/scripts/test_unions/test_unions.py" \ No newline at end of file diff --git a/zephyr/CMakeLists.txt b/zephyr/CMakeLists.txt index 59d52d0e..6e5b755e 100644 --- a/zephyr/CMakeLists.txt +++ b/zephyr/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright 2023 NXP +# Copyright 2023-2024 NXP # # SPDX-License-Identifier: BSD-3-Clause # @@ -54,6 +54,21 @@ if (CONFIG_ERPC) ${ERPC_DIR}/setup/erpc_setup_uart_zephyr.cpp ) + # Optional TCP transport + zephyr_library_sources_ifdef( + CONFIG_ERPC_TRANSPORT_TCP + ${ERPC_DIR}/transports/erpc_tcp_transport.cpp + ${ERPC_DIR}/setup/erpc_setup_tcp.cpp + ${ERPC_DIR}/port/erpc_threading_pthreads.cpp # Required for POSIX threading + ) + + # Optional MBOX transport + zephyr_library_sources_ifdef( + CONFIG_ERPC_TRANSPORT_MBOX + ${ERPC_DIR}/transports/erpc_mbox_zephyr_transport.cpp + ${ERPC_DIR}/setup/erpc_setup_mbox_zephyr.cpp + ) + # Optional RPMSG-LITE transport zephyr_library_sources_ifdef( CONFIG_ERPC_TRANSPORT_RPMSG_LITE diff --git a/zephyr/Kconfig b/zephyr/Kconfig index 810bd062..2dd28d4d 100644 --- a/zephyr/Kconfig +++ b/zephyr/Kconfig @@ -1,5 +1,5 @@ # -# Copyright 2023 NXP +# Copyright 2023-2024 NXP # # SPDX-License-Identifier: BSD-3-Clause # @@ -31,12 +31,24 @@ config ERPC_TRANSPORT_UART select SERIAL select UART_INTERRUPT_DRIVEN +config ERPC_TRANSPORT_TCP + bool "Enable eRPC TCP transport" + help + When enabled, eRPC will include TCP transport layer. This layer use Zephyr POSIX. + config ERPC_TRANSPORT_RPMSG_LITE bool "Enable eRPC rpsmg-lite transport" help When enabled, eRPC will include rpsmg-lite transport layer. depends on RPMSGLITE +config ERPC_TRANSPORT_MBOX + bool "Enable eRPC Zephyr MBOX transport" + help + When enabled, eRPC will include Zephyr MBOX transport layer. + select RING_BUFFER + + config ERPC_ARBITRATED_CLIENT bool "Enable eRPC arbitrated client" help