利用 libmodbus 快速部署一个 Modbus TCP Server

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

利用 libmodbus 快速部署一个 Modbus TCP Server

在现代工业通信中,Modbus protocol因其简洁性和易于実装而被广泛应用。本記事将経由一个具体的サンプル,详细介绍使い方は? libmodbus 库作成一个基于 TCP 的 Modbus Server。这个サーバー·サーバー能够処理クライアント側は的 Modbus Request,并对这些リクエスト作出レスポンス。

完全代码(Chinese annotation):

1. 初期化 Modbus TCP Server

首先,我们需要引入 libmodbus 库,并初期化一个 Modbus TCP Server。在我们的サンプル中,サーバー·サーバー将绑定到本地アドレス 127.0.0.1 ポートと港。 1502。経由调用 modbus_new_tcp 函数,我们作成了一个指向 modbus_t 構造的指针,这个構造体将作为后续すべての操作的Contextより:

ctx = modbus_new_tcp("127.0.0.1", 1502);

2. マッピング Modbus データ模型

接下来,我们需要定义サーバー·サーバー将要使用的 Modbus データ·マッピング。这一步骤是経由 modbus_mapping_new 函数完成的,它为不同タイプ的 Modbus data(位、入力位、レジスタを保持する。和入力レジスタ。)分配和初期化内存:

mb_mapping = modbus_mapping_new(500, 500, 500, 500);
if (mb_mapping == NULL) {
    fprintf(stderr, "Failed to allocate the mapping: %s\n", modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
}

3. 监听和接受クライアント側は连接

一旦データ·マッピング準備して,サーバー·サーバー就可以开始监听来自クライアント側は的接続リクエスト。使用 modbus_tcp_listen 函数开始监听,然后使用 modbus_tcp_accept 処理接入的クライアント側は连接:

s = modbus_tcp_listen(ctx, 1);
modbus_tcp_accept(ctx, &s);

4. 受信和レスポンスリクエスト

サーバー·サーバー的メイン·サイクル包括待機中クライアント側はリクエスト、受信リクエスト、処理リクエスト,并送信レスポンス。这経由不断调用 modbus_receive 函数来受信リクエスト,并使用 modbus_reply 函数来送信レスポンス:

for (;;) {
    rc = modbus_receive(ctx, query);
    if (rc > 0) {
        modbus_reply(ctx, query, rc, mb_mapping);
    } else if (rc == -1) {
        break;
    }
}

5. 清理和关闭リソース

一旦サーバー·サーバー完成任务(通常是由于エラー或クライアント側は接続を閉じる),它需要释放すべての分配的リソース,并优雅地接続を閉じる:

printf("Quit the loop: %s\n", modbus_strerror(errno));
if (s != -1) {
    close(s);
}
modbus_mapping_free(mb_mapping);
modbus_close(ctx);
modbus_free(ctx);

経由上述步骤,我们表示了使い方は? libmodbus 作成一个功能完备的 Modbus TCP Server。这个サーバー·サーバー能够処理標準的 Modbus function code,包括读単独で書く。或多个位和レジスタ的操作。本サンプル不仅適用される教育和测试目的,也可以作为实际应用中的基础。

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.