SDK Script modbus-tcp-rtu-gateway.are

modbus-tcp-rtu-gateway.are
/* DESC: This script can be used to read messages from the serial port.
 * Copyright (C) 2015 NetModule AG, Switzerland
 */
 
DEV         = "SERIAL1";
TCP_IP      = "192.168.1.1";
TCP_PORT    = 1502;
 
/* check serial port config */
st = nb_config_get("serial.0.status");
if (st != "2") {
    nb_syslog("Serial port is not enabled for us");
    exit(1);
}
 
/* set attributes */
ret = nb_serial_setattr(DEV, 115200, 8, 1, 0, 0);
 
if (ret != 0) {
    printf("Could not set serial attributes: %i \n",ret);
    exit(1);
}
 
/* open serial port */
serial_fd = nb_serial_open(DEV);
if (serial_fd < 0) {
    printf("Unable to open %s\n", DEV);
    exit(1);
}
 
/* register serial_fd as modbus RTU */
nb_modbus_register(serial_fd, MODBUS_TYPE_RTU);
 
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
    printf("Unable to open socket\n");
    exit(1);
}
 
ret = bind(sock, TCP_PORT, "");
if (ret == -1) {
    printf("Unable to bind port %d\n", port);
    close(sock);
    exit(1);
}
 
ret = listen(sock, 1);
if (ret == -1) {
    printf("Unable to listen\n");
    close(sock);
    exit(1);
}
 
printf("Listening for connections on port %d\n", port);
 
while (1) {
    tcp_client = accept(sock);
    if (tcp_client < 0) {
        printf("accept failed\n");
        sleep(1);
        continue;
    }
 
    /* register serial_fd as modbus TCP */ 
    if (nb_modbus_register(tcp_client, MODBUS_TYPE_TCP)) {
        printf("Unable to register client (%s)\n", nb_modbus_last_error());
        close(tcp_client);
        continue;
    }
 
    /* wait for modbus tcp request */
    request = nb_modbus_receive(tcp_client);    
 
    if (!is_void(request)) {
        /* extract payload and forward it to modbus rtu serial_fd */
        response = nb_modbus_send_raw(serial_fd, 
                                      nb_modbus_extract_payload(tcp_client, 
                                      request));
        if (response != NULL) {
            /* extract payload and send response to modbus tcp */
             nb_modbus_reply_raw_response(tcp_client, request, nb_modbus_extract_payload(serial_fd, response));
        } else {
            printf("Unable to send response (%s)\n",  nb_modbus_last_error());
        }
    } else {
        printf("Unable to receive request (%s)\n",  nb_modbus_last_error());
    }
 
}
 
nb_modbus_unregister(serial_fd);
nb_modbus_unregister(tcp_client);
close(serial_fd);
close(tcp_client);
exit(0);