Skip to content

Creating MODBUS TCP socket is failed every 26 th attempt #1

Description

@mmanoharan83

Binary file is created against to the program https://github.com/rscada/libmodbus/blob/master/bin/modbus-tcp-discrete-output.c

After creating the socket, every 26th attempt getting the below error.Further socket can't be executed.

ERROR Message:

main: modbus_tcp_init failed: modbus_tcp_init: couldn't connect: Connection timed out.

Modified the below parameters
"HOST COMMAND ADDRESS" values are passed inside the code itself. Instead of getting as argument.

Declared as below:

addr = 0;
range = 16;
char IP_ADDRESS;
char PORT;

host= test->IP_ADDRESS;
port = test->PORT;

Below part removed:

if (argc != 4 && argc != 5)
{
    printf("Error: Invalid arguments.\n\n");    
    usage(argv[0]);
}

host    = argv[1];
command = argv[2];

if (strcmp(command, "write") == 0)
{
    if (argc != 5)
    {
       printf("Error: Invalid arguments: COMMAND write requies additional argument VALUE\n\n");    
       usage(argv[0]);        
    }

    addr  = atoi(argv[3]);
    value = atoi(argv[4]);    
}
else if (strcmp(command, "read") == 0)
{
    addr = atoi(argv[3]);    
}
else if (strcmp(command, "readrange") == 0)
{
    addr = atoi(argv[3]);
    range = 8;
}    
else
{
    printf("Error: Invalid COMMAND: %s\n\n", command);
    usage(argv[0]);
}

Below modified part running in while loop:

while(1)
{
pkt = modbus_frame_new();

  modbus_read_coil_status(pkt, addr, range);

// setup tcp
if (modbus_tcp_init(host, port, &handle) != 0)
{
    printf("%s: modbus_tcp_init failed: %s.\n", __PRETTY_FUNCTION__, modbus_error_str);
    return 0;
}

if (debug)
    modbus_frame_print(pkt);

// Send command
if (modbus_tcp_send(&handle, pkt) != 0)
{
    printf("%s: modbus_tcp_send failed: %s.\n", __PRETTY_FUNCTION__, modbus_error_str);
    return 0;       
}

// recv response
if (modbus_tcp_recv(&handle, pkt) != 0)
{
    printf("%s: modbus_tcp_recv failed: %s.\n", __PRETTY_FUNCTION__, modbus_error_str);
    return 0;       
}

if (modbus_frame_verify(pkt) == -1)
{
    printf("%s: modbus_frame_verify failed: %s\n", __PRETTY_FUNCTION__, modbus_error_str);
    return 0;               
}

if (debug)
    modbus_frame_print(pkt);

if (strcmp(command, "write") == 0)
{
    ; //    
}
else // a read command
{
    for (i = range - 1; i >= 0; i--)
    {
        printf("%d ", pkt->data_buff[1] & (0x01<<i) ? 1 : 0);
    }
    printf("\n");
}
modbus_frame_free(pkt);

}//while loop
return 0;

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions