/*
 * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

// clang-format off
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>

# include <sys/socket.h>
# include <sys/ioctl.h>

#include <netinet/in.h>
#include <netinet/ip.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# include <netdb.h>

#if !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// clang-format on

#include "modbus-private.h"

#include "myLog.h"
#include "modbus-tcp-private.h"
#include "modbus-tcp.h"

static int _modbus_set_slave(modbus_t *ctx, int slave)
{
    int max_slave = (ctx->quirks & MODBUS_QUIRK_MAX_SLAVE) ? 255 : 247;

    /* 广播地址为 0（MODBUS_BROADCAST_ADDRESS） */
    if (slave >= 0 && slave <= max_slave) {
        ctx->slave = slave;
    } else if (slave == MODBUS_TCP_SLAVE) {
        /* 特殊值 MODBUS_TCP_SLAVE（0xFF）可在 TCP 模式下用于恢复默认值 */
        ctx->slave = slave;
    } else {
        errno = EINVAL;
        return -1;
    }

    return 0;
}

/* 构建 TCP 请求报文头（MBAP报文头） */
static int _modbus_tcp_build_request_basis(
    modbus_t *ctx, int function, int addr, int nb, uint8_t *req)
{
    modbus_tcp_t *ctx_tcp = ctx->backend_data;

    /* 递增事务ID（Transaction ID） */
    if (ctx_tcp->t_id < UINT16_MAX)
        ctx_tcp->t_id++;
    else
        ctx_tcp->t_id = 0;
    req[0] = ctx_tcp->t_id >> 8;
    req[1] = ctx_tcp->t_id & 0x00ff;

    /* Modbus 协议标识符 */
    req[2] = 0;
    req[3] = 0;

    /* 长度将在后面的 set_req_length_tcp 中通过偏移量 4 和 5 来定义 */

    req[6] = ctx->slave;
    req[7] = function;
    req[8] = addr >> 8;
    req[9] = addr & 0x00ff;
    req[10] = nb >> 8;
    req[11] = nb & 0x00ff;

    return _MODBUS_TCP_PRESET_REQ_LENGTH;
}

/* 构建 TCP 响应报文头（MBAP报文头） */
static int _modbus_tcp_build_response_basis(sft_t *sft, uint8_t *rsp)
{
    /* 摘自《MODBUS Messaging on TCP/IP Implementation Guide V1.0b》（第23/46页）：
       事务标识符用于将未来的响应与请求关联起来。 */
    rsp[0] = sft->t_id >> 8;
    rsp[1] = sft->t_id & 0x00ff;

    /* Modbus 协议标识符 */
    rsp[2] = 0;
    rsp[3] = 0;

    /* 长度将在后面的 send_msg 中设置（偏移量 4 和 5） */

    /* 从站ID 从请求指示中复制 */
    rsp[6] = sft->slave;
    rsp[7] = sft->function;

    return _MODBUS_TCP_PRESET_RSP_LENGTH;
}

static int _modbus_tcp_get_response_tid(const uint8_t *req)
{
    return (req[0] << 8) + req[1];
}

static int _modbus_tcp_send_msg_pre(uint8_t *req, int req_length)
{
    /* 从消息长度中减去报文头长度 */
    int mbap_length = req_length - 6;

    req[4] = mbap_length >> 8;
    req[5] = mbap_length & 0x00FF;

    return req_length;
}

static ssize_t _modbus_tcp_send(modbus_t *ctx, const uint8_t *req, int req_length)
{
    /* MSG_NOSIGNAL
       请求在面向流的套接字上发生错误时不发送 SIGPIPE 信号，
       当另一端断开连接时仍然返回 EPIPE 错误。 */
    return send(ctx->s, (const char *) req, req_length, MSG_NOSIGNAL);
}

static int _modbus_tcp_receive(modbus_t *ctx, uint8_t *req)
{
    return _modbus_receive_msg(ctx, req, MSG_INDICATION);
}

static ssize_t _modbus_tcp_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length)
{
    return recv(ctx->s, (char *) rsp, rsp_length, 0);
}

static int _modbus_tcp_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length)
{
    return msg_length;
}

