1 /*
2 * Copyright (c) 2022 Rodrigo Peixoto <rodrigopex@gmail.com>
3 * SPDX-License-Identifier: Apache-2.0
4 */
5 #include "messages.h"
6
7 #include <string.h>
8
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/uart.h>
11 #include <zephyr/kernel.h>
12 #include <zephyr/logging/log.h>
13 #include <zephyr/zbus/zbus.h>
14 LOG_MODULE_DECLARE(zbus, CONFIG_ZBUS_LOG_LEVEL);
15
16 ZBUS_SUBSCRIBER_DEFINE(bridge_sub, 4);
17
18 ZBUS_CHAN_DEFINE(finish_chan, /* Name */
19 struct action_msg, /* Message type */
20
21 NULL, /* Validator */
22 NULL, /* User data */
23 ZBUS_OBSERVERS(bridge_sub), /* observers */
24 ZBUS_MSG_INIT(false) /* Initial value */
25 );
26
27 const static struct device *bridge_uart = DEVICE_DT_GET(DT_NODELABEL(uart1));
28
bridge_tx_thread(void)29 static void bridge_tx_thread(void)
30 {
31 LOG_DBG("Bridge Started");
32
33 const struct zbus_channel *chan;
34
35 while (1) {
36 if (!zbus_sub_wait(&bridge_sub, &chan, K_FOREVER)) {
37 if (!zbus_chan_claim(chan, K_MSEC(500))) {
38 bool *user_data = (bool *)zbus_chan_user_data(chan);
39 bool generated_by_the_bridge = *user_data;
40 *user_data = false;
41
42 zbus_chan_finish(chan);
43
44 /* true here means the package was published by the bridge and must
45 * be discarded
46 */
47 if (!generated_by_the_bridge) {
48 LOG_DBG("Bridge send %s", zbus_chan_name(chan));
49
50 uart_poll_out(bridge_uart, '$');
51
52 for (int i = 0; i < strlen(zbus_chan_name(chan)); ++i) {
53 uart_poll_out(bridge_uart, zbus_chan_name(chan)[i]);
54 }
55
56 uart_poll_out(bridge_uart, ',');
57
58 uart_poll_out(bridge_uart, zbus_chan_msg_size(chan));
59
60 for (int i = 0; i < zbus_chan_msg_size(chan); ++i) {
61 uart_poll_out(bridge_uart,
62 ((uint8_t *)zbus_chan_msg(chan))[i]);
63 }
64
65 uart_poll_out(bridge_uart, '\r');
66
67 uart_poll_out(bridge_uart, '\n');
68 }
69 }
70 }
71 }
72 }
73
74 K_THREAD_DEFINE(bridge_thread_tid, 2048, bridge_tx_thread, NULL, NULL, NULL, 1, 0, 500);
75