Program Listing for File events.h

Return to documentation for file (microsync/src/events.h)

#pragma once

#ifdef min
#undef min
#endif

#ifdef max
#undef max
#endif

#include <queue>          // priority queue, FIFO queue

#ifndef UNIT_TEST
#include <asf.h>
#include "pins.h"
#endif

#include "globals.h"
#include "uart_comm.h"

extern volatile uint32_t default_pulse_duration_us;

using EventFunc = void (*)(uint32_t, uint32_t);

typedef struct  __attribute__((packed)) Event
{
    EventFunc func;
    uint32_t      arg1;
    uint32_t      arg2;
    union
    {
        uint64_t  ts64_cts;
        struct {
            uint32_t ts_lo32_cts;
            uint32_t ts_hi32_cts;
        };
    };
    uint32_t      N;
    uint32_t      interv_cts;
   // Constructor
   Event() : func([](uint32_t, uint32_t) { printf("ERR: Event func not set!\n"); }),
       arg1(0), arg2(0), ts64_cts(0), N(0), interv_cts(0) {}


    bool operator<(const Event& other) const {
        return this->ts64_cts > other.ts64_cts;
    }
} Event;  // 28 bytes


extern std::priority_queue<Event> event_queue;

extern volatile uint64_t sys_tc_ovf_count;

Event* event_from_datapacket(const DataPacket* packet, EventFunc func=nullptr);

void schedule_event(const Event *event, bool relative = true);

void schedule_pulse(const DataPacket *data, bool is_positive);

void schedule_pulse(uint32_t pin_idx, uint32_t pulse_duration_us, uint64_t timestamp_us,
                    uint32_t N, uint32_t interval_us, bool relative = true);

void schedule_pin(const DataPacket *data);

void schedule_toggle(const DataPacket *data);

void schedule_burst(const DataPacket *data);

void schedule_enable_pin(const DataPacket *data);

void schedule_disable_pin(const DataPacket *data);

void process_events();

void init_burst_timer();

void init_sys_timer();

void start_sys_timer();

void stop_sys_timer();

void pause_sys_timer();

extern volatile bool sys_timer_running;

inline uint64_t current_time_cts()
{
    return sys_tc_ovf_count | SYS_TC->TC_CHANNEL[SYS_TC_CH].TC_CV;
}
uint64_t current_time_us();

float current_time_s();

void tgl_pin_event_func(uint32_t arg1_pin_idx, uint32_t arg2);

void set_pin_event_func(uint32_t arg1_pin_idx, uint32_t arg2);

void start_burst_func  (uint32_t arg1_period,  uint32_t arg2_unused);

void stop_burst_func   (uint32_t arg1_unused,  uint32_t arg2_unused);

void enable_pin_func   (uint32_t arg1_pin_idx, uint32_t arg2);

void disable_pin_func  (uint32_t arg1_pin_idx, uint32_t arg2);

inline bool is_event_missed()
{
    static Event e;
    bool result = false;

    if (sys_timer_running && !event_queue.empty())
    {
        e = event_queue.top();
        result = current_time_cts() > (e.ts64_cts + TS_MISSED_TOLERANCE_CTS);
    }
    return result;
}