static int _modbus_tcp_pre_check_confirmation(modbus_t *ctx,
                                              const uint8_t *req,
                                              const uint8_t *rsp,
                                              int rsp_length)
{
    unsigned int protocol_id;
    /* 检查事务ID（Transaction ID） */
    if (req[0] != rsp[0] || req[1] != rsp[1]) {
        if (ctx->debug) {
            LOG_E(
                    "Invalid transaction ID received 0x%X (not 0x%X)",
                    (rsp[0] << 8) + rsp[1],
                    (req[0] << 8) + req[1]);
        }
        errno = EMBBADDATA;
        return -1;
    }

    /* 检查协议ID */
    protocol_id = (rsp[2] << 8) + rsp[3];
    if (protocol_id != 0x0) {
        if (ctx->debug) {
            LOG_E("Invalid protocol ID received 0x%X (not 0x0)", protocol_id);
        }
        errno = EMBBADDATA;
        return -1;
    }

    return 0;
}

static int _modbus_tcp_set_ipv4_options(int s)
{
    int rc;
    int option;

    /* 设置 TCP 无延迟标志（Nagle算法禁用） */
    /* SOL_TCP = IPPROTO_TCP */
    option = 1;
    rc = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const void *)&option, sizeof(int));
    if (rc == -1) {
        return -1;
    }

    /**
     * Cygwin 定义了 IPTOS_LOWDELAY 但无法处理该标志，
     * 因此需要绕过这个问题。
     **/
    /* 设置 IP 低延迟选项 */
    option = IPTOS_LOWDELAY;
    rc = setsockopt(s, IPPROTO_IP, IP_TOS, (const void *)&option, sizeof(int));
    if (rc == -1) {
        return -1;
    }

    return 0;
}

static int _connect(int sockfd,
                    const struct sockaddr *addr,
                    socklen_t addrlen,
                    const struct timeval *ro_tv)
{
    int rc = connect(sockfd, addr, addrlen);

    if (rc == -1 && errno == EINPROGRESS) {
        fd_set wset;
        int optval;
        socklen_t optlen = sizeof(optval);
        struct timeval tv = *ro_tv;

        /* 等待可写状态 */
        FD_ZERO(&wset);
        if (sockfd >= FD_SETSIZE) {
            errno = EINVAL;
            return -1;
        }
        FD_SET(sockfd, &wset);
        rc = select(sockfd + 1, NULL, &wset, NULL, &tv);
        if (rc < 0) {
            /* 失败 */
            return -1;
        }

        if (rc == 0) {
            /* 超时 */
            errno = ETIMEDOUT;
            return -1;
        }

        /* 如果 SO_ERROR 和 optval 都设置为 0，表示连接已建立 */
        rc = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
        if (rc == 0 && optval == 0) {
            return 0;
        } else {
            errno = ECONNREFUSED;
            return -1;
        }
    }
    return rc;
}

