基于libmodbus 开发RTU Master端测试程序

基于libmodbus 开发RTU Master端测试程序

  • 开发环境
  • 完整代码
  • 配合Modbus Slave进行测试
  • 测试运行演示

开发环境

  1. 编译软件:VS2019
  2. libmodbusbus库:3.1.6版本 下载地址:https://libmodbus.org/download/

完整代码

//******************************************************************************                                
//name:             TestRtuMaster.c                   
//introduce:        串口Modbus-RTU Master(主机)测试代码            
//author:           szq                                               
//changetime:       2019.8.13
//****************************************************************************** 

/*********************************************************************
 * INCLUDES
 */
#include 
#ifndef _MSC_VER
include <unistd.h>
#endif
#include 
#include 
#include 

#include "modbus.h"  //应用libmodbus库

/*The goal of this program is to check all major functions of libmodbus:
* 本程序的目的是检查libmodbus的所有主要功能:
* -write_coil      
* -read_bits       
* -write_coils     
* -write_register  
* -read_register  
* -write_registers 
* -read_registers
*/


/*All these functions arre called with random values on a address range defined by the following defines.
* 所有这些函数都是在以下定义的地址范围内使用随机值调用的。
*/
#define LOOP           1     //循环次数
#define SERVER_ID      17    //从端设备地址 
#define ADDRESS_START  0     //测试寄存器起始地址
#define ADDRESS_END    99    //测试寄存器结束地址

/*At each loop,the program works in the range ADDRESS_START to
* ADDRESS_END then ADDRESS_START+1 to ADDRESS_END and so on.
*/

