├── LICENSE ├── README.md ├── README_cn.md ├── SConscript ├── examples ├── SConscript └── example_umcn.c ├── inc └── uMCN.h └── src ├── SConscript ├── cmd_mcn.c └── uMCN.c /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [中文页](README_cn.md) | 3 | 4 | # uMCN 5 | 6 | uMCN is a module of [Firmament Autopilot](https://github.com/Firmament-Autopilot) project. 7 | 8 | ## Introduction 9 | 10 | The uMCN (Micro Multi-Communication Node) provides a secure inter-thread/inter-process communication method based on the *publish/subscribe* model. It is widely used in system to exchange data between tasks and modules. 11 | 12 | ## API 13 | 14 | ```c 15 | fmt_err_t mcn_init(void); 16 | fmt_err_t mcn_advertise(McnHub_t hub, int (*echo)(void* parameter)); 17 | McnNode_t mcn_subscribe(McnHub_t hub, MCN_EVENT_HANDLE event, void (*pub_cb)(void* parameter)); 18 | fmt_err_t mcn_unsubscribe(McnHub_t hub, McnNode_t node); 19 | fmt_err_t mcn_publish(McnHub_t hub, const void* data); 20 | rt_bool_t mcn_poll(McnNode_t node_t); 21 | rt_bool_t mcn_poll_sync(McnNode_t node_t, rt_int32_t timeout); 22 | fmt_err_t mcn_copy(McnHub_t hub, McnNode_t node_t, void* buffer); 23 | fmt_err_t mcn_copy_from_hub(McnHub_t hub, void* buffer); 24 | void mcn_suspend(McnHub_t hub); 25 | void mcn_resume(McnHub_t hub); 26 | McnList_t mcn_get_list(void); 27 | McnHub_t mcn_iterate(McnList_t* ite); 28 | void mcn_node_clear(McnNode_t node_t); 29 | ``` 30 | 31 | ## Adding New Topic 32 | 33 | To add a new uMCN topic, you need create a new topic content. e.g. 34 | 35 | ```c 36 | typedef struct { 37 | rt_uint32_t a; 38 | float b; 39 | int8_t c[4]; 40 | } data_content; 41 | ``` 42 | 43 | uMCN has no restrictions on the length and type of topic content, so in theory, it can be used to transmit any message type. 44 | 45 | Then you need add topic definition using the macro `MCN_DEFINE(name, size)`. Usually on the top of source file where the topic is published. e.g. 46 | 47 | ```c 48 | MCN_DEFINE(my_topic, sizeof(data_content)); 49 | ``` 50 | 51 | uMCN supports multiple publishers and subscribers for one toppic. Note that the same topic name is not allowed, as the compiler will complain about that. 52 | 53 | The next step is to register this topic using `mcn_advertise()`. e.g. 54 | 55 | ```c 56 | mcn_advertise(MCN_ID(my_topic), my_topic_echo); 57 | ``` 58 | 59 | `MCN_ID()` is a macro to find the hub node with a given topic name. `my_topic_echo` is the echo callback function which is used to print out the topic data. 60 | 61 | ```c 62 | static int my_topic_echo(void* param) 63 | { 64 | data_content data; 65 | if(mcn_copy_from_hub((McnHub*)param, &data) == FMT_EOK){ 66 | printf("a:%d b:%f c:%c %c %c %c\n", data.a, data.b, data.c[0], data.c[1], data.c[2], data.c[3]); 67 | return 0; 68 | } 69 | return -1; 70 | } 71 | ``` 72 | 73 | ## Publish Topic 74 | 75 | Publishing a topic can be done from anywhere in the system using function `mcn_publish()`. e.g. 76 | 77 | ```c 78 | data_content my_data = {50, -2.0, {1,2,3,4}}; 79 | mcn_publish(MCN_ID(my_topic), &my_data); 80 | ``` 81 | 82 | ## Subscribe Topic 83 | 84 | The uMCN supports to subscribe a topic with either synchronous or asynchronous method. For synchronous method, you need provide an event handle when subscribing a topic. Here is an example: 85 | 86 | **Synchronous subscription** 87 | 88 | ```c 89 | rt_sem_t event = rt_sem_create("my_event", 0, RT_IPC_FLAG_FIFO); 90 | McnNode_t my_nod = mcn_subscribe(MCN_ID(my_topic), event, RT_NULL); 91 | ``` 92 | 93 | **Asynchronous subscription** 94 | 95 | ```c 96 | McnNode_t my_nod = mcn_subscribe(MCN_ID(my_topic), RT_NULL, RT_NULL); 97 | ``` 98 | 99 | > Note that you need declare a topic with macro `MCN_DECLARE(name)` if you are visiting a topic outside of the source file where the topic defined. 100 | 101 | Correspondingly, there are synchronous and asynchronous methods when reading a topic. 102 | 103 | **Synchronous read** 104 | 105 | ```c 106 | data_content read_data; 107 | if(mcn_poll_sync(my_nod, RT_WAIT_FOREVER)){ 108 | mcn_copy(MCN_ID(my_topic), my_nod, &read_data); 109 | } 110 | ``` 111 | 112 | **Asynchronous read** 113 | 114 | ```c 115 | data_content read_data; 116 | if(mcn_poll(my_nod){ 117 | mcn_copy(MCN_ID(my_topic), my_nod, &read_data); 118 | } 119 | ``` 120 | 121 | ## Command 122 | 123 | ``` 124 | usage: mcn [options] 125 | 126 | command: 127 | list List all uMCN topics. 128 | echo Echo a uMCN topic. 129 | suspend Suspend a uMCN topic. 130 | resume Resume a uMCN topic. 131 | ``` 132 | -------------------------------------------------------------------------------- /README_cn.md: -------------------------------------------------------------------------------- 1 | 2 | [English](README.md) | 3 | 4 | # uMCN 5 | 6 | uMCN 是 [Firmament Autopilot](https://github.com/Firmament-Autopilot) 项目的一个子模块. 7 | 8 | ## 介绍 9 | 10 | uMCN (Micro Multi-Communication Node) 提供了一种基于发布/订阅模式的安全跨线程/进程的通信方式。在系统中,uMCN 被广泛应用于任务和模块间的数据通信。 11 | 12 | ## 接口函数 13 | 14 | ```c 15 | fmt_err_t mcn_init(void); 16 | fmt_err_t mcn_advertise(McnHub_t hub, int (*echo)(void* parameter)); 17 | McnNode_t mcn_subscribe(McnHub_t hub, MCN_EVENT_HANDLE event, void (*pub_cb)(void* parameter)); 18 | fmt_err_t mcn_unsubscribe(McnHub_t hub, McnNode_t node); 19 | fmt_err_t mcn_publish(McnHub_t hub, const void* data); 20 | rt_bool_t mcn_poll(McnNode_t node_t); 21 | rt_bool_t mcn_poll_sync(McnNode_t node_t, rt_int32_t timeout); 22 | fmt_err_t mcn_copy(McnHub_t hub, McnNode_t node_t, void* buffer); 23 | fmt_err_t mcn_copy_from_hub(McnHub_t hub, void* buffer); 24 | void mcn_suspend(McnHub_t hub); 25 | void mcn_resume(McnHub_t hub); 26 | McnList_t mcn_get_list(void); 27 | McnHub_t mcn_iterate(McnList_t* ite); 28 | void mcn_node_clear(McnNode_t node_t); 29 | ``` 30 | 31 | ## 添加新主题 32 | 33 | 为了添加新的主题 (topic),你需要先创建一个主题内容。例如: 34 | 35 | ```c 36 | typedef struct { 37 | rt_uint32_t a; 38 | float b; 39 | int8_t c[4]; 40 | } data_content; 41 | ``` 42 | 43 | uMCN对主题内容的长度和类型没有限制,所以理论上可以用来传输任何类型的消息。 44 | 45 | 然后你需要使用宏 `MCN_DEFINE(name, size)` 来定义主题。一般在发布主题的源文件的顶部定义主题。例如: 46 | 47 | ```c 48 | MCN_DEFINE(my_topic, sizeof(data_content)); 49 | ``` 50 | 51 | uMCN 支持一个主题拥有多个发布者和订阅者。注意同一个主题名字不同被重复定义,不然编译器会报错。 52 | 53 | 下一步就是使用 `mcn_advertise()` 来注册主题。例如: 54 | 55 | ```c 56 | mcn_advertise(MCN_ID(my_topic), my_topic_echo); 57 | ``` 58 | 59 | `MCN_ID()` 宏根据主题名获得枢纽节点。`my_topic_echo` 是一个回调函数,用来打印主题的数据。 60 | 61 | ```c 62 | static int my_topic_echo(void* param) 63 | { 64 | data_content data; 65 | if(mcn_copy_from_hub((McnHub*)param, &data) == FMT_EOK){ 66 | printf("a:%d b:%f c:%c %c %c %c\n", data.a, data.b, data.c[0], data.c[1], data.c[2], data.c[3]); 67 | return 0; 68 | } 69 | return -1; 70 | } 71 | ``` 72 | 73 | ## 发布主题 74 | 75 | 可以在系统的任意位置使用函数 `mcn_publish()` 来发布一个主题。例如: 76 | 77 | ```c 78 | data_content my_data = {50, -2.0, {1,2,3,4}}; 79 | mcn_publish(MCN_ID(my_topic), &my_data); 80 | ``` 81 | 82 | ## 订阅主题 83 | 84 | uMCN 支持使用同步或异步方法订阅主题。对于同步方法,订阅主题时需要提供事件处理句柄。下面是一个例子: 85 | 86 | **同步订阅** 87 | 88 | ```c 89 | rt_sem_t event = rt_sem_create("my_event", 0, RT_IPC_FLAG_FIFO); 90 | McnNode_t my_nod = mcn_subscribe(MCN_ID(my_topic), event, RT_NULL); 91 | ``` 92 | 93 | **异步订阅** 94 | 95 | ```c 96 | McnNode_t my_nod = mcn_subscribe(MCN_ID(my_topic), RT_NULL, RT_NULL); 97 | ``` 98 | 99 | > 注意,如果你在定义主题之外的文件来访问该主题,你需要使用宏 `MCN_DECLARE(name)` 来进行申明。 100 | 101 | 相应地,有同步和异步读取主题的方法。 102 | 103 | **同步读取** 104 | 105 | ```c 106 | data_content read_data; 107 | if(mcn_poll_sync(my_nod, RT_WAIT_FOREVER)){ 108 | mcn_copy(MCN_ID(my_topic), my_nod, &read_data); 109 | } 110 | ``` 111 | 112 | **异步读取** 113 | 114 | ```c 115 | data_content read_data; 116 | if(mcn_poll(my_nod){ 117 | mcn_copy(MCN_ID(my_topic), my_nod, &read_data); 118 | } 119 | ``` 120 | 121 | ## 命令 122 | 123 | ``` 124 | usage: mcn [options] 125 | 126 | command: 127 | list List all uMCN topics. 128 | echo Echo a uMCN topic. 129 | suspend Suspend a uMCN topic. 130 | resume Resume a uMCN topic. 131 | ``` 132 | -------------------------------------------------------------------------------- /SConscript: -------------------------------------------------------------------------------- 1 | # RT-Thread building script for bridge 2 | 3 | import os 4 | from building import * 5 | 6 | cwd = GetCurrentDir() 7 | objs = [] 8 | list = os.listdir(cwd) 9 | 10 | if GetDepend('PKG_USING_UMCN'): 11 | for d in list: 12 | path = os.path.join(cwd, d) 13 | if os.path.isfile(os.path.join(path, 'SConscript')): 14 | objs = objs + SConscript(os.path.join(d, 'SConscript')) 15 | 16 | Return('objs') 17 | -------------------------------------------------------------------------------- /examples/SConscript: -------------------------------------------------------------------------------- 1 | from building import * 2 | 3 | cwd = GetCurrentDir() 4 | src = Glob('*.c') + Glob('*.cpp') 5 | CPPPATH = [cwd] 6 | 7 | group = DefineGroup('uMCN', src, depend = ['UMCN_USING_DEMO'], CPPPATH = CPPPATH) 8 | 9 | Return('group') 10 | -------------------------------------------------------------------------------- /examples/example_umcn.c: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Copyright 2021 The Firmament Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | *****************************************************************************/ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | typedef struct { 22 | char str[20]; 23 | unsigned long count; 24 | } count_topic_t; 25 | 26 | typedef struct { 27 | rt_tick_t tick; 28 | } systick_topic_t; 29 | 30 | static rt_thread_t tid0; 31 | static McnNode_t count_nod; 32 | static McnNode_t systick_nod; 33 | static rt_sem_t event; 34 | 35 | MCN_DEFINE(count, sizeof(count_topic_t)); 36 | MCN_DEFINE(systick, sizeof(systick_topic_t)); 37 | 38 | static int count_topic_echo(void* parameter) 39 | { 40 | count_topic_t count_topic; 41 | 42 | if (mcn_copy_from_hub((McnHub*)parameter, &count_topic) != RT_EOK) { 43 | return -1; 44 | } 45 | 46 | rt_kprintf("string:%s count:%lu\n", count_topic.str, count_topic.count); 47 | return 0; 48 | } 49 | 50 | static int systick_topic_echo(void* parameter) 51 | { 52 | systick_topic_t systick_topic; 53 | 54 | if (mcn_copy_from_hub((McnHub*)parameter, &systick_topic) != RT_EOK) { 55 | return -1; 56 | } 57 | 58 | rt_kprintf("tick:%u\n", systick_topic.tick); 59 | return 0; 60 | } 61 | 62 | void count_topic_pub_cb(void* parameter) 63 | { 64 | count_topic_t count_topic = *(count_topic_t*)parameter; 65 | 66 | rt_kprintf("publish callback, string:%s count:%lu\n", count_topic.str, count_topic.count); 67 | 68 | /* publish callback once */ 69 | mcn_unsubscribe(MCN_HUB(count), count_nod); 70 | } 71 | 72 | static void test_entry(void* parameter) 73 | { 74 | rt_tick_t cnt = 0; 75 | rt_tick_t sec_tick = rt_tick_from_millisecond(1000); 76 | count_topic_t count_topic = { .count = 0, .str = "Hello RT-Thread!" }; 77 | 78 | while (1) { 79 | systick_topic_t systick_topic; 80 | systick_topic.tick = rt_tick_get(); 81 | 82 | if (++cnt >= sec_tick) { 83 | cnt = 0; 84 | count_topic.count++; 85 | /* publish count topic in 1Hz */ 86 | mcn_publish(MCN_HUB(count), &count_topic); 87 | } 88 | 89 | /* publish systick topic at each tick */ 90 | mcn_publish(MCN_HUB(systick), &systick_topic); 91 | rt_thread_delay(1); 92 | } 93 | } 94 | 95 | int mcn_test(int argc, char** argv) 96 | { 97 | /* advertise topic and provide echo function */ 98 | mcn_advertise(MCN_HUB(count), count_topic_echo); 99 | mcn_advertise(MCN_HUB(systick), systick_topic_echo); 100 | 101 | /* subscribe topic in asynchronous mode. 102 | * The call back function is called if topic is published */ 103 | count_nod = mcn_subscribe(MCN_HUB(count), RT_NULL, count_topic_pub_cb); 104 | /* subscribe topic in synchronous mode */ 105 | event = rt_sem_create("my_event", 0, RT_IPC_FLAG_FIFO); 106 | systick_nod = mcn_subscribe(MCN_HUB(systick), event, RT_NULL); 107 | 108 | tid0 = rt_thread_create("mcn_test", 109 | test_entry, RT_NULL, 110 | 1024, RT_THREAD_PRIORITY_MAX / 2, 20); 111 | if (tid0 != RT_NULL) 112 | rt_thread_startup(tid0); 113 | 114 | /* synchronous wait until topic received */ 115 | if (mcn_poll_sync(systick_nod, RT_WAITING_FOREVER)) { 116 | systick_topic_t data; 117 | /* copy topic data */ 118 | mcn_copy(MCN_HUB(systick), systick_nod, &data); 119 | rt_kprintf("get sync topic, tick=%ld\n", data.tick); 120 | } 121 | 122 | return 0; 123 | } 124 | MSH_CMD_EXPORT(mcn_test, uMCN API test); 125 | -------------------------------------------------------------------------------- /inc/uMCN.h: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Copyright 2021 The Firmament Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | *****************************************************************************/ 16 | 17 | #ifndef UMCN_H__ 18 | #define UMCN_H__ 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | #include 25 | 26 | #define MCN_MALLOC(size) rt_malloc(size) 27 | #define MCN_FREE(ptr) rt_free(ptr) 28 | #define MCN_ENTER_CRITICAL rt_enter_critical() 29 | #define MCN_EXIT_CRITICAL rt_exit_critical() 30 | #define MCN_EVENT_HANDLE rt_sem_t 31 | #define MCN_SEND_EVENT(event) rt_sem_release(event) 32 | #define MCN_WAIT_EVENT(event, time) rt_sem_take(event, time) 33 | #define MCN_ASSERT(EX) RT_ASSERT(EX) 34 | 35 | #define MCN_MAX_LINK_NUM 30 36 | #define MCN_FREQ_EST_WINDOW_LEN 5 37 | 38 | typedef struct mcn_node McnNode; 39 | typedef struct mcn_node* McnNode_t; 40 | struct mcn_node { 41 | volatile rt_uint8_t renewal; 42 | MCN_EVENT_HANDLE event; 43 | void (*pub_cb)(void* parameter); 44 | McnNode_t next; 45 | }; 46 | 47 | typedef struct mcn_hub McnHub; 48 | typedef struct mcn_hub* McnHub_t; 49 | struct mcn_hub { 50 | const char* obj_name; 51 | const rt_uint32_t obj_size; 52 | void* pdata; 53 | McnNode_t link_head; 54 | McnNode_t link_tail; 55 | rt_uint32_t link_num; 56 | rt_uint8_t published; 57 | rt_uint8_t suspend; 58 | int (*echo)(void* parameter); 59 | /* publish freq estimate */ 60 | float freq; 61 | rt_uint16_t freq_est_window[MCN_FREQ_EST_WINDOW_LEN]; 62 | rt_uint16_t window_index; 63 | }; 64 | 65 | typedef struct mcn_list McnList; 66 | typedef struct mcn_list* McnList_t; 67 | struct mcn_list { 68 | McnHub_t hub; 69 | McnList_t next; 70 | }; 71 | 72 | /* Obtain uMCN hub according to name */ 73 | #define MCN_HUB(_name) (&__mcn_##_name) 74 | /* Declare a uMCN topic. Declare the topic at places where you need use it */ 75 | #define MCN_DECLARE(_name) extern McnHub __mcn_##_name 76 | /* Define a uMCN topic. A topic should only be defined once */ 77 | #define MCN_DEFINE(_name, _size) \ 78 | McnHub __mcn_##_name = { \ 79 | .obj_name = #_name, \ 80 | .obj_size = _size, \ 81 | .pdata = RT_NULL, \ 82 | .link_head = RT_NULL, \ 83 | .link_tail = RT_NULL, \ 84 | .link_num = 0, \ 85 | .published = 0, \ 86 | .suspend = 0, \ 87 | .freq = 0.0f \ 88 | } 89 | 90 | int mcn_init(void); 91 | rt_err_t mcn_advertise(McnHub_t hub, int (*echo)(void* parameter)); 92 | McnNode_t mcn_subscribe(McnHub_t hub, MCN_EVENT_HANDLE event, void (*pub_cb)(void* parameter)); 93 | rt_err_t mcn_unsubscribe(McnHub_t hub, McnNode_t node); 94 | rt_err_t mcn_publish(McnHub_t hub, const void* data); 95 | rt_bool_t mcn_poll(McnNode_t node_t); 96 | rt_bool_t mcn_poll_sync(McnNode_t node_t, rt_int32_t timeout); 97 | rt_err_t mcn_copy(McnHub_t hub, McnNode_t node_t, void* buffer); 98 | rt_err_t mcn_copy_from_hub(McnHub_t hub, void* buffer); 99 | void mcn_suspend(McnHub_t hub); 100 | void mcn_resume(McnHub_t hub); 101 | McnList_t mcn_get_list(void); 102 | McnHub_t mcn_iterate(McnList_t* ite); 103 | void mcn_node_clear(McnNode_t node_t); 104 | 105 | #ifdef __cplusplus 106 | } 107 | #endif 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /src/SConscript: -------------------------------------------------------------------------------- 1 | from building import * 2 | 3 | cwd = GetCurrentDir() 4 | src = Glob('uMCN.c') 5 | CPPPATH = [cwd + '/../inc'] 6 | 7 | if GetDepend(['UMCN_USING_CMD']): 8 | src += ['cmd_mcn.c'] 9 | 10 | group = DefineGroup('uMCN', src, depend = ['PKG_USING_UMCN'], CPPPATH = CPPPATH) 11 | 12 | Return('group') 13 | -------------------------------------------------------------------------------- /src/cmd_mcn.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "uMCN.h" 11 | 12 | #define STRING_COMPARE(str1, str2) (strcmp(str1, str2) == 0) 13 | #define PRINT_USAGE(cmd, usage) rt_kprintf("usage: %s %s\n", #cmd, #usage) 14 | #define PRINT_STRING(str) rt_kprintf("%s", str) 15 | #define PRINT_ACTION(action, len, desc) rt_kprintf(" %-" #len "s %s\n", action, desc) 16 | #define COMMAND_USAGE(cmd, usage) rt_kprintf("usage: %s %s\n", cmd, usage) 17 | #define SHELL_COMMAND(cmd, desc) rt_kprintf(" %-10s %s\n", cmd, desc) 18 | #define SHELL_OPTION(opt, desc) rt_kprintf(" %-15s %s\n", opt, desc) 19 | 20 | enum { 21 | SYSCMD_ALIGN_LEFT, 22 | SYSCMD_ALIGN_MIDDLE, 23 | SYSCMD_ALIGN_RIGHT 24 | }; 25 | 26 | extern struct finsh_shell* shell; 27 | 28 | static rt_device_t console_dev; 29 | 30 | static void show_usage(void) 31 | { 32 | COMMAND_USAGE("mcn", " [options]"); 33 | 34 | PRINT_STRING("\ncommand:\n"); 35 | SHELL_COMMAND("list", "List all uMCN topics."); 36 | SHELL_COMMAND("echo", "Echo a uMCN topic."); 37 | SHELL_COMMAND("suspend", "Suspend a uMCN topic."); 38 | SHELL_COMMAND("resume", "Resume a uMCN topic."); 39 | } 40 | 41 | static void show_echo_usage(void) 42 | { 43 | COMMAND_USAGE("mcn echo", " [options]"); 44 | 45 | PRINT_STRING("\noptions:\n"); 46 | SHELL_OPTION("-n, --number", "Set topic echo number, e.g, -n 10 will echo 10 times."); 47 | SHELL_OPTION("-p, --period", "Set topic echo period (ms), -p 0 inherits topic period"); 48 | } 49 | 50 | static void show_suspend_usage(void) 51 | { 52 | COMMAND_USAGE("mcn suspend", ""); 53 | } 54 | 55 | static void show_resume_usage(void) 56 | { 57 | COMMAND_USAGE("mcn resume", ""); 58 | } 59 | 60 | rt_inline void object_split(int len) 61 | { 62 | while (len--) 63 | rt_kprintf("-"); 64 | } 65 | 66 | void list_print_char(const char c, int cnt) 67 | { 68 | while (cnt--) 69 | rt_device_write(console_dev, 0, &c, 1); 70 | } 71 | 72 | void list_printf(const char pad, rt_uint32_t len, rt_uint8_t align, const char* fmt, ...) 73 | { 74 | va_list args; 75 | char buffer[100]; 76 | int length; 77 | 78 | va_start(args, fmt); 79 | length = vsprintf(buffer, fmt, args); 80 | va_end(args); 81 | 82 | if (len <= length) { 83 | rt_device_write(console_dev, 0, buffer, length); 84 | return; 85 | } 86 | 87 | if (align == SYSCMD_ALIGN_LEFT) { 88 | rt_device_write(console_dev, 0, buffer, length); 89 | list_print_char(pad, len - length); 90 | } else if (align == SYSCMD_ALIGN_MIDDLE) { 91 | rt_uint32_t hl = (len - length + 1) / 2; 92 | list_print_char(pad, hl); 93 | rt_device_write(console_dev, 0, buffer, length); 94 | list_print_char(pad, (len - length) - hl); 95 | } else { 96 | list_print_char(pad, len - length); 97 | rt_device_write(console_dev, 0, buffer, length); 98 | } 99 | } 100 | 101 | static int name_maxlen(const char* title) 102 | { 103 | int max_len = strlen(title); 104 | 105 | McnList_t ite = mcn_get_list(); 106 | while (1) { 107 | McnHub_t hub = mcn_iterate(&ite); 108 | if (hub == RT_NULL) { 109 | break; 110 | } 111 | int len = strlen(hub->obj_name); 112 | 113 | if (len > max_len) { 114 | max_len = len; 115 | } 116 | } 117 | 118 | return max_len; 119 | } 120 | 121 | static void list_topic(void) 122 | { 123 | rt_uint32_t max_len = name_maxlen("Topic") + 2; 124 | 125 | rt_kprintf("%-*.s #SUB Freq(Hz) Echo Suspend\n", max_len - 2, "Topic"); 126 | object_split(max_len); 127 | rt_kprintf(" ------ ---------- ------ ---------\n"); 128 | 129 | McnList_t ite = mcn_get_list(); 130 | for (McnHub_t hub = mcn_iterate(&ite); hub != RT_NULL; hub = mcn_iterate(&ite)) { 131 | list_printf(' ', max_len, SYSCMD_ALIGN_LEFT, hub->obj_name); rt_kprintf(" "); 132 | list_printf(' ', strlen("#SUB") + 2, SYSCMD_ALIGN_MIDDLE, "%d", (int)hub->link_num); rt_kprintf(" "); 133 | list_printf(' ', strlen("Freq(Hz)") + 2, SYSCMD_ALIGN_MIDDLE, "%.1f", hub->freq); rt_kprintf(" "); 134 | list_printf(' ', strlen("Echo") + 2, SYSCMD_ALIGN_MIDDLE, "%s", hub->echo ? "true" : "false"); rt_kprintf(" "); 135 | list_printf(' ', strlen("Suspend") + 2, SYSCMD_ALIGN_MIDDLE, "%s", hub->suspend ? "true" : "false"); rt_kprintf("\n"); 136 | } 137 | } 138 | 139 | static int suspend_topic(struct optparse options) 140 | { 141 | char* arg; 142 | int option; 143 | struct optparse_long longopts[] = { 144 | { "help", 'h', OPTPARSE_NONE }, 145 | { RT_NULL } /* Don't remove this line */ 146 | }; 147 | 148 | while ((option = optparse_long(&options, longopts, RT_NULL)) != -1) { 149 | switch (option) { 150 | case 'h': 151 | show_suspend_usage(); 152 | return EXIT_SUCCESS; 153 | case '?': 154 | rt_kprintf("%s: %s\n", "mcn echo", options.errmsg); 155 | return EXIT_FAILURE; 156 | } 157 | } 158 | 159 | if ((arg = optparse_arg(&options)) == RT_NULL) { 160 | show_suspend_usage(); 161 | return EXIT_FAILURE; 162 | } 163 | 164 | McnList_t ite = mcn_get_list(); 165 | McnHub_t target_hub = RT_NULL; 166 | 167 | while (1) { 168 | McnHub_t hub = mcn_iterate(&ite); 169 | if (hub == RT_NULL) { 170 | break; 171 | } 172 | if (strcmp(hub->obj_name, arg) == 0) { 173 | target_hub = hub; 174 | break; 175 | } 176 | } 177 | 178 | if (target_hub == RT_NULL) { 179 | rt_kprintf("can not find topic %s\n", arg); 180 | return EXIT_FAILURE; 181 | } 182 | 183 | mcn_suspend(target_hub); 184 | 185 | return EXIT_SUCCESS; 186 | } 187 | 188 | static int resume_topic(struct optparse options) 189 | { 190 | char* arg; 191 | int option; 192 | struct optparse_long longopts[] = { 193 | { "help", 'h', OPTPARSE_NONE }, 194 | { RT_NULL } /* Don't remove this line */ 195 | }; 196 | 197 | while ((option = optparse_long(&options, longopts, RT_NULL)) != -1) { 198 | switch (option) { 199 | case 'h': 200 | show_resume_usage(); 201 | return EXIT_SUCCESS; 202 | case '?': 203 | rt_kprintf("%s: %s\n", "mcn echo", options.errmsg); 204 | return EXIT_FAILURE; 205 | } 206 | } 207 | 208 | if ((arg = optparse_arg(&options)) == RT_NULL) { 209 | show_resume_usage(); 210 | return EXIT_FAILURE; 211 | } 212 | 213 | McnList_t ite = mcn_get_list(); 214 | McnHub_t target_hub = RT_NULL; 215 | 216 | while (1) { 217 | McnHub_t hub = mcn_iterate(&ite); 218 | if (hub == RT_NULL) { 219 | break; 220 | } 221 | if (strcmp(hub->obj_name, arg) == 0) { 222 | target_hub = hub; 223 | break; 224 | } 225 | } 226 | 227 | if (target_hub == RT_NULL) { 228 | rt_kprintf("can not find topic %s\n", arg); 229 | return EXIT_FAILURE; 230 | } 231 | 232 | mcn_resume(target_hub); 233 | 234 | return EXIT_SUCCESS; 235 | } 236 | 237 | static int echo_topic(struct optparse options) 238 | { 239 | char* arg; 240 | int option; 241 | struct optparse_long longopts[] = { 242 | { "help", 'h', OPTPARSE_NONE }, 243 | { "number", 'n', OPTPARSE_REQUIRED }, 244 | { "period", 'p', OPTPARSE_REQUIRED }, 245 | { RT_NULL } /* Don't remove this line */ 246 | }; 247 | 248 | #if defined(RT_USING_DEVICE) && !defined(RT_USING_POSIX) 249 | rt_uint32_t cnt = 0xFFFFFFFF; 250 | #else 251 | rt_uint32_t cnt = 1; 252 | #endif 253 | rt_uint32_t period = 500; 254 | 255 | while ((option = optparse_long(&options, longopts, RT_NULL)) != -1) { 256 | switch (option) { 257 | case 'h': 258 | show_echo_usage(); 259 | return EXIT_SUCCESS; 260 | case 'n': 261 | cnt = atoi(options.optarg); 262 | break; 263 | case 'p': 264 | period = atoi(options.optarg); 265 | break; 266 | case '?': 267 | rt_kprintf("%s: %s\n", "mcn echo", options.errmsg); 268 | return EXIT_FAILURE; 269 | } 270 | } 271 | 272 | if ((arg = optparse_arg(&options)) == RT_NULL) { 273 | show_echo_usage(); 274 | return EXIT_FAILURE; 275 | } 276 | 277 | McnList_t ite = mcn_get_list(); 278 | McnHub_t target_hub = RT_NULL; 279 | while (1) { 280 | McnHub_t hub = mcn_iterate(&ite); 281 | if (hub == RT_NULL) { 282 | break; 283 | } 284 | if (strcmp(hub->obj_name, arg) == 0) { 285 | target_hub = hub; 286 | break; 287 | } 288 | } 289 | 290 | if (target_hub == RT_NULL) { 291 | rt_kprintf("can not find topic %s\n", arg); 292 | return EXIT_FAILURE; 293 | } 294 | 295 | if (target_hub->echo == RT_NULL) { 296 | rt_kprintf("there is no topic echo function defined!\n"); 297 | return EXIT_FAILURE; 298 | } 299 | 300 | McnNode_t node = mcn_subscribe(target_hub, RT_NULL, RT_NULL); 301 | 302 | if (node == RT_NULL) { 303 | rt_kprintf("mcn subscribe fail\n"); 304 | return EXIT_FAILURE; 305 | } 306 | 307 | while (cnt) { 308 | #if !defined(RT_USING_POSIX_STDIO) && defined(RT_USING_DEVICE) 309 | /* type any key to exit */ 310 | if (rt_sem_trytake(&shell->rx_sem) == RT_EOK) { 311 | int ch; 312 | while (rt_device_read(shell->device, -1, &ch, 1) == 1) 313 | ; 314 | break; 315 | } 316 | #endif 317 | 318 | if (mcn_poll(node)) { 319 | /* call custom echo function */ 320 | target_hub->echo(target_hub); 321 | mcn_node_clear(node); 322 | cnt--; 323 | } 324 | 325 | if (period) { 326 | usleep(period * 1000); 327 | } 328 | } 329 | 330 | if (mcn_unsubscribe(target_hub, node) != RT_EOK) { 331 | rt_kprintf("mcn unsubscribe fail\n"); 332 | return EXIT_FAILURE; 333 | } 334 | 335 | return EXIT_SUCCESS; 336 | } 337 | 338 | int cmd_mcn(int argc, char** argv) 339 | { 340 | char* arg; 341 | struct optparse options; 342 | int res = EXIT_SUCCESS; 343 | 344 | console_dev = rt_console_get_device(); 345 | 346 | optparse_init(&options, argv); 347 | 348 | arg = optparse_arg(&options); 349 | if (arg) { 350 | if (STRING_COMPARE(arg, "list")) { 351 | list_topic(); 352 | } else if (STRING_COMPARE(arg, "echo")) { 353 | res = echo_topic(options); 354 | } else if (STRING_COMPARE(arg, "suspend")) { 355 | res = suspend_topic(options); 356 | } else if (STRING_COMPARE(arg, "resume")) { 357 | res = resume_topic(options); 358 | } else { 359 | show_usage(); 360 | } 361 | } else { 362 | show_usage(); 363 | } 364 | 365 | return res; 366 | } 367 | MSH_CMD_EXPORT_ALIAS(cmd_mcn, mcn, uMCN topics operations); -------------------------------------------------------------------------------- /src/uMCN.c: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Copyright 2021 The Firmament Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | *****************************************************************************/ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | #define DBG_TAG "uMCN" 22 | #define DBG_LVL DBG_INFO 23 | #include 24 | 25 | static McnList __mcn_list = { .hub = RT_NULL, .next = RT_NULL }; 26 | static struct rt_timer timer_mcn_freq_est; 27 | 28 | /** 29 | * @brief Topic publish frequency estimator entry 30 | * 31 | * @param parameter Unused 32 | */ 33 | static void mcn_freq_est_entry(void* parameter) 34 | { 35 | for (McnList_t cp = &__mcn_list; cp != RT_NULL; cp = cp->next) { 36 | McnHub_t hub = cp->hub; 37 | if (hub == RT_NULL) { 38 | break; 39 | } 40 | /* calculate publish frequency */ 41 | rt_uint32_t cnt = 0; 42 | for (int i = 0; i < MCN_FREQ_EST_WINDOW_LEN; i++) { 43 | cnt += hub->freq_est_window[i]; 44 | hub->freq = (float)cnt / MCN_FREQ_EST_WINDOW_LEN; 45 | } 46 | /* move window */ 47 | hub->window_index = (hub->window_index + 1) % MCN_FREQ_EST_WINDOW_LEN; 48 | hub->freq_est_window[hub->window_index] = 0; 49 | } 50 | } 51 | 52 | /** 53 | * @brief Clear uMCN node renewal flag 54 | * 55 | * @param node_t uMCN node 56 | */ 57 | void mcn_node_clear(McnNode_t node_t) 58 | { 59 | MCN_ASSERT(node_t != RT_NULL); 60 | 61 | if (node_t == RT_NULL) { 62 | return; 63 | } 64 | 65 | MCN_ENTER_CRITICAL; 66 | node_t->renewal = 0; 67 | MCN_EXIT_CRITICAL; 68 | } 69 | 70 | /** 71 | * @brief Suspend a uMCN topic 72 | * 73 | * @param hub uMCN hub 74 | */ 75 | void mcn_suspend(McnHub_t hub) 76 | { 77 | hub->suspend = 1; 78 | } 79 | 80 | /** 81 | * @brief Resume a uMCN topic 82 | * 83 | * @param hub uMCN hub 84 | */ 85 | void mcn_resume(McnHub_t hub) 86 | { 87 | hub->suspend = 0; 88 | } 89 | 90 | /** 91 | * @brief Get uMCN list 92 | * 93 | * @return McnList_t uMCN list pointer 94 | */ 95 | McnList_t mcn_get_list(void) 96 | { 97 | return &__mcn_list; 98 | } 99 | 100 | /** 101 | * @brief Iterate all uMCN hubs in list 102 | * 103 | * @param ite uMCN list pointer 104 | * @return McnHub_t uMCN hub 105 | */ 106 | McnHub_t mcn_iterate(McnList_t* ite) 107 | { 108 | McnHub_t hub; 109 | McnList_t node = *ite; 110 | 111 | if (node == RT_NULL) { 112 | return RT_NULL; 113 | } 114 | hub = node->hub; 115 | *ite = node->next; 116 | 117 | return hub; 118 | } 119 | 120 | /** 121 | * @brief Poll for topic status 122 | * @note This function would return immediately 123 | * 124 | * @param node_t uMCN node 125 | * @return RT_TRUE Topic updated 126 | * @return RT_FALSE Topic not updated 127 | */ 128 | rt_bool_t mcn_poll(McnNode_t node_t) 129 | { 130 | rt_bool_t renewal; 131 | 132 | MCN_ASSERT(node_t != RT_NULL); 133 | 134 | MCN_ENTER_CRITICAL; 135 | renewal = node_t->renewal; 136 | MCN_EXIT_CRITICAL; 137 | 138 | return renewal; 139 | } 140 | 141 | /** 142 | * @brief Synchronize poll for topic status 143 | * @note event must has been provided when subscribe the topic 144 | * 145 | * @param node_t uMCN node 146 | * @param timeout Wait timeout 147 | * @return RT_TRUE RT_TRUE Topic updated 148 | * @return RT_FALSE RT_FALSE Topic not updated 149 | */ 150 | rt_bool_t mcn_poll_sync(McnNode_t node_t, rt_int32_t timeout) 151 | { 152 | MCN_ASSERT(node_t != RT_NULL); 153 | MCN_ASSERT(node_t->event != RT_NULL); 154 | 155 | return MCN_WAIT_EVENT(node_t->event, timeout) == 0 ? RT_TRUE : RT_FALSE; 156 | } 157 | 158 | /** 159 | * @brief Copy uMCN topic data from hub 160 | * @note This function will clear the renewal flag 161 | * 162 | * @param hub uMCN hub 163 | * @param node_t uMCN node 164 | * @param buffer buffer to received the data 165 | * @return rt_err_t RT_EOK indicates success 166 | */ 167 | rt_err_t mcn_copy(McnHub_t hub, McnNode_t node_t, void* buffer) 168 | { 169 | MCN_ASSERT(hub != RT_NULL); 170 | MCN_ASSERT(node_t != RT_NULL); 171 | MCN_ASSERT(buffer != RT_NULL); 172 | 173 | if (hub->pdata == RT_NULL) { 174 | /* copy from non-advertised hub */ 175 | return -RT_ERROR; 176 | } 177 | 178 | if (!hub->published) { 179 | /* copy before published */ 180 | return -RT_ERROR; 181 | } 182 | 183 | MCN_ENTER_CRITICAL; 184 | rt_memcpy(buffer, hub->pdata, hub->obj_size); 185 | node_t->renewal = 0; 186 | MCN_EXIT_CRITICAL; 187 | 188 | return RT_EOK; 189 | } 190 | 191 | /** 192 | * @brief Copy uMCN topic data from hub 193 | * @note This function will directly copy topic data from hub no matter it has been 194 | * updated or not and won't clear the renewal flag 195 | * 196 | * @param hub 197 | * @param buffer 198 | * @return rt_err_t 199 | */ 200 | rt_err_t mcn_copy_from_hub(McnHub_t hub, void* buffer) 201 | { 202 | MCN_ASSERT(hub != RT_NULL); 203 | MCN_ASSERT(buffer != RT_NULL); 204 | 205 | if (hub->pdata == RT_NULL) { 206 | /* copy from non-advertised hub */ 207 | return -RT_ERROR; 208 | } 209 | 210 | if (!hub->published) { 211 | /* copy before published */ 212 | return -RT_ERROR; 213 | } 214 | 215 | MCN_ENTER_CRITICAL; 216 | rt_memcpy(buffer, hub->pdata, hub->obj_size); 217 | MCN_EXIT_CRITICAL; 218 | 219 | return RT_EOK; 220 | } 221 | 222 | /** 223 | * @brief Advertise a uMCN topic 224 | * 225 | * @param hub uMCN hub 226 | * @param echo Echo function to print topic contents 227 | * @return rt_err_t RT_EOK indicates success 228 | */ 229 | rt_err_t mcn_advertise(McnHub_t hub, int (*echo)(void* parameter)) 230 | { 231 | void* pdata; 232 | void* next; 233 | 234 | MCN_ASSERT(hub != RT_NULL); 235 | 236 | if (hub->pdata != RT_NULL) { 237 | /* already advertised */ 238 | return -RT_ERROR; 239 | } 240 | 241 | pdata = MCN_MALLOC(hub->obj_size); 242 | if (pdata == RT_NULL) { 243 | return -RT_ENOMEM; 244 | } 245 | memset(pdata, 0, hub->obj_size); 246 | 247 | next = MCN_MALLOC(sizeof(McnList)); 248 | if (next == RT_NULL) { 249 | MCN_FREE(pdata); 250 | return -RT_ENOMEM; 251 | } 252 | 253 | MCN_ENTER_CRITICAL; 254 | hub->pdata = pdata; 255 | hub->echo = echo; 256 | 257 | /* update Mcn List */ 258 | McnList_t cp = &__mcn_list; 259 | 260 | while (cp->next != RT_NULL) { 261 | /* find last node */ 262 | cp = cp->next; 263 | } 264 | 265 | if (cp->hub != RT_NULL) { 266 | cp->next = (McnList_t)next; 267 | cp = cp->next; 268 | } 269 | 270 | cp->hub = hub; 271 | cp->next = RT_NULL; 272 | 273 | /* init publish freq estimator window */ 274 | memset(hub->freq_est_window, 0, 2 * MCN_FREQ_EST_WINDOW_LEN); 275 | hub->window_index = 0; 276 | 277 | MCN_EXIT_CRITICAL; 278 | 279 | return RT_EOK; 280 | } 281 | 282 | /** 283 | * @brief Subscribe a uMCN topic 284 | * 285 | * @param hub uMCN hub 286 | * @param event Event handler to provide synchronize poll 287 | * @param pub_cb Topic published callback function 288 | * @return McnNode_t Subscribe node, return RT_NULL if fail 289 | */ 290 | McnNode_t mcn_subscribe(McnHub_t hub, MCN_EVENT_HANDLE event, void (*pub_cb)(void* parameter)) 291 | { 292 | MCN_ASSERT(hub != RT_NULL); 293 | 294 | if (hub->link_num >= MCN_MAX_LINK_NUM) { 295 | LOG_E("mcn link num is already full!"); 296 | return RT_NULL; 297 | } 298 | 299 | McnNode_t node = (McnNode_t)MCN_MALLOC(sizeof(McnNode)); 300 | 301 | if (node == RT_NULL) { 302 | LOG_E("mcn create node fail!"); 303 | return RT_NULL; 304 | } 305 | 306 | node->renewal = 0; 307 | node->event = event; 308 | node->pub_cb = pub_cb; 309 | node->next = RT_NULL; 310 | 311 | MCN_ENTER_CRITICAL; 312 | 313 | /* no node link yet */ 314 | if (hub->link_tail == RT_NULL) { 315 | hub->link_head = hub->link_tail = node; 316 | } else { 317 | hub->link_tail->next = node; 318 | hub->link_tail = node; 319 | } 320 | 321 | hub->link_num++; 322 | MCN_EXIT_CRITICAL; 323 | 324 | if (hub->published) { 325 | /* update renewal flag as it's already published */ 326 | node->renewal = 1; 327 | 328 | if (node->pub_cb) { 329 | /* if data published before subscribe, then call callback immediately */ 330 | node->pub_cb(hub->pdata); 331 | } 332 | } 333 | 334 | return node; 335 | } 336 | 337 | /** 338 | * @brief Unsubscribe a uMCN topic 339 | * 340 | * @param hub uMCN hub 341 | * @param node Subscribe node 342 | * @return rt_err_t RT_EOK indicates success 343 | */ 344 | rt_err_t mcn_unsubscribe(McnHub_t hub, McnNode_t node) 345 | { 346 | MCN_ASSERT(hub != RT_NULL); 347 | MCN_ASSERT(node != RT_NULL); 348 | 349 | /* traverse each node */ 350 | McnNode_t cur_node = hub->link_head; 351 | McnNode_t pre_node = RT_NULL; 352 | 353 | while (cur_node != RT_NULL) { 354 | if (cur_node == node) { 355 | /* find node */ 356 | break; 357 | } 358 | 359 | pre_node = cur_node; 360 | cur_node = cur_node->next; 361 | } 362 | 363 | if (cur_node == RT_NULL) { 364 | /* can not find */ 365 | return -RT_EEMPTY; 366 | } 367 | 368 | /* update list */ 369 | MCN_ENTER_CRITICAL; 370 | 371 | if (hub->link_num == 1) { 372 | hub->link_head = hub->link_tail = RT_NULL; 373 | } else { 374 | if (cur_node == hub->link_head) { 375 | hub->link_head = cur_node->next; 376 | } else if (cur_node == hub->link_tail) { 377 | if (pre_node) { 378 | pre_node->next = RT_NULL; 379 | } 380 | hub->link_tail = pre_node; 381 | } else { 382 | pre_node->next = cur_node->next; 383 | } 384 | } 385 | 386 | hub->link_num--; 387 | 388 | MCN_EXIT_CRITICAL; 389 | 390 | /* free current node */ 391 | MCN_FREE(cur_node); 392 | 393 | return RT_EOK; 394 | } 395 | 396 | /** 397 | * @brief Publish uMCN topic 398 | * 399 | * @param hub uMCN hub, which can be obtained by MCN_HUB() macro 400 | * @param data Data of topic to publish 401 | * @return rt_err_t RT_EOK indicates success 402 | */ 403 | rt_err_t mcn_publish(McnHub_t hub, const void* data) 404 | { 405 | MCN_ASSERT(hub != RT_NULL); 406 | MCN_ASSERT(data != RT_NULL); 407 | 408 | if (hub->pdata == RT_NULL) { 409 | /* hub is not advertised yet */ 410 | return -RT_ERROR; 411 | } 412 | 413 | if (hub->suspend) { 414 | return -RT_ERROR; 415 | } 416 | 417 | /* update freq estimator window */ 418 | hub->freq_est_window[hub->window_index]++; 419 | 420 | MCN_ENTER_CRITICAL; 421 | /* copy data to hub */ 422 | rt_memcpy(hub->pdata, data, hub->obj_size); 423 | /* traverse each node */ 424 | McnNode_t node = hub->link_head; 425 | 426 | while (node != RT_NULL) { 427 | /* update each node's renewal flag */ 428 | node->renewal = 1; 429 | 430 | /* send out event to wakeup waiting task */ 431 | if (node->event) { 432 | /* stimulate as mutex */ 433 | if (node->event->value == 0) 434 | MCN_SEND_EVENT(node->event); 435 | } 436 | 437 | node = node->next; 438 | } 439 | 440 | hub->published = 1; 441 | MCN_EXIT_CRITICAL; 442 | 443 | /* invoke callback func */ 444 | node = hub->link_head; 445 | 446 | while (node != RT_NULL) { 447 | if (node->pub_cb != RT_NULL) { 448 | node->pub_cb(hub->pdata); 449 | } 450 | 451 | node = node->next; 452 | } 453 | 454 | return RT_EOK; 455 | } 456 | 457 | /** 458 | * @brief Initialize uMCN module 459 | * 460 | * @return int RT_EOK indicates success 461 | */ 462 | int mcn_init(void) 463 | { 464 | rt_timer_init(&timer_mcn_freq_est, "mcn_freq_est", 465 | mcn_freq_est_entry, 466 | RT_NULL, 467 | RT_TICK_PER_SECOND, 468 | RT_TIMER_FLAG_PERIODIC | RT_TIMER_FLAG_SOFT_TIMER); 469 | 470 | if (rt_timer_start(&timer_mcn_freq_est) != RT_EOK) { 471 | LOG_E("timer start error!"); 472 | return -RT_ERROR; 473 | } 474 | 475 | return RT_EOK; 476 | } 477 | INIT_DEVICE_EXPORT(mcn_init); 478 | --------------------------------------------------------------------------------