1/*
2 * Copyright 2017, Data61, CSIRO (ABN 41 687 119 230)
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7/* CAmkES provides a generated header that prototypes all the relevant
8 * generated symbols.
9 */
10#include <camkes.h>
11
12#include <ringbuffer/ringbuffer.h>
13#include <stdlib.h>
14
15/* If we receive this character, interpret it as a request to switch outputs.
16 */
17#define SWITCH_CHAR '\t'
18
19/* The current output we're sending data to. */
20static enum {
21    LOW,
22    HIGH,
23} selected = LOW;
24
25/* This function is invoked by the main CAmkES thread in this component. */
26int run(void) {
27    ringbuffer_t *low = rb_new((void*)low_output, sizeof(*low_output));
28    if (low == NULL) {
29        abort();
30    }
31
32    ringbuffer_t *high = rb_new((void*)high_output, sizeof(*high_output));
33    if (high == NULL) {
34        abort();
35    }
36
37    ringbuffer_t *input = rb_new((void*)char_in, sizeof(*char_in));
38    if (input == NULL) {
39        abort();
40    }
41
42    while (true) {
43        char c = (char)rb_receive_byte(input);
44//        printf("Switch received: %x\n", c);
45        if (c == SWITCH_CHAR) {
46//            printf("Switching!\n");
47            /* Swap which output we see as active. */
48            if (selected == LOW) {
49                selected = HIGH;
50            } else {
51                selected = LOW;
52            }
53        } else {
54            /* Send the character to the active output. */
55            if (selected == LOW) {
56                rb_transmit_byte(low, (unsigned char)c);
57            } else {
58                rb_transmit_byte(high, (unsigned char)c);
59            }
60        }
61    }
62    return 0;
63}
64