Differences

This shows you the differences between two versions of the page.

Link to this comparison view

sdk:scripts:modbus-rtu-slave [2015/05/05 15:04]
sdk:scripts:modbus-rtu-slave [2015/05/05 15:04] (current)
Line 1: Line 1:
 +====== SDK Script modbus-rtu-slave.are ======
 +<code c modbus-rtu-slave.are>​
 +/* DESC: This script implements a modbus slave server
 + * Copyright (C) 2015 NetModule AG, Switzerland
 + */
 +
 +DEV = "​SERIAL1";​
 +SLAVEID = 1;
 +DEBUG = 0;
 +
 +/* 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 */
 +fd = nb_serial_open(DEV);​
 +if (fd < 0) {
 +    printf("​Unable to open %s\n", DEV);
 +    exit(1);
 +}
 +
 +status = nb_config_get("​serial.0.status"​);​
 +if (status == "​2"​) {
 +    printf("​serial port enabled for sdk\n"​);​
 +} else {
 +    printf("​serial port not enabled for sdk\n\n",​ status);
 +    exit(1);
 +}
 +
 +/* register fd for modbus functions */
 +if (nb_modbus_register(fd,​ MODBUS_TYPE_RTU) < 0) {
 +    printf("​unable to register rtu descriptor"​);​
 +    exit(1);
 +}
 +
 +if (DEBUG > 0) {
 +    /* enable debug mode */
 +    if (nb_modbus_set_debug(fd,​ true) < 0) {
 +        printf("​unable to enable debug"​);​
 +        exit(1);
 +    }
 +}
 +
 +/* set slave id */
 +if (nb_modbus_set_slave(fd,​ SLAVEID) < 0) {
 +    printf("​unable to set slave id");
 +    exit(1);
 +}
 +
 +for (ctr = 0;;ctr++) {
 +    request = nb_modbus_receive(fd);​
 +    if (request == NULL) {
 +        printf("​receive failed (%s)\n",​ nb_modbus_last_error());​
 +        break;
 +    }
 +    ​
 +    resp = mkstruct(
 +        "​bits",​ mkarray
 +        (
 +            ctr%2, 0, 0, 0, 1, 1, 1, 1, 
 +            0    , 0, 0, 0, 1, 1, 1, 1
 +        ), 
 +        "​ibits",​ mkarray
 +        (
 +            ctr%2, 1, 0, 1, 0, 1, 0, 1, 
 +            0    , 1, 0, 1, 0, 1, 0, 1
 +        ), 
 +        "​regs",​ mkarray
 +        (
 +            ctr,    0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, ​
 +            0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F
 +        ), 
 +        "​iregs",​ mkarray
 +        (
 +            ctr,    0xFF01, 0xFF02, 0xFF03, 0xFF04, 0xFF05, 0xFF06, 0xFF07, ​
 +            0xFF08, 0xFF09, 0xFF0A, 0xFF0B, 0xFF0C, 0xFF0D, 0xFF0E, 0xFF0F
 +        )
 +    );
 +
 +    ret = nb_modbus_reply(fd,​ request, resp);
 +    if (ret < 0) {
 +        printf("​unable to reply to request (%s)\n",​ nb_modbus_last_error());​
 +    } else {
 +        printf("​replied %d bytes\n"​ , ret);
 +    }
 +}
 +
 +nb_modbus_unregister(fd);​
 +close(fd);
 +exit(0);
 +
 +
 +</​code>​