修改tcp连接的返回值,增加套接字的有效性进行判断

main
huyizhong 11 months ago
parent 03722cdf1b
commit 8ab3e983c0

@ -1,5 +1,5 @@
[MODBUS_SLAVE]
SLAVE_IP_ADDR=192.168.1.7
SLAVE_IP_PORT=503
SLAVE_IP_ADDR=192.168.50.155
SLAVE_IP_PORT=502

@ -371,7 +371,7 @@ static int _modbus_tcp_connect(modbus_t *ctx)
return -1;
}
return 0;
return ctx->s;
}
/* Establishes a modbus TCP PI connection with a Modbus server. */

@ -1,6 +1,7 @@
#include <iostream>
#include "modbus_lib/modbus-tcp.h"
#include "common.h"
#include "time.h"
using namespace std;
#define REG_ADDR (header_length+1)
@ -56,7 +57,7 @@ void xMaster_Set_slave_port(const char* tcp_port)
DWORD WINAPI xModbus_master_Proc(LPVOID lp) {
char* com = (char*)lp;
CHAR rcv_buf[1024] = { 0 };
int s = -1;
int sockt = -1;
int i = 0;
int rc = 0;
modbus_t* ctx = NULL;
@ -69,6 +70,8 @@ DWORD WINAPI xModbus_master_Proc(LPVOID lp) {
modbus_mapping_t* mb_mapping;
int nb_points;
uint16_t* tab_rp_registers = NULL;
fd_set fdset_ro, fdset_wr, fdset_ex;
struct timeval timeout;
//Read the starting address of the holding register
unsigned short start_hold_register = 0x0000;//读保持寄存器的起始地址
@ -89,15 +92,50 @@ DWORD WINAPI xModbus_master_Proc(LPVOID lp) {
}
modbus_set_response_timeout(ctx, 20, 0);
if (modbus_connect(ctx) == -1) {
sockt = modbus_connect(ctx);
if (sockt == -1) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return -1;
}
unsigned char* src = (unsigned char*)tab_rp_registers;
while (1)
{
#if 0
if (sockt < 0)
return -1;
FD_ZERO(&fdset_ro);
FD_ZERO(&fdset_wr);
FD_ZERO(&fdset_ex);
FD_SET(sockt, &fdset_ro);
FD_SET(sockt, &fdset_wr);
FD_SET(sockt, &fdset_ex);
memset((char*)&timeout, 0, sizeof(struct timeval));
if (select(sockt + 1, &fdset_ro, &fdset_wr, &fdset_ex, &timeout) < 1)
{
Sleep(1);
continue;
}
if (FD_ISSET(sockt, &fdset_ex))
{
//printf("关闭tcp端口\n");
closesocket(sockt);
sockt = -1;
break;
}
if (FD_ISSET(sockt, &fdset_ro))
#endif
rc = modbus_read_registers(ctx, start_hold_register, number_regs, tab_rp_registers);
#if 0
if (rc == -1)
{
closesocket(sockt);
sockt = -1;
printf("End Thread\n");
return -1;
}
#endif
Sleep(3 * 1000);
//xUnsigned_char_hex_out("recv", src, 0, number_regs*2);
xRead_reg_hex_out(start_hold_register, "master recv", src, 0, number_regs * 2);
@ -134,12 +172,19 @@ DWORD WINAPI xModbus_master_Proc(LPVOID lp) {
printf("t=%ld\n", t);
time_t now = time(NULL);
struct tm t0;
localtime_s(&t0, &now);
printf("收到数据时间是:%d年%d月%d日 %d时%d分%d秒\n", t0.tm_year + 1900, t0.tm_mon + 1, t0.tm_mday, t0.tm_hour, t0.tm_min, t0.tm_sec);
//printf("t=%d\n", (int)time(NULL));
//time_t t3 = 0x64F9 << 16 | 0x4204;
//printf("t3=%ld\n", t3);
//time_t t4 = 1694056964;
//printf("%02x\n",t4);
while (1);
Sleep(15 * 1000);
}
//while (1);
return 0;

Loading…
Cancel
Save