int main(void)
{
	modbus_t* ctx;
	int rc;
	int nb_fail;
	int nb_loop;
	int addr;
	int nb;
	int seed_c,RTU_mode,loop_n;
	uint8_t* tab_rq_bits;  //用于保存发送或接收的数据(下同)
	uint8_t* tab_rp_bits;
	uint16_t* tab_rq_registers;
	uint16_t* tab_rw_rq_registers;
	uint16_t* tab_rp_registers;

	system("title C++ modbus-RTU 测试程序");//设置cmd窗口标题
	system("mode con cols=48 lines=25");//窗口宽度高度
	system("color 0B");//0背景色黑色 B前景色浅绿色
	system("date /T");//输出当前日期时间
	system("TIME /T");

	printf(" ╪╪╪╪╪╪╧╧╧╧╧╧╧╧╪╪╪╪╪╪\n");
	printf("╔═╧╧ C++ modbus-RTU 测试程序  ╧╧═╗\n");
	printf("║※1. 单个读写寄存器║\n");
	printf("║※2. 多个读写寄存器║\n");
	printf("║※3. 0x17功能码读写寄存器║\n");
	printf("║※0. ║\n");
	printf("╚═══════════════════╝\n");
	Sleep(1000);//延时1秒 

	printf("输入一个随机数种子:");
	scanf_s("%d", &seed_c);
	srand(seed_c);
	printf("输入测试模式(1~3):");
	scanf_s("%d", &RTU_mode);
	printf("测试循环次数:");
	scanf_s("%d", &loop_n);

	/* RTU */
	ctx = modbus_new_rtu("COM3", 9600, 'N', 8, 1);  //创建一个RTU类型的容器,即创建一个COM口为C0M3 波特率9600bit/s
	modbus_set_slave(ctx, SERVER_ID);               //设置从机地址

	//modbus_set_debug(ctx, TRUE);                    //设置debug模式
	if (modbus_connect(ctx) == -1)
	{
		fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
		modbus_free(ctx);
		return -1;
	}

	/*Allocate and initialize the different memory spaces
	* 分配和初始化不同的内存空间
	*/
	nb = ADDRESS_END - ADDRESS_START;
	
	//以下申请内存,用以保存发送和接收各种数据
	tab_rq_bits = (uint8_t*)malloc(nb * sizeof(uint8_t));  //动态申请内存;(nb * sizeof(uint8_t)申请的内存空间的大小;sizeof(uint8_t)= 1;
	memset(tab_rq_bits, 0, nb * sizeof(uint8_t));          //清零

	tab_rp_bits = (uint8_t*)malloc(nb * sizeof(uint8_t));
	memset(tab_rp_bits, 0, nb * sizeof(uint8_t));

	tab_rq_registers = (uint16_t*)malloc(nb * sizeof(uint16_t));
	memset(tab_rq_registers, 0, nb * sizeof(uint16_t));

	tab_rp_registers = (uint16_t*)malloc(nb * sizeof(uint16_t));
	memset(tab_rp_registers, 0, nb * sizeof(uint16_t));

	tab_rw_rq_registers = (uint16_t*)malloc(nb * sizeof(uint16_t));
	memset(tab_rw_rq_registers, 0, nb * sizeof(uint16_t));

	Sleep(1000);//延时1秒 

	//循环发送
	nb_loop = nb_fail = 0;
	while (nb_loop++ < loop_n)
	{
		if (RTU_mode == 1)
		{
			for (addr = ADDRESS_START; addr < ADDRESS_END; addr++)
			{
				Sleep(100);//延时100ms 
				//生成随机数用于测试
				tab_rq_registers[0] = (uint16_t)rand();
				tab_rq_bits[0] = tab_rq_registers[0] % 2;
				printf("tab_rq_registers[0] =0x%04X;tab_rq_bits[0] =%d\n", tab_rq_registers[0], tab_rq_bits[0]);

				nb = ADDRESS_END - addr;

				/*测试线圈寄存器的单个读写*/
				rc = modbus_write_bit(ctx, addr, tab_rq_bits[0]);//写线圈寄存器   MODBUS_FC_WRITE_SINGLE_COIL  0x05指令
				if (rc != 1)
				{
					printf("ERROR modbus_write_bit (%d)\n", rc);
					printf("Address =%d, value =%d\n", addr, tab_rq_bits[0]);
					nb_fail++;
				}
				else
				{
					//写入之后,在读取并比较
					rc = modbus_read_bits(ctx, addr, 1, tab_rp_bits);    //MODBUS_FC_READ_COILS  0x01指令
					if (rc != 1 || tab_rq_bits[0] != tab_rp_bits[0])
					{
						printf("ERROR modbus_read_bits single (%d)\n", rc);
						printf("address =%d\n", addr);
						nb_fail++;
					}
				}

				/*测试保持寄存器的单个读写*/
				rc = modbus_write_register(ctx, addr, tab_rq_registers[0]);  //MODBUS_FC_WRITE_SINGLE_REGISTER  0x06指令
				if (rc != 1)
				{
					printf("ERROR modbus_write_register (%d)\n", rc);
					printf("Address =%d, Val =%d(0x%X)\n", addr, tab_rq_registers[0], tab_rq_registers[0]);
					nb_fail++;
				}
				else
				{
					//写入之后,在读取并比较
					rc = modbus_read_registers(ctx, addr, 1, tab_rp_registers);  //modbus_read_registers   0x03指令
					if (rc != 1)
					{
						printf("ERROR modbus_read_registers (%d)\n", rc);
						printf("Address =%d\n", addr);
						nb_fail++;
					}
					else
					{
						if (tab_rp_registers[0] != tab_rq_registers[0])
						{
							printf("ERROR modbus_read_registers\n");
							printf("Addr =%d, val =%d(0x%X) != %d(0x%X)\n", addr, tab_rq_registers[0], tab_rq_registers[0], tab_rp_registers[0], tab_rp_registers[0]);
							nb_fail++;
						}
					}
				}
			}
		}
		else if(RTU_mode == 2)
		{
			addr = ADDRESS_START;
			nb = ADDRESS_END - addr;
			//生成随机数用于测试
			int i;
			for (i = 0; i < nb; i++)
			{
				tab_rq_registers[i] =
					(uint16_t)(65535.0 * rand() / (RAND_MAX + 1.0));
				tab_rq_bits[i] = tab_rq_registers[i] % 2;
			}

			/*测试线圈寄存器的批量读写*/
			rc = modbus_write_bits(ctx, addr, nb, tab_rq_bits);     //MODBUS_FC_WRITE_MULTIPLE_COILS   0x0F指令
			if (rc != nb)
			{
				printf("ERROR modbus_write_bits (%d)\n", rc);
				printf("Address =%d, nb =%d\n", addr, nb);
				nb_fail++;
			}
			else
			{
				//写入之后,在读取并比较
				rc = modbus_read_bits(ctx, addr, nb, tab_rp_bits);  //MODBUS_FC_READ_COILS  0x01指令
				if (rc != nb)
				{
					printf("ERROR modbus_read_bits\n");
					printf("Address =%d, nb =%d\n", addr,nb);
					nb_fail++;
				}
				else
				{
					for (i = 0; i < nb; i++)
					{
						if (tab_rp_bits[i] != tab_rq_bits[i])
						{
							printf("ERROR modbus_read_bits\n");
							printf("Addr =%d, val =%d(0x%X) != %d(0x%X)\n",addr,tab_rq_bits[i],tab_rq_bits[i],tab_rp_bits[i],tab_rq_bits[i]);
							nb_fail++;
						}
					}
				}
			}

			/*测试线圈寄存器的批量读写*/
			rc = modbus_write_registers(ctx, addr, nb,tab_rq_registers);    //modbus_write_registers  0x10指令
			if (rc != nb)
			{
				printf("ERROR modbus_write_register (%d)\n", rc);
				printf("Address =%d, nb =%d\n", addr, nb);
				nb_fail++;
			}
			else
			{
				//写入之后,在读取并比较
				rc = modbus_read_registers(ctx, addr, nb, tab_rp_registers);  //modbus_read_registers   0x03指令
				if (rc != nb)
				{
					printf("ERROR modbus_read_registers (%d)\n", rc);
					printf("Address =%d, nb =%d\n", addr, nb);
					nb_fail++;
				}
				else
				{
					for (i = 0; i < nb; i++)
					{
						if (tab_rp_registers[i] != tab_rq_registers[i])
						{
							printf("ERROR modbus_read_registers\n");
							printf("Addr =%d, val =%d(0x%X) != %d(0x%X)\n", addr, tab_rq_registers[i], tab_rq_registers[i], tab_rp_registers[i], tab_rp_registers[i]);
							nb_fail++;
						}
					}
				}
			}
		}
		else if (RTU_mode == 3)
		{
			addr = ADDRESS_START;
			nb = ADDRESS_END - addr;
			//生成随机数用于测试
			int i;
			for (i = 0; i < nb; i++)
			{
				tab_rq_registers[i] =
					(uint16_t)(65535.0 * rand() / (RAND_MAX + 1.0));
				tab_rw_rq_registers[i] = ~tab_rq_registers[i];
			}
			/*功能码23(0x17)读写多个寄存器测试*/
			rc = modbus_write_and_read_registers(ctx, addr, nb, tab_rw_rq_registers, addr, nb, tab_rp_registers);  //MODBUS_FC_WRITE_AND_READ_REGISTERS  0x17指令
			if (rc != nb)
			{
				printf("ERROR modbus_write_and_read_register (%d)\n", rc);
				printf("Address =%d, nb =%d\n", addr, nb);
				nb_fail++;
			}
			else
			{
				//读取并比较
				for (i = 0; i < nb; i++)
				{
					if (tab_rp_registers[i] != tab_rw_rq_registers[i])
					{
						printf("ERROR modbus_write_and_read_register READ\n");
						printf("Addr =%d, val =%d(0x%X) != %d(0x%X)\n", addr, tab_rq_registers[i], tab_rq_registers[i], tab_rp_registers[i], tab_rp_registers[i]);
						nb_fail++;
					}
				}

				rc = modbus_read_registers(ctx, addr, nb, tab_rp_registers);   //modbus_read_registers   0x03指令
				if (rc != nb)
				{
					printf("ERROR modbus_write_and_read_register Write ti READ\n");
					printf("Address =%d, nb =%d\n", addr, nb);
					nb_fail++;
				}
				else
				{
					for (i = 0; i < nb; i++)
					{
						if (tab_rp_registers[i] != tab_rw_rq_registers[i])
						{
							printf("ERROR modbus_write_and_read_register Write ti READ\n");
							printf("Addr =%d, val =%d(0x%X) != %d(0x%X)\n", addr, tab_rw_rq_registers[i], tab_rw_rq_registers[i], tab_rp_registers[i], tab_rp_registers[i]);
							nb_fail++;
						}
					}
				}
			}
		}

		/*输出测试结果*/
		printf("Test Rtu:");
		if (nb_fail)
			printf("%d FAILS\n", nb_fail);
		else
			printf("SUCCESS\n");

		srand(seed_c + nb_loop + 1);//重装伪随机数种子
	}
	/*Free the memory
	*释放内存
	*/
	free(tab_rq_bits);
	free(tab_rp_bits);
	free(tab_rq_registers);
	free(tab_rp_registers);
	free(tab_rw_rq_registers);

	/*Close the connection*/
	modbus_close(ctx);
	modbus_free(ctx);

	system("pause");//可以实现冻结屏幕,便于观察程序的执行结果
	
	return 0;
}

配合Modbus Slave进行测试

Modbus Slave 如下图设置
基于libmodbus 开发RTU Master端测试程序_第1张图片基于libmodbus 开发RTU Master端测试程序_第2张图片基于libmodbus 开发RTU Master端测试程序_第3张图片基于libmodbus 开发RTU Master端测试程序_第4张图片

测试运行演示

基于libmodbus 开发RTU Master端测试程序_第5张图片
基于libmodbus 开发RTU Master端测试程序_第6张图片

你可能感兴趣的:(Modbus学习)