/*
 * Created by jiaqiang.ye@lnxall.com
 *
 * GPIO input/output as modbus TCP
 *
 * 2022/05/12
 */

#ifndef DIDO_MODBUS_H
#define DIDO_MODBUS_H 1

#include <modbus.h>
#include <pthread.h>

#include "lnxall_gpio.h"

#ifdef __cplusplus
extern "C" {
#endif

#define NB_CONNECTION      32

#define WOOLINK_DO_MAX     128
#define WOOLINK_DI_MAX     128
#define WOOLINK_DIDO_MAX   (WOOLINK_DO_MAX + WOOLINK_DI_MAX)
#define WOOLINK_DO_OFFSET  0
#define WOOLINK_DI_OFFSET  128

struct dido_modbus {
    int                    dm_num_output;   /* number of GPIO output Pins */
    int                    dm_num_input;    /* number of GPIO input Pins */
    struct lnxall_gpio   * dm_gpios;        /* GPIO array, output comes first */
    modbus_t             * dm_ctx;          /* modbus context */
    modbus_mapping_t     * dm_map;          /* modbus data mapping */
    pthread_t              dm_thread;       /* GPIO monitor thread */
    pthread_mutex_t        dm_lock;         /* mutex lock for multiple threads */
    int                    dm_sock;         /* modbus TCP listening socket */
    int                    dm_verbose;
    uint8_t                dm_query[MODBUS_TCP_MAX_ADU_LENGTH];
};

/*
 * Get the numbers of output and input GPIO Pins
 */
int dido_modbus_gpio_get(int * p_out, int * p_in);

struct dido_modbus * dido_modbus_create(int num_output, int num_input);

int dido_modbus_opengpio(struct dido_modbus * dido);

int dido_modbus_opentcp(struct dido_modbus * dido, const char * hostaddr, int portno);

void dido_modbus_free(struct dido_modbus * dido);

#ifdef __cplusplus
};
#endif
#endif