/* 建立与 Modbus 服务器的 Modbus TCP 连接 */
static int _modbus_tcp_connect(modbus_t *ctx)
{
    int rc;
    /* 专用于 Internet 套接字地址的 sockaddr 版本（相同大小） */
    struct sockaddr_in addr;
    modbus_tcp_t *ctx_tcp = ctx->backend_data;
    int flags = SOCK_STREAM;

    flags |= SOCK_CLOEXEC;

    flags |= SOCK_NONBLOCK;

    ctx->s = socket(PF_INET, flags, 0);
    if (ctx->s < 0) {
        return -1;
    }

    if (ctx->s >= FD_SETSIZE) {
        if (ctx->debug) 
        {
            LOG_E("ERROR Socket descriptor %d exceeds FD_SETSIZE (%d)", ctx->s, FD_SETSIZE);
        }
        close(ctx->s);
        ctx->s = -1;
        errno = EINVAL;
        return -1;
    }

    rc = _modbus_tcp_set_ipv4_options(ctx->s);
    if (rc == -1) {
        close(ctx->s);
        ctx->s = -1;
        return -1;
    }

    if (ctx->debug) {
        LOG_I("Connecting to %s:%d\n", ctx_tcp->ip, ctx_tcp->port);
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(ctx_tcp->port);
    rc = inet_pton(addr.sin_family, ctx_tcp->ip, &(addr.sin_addr));
    if (rc <= 0) {
        if (ctx->debug) {
            LOG_E("Invalid IP address: %s", ctx_tcp->ip);
        }
        close(ctx->s);
        ctx->s = -1;
        return -1;
    }

    rc =
        _connect(ctx->s, (struct sockaddr *) &addr, sizeof(addr), &ctx->response_timeout);
    if (rc == -1) {
        close(ctx->s);
        ctx->s = -1;
        return -1;
    }

    return 0;
}

/* 建立与 Modbus 服务器的 Modbus TCP PI（协议无关）连接 */
static int _modbus_tcp_pi_connect(modbus_t *ctx)
{
    int rc;
    struct addrinfo *ai_list;
    struct addrinfo *ai_ptr;
    struct addrinfo ai_hints;
    modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;

    memset(&ai_hints, 0, sizeof(ai_hints));
#ifdef AI_ADDRCONFIG
    ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
    ai_hints.ai_family = AF_UNSPEC;
    ai_hints.ai_socktype = SOCK_STREAM;
    ai_hints.ai_addr = NULL;
    ai_hints.ai_canonname = NULL;
    ai_hints.ai_next = NULL;

    ai_list = NULL;
    rc = getaddrinfo(ctx_tcp_pi->node, ctx_tcp_pi->service, &ai_hints, &ai_list);
    if (rc != 0) {
        if (ctx->debug) {
            LOG_E("Error returned by getaddrinfo: %s", gai_strerror(rc));
        }
        freeaddrinfo(ai_list);
        errno = ECONNREFUSED;
        return -1;
    }

    for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
        int flags = ai_ptr->ai_socktype;
        int s;

        flags |= SOCK_CLOEXEC;

        flags |= SOCK_NONBLOCK;

        s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
        if (s < 0)
            continue;

        if (s >= FD_SETSIZE) {
            if (ctx->debug) 
            {
                LOG_E("ERROR Socket descriptor %d exceeds FD_SETSIZE (%d)", s, FD_SETSIZE);
            }
            close(s);
            continue;
        }

        if (ai_ptr->ai_family == AF_INET)
            _modbus_tcp_set_ipv4_options(s);

        if (ctx->debug) {
            LOG_I("Connecting to [%s]:%s\n", ctx_tcp_pi->node, ctx_tcp_pi->service);
        }

        rc = _connect(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen, &ctx->response_timeout);
        if (rc == -1) {
            close(s);
            continue;
        }

        ctx->s = s;
        break;
    }

    freeaddrinfo(ai_list);

    if (ctx->s < 0) {
        return -1;
    }

    return 0;
}

static unsigned int _modbus_tcp_is_connected(modbus_t *ctx)
{
    return ctx->s >= 0;
}

/* 在 TCP 模式下关闭网络连接和套接字 */
static void _modbus_tcp_close(modbus_t *ctx)
{
    if (ctx->s >= 0) {
        shutdown(ctx->s, SHUT_RDWR);
        close(ctx->s);
        ctx->s = -1;
    }
}

static int _modbus_tcp_flush(modbus_t *ctx)
{
    int rc;
    // 使用无符号16位整数来降低溢出风险。flush 函数不期望处理大量数据（> 2GB）。
    uint16_t rc_sum = 0;

    do {
        /* 从套接字中取出垃圾数据 */
        char devnull[MODBUS_TCP_MAX_ADU_LENGTH];
        rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, MSG_DONTWAIT);
        if (rc > 0) {
            // 在累加之前检查是否溢出
            if (rc_sum <= UINT16_MAX - rc) {
                rc_sum += rc;
            } else {
                // 处理溢出
                ctx->error_recovery = MODBUS_ERROR_RECOVERY_PROTOCOL;
                errno = EOVERFLOW;
                return -1;
            }
        }
    } while (rc == MODBUS_TCP_MAX_ADU_LENGTH);

    /* 类型转换是安全的：uint16_t 总是能放入 int，溢出已在上面检查过 */
    return (int) rc_sum;
}

