/*
 * Copyright (C) 2022 EXOLIGENT (www.exoligent.com)
 * Author: Maxime Coroyer <maxime.coroyer@exoligent.com>
 */

#ifndef __FIP_H__
#define __FIP_H__

#include <powerfip/libpowerfip.h>

#define FIP_OPC_PUB_PERIOD_WAIT_COUNT 4

#define FIP_BA_WIND_COUNT_MAX 10
#define FIP_BA_PER_REQ_COUNT_MAX 1000
struct gw_fip_mcycle {
    struct pwrfip_ba_wind_cfg ba_wind_cfglist[FIP_BA_WIND_COUNT_MAX];
    struct pwrfip_ba_request ba_reqlist[FIP_BA_PER_REQ_COUNT_MAX];
    struct pwrfip_ba_mcycle_cfg mc_cfg;
};

#define FIP_STR_BSZ_MAX 255
#define FIP_VAR_COUNT_MAX 500
#define FIP_BA_MCYCLE_COUNT_MAX 10
struct gw_fip {
    int dev_idx;
    /* node configuration */
    char name_str[FIP_STR_BSZ_MAX]; /* node name */
    uint8_t addr;
    uint8_t seg;
    uint8_t frm_type;
    uint8_t bitrate;
    uint32_t tr_ustime;
    uint32_t ts_ustime;
    uint8_t has_r_op_evt; /* has json file defined an read op event flag ? */
    uint8_t has_w_op_evt; /* has json file defined an write op event flag ? */
    struct pwrfip_node_cfg n_cfg;
    /* macrocycles configuration */
    struct gw_fip_mcycle mc_cfglist[FIP_BA_MCYCLE_COUNT_MAX];
    int mc_cfg_cnt;
    /* device object */
    struct pwrfip_dev *dev; /* pci device handle */
    /* node object */
    struct pwrfip_node *n;
    /* aele object */
    struct pwrfip_aele *al;
    /* consumed variables list */
    struct pwrfip_var *cons_varlist[FIP_VAR_COUNT_MAX];
    int cons_varcnt;
    /* produced variables list */
    struct pwrfip_var *prod_varlist[FIP_VAR_COUNT_MAX];
    int prod_varcnt;
    /* synchronization variables list */
    struct pwrfip_var *sync_varlist[FIP_VAR_COUNT_MAX];
    int sync_varcnt;
    /* bus arbiter: macrocycles list */
    struct pwrfip_ba_mcycle *mc_list[FIP_BA_MCYCLE_COUNT_MAX];
    int mc_cnt;
    /* node report */
    struct pwrfip_node_report report;
    volatile int rw_op;
    volatile int wr_op;
    volatile int r_op;
    volatile int w_op;
    volatile int sync_in_progress;
};

#define PWRFIP_BITRATE_RANGE (_PWRFIP_BITRATE_MAX - _PWRFIP_BITRATE_MIN)
extern const char *bitrate[PWRFIP_BITRATE_RANGE];
extern const uint32_t tr_ustime[PWRFIP_BITRATE_RANGE];
extern const uint32_t ts_ustime[PWRFIP_BITRATE_RANGE];
extern const char *pwrfip_var_err_str[_PWRFIP_VAR_ERR_MAX];

/* global handlers */
void fip_id_sync_r_op_handler(struct pwrfip_node *node,
        struct pwrfip_var *var, struct pwrfip_event *evt);
void fip_id_sync_w_op_handler(struct pwrfip_node *node,
        struct pwrfip_var *var, struct pwrfip_event *evt);
void fip_id_sync_rw_op_handler(struct pwrfip_node *node,
        struct pwrfip_var *var, struct pwrfip_event *evt);
void fip_id_sync_wr_op_handler(struct pwrfip_node *node,
        struct pwrfip_var *var, struct pwrfip_event *evt);
void fip_error_handler(struct pwrfip_node *node,
        enum pwrfip_error_code code);
void fip_reset_handler(struct pwrfip_node *node);
/* utility */
void print_node_infos(struct pwrfip_node *node);
#endif
