/* Reference sample — build with nRF Connect SDK; not CI-built here.
 * nRF54LM20 DK CPU app. UART: 115200 baud, 8N1, no flow control.
 * Optional capture-sensor devicetree alias: generic Zephyr temperature sensor.
 * Without a ready sensor, emit a visibly named synthetic signal instead.
 */
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/drivers/uart.h>
#include <zephyr/sys/printk.h>

#define CAPTURE_RATE_HZ 50
#define CAPTURE_PERIOD_MS (1000 / CAPTURE_RATE_HZ)
#if DT_NODE_HAS_STATUS(DT_ALIAS(capture_sensor), okay)
static const struct device *const sensor = DEVICE_DT_GET(DT_ALIAS(capture_sensor));
#endif

int main(void)
{
    const struct device *const uart = DEVICE_DT_GET(DT_CHOSEN(zephyr_console));
    struct uart_config config = {
        .baudrate = 115200, .parity = UART_CFG_PARITY_NONE,
        .stop_bits = UART_CFG_STOP_BITS_1, .data_bits = UART_CFG_DATA_BITS_8,
        .flow_ctrl = UART_CFG_FLOW_CTRL_NONE,
    };
    /* Fail silent if UART cannot be configured; no malformed protocol output. */
    if (!device_is_ready(uart) || uart_configure(uart, &config) != 0) return 1;
    bool use_sensor = false;
#if DT_NODE_HAS_STATUS(DT_ALIAS(capture_sensor), okay)
    use_sensor = device_is_ready(sensor);
#endif
    printk("# ficus-capture v1 channels=%s rate_hz=%d\n",
           use_sensor ? "temperature_c" : "synthetic_signal", CAPTURE_RATE_HZ);
    int64_t next = k_uptime_get();
    for (uint32_t index = 0; ; ++index) {
        float value;
#if DT_NODE_HAS_STATUS(DT_ALIAS(capture_sensor), okay)
        if (use_sensor) {
            struct sensor_value reading;
            if (sensor_sample_fetch(sensor) != 0 ||
                sensor_channel_get(sensor, SENSOR_CHAN_AMBIENT_TEMP, &reading) != 0) {
                /* Do not change channel meaning to synthetic after a sensor failure.
                 * Skip failed rows; timestamp gaps remain visible in the browser. */
                next += CAPTURE_PERIOD_MS;
                int64_t delay = next - k_uptime_get();
                if (delay > 0) k_sleep(K_MSEC(delay));
                continue;
            }
            value = (float)sensor_value_to_double(&reading);
        } else
#endif
        {
            /* Repeating triangular signal; no sensor or accuracy claim. */
            uint32_t phase = index % 100u;
            value = (float)(phase < 50u ? phase : 100u - phase) / 25.0f - 1.0f;
        }
        const int64_t t_ms = k_uptime_get();
        printk("%lld,%.6f\n", (long long)t_ms, (double)value);
        next += CAPTURE_PERIOD_MS;
        int64_t delay = next - k_uptime_get();
        if (delay > 0) k_sleep(K_MSEC(delay));
        else next = k_uptime_get(); /* Missed deadlines are not hidden as exact sampling. */
    }
    return 0;
}