/* 在 TCP 模式下监听来自一个或多个 Modbus 主站的请求 */
int modbus_tcp_listen(modbus_t *ctx, int nb_connection)
{
    int new_s;
    int enable;
    int flags;
    struct sockaddr_in addr;
    modbus_tcp_t *ctx_tcp;
    int rc;

    if (ctx == NULL) {
        errno = EINVAL;
        return -1;
    }

    ctx_tcp = ctx->backend_data;

    flags = SOCK_STREAM;

    flags |= SOCK_CLOEXEC;

    new_s = socket(PF_INET, flags, IPPROTO_TCP);
    if (new_s == -1) {
        return -1;
    }

    enable = 1;
    if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR, (const void *)&enable, sizeof(enable)) == -1) {
        close(new_s);
        return -1;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    /* 如果 Modbus 端口号小于 1024，则需要 setuid root 权限 */
    addr.sin_port = htons(ctx_tcp->port);
    if (ctx_tcp->ip[0] == '0') {
        /* 监听所有地址 */
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
    } else {
        /* 仅监听指定的 IP 地址 */
        rc = inet_pton(addr.sin_family, ctx_tcp->ip, &(addr.sin_addr));
        if (rc <= 0) {
            if (ctx->debug) {
                LOG_E("Invalid IP address: %s", ctx_tcp->ip);
            }
            close(new_s);
            return -1;
        }
    }

    if (bind(new_s, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
        close(new_s);
        return -1;
    }

    if (listen(new_s, nb_connection) == -1) {
        close(new_s);
        return -1;
    }

    return new_s;
}

int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection)
{
    int rc;
    struct addrinfo *ai_list;
    struct addrinfo *ai_ptr;
    struct addrinfo ai_hints;
    const char *node;
    const char *service;
    int new_s;
    modbus_tcp_pi_t *ctx_tcp_pi;

    if (ctx == NULL) {
        errno = EINVAL;
        return -1;
    }

    ctx_tcp_pi = ctx->backend_data;

    if (ctx_tcp_pi->node[0] == 0) {
        node = NULL; /* == 任意地址 */
    } else {
        node = ctx_tcp_pi->node;
    }

    if (ctx_tcp_pi->service[0] == 0) {
        service = "502";
    } else {
        service = ctx_tcp_pi->service;
    }

    memset(&ai_hints, 0, sizeof(ai_hints));
    /* 如果 node 不为 NULL，则 AI_PASSIVE 标志会被忽略 */
    ai_hints.ai_flags |= AI_PASSIVE;
#ifdef AI_ADDRCONFIG
    ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
    ai_hints.ai_family = AF_UNSPEC;
    ai_hints.ai_socktype = SOCK_STREAM;
    ai_hints.ai_addr = NULL;
    ai_hints.ai_canonname = NULL;
    ai_hints.ai_next = NULL;

    ai_list = NULL;
    rc = getaddrinfo(node, service, &ai_hints, &ai_list);
    if (rc != 0) {
        if (ctx->debug) {
            LOG_E("Error returned by getaddrinfo: %s", gai_strerror(rc));
        }
        if (ai_list != NULL) {
            freeaddrinfo(ai_list);
        }
        errno = ECONNREFUSED;
        return -1;
    }

    new_s = -1;
    for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
        int flags = ai_ptr->ai_socktype;
        int s;

        flags |= SOCK_CLOEXEC;

        s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol);
        if (s < 0) {
            if (ctx->debug) {
                perror("socket");
            }
            continue;
        } else {
            int enable = 1;
            rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const void *)&enable, sizeof(enable));
            if (rc != 0) {
                close(s);
                if (ctx->debug) {
                    perror("setsockopt");
                }
                continue;
            }
        }

        rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
        if (rc != 0) {
            close(s);
            if (ctx->debug) {
                perror("bind");
            }
            continue;
        }

        rc = listen(s, nb_connection);
        if (rc != 0) {
            close(s);
            if (ctx->debug) {
                perror("listen");
            }
            continue;
        }

        new_s = s;
        break;
    }
    freeaddrinfo(ai_list);

    if (new_s < 0) {
        return -1;
    }

    return new_s;
}

int modbus_tcp_accept(modbus_t *ctx, int *s)
{
    struct sockaddr_in addr;
    socklen_t addrlen;

    if (ctx == NULL) {
        errno = EINVAL;
        return -1;
    }

    addrlen = sizeof(addr);
    /* 继承套接字标志并使用 accept4 调用 */
    ctx->s = accept4(*s, (struct sockaddr *) &addr, &addrlen, SOCK_CLOEXEC);

    if (ctx->s < 0) {
        return -1;
    }

    if (ctx->s >= FD_SETSIZE) {
        if (ctx->debug) 
        {
            LOG_E("ERROR Socket descriptor %d exceeds FD_SETSIZE (%d)", ctx->s, FD_SETSIZE);
        }
        close(ctx->s);
        ctx->s = -1;
        errno = EINVAL;
        return -1;
    }

    if (ctx->debug) {
        char buf[INET_ADDRSTRLEN];
        if (inet_ntop(AF_INET, &(addr.sin_addr), buf, INET_ADDRSTRLEN) == NULL) {
            LOG_E("Client connection accepted from unparsable IP.");
        } else {
            LOG_I("Client connection accepted from %s.\n", buf);
        }
    }

    return ctx->s;
}

int modbus_tcp_pi_accept(modbus_t *ctx, int *s)
{
    struct sockaddr_in6 addr;
    socklen_t addrlen;

    if (ctx == NULL) {
        errno = EINVAL;
        return -1;
    }

    addrlen = sizeof(addr);
    /* 继承套接字标志并使用 accept4 调用 */
    ctx->s = accept4(*s, (struct sockaddr *) &addr, &addrlen, SOCK_CLOEXEC);

    if (ctx->s < 0) {
        return -1;
    }

    if (ctx->s >= FD_SETSIZE) {
        if (ctx->debug) 
        {
            LOG_E("ERROR Socket descriptor %d exceeds FD_SETSIZE (%d)", ctx->s, FD_SETSIZE);
        }
        close(ctx->s);
        ctx->s = -1;
        errno = EINVAL;
        return -1;
    }

    if (ctx->debug) {
        char buf[INET6_ADDRSTRLEN];
        if (inet_ntop(AF_INET6, &(addr.sin6_addr), buf, INET6_ADDRSTRLEN) == NULL) {
            LOG_E("Client connection accepted from unparsable IP.");
        } else {
            LOG_I("Client connection accepted from %s.\n", buf);
        }
    }

    return ctx->s;
}

static int
_modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read)
{
    int s_rc;
    while ((s_rc = select(ctx->s + 1, rset, NULL, NULL, tv)) == -1) {
        if (errno == EINTR) {
            if (ctx->debug) {
                LOG_E("A non blocked signal was caught");
            }
            /* 发生错误后需要重新设置 */
            FD_ZERO(rset);
            if (ctx->s < 0 || ctx->s >= FD_SETSIZE) {
                errno = EINVAL;
                return -1;
            }
            FD_SET(ctx->s, rset);
        } else {
            return -1;
        }
    }

    if (s_rc == 0) {
        errno = ETIMEDOUT;
        return -1;
    }

    return s_rc;
}

static void _modbus_tcp_free(modbus_t *ctx)
{
    if (ctx->backend_data) {
        free(ctx->backend_data);
    }
    free(ctx);
}

static void _modbus_tcp_pi_free(modbus_t *ctx)
{
    if (ctx->backend_data) {
        modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data;
        free(ctx_tcp_pi->node);
        free(ctx_tcp_pi->service);
        free(ctx->backend_data);
    }

    free(ctx);
}

// clang-format off
const modbus_backend_t _modbus_tcp_backend = {
    _MODBUS_BACKEND_TYPE_TCP,
    _MODBUS_TCP_HEADER_LENGTH,
    _MODBUS_TCP_CHECKSUM_LENGTH,
    MODBUS_TCP_MAX_ADU_LENGTH,
    _modbus_set_slave,
    _modbus_tcp_build_request_basis,
    _modbus_tcp_build_response_basis,
    _modbus_tcp_get_response_tid,
    _modbus_tcp_send_msg_pre,
    _modbus_tcp_send,
    _modbus_tcp_receive,
    _modbus_tcp_recv,
    _modbus_tcp_check_integrity,
    _modbus_tcp_pre_check_confirmation,
    _modbus_tcp_connect,
    _modbus_tcp_is_connected,
    _modbus_tcp_close,
    _modbus_tcp_flush,
    _modbus_tcp_select,
    _modbus_tcp_free
};

const modbus_backend_t _modbus_tcp_pi_backend = {
    _MODBUS_BACKEND_TYPE_TCP,
    _MODBUS_TCP_HEADER_LENGTH,
    _MODBUS_TCP_CHECKSUM_LENGTH,
    MODBUS_TCP_MAX_ADU_LENGTH,
    _modbus_set_slave,
    _modbus_tcp_build_request_basis,
    _modbus_tcp_build_response_basis,
    _modbus_tcp_get_response_tid,
    _modbus_tcp_send_msg_pre,
    _modbus_tcp_send,
    _modbus_tcp_receive,
    _modbus_tcp_recv,
    _modbus_tcp_check_integrity,
    _modbus_tcp_pre_check_confirmation,
    _modbus_tcp_pi_connect,
    _modbus_tcp_is_connected,
    _modbus_tcp_close,
    _modbus_tcp_flush,
    _modbus_tcp_select,
    _modbus_tcp_pi_free
};

// clang-format on

modbus_t *modbus_new_tcp(const char *ip, int port)
{
    modbus_t *ctx;
    modbus_tcp_t *ctx_tcp;
    size_t dest_size;
    size_t ret_size;

    ctx = (modbus_t *) malloc(sizeof(modbus_t));
    if (ctx == NULL) {
        return NULL;
    }

    _modbus_init_common(ctx);
    ctx->backend = &_modbus_tcp_backend;

    ctx->backend_data = (modbus_tcp_t *) malloc(sizeof(modbus_tcp_t));
    if (ctx->backend_data == NULL) {
        modbus_free(ctx);
        errno = ENOMEM;
        return NULL;
    }
    ctx_tcp = (modbus_tcp_t *) ctx->backend_data;

    if (ip != NULL) {
        dest_size = sizeof(char) * 16;
        ret_size = strlcpy(ctx_tcp->ip, ip, dest_size);
        if (ret_size == 0) {
            LOG_E("The IP string is empty");
            modbus_free(ctx);
            errno = EINVAL;
            return NULL;
        }

        if (ret_size >= dest_size) {
            LOG_E("The IP string has been truncated");
            modbus_free(ctx);
            errno = EINVAL;
            return NULL;
        }
    } else {
        ctx_tcp->ip[0] = '0';
    }
    ctx_tcp->port = port;
    ctx_tcp->t_id = 0;

    return ctx;
}

modbus_t *modbus_new_tcp_pi(const char *node, const char *service)
{
    modbus_t *ctx;
    modbus_tcp_pi_t *ctx_tcp_pi;

    ctx = (modbus_t *) malloc(sizeof(modbus_t));
    if (ctx == NULL) {
        return NULL;
    }
    _modbus_init_common(ctx);

    /* 之后可以更改此值以访问远程串行 Modbus 设备 */
    ctx->slave = MODBUS_TCP_SLAVE;

    ctx->backend = &_modbus_tcp_pi_backend;

    ctx->backend_data = (modbus_tcp_pi_t *) malloc(sizeof(modbus_tcp_pi_t));
    if (ctx->backend_data == NULL) {
        modbus_free(ctx);
        errno = ENOMEM;
        return NULL;
    }
    ctx_tcp_pi = (modbus_tcp_pi_t *) ctx->backend_data;
    ctx_tcp_pi->node = NULL;
    ctx_tcp_pi->service = NULL;

    if (node != NULL) {
        ctx_tcp_pi->node = strdup(node);
    } else {
        /* node 参数可以为空，表示任意主机 */
        ctx_tcp_pi->node = strdup("");
    }

    if (ctx_tcp_pi->node == NULL) {
        modbus_free(ctx);
        errno = ENOMEM;
        return NULL;
    }

    if (service != NULL && service[0] != '\0') {
        ctx_tcp_pi->service = strdup(service);
    } else {
        /* 默认的 Modbus 端口号 */
        ctx_tcp_pi->service = strdup("502");
    }

    if (ctx_tcp_pi->service == NULL) {
        modbus_free(ctx);
        errno = ENOMEM;
        return NULL;
    }

    ctx_tcp_pi->t_id = 0;

    return ctx;
}
